iDokladAbstractModel::getModelMap()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Fousky\Component\iDoklad\Model;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Doctrine\Common\Collections\Collection;
7
use Fousky\Component\iDoklad\LOV\iDokladAbstractEnum;
8
use Fousky\Component\iDoklad\LOV\iDokladEnumInterface;
9
use Fousky\Component\iDoklad\Model\Void\BooleanModel;
10
use Fousky\Component\iDoklad\Util\AnnotationLoader;
11
use Fousky\Component\iDoklad\Util\ResponseUtil;
12
use Psr\Http\Message\ResponseInterface;
13
use Symfony\Component\Validator\ConstraintViolationListInterface;
14
use Symfony\Component\Validator\Validation;
15
16
/**
17
 * @author Lukáš Brzák <[email protected]>
18
 */
19
abstract class iDokladAbstractModel implements iDokladModelInterface
20
{
21
    // remove nulls in toArray() calling.
22
    const TOARRAY_REMOVE_NULLS = 'rnulls';
23
24
    /**
25
     * @param ResponseInterface $response
26
     *
27
     * @throws \RuntimeException
28
     *
29
     * @return iDokladModelInterface
30
     */
31
    public static function createFromResponse(ResponseInterface $response): iDokladModelInterface
32
    {
33
        $data = ResponseUtil::handle($response);
34
35
        if (is_bool($data)) {
36
            return BooleanModel::createFromResponse($response);
37
        }
38
39
        return static::createFromStd($data);
40
    }
41
42
    /**
43
     * Need convert some property to iDokladAbstractModel instance?
44
     *
45
     * @return array
46
     */
47
    public static function getModelMap(): array
48
    {
49
        return [];
50
    }
51
52
    /**
53
     * Need convert some property to Enum object?
54
     *
55
     * @return array
56
     */
57
    public static function getEnumMap(): array
58
    {
59
        return [];
60
    }
61
62
    /**
63
     * Need convert some DateTime public properties of this model?
64
     *
65
     * @return array
66
     */
67
    public static function getDateMap(): array
68
    {
69
        return [];
70
    }
71
72
    /**
73
     * @param \stdClass $data
74
     *
75
     * @return iDokladModelInterface
76
     */
77
    public static function createFromStd(\stdClass $data): iDokladModelInterface
78
    {
79
        $model = new static();
80
81
        $modelMap = static::getModelMap();
82
        $enumMap = static::getEnumMap();
83
        $dateMap = static::getDateMap();
84
85
        foreach ((array) $data as $key => $value) {
86
            if (property_exists($model, $key)) {
87
                $model->{$key} = $value;
88
89
                if (array_key_exists($key, $modelMap)) {
90
                    /** @var iDokladAbstractModel $modelClass */
91
                    $modelClass = $modelMap[$key];
92
93
                    if ($value instanceof \stdClass) {
94
                        $model->{$key} = $modelClass::createFromStd($value);
95
                    }
96
97
                    if (\is_array($value)) {
98
                        $collection = new ArrayCollection();
99
                        foreach ($value as $valueItem) {
100
                            $collection->add($modelClass::createFromStd($valueItem));
101
                        }
102
                        $model->{$key} = $collection;
103
                    }
104
                } elseif (array_key_exists($key, $enumMap)) {
105
                    /** @var iDokladAbstractEnum $enumClass */
106
                    $enumClass = $enumMap[$key];
107
                    $model->{$key} = new $enumClass((int) $value);
108
                } elseif (\in_array($key, $dateMap, true) &&
109
                          $val = new \DateTime($model->{$key}, new \DateTimeZone('UTC'))
110
                ) {
111
                    $model->{$key} = $val;
112
                }
113
            }
114
        }
115
116
        return $model;
117
    }
118
119
    /**
120
     * @param array $options
121
     *
122
     * @throws \InvalidArgumentException
123
     *
124
     * @return array
125
     */
126
    public function toArray(array $options = []): array
127
    {
128
        $result = [];
129
        $reflection = new \ReflectionClass($this);
130
131
        foreach ($reflection->getProperties() as $property) {
132
            $name = $property->getName();
133
            $getter = 'get'.ucfirst($property->getName());
134
            $value = $this->{$getter}();
135
136
            $result[$name] = $this->recursiveToArray($value, $options);
137
        }
138
139
        return $this->toArrayProcessOptions($options, $result);
140
    }
141
142
    /**
143
     * @param mixed $value
144
     * @param array $options
145
     *
146
     * @return array|string
147
     */
148
    public function recursiveToArray($value, array $options)
149
    {
150
        // convert \DateTime to string date representation.
151
        if ($value instanceof \DateTime) {
152
            // DateTime string without TimeZone definition - time zone recalculation causes unexpected problems.
153
            return $value->format('Y-m-d\TH:i:s');
154
        }
155
156
        if (\is_array($value) || $value instanceof Collection) {
157
            $subArray = [];
158
159
            foreach ($value as $k => $v) {
160
                $subArray[$k] = $this->recursiveToArray($v, $options);
161
            }
162
163
            return $subArray;
164
        }
165
166
        if ($value instanceof iDokladModelInterface || method_exists($value, 'toArray')) {
167
            return $value->toArray($options);
168
        }
169
170
        if ($value instanceof iDokladEnumInterface || method_exists($value, 'createJson')) {
171
            return $value->createJson();
172
        }
173
174
        if (\is_object($value) && method_exists($value, '__toString')) {
175
            return (string) $value;
176
        }
177
178
        return $value;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $value; (integer|double|string|null|boolean|object) is incompatible with the return type documented by Fousky\Component\iDoklad...Model::recursiveToArray of type array|string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
179
    }
180
181
    /**
182
     * @param array $options
183
     * @param array $data
184
     *
185
     * @return array
186
     */
187
    protected function toArrayProcessOptions(array $options, array $data): array
188
    {
189
        // remove null keys.
190
        if (array_key_exists(self::TOARRAY_REMOVE_NULLS, $options)) {
191
            foreach ($data as $key => $value) {
192
                if (null === $value) {
193
                    unset($data[$key]);
194
                }
195
                if (is_array($value)) {
196
                    $data[$key] = $this->toArrayProcessOptions($options, $value);
197
                }
198
            }
199
        }
200
201
        return $data;
202
    }
203
204
    /**
205
     * @return ConstraintViolationListInterface
206
     *
207
     * @throws \RuntimeException
208
     * @throws \InvalidArgumentException
209
     * @throws \ReflectionException
210
     */
211
    public function validate(): ConstraintViolationListInterface
212
    {
213
        AnnotationLoader::init();
214
215
        return Validation::createValidatorBuilder()
216
            ->enableAnnotationMapping()
217
            ->getValidator()
218
            ->validate($this);
219
    }
220
221
    /**
222
     * @param string $name
223
     * @param array  $arguments
224
     *
225
     * @throws \InvalidArgumentException
226
     *
227
     * @return mixed
228
     */
229
    public function __call($name, $arguments)
230
    {
231
        if (method_exists($this, $name)) {
232
            return call_user_func_array([$this, $name], $arguments);
233
        }
234
235
        if (0 === stripos($name, 'get')) {
236
            $property = ucfirst(substr($name, 3));
237
238
            if (property_exists($this, $property)) {
239
                return $this->{$property};
240
            }
241
        }
242
243
        throw new \InvalidArgumentException(sprintf(
244
            'Method %s of class %s does not exists.',
245
            $name,
246
            get_class($this)
247
        ));
248
    }
249
250
    /**
251
     * @param array $properties
252
     *
253
     * @throws \InvalidArgumentException
254
     */
255 View Code Duplication
    protected function processProperties(array $properties)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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.

Loading history...
256
    {
257
        foreach ($properties as $property => $value) {
258
            if (!property_exists($this, $property)) {
259
                throw new \InvalidArgumentException(sprintf(
260
                    'Property %s of class %s does not exists.',
261
                    $property,
262
                    get_class($this)
263
                ));
264
            }
265
266
            $this->{$property} = $value;
267
        }
268
    }
269
}
270