1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Stack Exchange Api Client library. |
5
|
|
|
* |
6
|
|
|
* Copyright (c) 2014-2016 Beñat Espiña <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace BenatEspina\StackExchangeApiClient\Serializer; |
13
|
|
|
|
14
|
|
|
use BenatEspina\StackExchangeApiClient\Model\Model; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* The serializer abstract class. |
18
|
|
|
* |
19
|
|
|
* @author Beñat Espiña <[email protected]> |
20
|
|
|
*/ |
21
|
|
|
abstract class Serializer |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* Fully qualified model class name. |
25
|
|
|
* |
26
|
|
|
* @var string |
27
|
|
|
*/ |
28
|
|
|
protected static $class; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Serializes the given data in a correct domain model class. |
32
|
|
|
* |
33
|
|
|
* @param mixed $data The given data |
34
|
|
|
* |
35
|
|
|
* @throws \Exception when the given data is incorrect |
36
|
|
|
* |
37
|
|
|
* @return array|Model |
38
|
|
|
*/ |
39
|
|
|
public static function serialize($data) |
40
|
|
|
{ |
41
|
|
|
if (false === array_key_exists('items', $data)) { |
42
|
|
|
throw new \Exception('Given data is incorrect'); |
43
|
|
|
} |
44
|
|
|
$class = static::className(); |
|
|
|
|
45
|
|
|
if (count($data['items']) > 1) { |
46
|
|
|
$objects = []; |
47
|
|
|
foreach ($data['items'] as $item) { |
48
|
|
|
$objects[] = $class::fromJson($item); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $objects; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $class::fromJson($data['items'][0]); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Gets the fully qualified class name. |
59
|
|
|
* |
60
|
|
|
* @throws \Exception when the class is not a model instance |
61
|
|
|
* |
62
|
|
|
* @return string |
63
|
|
|
*/ |
64
|
|
|
private static function className() |
65
|
|
|
{ |
66
|
|
|
$reflectionClass = new \ReflectionClass(static::$class); |
67
|
|
|
if (false === $reflectionClass->implementsInterface(Model::class)) { |
68
|
|
|
throw new \Exception('Given class name is not a model instance'); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return static::$class; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
Let’s assume you have a class which uses late-static binding:
}
The code above will run fine in your PHP runtime. However, if you now create a sub-class and call the
getSomeVariable()
on that sub-class, you will receive a runtime error:In the case above, it makes sense to update
SomeClass
to useself
instead: