Completed
Push — v3 ( 862d0b...57b69a )
by Beñat
05:33
created

ResponseToModelDataTransformer::build()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
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\Application\DataTransformer;
13
14
use Psr\Http\Message\ResponseInterface as Response;
15
16
/**
17
 * Response to model data transformer.
18
 *
19
 * @author Beñat Espiña <[email protected]>
20
 */
21
abstract class ResponseToModelDataTransformer implements ResponseDataTransformer
22
{
23
    /**
24
     * The response.
25
     *
26
     * @var Response
27
     */
28
    private $response;
29
30
    /**
31
     * The fully qualified class name.
32
     *
33
     * @var string
34
     */
35
    private $fqcn;
36
37
    /**
38
     * The model class.
39
     *
40
     * @var string
41
     */
42
    protected $class;
43
44
    /**
45
     * Constructor.
46
     *
47
     * @param string $fqcn The fully qualified class name
48
     *
49
     * @throws \LogicException when the given fqcn is invalid
50
     */
51
    public function __construct($fqcn)
52
    {
53
        $answerReflectionClass = new \ReflectionClass($fqcn);
54
        if (!$answerReflectionClass->implementsInterface($this->class)) {
55
            throw new \LogicException(
56
                sprintf('Given %s class must implement the %s', $fqcn, $this->class)
57
            );
58
        }
59
        $this->fqcn = $fqcn;
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65
    public function write(Response $response)
66
    {
67
        $this->response = $response;
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function read()
74
    {
75
        $data = json_decode($this->response->getBody()->getContents(), true);
76
        if (false === array_key_exists('items', $data)) {
77
            throw new \Exception('Given data is incorrect');
78
        }
79
        if (count($data['items']) > 1) {
80
            $objects = [];
81
            foreach ($data['items'] as $item) {
82
                $objects[] = $this->build($item);
83
            }
84
85
            return $objects;
86
        }
87
88
        return $this->build($data['items'][0]);
89
    }
90
91
    /**
92
     * Builds the object with the response data given.
93
     *
94
     * @param mixed $data The data
95
     *
96
     * @return mixed
97
     */
98
    private function build($data)
99
    {
100
        return forward_static_call_array([$this->fqcn, 'fromJson'], [$data]);
101
    }
102
}
103