|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* (c) Kévin Dunglas <[email protected]> |
|
5
|
|
|
* |
|
6
|
|
|
* This source file is subject to the MIT license that is bundled |
|
7
|
|
|
* with this source code in the file LICENSE. |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace Dunglas\DoctrineJsonOdm; |
|
11
|
|
|
|
|
12
|
|
|
use Symfony\Component\Serializer\Serializer as BaseSerializer; |
|
13
|
|
|
|
|
14
|
|
|
final class Serializer extends BaseSerializer |
|
15
|
|
|
{ |
|
16
|
|
|
private const KEY_TYPE = '#type'; |
|
17
|
|
|
private const KEY_SCALAR = '#scalar'; |
|
18
|
|
|
|
|
19
|
|
|
public function normalize($data, $format = null, array $context = []) |
|
20
|
|
|
{ |
|
21
|
|
|
$normalizedData = parent::normalize($data, $format, $context); |
|
22
|
|
|
|
|
23
|
|
|
if (is_object($data)) { |
|
24
|
|
|
$typeData = [self::KEY_TYPE => get_class($data)]; |
|
25
|
|
|
$valueData = is_scalar($normalizedData) ? [self::KEY_SCALAR => $normalizedData] : $normalizedData; |
|
26
|
|
|
$normalizedData = array_merge($typeData, $valueData); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
return $normalizedData; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function denormalize($data, $class, $format = null, array $context = []) |
|
33
|
|
|
{ |
|
34
|
|
|
if (is_array($data) && (isset($data[self::KEY_TYPE]))) { |
|
35
|
|
|
$type = $data[self::KEY_TYPE]; |
|
36
|
|
|
unset($data[self::KEY_TYPE]); |
|
37
|
|
|
|
|
38
|
|
|
$data = $data[self::KEY_SCALAR] ?? $data; |
|
39
|
|
|
$data = $this->denormalize($data, $type, $format, $context); |
|
40
|
|
|
|
|
41
|
|
|
return parent::denormalize($data, $type, $format, $context); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if (is_iterable($data)) { |
|
45
|
|
|
$class = ($class === '') ? 'stdClass' : $class; |
|
46
|
|
|
|
|
47
|
|
|
return parent::denormalize($data, $class.'[]', $format, $context); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
return $data; |
|
|
|
|
|
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_functionexpects aPostobject, and outputs the author of the post. The base classPostreturns a simple string and outputting a simple string will work just fine. However, the child classBlogPostwhich is a sub-type ofPostinstead decided to return anobject, and is therefore violating the SOLID principles. If aBlogPostwere passed tomy_function, PHP would not complain, but ultimately fail when executing thestrtouppercall in its body.