|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of RussianPost SDK package. |
|
5
|
|
|
* |
|
6
|
|
|
* © Appwilio (http://appwilio.com), greabock (https://github.com/greabock), JhaoDa (https://github.com/jhaoda) |
|
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
|
|
|
declare(strict_types = 1); |
|
13
|
|
|
|
|
14
|
|
|
namespace Appwilio\RussianPostSDK\Dispatching; |
|
15
|
|
|
|
|
16
|
|
|
use Appwilio\RussianPostSDK\Dispatching\Http\ArrayOf; |
|
17
|
|
|
|
|
18
|
|
|
class Instantiator |
|
19
|
|
|
{ |
|
20
|
|
|
/** @var ArrayOf|string $class */ |
|
21
|
|
|
private $class; |
|
22
|
|
|
|
|
23
|
|
|
/** @var bool */ |
|
24
|
|
|
private $array = false; |
|
25
|
|
|
|
|
26
|
|
|
/** @var \ReflectionClass */ |
|
27
|
|
|
private $reflector; |
|
28
|
|
|
|
|
29
|
|
|
public function __construct($class) |
|
30
|
|
|
{ |
|
31
|
|
|
if ($class instanceof ArrayOf) { |
|
32
|
|
|
$this->array = true; |
|
33
|
|
|
$this->class = $class->getClass(); |
|
34
|
|
|
} else { |
|
35
|
|
|
$this->class = $class; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
$this->reflector = new \ReflectionClass($class); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* @param ArrayOf|string $class |
|
43
|
|
|
* @param mixed $data |
|
44
|
|
|
* |
|
45
|
|
|
* @throws \ReflectionException |
|
46
|
|
|
* |
|
47
|
|
|
* @return mixed |
|
48
|
|
|
*/ |
|
49
|
|
|
public static function instantiate($class, $data) |
|
50
|
|
|
{ |
|
51
|
|
|
if (null === $data) { |
|
52
|
|
|
return null; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return (new self($class))->fill($data); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function fill($data) |
|
59
|
|
|
{ |
|
60
|
|
|
if (null === $data) { |
|
61
|
|
|
return null; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
if ($this->array) { |
|
65
|
|
|
$objects = []; |
|
66
|
|
|
|
|
67
|
|
|
foreach ($data as $item) { |
|
68
|
|
|
$objects[] = $this->build($this->class, $item); |
|
|
|
|
|
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return $objects; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
return $this->build($this->class, $data); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
private function build(string $class, array $data) |
|
78
|
|
|
{ |
|
79
|
|
|
$object = new $class; |
|
80
|
|
|
|
|
81
|
|
|
$property = $this->reflector->getProperty('data'); |
|
82
|
|
|
|
|
83
|
|
|
$property->setAccessible(true); |
|
84
|
|
|
|
|
85
|
|
|
$property->setValue($object, $data); |
|
86
|
|
|
|
|
87
|
|
|
return $object; |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|