ItemSerializer.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace App\Serializer;
  3. use App\Entity\AbstractWebflowEntity;
  4. use Closure;
  5. use Doctrine\Common\Annotations\Reader;
  6. use ReflectionClass;
  7. class ItemSerializer {
  8. private $class;
  9. private $map;
  10. private $reader;
  11. private $methods;
  12. public function __construct(Reader $reader, AbstractWebflowEntity $class) {
  13. $this->reader = $reader;
  14. $this->class = $class;
  15. $this->refClass = new ReflectionClass(get_class($class));
  16. foreach ($this->refClass->getMethods() as $key => $method)
  17. $this->methods[strtolower($method->getName())] = $method;
  18. foreach ($this->refClass->getParentClass() as $class)
  19. $this->mapProperties(new ReflectionClass($class));
  20. $this->mapProperties($this->refClass);
  21. }
  22. private function mapProperties(ReflectionClass $c): void {
  23. foreach ($c->getProperties() as $prop) {
  24. $c = $this->reader->getPropertyAnnotation($prop, ItemSerializedName::class);
  25. if ($c && $c->getFieldName() == '@ignore')
  26. continue;
  27. $this->map[$prop->getName()] = $c ? $c->getFieldName() : $prop->getName();
  28. }
  29. }
  30. public function restoreProperties(): array {
  31. $d = [];
  32. foreach ($this->map as $field => $origField)
  33. $d[$origField] = ($fn = $this->getFn($field)) ? $fn() : null;
  34. return $d;
  35. }
  36. public function setFn(string $name): ?array {
  37. $m = array_filter($this->map, function(string $val) use ($name) {
  38. return $val == $name;
  39. });
  40. if (sizeof($m) == 0)
  41. return null;
  42. $fn = sprintf("set%s", strtolower(current(array_flip($m))));
  43. if (!isset($this->methods[$fn]))
  44. return null;
  45. return ([$this->class, $this->methods[$fn]->getName()]);
  46. }
  47. public function getFn(string $name): ?array {
  48. $m = array_filter($this->map, function (string $key) use ($name) {
  49. return $key == $name;
  50. }, ARRAY_FILTER_USE_KEY);
  51. if (sizeof($m) == 0)
  52. return null;
  53. $fn = sprintf("get%s", strtolower(current(array_flip($m))));
  54. if (!isset($this->methods[$fn]))
  55. return null;
  56. return [$this->class, $this->methods[$fn]->getName()];
  57. }
  58. }