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 ( c22db0...fa2159 )
by Sergey
03:18
created

AnnotationLoader::loadClassMetadata()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 12
ccs 7
cts 7
cp 1
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
crap 3
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\Document as ApiDocument;
17
use Reva2\JsonApi\Annotations\Resource as ApiResource;
18
use Reva2\JsonApi\Annotations\Object as ApiObject;
19
use Reva2\JsonApi\Annotations\Content as ApiContent;
20
use Reva2\JsonApi\Annotations\Property;
21
use Reva2\JsonApi\Annotations\Relationship;
22
use Reva2\JsonApi\Contracts\Decoders\Mapping\Loader\LoaderInterface;
23
use Reva2\JsonApi\Decoders\Mapping\ClassMetadata;
24
use Reva2\JsonApi\Decoders\Mapping\DocumentMetadata;
25
use Reva2\JsonApi\Decoders\Mapping\ObjectMetadata;
26
use Reva2\JsonApi\Decoders\Mapping\PropertyMetadata;
27
use Reva2\JsonApi\Decoders\Mapping\ResourceMetadata;
28
29
/**
30
 * Loads JSON API metadata using a Doctrine annotations
31
 *
32
 * @package Reva2\JsonApi\Decoders\Mapping\Loader
33
 * @author Sergey Revenko <[email protected]>
34
 */
35
class AnnotationLoader implements LoaderInterface
36
{
37
    /**
38
     * @var Reader
39
     */
40
    protected $reader;
41
42
    /**
43
     * Constructor
44
     *
45
     * @param Reader $reader
46
     */
47 6
    public function __construct(Reader $reader)
48
    {
49 6
        $this->reader = $reader;
50 6
    }
51
52
    /**
53
     * @inheritdoc
54
     */
55 6
    public function loadClassMetadata(\ReflectionClass $class)
56
    {
57 6
        if (null !== ($resource = $this->reader->getClassAnnotation($class, ApiResource::class))) {
58 3
            return $this->loadResourceMetadata($resource, $class);
59 3
        } elseif (null !== ($document = $this->reader->getClassAnnotation($class, ApiDocument::class))) {
60 1
            return $this->loadDocumentMetadata($document, $class);
61
        } else {
62 2
            $object = $this->reader->getClassAnnotation($class, ApiObject::class);
63
64 2
            return $this->loadObjectMetadata($class, $object);
1 ignored issue
show
Bug introduced by
It seems like $object defined by $this->reader->getClassA...otations\Object::class) on line 62 can also be of type object; however, Reva2\JsonApi\Decoders\M...r::loadObjectMetadata() does only seem to accept null|object<Reva2\JsonApi\Annotations\Object>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
65
        }
66
    }
67
68
    /**
69
     * Parse JSON API resource metadata
70
     *
71
     * @param ApiResource $resource
72
     * @param \ReflectionClass $class
73
     * @return ResourceMetadata
74
     */
75 3
    private function loadResourceMetadata(ApiResource $resource, \ReflectionClass $class)
76
    {
77 3
        $metadata = new ResourceMetadata( $class->getName());
0 ignored issues
show
Bug introduced by
Consider using $class->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
78 3
        $metadata->setName($resource->name);
79
80 3
        $this->loadDiscriminatorMetadata($resource, $metadata);
81
82 3
        $properties = $class->getProperties();
83 3
        foreach ($properties as $property) {
84 3
            if ($property->getDeclaringClass()->name !== $class->name) {
85 1
                continue;
86
            }
87
88 3
            foreach ($this->reader->getPropertyAnnotations($property) as $annotation) {
89 3
                if ($annotation instanceof Attribute) {
90 3
                    $metadata->addAttribute($this->loadPropertyMetadata($annotation, $property));
91 3
                } elseif ($annotation instanceof Relationship) {
92 3
                    $metadata->addRelationship($this->loadPropertyMetadata($annotation, $property));
93 3
                }
94 3
            }
95 3
        }
96
97 3
        return $metadata;
98
    }
99
100
    /**
101
     * @param \ReflectionClass $class
102
     * @param ApiObject|null $object
103
     * @return ObjectMetadata
104
     */
105 2
    private function loadObjectMetadata(\ReflectionClass $class, ApiObject $object = null)
106
    {
107 2
        $metadata = new ObjectMetadata($class->name);
108
109 2
        if (null !== $object) {
110 1
            $this->loadDiscriminatorMetadata($object, $metadata);
111 1
        }
112
113 2
        $properties = $class->getProperties();
114 2 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 2
            if ($property->getDeclaringClass()->name !== $class->name) {
116 1
                continue;
117
            }
118
119 2
            $annotation = $this->reader->getPropertyAnnotation($property, Property::class);
120 2
            if (null !== $annotation) {
121 2
                $metadata->addProperty($this->loadPropertyMetadata($annotation, $property));
122 2
            }
123 2
        }
124
125 2
        return $metadata;
126
    }
127
128
    /**
129
     * Parse JSON API document metadata
130
     *
131
     * @param ApiDocument $document
132
     * @param \ReflectionClass $class
133
     * @return DocumentMetadata
134
     */
135 1
    private function loadDocumentMetadata(ApiDocument $document, \ReflectionClass $class)
136
    {
137 1
        $metadata = new DocumentMetadata($class->getName());
0 ignored issues
show
Bug introduced by
Consider using $class->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
138 1
        $metadata->setAllowEmpty($document->allowEmpty);
139
140 1
        $properties = $class->getProperties();
141 1 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...
142 1
            if ($property->getDeclaringClass()->name !== $class->name) {
143
                continue;
144
            }
145
146 1
            $annotation = $this->reader->getPropertyAnnotation($property, ApiContent::class);
147 1
            if (null !== $annotation) {
148 1
                $metadata->setContentMetadata($this->loadPropertyMetadata($annotation, $property));
149
150 1
                break;
151
            }
152 1
        }
153
154 1
        return $metadata;
155
    }
156
157
    /**
158
     * Parse property metadata
159
     *
160
     * @param Property $annotation
161
     * @param \ReflectionProperty $property
162
     * @return PropertyMetadata
163
     */
164 6
    private function loadPropertyMetadata(Property $annotation, \ReflectionProperty $property)
165
    {
166 6
        $metadata = new PropertyMetadata($property->name, $property->class);
167
168 6
        list($dataType, $dataTypeParams) = $this->parseDataType($annotation, $property);
169
170
        $metadata
171 6
            ->setDataType($dataType)
172 6
            ->setDataTypeParams($dataTypeParams)
173 6
            ->setOrmEntityClass($annotation->ormEntity);
174
175 6
        if ($annotation->setter) {
176
            $metadata->setSetter($annotation->setter);
177 6
        } elseif (false === $property->isPublic()) {
178 1
            $setter = 'set' . ucfirst($property->name);
179 1
            if (false == $property->getDeclaringClass()->hasMethod($setter)) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
180
                throw new \RuntimeException(sprintf(
181
                    "Couldn't find setter for non public property: %s:%s",
182
                    $property->class,
183
                    $property->name
184
                ));
185
            }
186
187 1
            $metadata->setSetter($setter);
188 1
        }
189
190 6
        return $metadata;
191
    }
192
193
    /**
194
     * Parse property data type
195
     *
196
     * @param Property $annotation
197
     * @param \ReflectionProperty $property
198
     * @return array
199
     */
200 6
    private function parseDataType(Property $annotation, \ReflectionProperty $property)
201
    {
202 6
        if (!empty($annotation->parser)) {
203 1
            if (!$property->getDeclaringClass()->hasMethod($annotation->parser)) {
204
                throw new \InvalidArgumentException(sprintf(
205
                    "Custom parser function %s:%s() for property '%s' does not exist",
206
                    $property->class,
207
                    $annotation->parser,
208
                    $property->name
209
                ));
210
            }
211 1
            return ['custom', $annotation->parser];
212 6
        } elseif (!empty($annotation->type)) {
213 5
            return $this->parseDataTypeString($annotation->type);
214 5
        } elseif (preg_match('~@var\s(.*?)\s~si', $property->getDocComment(), $matches)) {
215 5
            return $this->parseDataTypeString($matches[1]);
216
        } else {
217 1
            return ['raw', null];
218
        }
219
    }
220
221
    /**
222
     * Parse data type string
223
     *
224
     * @param string $type
225
     * @return array
226
     */
227 6
    private function parseDataTypeString($type)
228
    {
229 6
        $params = null;
230
231 6
        if ($this->isScalarDataType($type)) {
232 5
            $dataType = 'scalar';
233 5
            $params = $type;
234 6
        } elseif (preg_match('~^DateTime(<(.*?)>)?$~', $type, $matches)) {
235 1
            $dataType = 'datetime';
236 1
            if (3 === count($matches)) {
237 1
                $params = $matches[2];
238 1
            }
239 1
        } elseif (
240 5
            (preg_match('~Array(<(.*?)>)?$~si', $type, $matches)) ||
241 5
            (preg_match('~^(.*?)\[\]$~si', $type, $matches))
242 5
        ) {
243 2
            $dataType = 'array';
244 2
            if (3 === count($matches)) {
245 2
                $params = $this->parseDataTypeString($matches[2]);
246 2
            } elseif (2 === count($matches)) {
247 1
                $params = $this->parseDataTypeString($matches[1]);
248 1
            } else {
249 1
                $params = ['raw', null];
250
            }
251 2
        } else {
252 5
            $type = ltrim($type, '\\');
253
254 5
            if (!class_exists($type)) {
255
                throw new \InvalidArgumentException(sprintf(
256
                    "Unknown object type '%s' specified",
257
                    $type
258
                ));
259
            }
260
261 5
            $dataType = 'object';
262 5
            $params = $type;
263
        }
264
265 6
        return [$dataType, $params];
266
    }
267
268
    /**
269
     * Returns true if specified type scalar. False otherwise.
270
     *
271
     * @param string $type
272
     * @return bool
273
     */
274 6
    private function isScalarDataType($type)
275
    {
276 6
        return in_array($type, ['string', 'bool', 'boolean', 'int', 'integer', 'float', 'double']);
277
    }
278
279
    /**
280
     * Load discriminator metadata
281
     *
282
     * @param ApiObject $object
283
     * @param ClassMetadata $metadata
284
     */
285 4
    private function loadDiscriminatorMetadata(ApiObject $object, ClassMetadata $metadata)
286
    {
287 4
        if (!$object->discField) {
288 1
            return;
289
        }
290
291 4
        $metadata->setDiscriminatorField($object->discField);
292 4
        $metadata->setDiscriminatorMap($object->discMap);
293
    }
294
}