1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the BenGorUser library. |
5
|
|
|
* |
6
|
|
|
* (c) Beñat Espiña <[email protected]> |
7
|
|
|
* (c) Gorka Laucirica <[email protected]> |
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 BenatEspina\StackExchangeApiClient\Application\DataTransformer; |
14
|
|
|
|
15
|
|
|
use BenatEspina\StackExchangeApiClient\Domain\Model\Response; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Response data transformer. |
19
|
|
|
* |
20
|
|
|
* @author Beñat Espiña <[email protected]> |
21
|
|
|
*/ |
22
|
|
|
abstract class ResponseDataTransformer implements DataTransformer |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* The response. |
26
|
|
|
* |
27
|
|
|
* @var Response |
28
|
|
|
*/ |
29
|
|
|
private $response; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* The fully qualified class name. |
33
|
|
|
* |
34
|
|
|
* @var string |
35
|
|
|
*/ |
36
|
|
|
private $fqcn; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* The model class. |
40
|
|
|
* |
41
|
|
|
* @var string |
42
|
|
|
*/ |
43
|
|
|
protected $class; |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Constructor. |
47
|
|
|
* |
48
|
|
|
* @param string $fqcn The fully qualified class name |
49
|
|
|
* |
50
|
|
|
* @throws InvalidModelClassName when the given fqcn is invalid |
51
|
|
|
*/ |
52
|
|
|
public function __construct($fqcn) |
53
|
|
|
{ |
54
|
|
|
$answerReflectionClass = new \ReflectionClass($fqcn); |
55
|
|
|
if ($answerReflectionClass->implementsInterface($this->class)) { |
56
|
|
|
throw new InvalidModelClassName($fqcn); |
57
|
|
|
} |
58
|
|
|
$this->fqcn = $fqcn; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* {@inheritdoc} |
63
|
|
|
*/ |
64
|
|
|
public function write(Response $response) |
65
|
|
|
{ |
66
|
|
|
$this->response = $response; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* {@inheritdoc} |
71
|
|
|
*/ |
72
|
|
|
public function read() |
73
|
|
|
{ |
74
|
|
|
$data = json_decode($this->response->getBody()->getContents(), true); |
75
|
|
|
if (false === array_key_exists('items', $data)) { |
76
|
|
|
throw new \Exception('Given data is incorrect'); |
77
|
|
|
} |
78
|
|
|
if (count($data['items']) > 1) { |
79
|
|
|
$objects = []; |
80
|
|
|
foreach ($data['items'] as $item) { |
81
|
|
|
$objects[] = $this->build($item); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return $objects; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
return $this->build($data['items'][0]); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
/** |
91
|
|
|
* Builds the object with the response data given. |
92
|
|
|
* |
93
|
|
|
* @param mixed $data The data |
94
|
|
|
* |
95
|
|
|
* @return mixed |
96
|
|
|
*/ |
97
|
|
|
private function build($data) |
98
|
|
|
{ |
99
|
|
|
return call_user_func([$this->fqcn, 'fromJson', $data]); |
100
|
|
|
} |
101
|
|
|
} |
102
|
|
|
|