HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/shop.komma.nl/app/Discounts/DiscountPropertyService.php
<?php declare(strict_types=1);


namespace App\Discounts;


use App\Cart\ShoppingCart;
use App\Cart\ShoppingCartItem;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class DiscountPropertyService
{
    protected ?\ReflectionClass $reflectionClass = null;

    protected array $hiddenMethods = ['__construct', 'toArray'];
    protected array $hiddenProperties = ['__construct', 'toArray'];

    protected bool $allowPropertiesWithoutTranslations = false;

    public function discountablePropertiesForShoppingCart() {
        $this->reflectionClass= new \ReflectionClass(ShoppingCart::class);
        return $this->publicMethods()->merge($this->publicProperties());
    }

    public function discountablePropertiesForShoppingCartItem() {
        $this->reflectionClass= new \ReflectionClass(ShoppingCartItem::class);
        return $this->publicMethods()->merge($this->publicProperties());
    }

    private function publicMethods() {
        return $this->mapCollectionByNameAndTranslation(
            collect($this->reflectionClass->getMethods(\ReflectionProperty::IS_PUBLIC))
        )->mapWithKeys(function($translation, $key) {
            return [$key.'()' => $translation]; //Append () to method name to make it clear that it is a method
        });
    }

    private function publicProperties() {
        return $this->mapCollectionByNameAndTranslation(collect($this->reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC)));
    }

    private function mapCollectionByNameAndTranslation(Collection $collection) {
        $reflectionProperties = $collection->filter(fn($method) => !in_array($method->getName(), $this->hiddenMethods));
        return $reflectionProperties->mapWithKeys(function(\ReflectionMethod $reflectionMethod) {
            return [$reflectionMethod->name => $this->translationOrDefault($this->translationKey($reflectionMethod->getName()), null)];
        })->filter(function($translation, $key) {
           return $this->allowPropertiesWithoutTranslations || $translation !== null;
        });
    }

    private function translationOrDefault(string $key, string $default = null) {
        if($key !== __($key)) return __($key);
        return $default;
    }

    private function translationKey($key) {
        return 'KMS::discounts.properties.'.Str::snake($this->reflectionClass->getShortName()).'.'.$key;
    }
}