1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @copyright Daniel Król <[email protected]> |
4
|
|
|
* @license MIT |
5
|
|
|
* @package Mleko\Alchemist |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
declare(strict_types=1); |
11
|
|
|
|
12
|
|
|
namespace Mleko\Alchemist\Normalizer; |
13
|
|
|
|
14
|
|
|
|
15
|
|
|
use Mleko\Alchemist\Normalizer; |
16
|
|
|
use Mleko\Alchemist\Type; |
17
|
|
|
|
18
|
|
|
class ArrayNormalizer implements Normalizer, NormalizerAware |
19
|
|
|
{ |
20
|
|
|
/** @var Normalizer|null */ |
21
|
|
|
private $subNormalizer; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @inheritDoc |
25
|
|
|
*/ |
26
|
4 |
|
public function normalize($value, string $format, array $context = []) { |
27
|
4 |
|
if (null === $this->subNormalizer) { |
28
|
1 |
|
throw new \RuntimeException("Cannot normalize array without subNormalizer"); |
29
|
|
|
} |
30
|
3 |
|
$data = []; |
31
|
3 |
|
foreach ($value as $key => $val) { |
32
|
3 |
|
$data[$key] = $this->subNormalizer->normalize($val, $format, $context); |
33
|
|
|
} |
34
|
3 |
|
return $data; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @inheritDoc |
39
|
|
|
*/ |
40
|
3 |
|
public function denormalize($data, Type $type, string $format, array $context = []) { |
41
|
3 |
|
if (1 === \count($type->getSubTypes())) { |
42
|
3 |
|
if (null === $this->subNormalizer) { |
43
|
1 |
|
throw new \RuntimeException("Cannot denormalize array without subNormalizer"); |
44
|
|
|
} |
45
|
2 |
|
$subType = $type->getSubTypes()[0]; |
46
|
2 |
|
foreach ($data as $key => $value) { |
47
|
2 |
|
$data[$key] = $this->subNormalizer->denormalize($value, $subType, $format, $context); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
2 |
|
if ("ArrayObject" === $type->getName()) { |
52
|
2 |
|
return new \ArrayObject($data); |
53
|
|
|
} |
54
|
1 |
|
return $data; |
55
|
|
|
} |
56
|
|
|
|
57
|
5 |
|
public function canProcess(Type $type, string $format): bool { |
58
|
5 |
|
if (!\in_array($type->getName(), ["array", "ArrayObject"])) { |
59
|
2 |
|
return false; |
60
|
|
|
} |
61
|
5 |
|
$subTypeCount = \count($type->getSubTypes()); |
62
|
5 |
|
if (0 === $subTypeCount) { |
63
|
3 |
|
return true; |
64
|
3 |
|
} elseif (1 === $subTypeCount && null !== $this->subNormalizer) { |
65
|
3 |
|
return $this->subNormalizer->canProcess($type->getSubTypes()[0], $format); |
66
|
|
|
} |
67
|
1 |
|
return false; |
68
|
|
|
} |
69
|
|
|
|
70
|
6 |
|
public function setNormalizer(Normalizer $normalizer): void { |
71
|
6 |
|
$this->subNormalizer = $normalizer; |
72
|
6 |
|
} |
73
|
|
|
} |
74
|
|
|
|