1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the fnayou/instapush-php project. |
4
|
|
|
* |
5
|
|
|
* Copyright (c) 2017. Aymen FNAYOU <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Fnayou\InstapushPHP\Transformer; |
12
|
|
|
|
13
|
|
|
use Fnayou\InstapushPHP\Exception\TransformerException; |
14
|
|
|
use Fnayou\InstapushPHP\Model\FromArrayInterface; |
15
|
|
|
use Psr\Http\Message\ResponseInterface; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Class ModelTransformer. |
19
|
|
|
*/ |
20
|
|
|
class ModelTransformer implements TransformerInterface |
21
|
|
|
{ |
22
|
|
|
/** |
23
|
|
|
* {@inheritdoc} |
24
|
|
|
*/ |
25
|
|
|
public function transform(ResponseInterface $response, string $class) |
26
|
|
|
{ |
27
|
|
View Code Duplication |
if (0 !== \strpos($response->getHeaderLine('Content-Type'), 'application/json')) { |
|
|
|
|
28
|
|
|
throw new TransformerException( |
29
|
|
|
\sprintf( |
30
|
|
|
'The ModelTransformer can transform json response but %s given', |
31
|
|
|
$response->getHeaderLine('Content-Type') |
32
|
|
|
) |
33
|
|
|
); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
$body = $response->getBody()->__toString(); |
37
|
|
|
$data = \json_decode($body, true); |
38
|
|
|
|
39
|
|
|
if (JSON_ERROR_NONE !== \json_last_error()) { |
40
|
|
|
throw new TransformerException( |
41
|
|
|
\sprintf( |
42
|
|
|
'Invalid json response format : Error %d when trying to \json_decode response', |
43
|
|
|
\json_last_error() |
44
|
|
|
) |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$reflection = new \ReflectionClass($class); |
49
|
|
|
if (true === $reflection->implementsInterface(FromArrayInterface::class)) { |
50
|
|
|
$object = \call_user_func($class.'::fromArray', $data); |
51
|
|
|
} else { |
52
|
|
|
$object = new $class($data); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
return $object; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.