src/StructSerializer/Main/StructSerializer.php line 33

Open in your IDE?
  1. <?php
  2. /*
  3.  * Author: Dominik Piekarski <code@dompie.de>
  4.  * Created at: 2022/07/27 12:49
  5.  */
  6. declare(strict_types=1);
  7. namespace App\StructSerializer\Main;
  8. use App\StructSerializer\AbstractStruct;
  9. use Frivol\Common\JSON;
  10. class StructSerializer
  11. {
  12.     private array $services = [];
  13.     public function toArray(StructOptions $optionsobject $entity): ?array
  14.     {
  15.         $classParts explode('\\'get_class($entity));
  16.         $structSerializerClass 'App\\StructSerializer\\'.array_pop($classParts).'Struct';
  17.         AbstractStruct::setServices($this->services);
  18.         return $structSerializerClass::toArray($options$entity);
  19.     }
  20.     public function multipleToArray(StructOptions $optionsiterable $entities): array
  21.     {
  22.         if ([] === $entities) {
  23.             return [];
  24.         }
  25.         $elements = [];
  26.         foreach ($entities as $entity) {
  27.             $elements[] = $this->toArray($options$entity);
  28.         }
  29.         return $elements;
  30.     }
  31.     /**
  32.      * @throws \JsonException
  33.      */
  34.     public function serialize(StructOptions $optionsobject $entity): string
  35.     {
  36.         return JSON::encode($this->toArray($options$entity));
  37.     }
  38.     public function serializeArray(array $data): string
  39.     {
  40.         return JSON::encode($data);
  41.     }
  42.     /**
  43.      * @return $this
  44.      */
  45.     public function addService(object $service): self
  46.     {
  47.         $this->services[get_class($service)] = $service;
  48.         return $this;
  49.     }
  50.     protected function getService(string $class): ?object
  51.     {
  52.         return $this->services[$class] ?? null;
  53.     }
  54. }