Completed
Push — v2 ( 68097e...ed5395 )
by Beñat
03:15
created

ToModelSerializer::setClassName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Stack Exchange Api Client library.
5
 *
6
 * (c) 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
declare(strict_types=1);
13
14
namespace BenatEspina\StackExchangeApiClient\Serializer;
15
16
use BenatEspina\StackExchangeApiClient\Model\Model;
17
18
/**
19
 * @author Beñat Espiña <[email protected]>
20
 */
21
final class ToModelSerializer implements Serializer
22
{
23
    private $className;
24
25
    public function __construct(string $className)
26
    {
27
        $this->setClassName($className);
28
    }
29
30
    public function serialize(array $data)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
31
    {
32
        if (false === array_key_exists('items', $data)) {
33
            throw new \Exception('Given data is incorrect');
34
        }
35
        if (count($data['items']) > 1) {
36
            $objects = [];
37
            foreach ($data['items'] as $item) {
38
                $objects[] = $this->className::fromJson($item);
0 ignored issues
show
Bug introduced by
The method fromJson cannot be called on $this->className (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
39
            }
40
41
            return $objects;
42
        }
43
44
        return $this->className::fromJson($data['items'][0]);
0 ignored issues
show
Bug introduced by
The method fromJson cannot be called on $this->className (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
45
    }
46
47
    private function setClassName(string $className) : void
48
    {
49
        $this->checkClassNameIsModel($className);
50
        $this->className = $className;
51
    }
52
53
    private function checkClassNameIsModel(string $className) : void
54
    {
55
        $reflectionClass = new \ReflectionClass($className);
56
        if (false === $reflectionClass->implementsInterface(Model::class)) {
57
            throw new ClassIsNotAModel();
58
        }
59
    }
60
}
61