|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Morrislaptop\SymfonyCustomNormalizers; |
| 4 | + |
| 5 | +use Illuminate\Contracts\Database\ModelIdentifier; |
| 6 | +use Illuminate\Contracts\Queue\QueueableCollection; |
| 7 | +use Illuminate\Contracts\Queue\QueueableEntity; |
| 8 | +use Illuminate\Queue\SerializesAndRestoresModelIdentifiers; |
| 9 | +use InvalidArgumentException; |
| 10 | +use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; |
| 11 | +use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
| 12 | + |
| 13 | +class ModelIdentifierNormalizer implements NormalizerInterface, DenormalizerInterface |
| 14 | +{ |
| 15 | + use SerializesAndRestoresModelIdentifiers; |
| 16 | + |
| 17 | + /** |
| 18 | + * @inheritdoc |
| 19 | + */ |
| 20 | + public function normalize($object, string $format = null, array $context = []) |
| 21 | + { |
| 22 | + if (! $this->supportsNormalization($object)) { |
| 23 | + throw new InvalidArgumentException('Cannot serialize an object that is not a QueueableEntity or QueueableCollection in ModelIdentifierNormalizer.'); |
| 24 | + } |
| 25 | + |
| 26 | + return $this->getSerializedPropertyValue($object); |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * @inheritdoc |
| 31 | + */ |
| 32 | + public function supportsNormalization($data, string $format = null) |
| 33 | + { |
| 34 | + return ($data instanceof QueueableEntity || $data instanceof QueueableCollection); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * @inheritdoc |
| 39 | + */ |
| 40 | + public function denormalize($data, $type, string $format = null, array $context = []) |
| 41 | + { |
| 42 | + $identifier = $data instanceof ModelIdentifier |
| 43 | + ? $data |
| 44 | + : new ModelIdentifier($data['class'], $data['id'], $data['relations'], $data['connection']); |
| 45 | + |
| 46 | + return $this->getRestoredPropertyValue($identifier); |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * @inheritdoc |
| 51 | + */ |
| 52 | + public function supportsDenormalization($data, $type, string $format = null) |
| 53 | + { |
| 54 | + return $this->normalizedDataIsModelIdentifier($data) |
| 55 | + && $this->isNormalizedToModelIdentifier($type); |
| 56 | + } |
| 57 | + |
| 58 | + protected function normalizedDataIsModelIdentifier($data): bool |
| 59 | + { |
| 60 | + return $data instanceof ModelIdentifier |
| 61 | + || isset($data['class'], $data['id'], $data['relations'], $data['connection']); |
| 62 | + } |
| 63 | + |
| 64 | + protected function isNormalizedToModelIdentifier($class): bool |
| 65 | + { |
| 66 | + return is_a($class, QueueableEntity::class, true) |
| 67 | + || is_a($class, QueueableCollection::class, true); |
| 68 | + } |
| 69 | +} |
0 commit comments