|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the badams\GoogleUrl library |
|
4
|
|
|
* |
|
5
|
|
|
* @license http://opensource.org/licenses/MIT |
|
6
|
|
|
* @link https://github.com/badams/google-url |
|
7
|
|
|
* @package badams/google-url |
|
8
|
|
|
* |
|
9
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
10
|
|
|
* file that was distributed with this source code. |
|
11
|
|
|
*/ |
|
12
|
|
|
|
|
13
|
|
|
namespace badams\GoogleUrl; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Class Resource |
|
17
|
|
|
* @package badams\GoogleUrl\Resource |
|
18
|
|
|
*/ |
|
19
|
|
|
abstract class Resource implements \JsonSerializable |
|
20
|
|
|
{ |
|
21
|
|
|
/** |
|
22
|
|
|
* @param \stdClass $json |
|
23
|
|
|
* @return static |
|
24
|
|
|
*/ |
|
25
|
9 |
|
public static function createFromJson(\stdClass $json) |
|
26
|
|
|
{ |
|
27
|
9 |
|
$resource = new static; |
|
28
|
9 |
|
$class = new \ReflectionClass($resource); |
|
29
|
|
|
|
|
30
|
9 |
|
foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { |
|
31
|
9 |
|
$name = $property->getName(); |
|
32
|
9 |
|
if (property_exists($json, $name)) { |
|
33
|
9 |
|
$resource->setProperty($name, $json->$name); |
|
34
|
6 |
|
} |
|
35
|
6 |
|
} |
|
36
|
|
|
|
|
37
|
9 |
|
return $resource; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** |
|
41
|
|
|
* Serialize this resource into an array for json |
|
42
|
|
|
* |
|
43
|
|
|
* @return array |
|
44
|
|
|
*/ |
|
45
|
12 |
|
public function jsonSerialize() |
|
46
|
|
|
{ |
|
47
|
12 |
|
$class = new \ReflectionClass($this); |
|
48
|
12 |
|
$json = []; |
|
49
|
|
|
|
|
50
|
12 |
|
foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { |
|
51
|
12 |
|
if (null !== ($value = $property->getValue($this))) { |
|
52
|
12 |
|
$json[$property->getName()] = $value; |
|
53
|
8 |
|
} |
|
54
|
8 |
|
} |
|
55
|
|
|
|
|
56
|
12 |
|
return $json; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* @param $name |
|
61
|
|
|
* @param $value |
|
62
|
|
|
*/ |
|
63
|
9 |
|
public function setProperty($name, $value) |
|
64
|
|
|
{ |
|
65
|
9 |
|
$setter = 'set'.$name; |
|
66
|
|
|
|
|
67
|
9 |
|
if (method_exists($this, $setter)) { |
|
68
|
3 |
|
call_user_func([$this, $setter], $value); |
|
69
|
3 |
|
return; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
9 |
|
$this->$name = $value; |
|
73
|
9 |
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|