-
Notifications
You must be signed in to change notification settings - Fork 1
/
IdInterfaceNormalizer.php
82 lines (71 loc) · 2.29 KB
/
IdInterfaceNormalizer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
declare(strict_types=1);
namespace Xthiago\ValueObject\Id\Serializer\Symfony;
use InvalidArgumentException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Xthiago\ValueObject\Id\Id;
use Xthiago\ValueObject\Id\IdInterface;
/**
* @psalm-suppress DeprecatedInterface
*/
class IdInterfaceNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{
/** @var array<class-string, string|bool|null> */
private $supportedClasses = [];
/** @psalm-param array<class-string, string|bool|null> $supportedClasses */
public function __construct(array $supportedClasses = [])
{
$this->supportedClasses = $supportedClasses;
}
public static function default(): self
{
return new self([
Id::class => true,
IdInterface::class => true,
]);
}
/** {@inheritDoc} */
public function normalize($object, string $format = null, array $context = [])
{
return (string) $object;
}
/** {@inheritDoc} */
public function supportsNormalization($data, string $format = null)
{
return $data instanceof IdInterface;
}
/**
* {@inheritdoc}
*/
public function denormalize($data, string $type, string $format = null, array $context = [])
{
try {
/** @psalm-suppress InvalidStringClass */
return $type::fromString($data);
} catch (InvalidArgumentException $exception) {
throw new NotNormalizableValueException(sprintf(
'The data is not a valid "%s" string representation.',
$type
));
}
}
/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, string $type, string $format = null)
{
return is_a($type, IdInterface::class, true);
}
public function getSupportedTypes(?string $format): array
{
return $this->supportedClasses;
}
/** @deprecated on Symfony 6.3. */
public function hasCacheableSupportsMethod(): bool
{
return true;
}
}