1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- namespace App\Serializer;
- use App\Entity\AbstractWebflowEntity;
- use Closure;
- use Doctrine\Common\Annotations\Reader;
- use ReflectionClass;
- class ItemSerializer {
- private $class;
- private $map;
- private $reader;
- private $methods;
- public function __construct(Reader $reader, AbstractWebflowEntity $class) {
- $this->reader = $reader;
- $this->class = $class;
- $this->refClass = new ReflectionClass(get_class($class));
- foreach ($this->refClass->getMethods() as $key => $method)
- $this->methods[strtolower($method->getName())] = $method;
- foreach ($this->refClass->getParentClass() as $class)
- $this->mapProperties(new ReflectionClass($class));
- $this->mapProperties($this->refClass);
- }
- private function mapProperties(ReflectionClass $c): void {
- foreach ($c->getProperties() as $prop) {
- $c = $this->reader->getPropertyAnnotation($prop, ItemSerializedName::class);
-
- if ($c && $c->getFieldName() == '@ignore')
- continue;
- $this->map[$prop->getName()] = $c ? $c->getFieldName() : $prop->getName();
- }
- }
- public function restoreProperties(): array {
- $d = [];
- foreach ($this->map as $field => $origField)
- $d[$origField] = ($fn = $this->getFn($field)) ? $fn() : null;
- return $d;
- }
- public function setFn(string $name): ?array {
- $m = array_filter($this->map, function(string $val) use ($name) {
- return $val == $name;
- });
- if (sizeof($m) == 0)
- return null;
- $fn = sprintf("set%s", strtolower(current(array_flip($m))));
- if (!isset($this->methods[$fn]))
- return null;
- return ([$this->class, $this->methods[$fn]->getName()]);
- }
- public function getFn(string $name): ?array {
- $m = array_filter($this->map, function (string $key) use ($name) {
- return $key == $name;
- }, ARRAY_FILTER_USE_KEY);
- if (sizeof($m) == 0)
- return null;
- $fn = sprintf("get%s", strtolower(current(array_flip($m))));
- if (!isset($this->methods[$fn]))
- return null;
- return [$this->class, $this->methods[$fn]->getName()];
- }
- }
|