Skip to content

Commit

Permalink
Use ReflectionObject to iterate an object on properties
Browse files Browse the repository at this point in the history
  • Loading branch information
JoMessina committed Oct 18, 2023
1 parent 5d2304b commit de6bacc
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions src/PrepareRejectBucket.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Kiboko\Component\ExpressionLanguage\Magento\Serializable\ProductCatalogSerializableRejectData;
use Kiboko\Component\ExpressionLanguage\Magento\Serializable\SerializableRejectDataInterface;
use ReflectionObject;
use Symfony\Component\ExpressionLanguage\ExpressionFunction;

class PrepareRejectBucket extends ExpressionFunction
Expand All @@ -17,15 +18,45 @@ public function __construct($name)
);
}

private function compile(string $dataToFormat): string
private function compile(string $input, int $depth = 2): string
{
return <<<PHP
new \Kiboko\Component\ExpressionLanguage\Magento\Serializable\ProductCatalogSerializableRejectData($dataToFormat)
(function(){
\$serializer = function(\$input, int \$depth = 2) use (&\$serializer) {
if (\$depth === 0 || !is_object(\$input)) {
return json_encode(\$input);
}
\$object = new ReflectionObject(\$input);
\$output = [];
foreach (\$object->getProperties() as \$property) {
\$value = \$property->getValue(\$input);
\$output[] = \$serializer(\$value, \$depth - 1);
}
return \$output;
};
return \$serializer($input, $depth)
})()
PHP;
}

private function evaluate(array $context, array $dataToFormat): SerializableRejectDataInterface
private function evaluate(array $context, mixed $input, int $depth = 2): array
{
return new ProductCatalogSerializableRejectData($dataToFormat);
$serializer = function($input, int $depth = 2) use (&$serializer) {
if ($depth === 0 || !is_object($input)) {
return json_encode($input);
}

$output = [];
$object = new ReflectionObject($input);

foreach ($object->getProperties() as $property) {
$value = $property->getValue($input);
$output[] = $serializer($value, $depth - 1);
}

return $output;
};

return $serializer($input, $depth);
}
}

0 comments on commit de6bacc

Please sign in to comment.