Sf4 /
Api
| 1 | <?php |
||
| 2 | /** |
||
| 3 | * Created by PhpStorm. |
||
| 4 | * User: siim |
||
| 5 | * Date: 11.02.19 |
||
| 6 | * Time: 9:56 |
||
| 7 | */ |
||
| 8 | |||
| 9 | namespace Sf4\Api\Utils\Traits; |
||
| 10 | |||
| 11 | use Symfony\Component\Serializer\Encoder\JsonEncoder; |
||
| 12 | use Symfony\Component\Serializer\Exception\ExceptionInterface; |
||
| 13 | use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; |
||
| 14 | use Symfony\Component\Serializer\Serializer; |
||
| 15 | |||
| 16 | trait SerializerTrait |
||
| 17 | { |
||
| 18 | |||
| 19 | /** |
||
| 20 | * @param array|object|null $data |
||
| 21 | */ |
||
| 22 | public function populate(array $data): void |
||
| 23 | { |
||
| 24 | $this->populateObject($data); |
||
| 25 | } |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @param array $data |
||
| 29 | * @param null $object |
||
|
0 ignored issues
–
show
Documentation
Bug
introduced
by
Loading history...
|
|||
| 30 | */ |
||
| 31 | public function populateObject(array $data, $object = null): void |
||
| 32 | { |
||
| 33 | if (null === $object) { |
||
|
0 ignored issues
–
show
|
|||
| 34 | $object = $this; |
||
| 35 | } |
||
| 36 | |||
| 37 | if (is_array($data)) { |
||
|
0 ignored issues
–
show
|
|||
| 38 | $json = json_encode($data); |
||
| 39 | $class = get_class($object); |
||
| 40 | $this->createSerializer()->deserialize($json, $class, 'json', [ |
||
| 41 | 'object_to_populate' => $object |
||
| 42 | ]); |
||
| 43 | } |
||
| 44 | } |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @return array |
||
| 48 | */ |
||
| 49 | public function toArray(): array |
||
| 50 | { |
||
| 51 | return $this->objectToArray(); |
||
| 52 | } |
||
| 53 | |||
| 54 | /** |
||
| 55 | * @param null $object |
||
|
0 ignored issues
–
show
|
|||
| 56 | * @param array $ignoredAttributes |
||
| 57 | * @return array |
||
| 58 | */ |
||
| 59 | public function objectToArray($object = null, $ignoredAttributes = ['id', 'uuid']): array |
||
| 60 | { |
||
| 61 | if (null === $object) { |
||
|
0 ignored issues
–
show
|
|||
| 62 | $object = $this; |
||
| 63 | } elseif (is_scalar($object)) { |
||
| 64 | $object = [$object]; |
||
| 65 | } |
||
| 66 | |||
| 67 | if (is_array($object)) { |
||
|
0 ignored issues
–
show
|
|||
| 68 | return $object; |
||
| 69 | } |
||
| 70 | |||
| 71 | try { |
||
| 72 | $response = $this->createSerializer()->normalize($object, null, [ |
||
| 73 | ObjectNormalizer::ENABLE_MAX_DEPTH => true, |
||
| 74 | ObjectNormalizer::IGNORED_ATTRIBUTES => $ignoredAttributes |
||
| 75 | ]); |
||
| 76 | } catch (ExceptionInterface $e) { |
||
| 77 | $response = []; |
||
| 78 | } |
||
| 79 | |||
| 80 | return $response; |
||
| 81 | } |
||
| 82 | |||
| 83 | private function createSerializer(): Serializer |
||
| 84 | { |
||
| 85 | $encoders = [new JsonEncoder()]; |
||
| 86 | $normalizers = [new ObjectNormalizer()]; |
||
| 87 | return new Serializer($normalizers, $encoders); |
||
| 88 | } |
||
| 89 | } |
||
| 90 |