GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 0d846c...fab3df )
by Sergey
03:21
created

AnnotationLoader::loadPropertyMetadata()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 4.002

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 29
ccs 19
cts 20
cp 0.95
rs 8.5806
cc 4
eloc 19
nc 4
nop 2
crap 4.002
1
<?php
2
/*
3
 * This file is part of the reva2/jsonapi.
4
 *
5
 * (c) Sergey Revenko <[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
12
namespace Reva2\JsonApi\Decoders\Mapping\Loader;
13
14
use Doctrine\Common\Annotations\Reader;
15
use Reva2\JsonApi\Annotations\Attribute;
16
use Reva2\JsonApi\Annotations\ApiDocument;
17
use Reva2\JsonApi\Annotations\Id;
18
use Reva2\JsonApi\Annotations\ApiResource;
19
use Reva2\JsonApi\Annotations\ApiObject;
20
use Reva2\JsonApi\Annotations\Content as ApiContent;
21
use Reva2\JsonApi\Annotations\Property;
22
use Reva2\JsonApi\Annotations\Relationship;
23
use Reva2\JsonApi\Contracts\Decoders\Mapping\Loader\LoaderInterface;
24
use Reva2\JsonApi\Contracts\Decoders\Mapping\ObjectMetadataInterface;
25
use Reva2\JsonApi\Decoders\Mapping\ClassMetadata;
26
use Reva2\JsonApi\Decoders\Mapping\DocumentMetadata;
27
use Reva2\JsonApi\Decoders\Mapping\ObjectMetadata;
28
use Reva2\JsonApi\Decoders\Mapping\PropertyMetadata;
29
use Reva2\JsonApi\Decoders\Mapping\ResourceMetadata;
30
31
/**
32
 * Loads JSON API metadata using a Doctrine annotations
33
 *
34
 * @package Reva2\JsonApi\Decoders\Mapping\Loader
35
 * @author Sergey Revenko <[email protected]>
36
 */
37
class AnnotationLoader implements LoaderInterface
38
{
39
    /**
40
     * @var Reader
41
     */
42
    protected $reader;
43
44
    /**
45
     * Constructor
46
     *
47
     * @param Reader $reader
48
     */
49 18
    public function __construct(Reader $reader)
50
    {
51 18
        $this->reader = $reader;
52 18
    }
53
54
    /**
55
     * @inheritdoc
56
     */
57 12
    public function loadClassMetadata(\ReflectionClass $class)
58
    {
59 12
        if (null !== ($resource = $this->reader->getClassAnnotation($class, ApiResource::class))) {
60 6
            return $this->loadResourceMetadata($resource, $class);
61 8
        } elseif (null !== ($document = $this->reader->getClassAnnotation($class, ApiDocument::class))) {
62 3
            return $this->loadDocumentMetadata($document, $class);
63
        } else {
64 5
            $object = $this->reader->getClassAnnotation($class, ApiObject::class);
65
66 5
            return $this->loadObjectMetadata($class, $object);
67
        }
68
    }
69
70
    /**
71
     * Parse JSON API resource metadata
72
     *
73
     * @param ApiResource $resource
74
     * @param \ReflectionClass $class
75
     * @return ResourceMetadata
76
     */
77 6
    private function loadResourceMetadata(ApiResource $resource, \ReflectionClass $class)
78
    {
79 6
        $metadata = new ResourceMetadata($class->name);
80 6
        $metadata->setName($resource->name);
81
82 6
        $properties = $class->getProperties();
83 6
        foreach ($properties as $property) {
84 6
            if ($property->getDeclaringClass()->name !== $class->name) {
85 4
                continue;
86
            }
87
88 6
            foreach ($this->reader->getPropertyAnnotations($property) as $annotation) {
89 6
                if ($annotation instanceof Attribute) {
90 6
                    $metadata->addAttribute($this->loadPropertyMetadata($annotation, $property));
91 6
                } elseif ($annotation instanceof Relationship) {
92 6
                    $metadata->addRelationship($this->loadPropertyMetadata($annotation, $property));
93 6
                } elseif ($annotation instanceof Id) {
94 6
                    $metadata->setIdMetadata($this->loadPropertyMetadata($annotation, $property));
95 6
                }
96 6
            }
97 6
        }
98
99 6
        $this->loadDiscriminatorMetadata($resource, $metadata);
100
101 6
        return $metadata;
102
    }
103
104
    /**
105
     * @param \ReflectionClass $class
106
     * @param ApiObject|null $object
107
     * @return ObjectMetadata
108
     */
109 5
    private function loadObjectMetadata(\ReflectionClass $class, ApiObject $object = null)
110
    {
111 5
        $metadata = new ObjectMetadata($class->name);
112
113 5
        $properties = $class->getProperties();
114 5 View Code Duplication
        foreach ($properties as $property) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
115 5
            if ($property->getDeclaringClass()->name !== $class->name) {
116 2
                continue;
117
            }
118
119 5
            $annotation = $this->reader->getPropertyAnnotation($property, Property::class);
120 5
            if (null !== $annotation) {
121 5
                $metadata->addProperty($this->loadPropertyMetadata($annotation, $property));
122 3
            }
123 3
        }
124
125 3
        if (null !== $object) {
126 2
            $this->loadDiscriminatorMetadata($object, $metadata);
127 2
        }
128
129 3
        return $metadata;
130
    }
131
132
    /**
133
     * Parse JSON API document metadata
134
     *
135
     * @param ApiDocument $document
136
     * @param \ReflectionClass $class
137
     * @return DocumentMetadata
138
     */
139 3
    private function loadDocumentMetadata(ApiDocument $document, \ReflectionClass $class)
140
    {
141 3
        $metadata = new DocumentMetadata($class->name);
142 3
        $metadata->setAllowEmpty($document->allowEmpty);
143
144 3
        $properties = $class->getProperties();
145 3 View Code Duplication
        foreach ($properties as $property) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across 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...
146 3
            if ($property->getDeclaringClass()->name !== $class->name) {
147
                continue;
148
            }
149
150 3
            $annotation = $this->reader->getPropertyAnnotation($property, ApiContent::class);
151 3
            if (null !== $annotation) {
152 3
                $metadata->setContentMetadata($this->loadPropertyMetadata($annotation, $property));
153
154 3
                break;
155
            }
156 3
        }
157
158 3
        return $metadata;
159
    }
160
161
    /**
162
     * Parse property metadata
163
     *
164
     * @param Property $annotation
165
     * @param \ReflectionProperty $property
166
     * @return PropertyMetadata
167
     */
168 12
    private function loadPropertyMetadata(Property $annotation, \ReflectionProperty $property)
169
    {
170 12
        $metadata = new PropertyMetadata($property->name, $property->class);
171
172 12
        list($dataType, $dataTypeParams) = $this->parseDataType($annotation, $property);
173
174
        $metadata
175 11
            ->setDataType($dataType)
176 11
            ->setDataTypeParams($dataTypeParams)
177 11
            ->setDataPath($this->getDataPath($annotation, $property))
178 11
            ->setOrmEntityClass($annotation->ormEntity);
179
180 11
        if ($annotation->setter) {
181
            $metadata->setSetter($annotation->setter);
182 11
        } elseif (false === $property->isPublic()) {
183 6
            $setter = 'set' . ucfirst($property->name);
184 6
            if (false === $property->getDeclaringClass()->hasMethod($setter)) {
185 1
                throw new \RuntimeException(sprintf(
186 1
                    "Couldn't find setter for non public property: %s:%s",
187 1
                    $property->class,
188 1
                    $property->name
189 1
                ));
190
            }
191
192 5
            $metadata->setSetter($setter);
193 5
        }
194
195 10
        return $metadata;
196
    }
197
198
    /**
199
     * Parse property data type
200
     *
201
     * @param Property $annotation
202
     * @param \ReflectionProperty $property
203
     * @return array
204
     */
205 12
    private function parseDataType(Property $annotation, \ReflectionProperty $property)
206
    {
207 12
        if (!empty($annotation->parser)) {
208 3
            if (!$property->getDeclaringClass()->hasMethod($annotation->parser)) {
209 1
                throw new \InvalidArgumentException(sprintf(
210 1
                    "Custom parser function %s:%s() for property '%s' does not exist",
211 1
                    $property->class,
212 1
                    $annotation->parser,
213 1
                    $property->name
214 1
                ));
215
            }
216 2
            return ['custom', $annotation->parser];
217 11
        } elseif (!empty($annotation->type)) {
218 9
            return $this->parseDataTypeString($annotation->type);
219 10
        } elseif (preg_match('~@var\s(.*?)\s~si', $property->getDocComment(), $matches)) {
220 10
            return $this->parseDataTypeString($matches[1]);
221
        } else {
222 2
            return ['raw', null];
223
        }
224
    }
225
226
    /**
227
     * Parse data type string
228
     *
229
     * @param string $type
230
     * @return array
231
     */
232 11
    private function parseDataTypeString($type)
233
    {
234 11
        $params = null;
235
236 11
        if ($this->isScalarDataType($type)) {
237 10
            $dataType = 'scalar';
238 10
            $params = $type;
239 11
        } elseif (preg_match('~^DateTime(<(.*?)>)?$~', $type, $matches)) {
240 2
            $dataType = 'datetime';
241 2
            if (3 === count($matches)) {
242 2
                $params = $matches[2];
243 2
            }
244 2
        } elseif (
245 9
            (preg_match('~Array(<(.*?)>)?$~si', $type, $matches)) ||
246 9
            (preg_match('~^(.*?)\[\]$~si', $type, $matches))
247 9
        ) {
248 5
            $dataType = 'array';
249 5
            if (3 === count($matches)) {
250 5
                $params = $this->parseDataTypeString($matches[2]);
251 5
            } elseif (2 === count($matches)) {
252 2
                $params = $this->parseDataTypeString($matches[1]);
253 2
            } else {
254 2
                $params = ['raw', null];
255
            }
256 5
        } else {
257 9
            $type = ltrim($type, '\\');
258
259 9
            if (!class_exists($type)) {
260
                throw new \InvalidArgumentException(sprintf(
261
                    "Unknown object type '%s' specified",
262
                    $type
263
                ));
264
            }
265
266 9
            $dataType = 'object';
267 9
            $params = $type;
268
        }
269
270 11
        return [$dataType, $params];
271
    }
272
273
    /**
274
     * Returns true if specified type scalar. False otherwise.
275
     *
276
     * @param string $type
277
     * @return bool
278
     */
279 11
    private function isScalarDataType($type)
280
    {
281 11
        return in_array($type, ['string', 'bool', 'boolean', 'int', 'integer', 'float', 'double']);
282
    }
283
284
    /**
285
     * Load discriminator metadata
286
     *
287
     * @param ApiObject $object
288
     * @param ClassMetadata $metadata
289
     */
290 8
    private function loadDiscriminatorMetadata(ApiObject $object, ClassMetadata $metadata)
291
    {
292 8
        if (!$object->discField) {
293 4
            return;
294
        }
295
296 8
        $fieldMeta = null;
297 8
        $field = $object->discField;
298 8
        if ($metadata instanceof ObjectMetadataInterface) {
299 2
            $properties = $metadata->getProperties();
300 2
            if (array_key_exists($field, $properties)) {
301 2
                $fieldMeta = $properties[$field];
302 2
            }
303 8
        } elseif ($metadata instanceof ResourceMetadata) {
304 6
            $attributes = $metadata->getAttributes();
305 6
            if (array_key_exists($field, $attributes)) {
306 6
                $fieldMeta = $attributes[$field];
307 6
            }
308 6
        }
309
310 8
        if (null === $fieldMeta) {
311
            throw new \InvalidArgumentException("Specified discriminator field not found in object properties");
312 8
        } elseif (('scalar' !== $fieldMeta->getDataType()) || ('string' !== $fieldMeta->getDataTypeParams())) {
313
            throw new \InvalidArgumentException("Discriminator field must point to property that contain string value");
314
        }
315
316 8
        $metadata->setDiscriminatorField($fieldMeta);
317 8
        $metadata->setDiscriminatorMap($object->discMap);
318 8
    }
319
320
    /**
321
     * Returns data path
322
     *
323
     * @param Property $annotation
324
     * @param \ReflectionProperty $property
325
     * @return string
326
     */
327 11
    private function getDataPath(Property $annotation, \ReflectionProperty $property)
328
    {
329 11
        $prefix = '';
330 11
        if ($annotation instanceof Attribute) {
331 6
            $prefix = 'attributes.';
332 11
        } elseif ($annotation instanceof Relationship) {
333 6
            $prefix = 'relationships.';
334 6
        }
335
336 11
        if (!empty($prefix)) {
337 6
            return (null !== $annotation->path) ? $prefix . $annotation->path : $prefix . $property->name;
338
        }
339
340 11
        return $annotation->path;
341
    }
342
}
343