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 ( d96736...643d67 )
by Sergey
03:19
created

AnnotationLoader::loadObjectMetadata()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 27
Code Lines 15

Duplication

Lines 11
Ratio 40.74 %

Code Coverage

Tests 12
CRAP Score 6.288

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 11
loc 27
ccs 12
cts 15
cp 0.8
rs 8.439
cc 6
eloc 15
nc 12
nop 1
crap 6.288
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\Property;
18
use Reva2\JsonApi\Annotations\Relationship;
19
use Reva2\JsonApi\Annotations\Resource as ApiResource;
20
use Reva2\JsonApi\Contracts\Decoders\Mapping\Loader\LoaderInterface;
21
use Reva2\JsonApi\Contracts\Decoders\Mapping\ObjectMetadataInterface;
22
use Reva2\JsonApi\Contracts\Decoders\Mapping\ResourceMetadataInterface;
23
use Reva2\JsonApi\Decoders\Mapping\DocumentMetadata;
24
use Reva2\JsonApi\Decoders\Mapping\ObjectMetadata;
25
use Reva2\JsonApi\Decoders\Mapping\PropertyMetadata;
26
use Reva2\JsonApi\Decoders\Mapping\ResourceMetadata;
27
28
/**
29
 * Loads JSON API metadata using a Doctrine annotations
30
 *
31
 * @package Reva2\JsonApi\Decoders\Mapping\Loader
32
 * @author Sergey Revenko <[email protected]>
33
 */
34
class AnnotationLoader implements LoaderInterface
35
{
36
    /**
37
     * @var Reader
38
     */
39
    protected $reader;
40
41
    /**
42
     * Constructor
43
     *
44
     * @param Reader $reader
45
     */
46 1
    public function __construct(Reader $reader)
47
    {
48 1
        $this->reader = $reader;
49 1
    }
50
51
    /**
52
     * @inheritdoc
53
     */
54 1
    public function loadClassMetadata(\ReflectionClass $class)
55
    {
56 1
        if (null !== ($resource = $this->reader->getClassAnnotation($class, ApiResource::class))) {
57
            return $this->loadResourceMetadata($resource, $class);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->loadResour...ata($resource, $class); (Reva2\JsonApi\Decoders\Mapping\ResourceMetadata) is incompatible with the return type declared by the interface Reva2\JsonApi\Contracts\...face::loadClassMetadata of type boolean.

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...
58 1
        } elseif (null !== ($document = $this->reader->getClassAnnotation($class, ApiDocument::class))) {
59
            return $this->loadDocumentMetadata($document, $class);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->loadDocume...ata($document, $class); (Reva2\JsonApi\Decoders\Mapping\DocumentMetadata) is incompatible with the return type declared by the interface Reva2\JsonApi\Contracts\...face::loadClassMetadata of type boolean.

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...
60
        } else {
61 1
            return $this->loadObjectMetadata($class);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->loadObjectMetadata($class); (Reva2\JsonApi\Decoders\Mapping\ObjectMetadata) is incompatible with the return type declared by the interface Reva2\JsonApi\Contracts\...face::loadClassMetadata of type boolean.

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...
62
        }
63
    }
64
65
    /**
66
     * Parse JSON API resource metadata
67
     *
68
     * @param ApiResource $resource
69
     * @param \ReflectionClass $class
70
     * @return ResourceMetadata
71
     */
72
    private function loadResourceMetadata(ApiResource $resource, \ReflectionClass $class)
73
    {
74
        $metadata = new ResourceMetadata($resource->name, $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...
75
76
        $properties = $class->getProperties();
77
        foreach ($properties as $property) {
78
            foreach ($this->reader->getPropertyAnnotations($property) as $annotation) {
79
                if ($annotation instanceof Attribute) {
80
                    $metadata->addAttribute($this->loadPropertyMetadata($annotation, $property));
81
                } elseif ($annotation instanceof Relationship) {
82
                    $metadata->addRelationship($this->loadPropertyMetadata($annotation, $property));
83
                }
84
            }
85
        }
86
87 View Code Duplication
        if (false !== ($parent = $class->getParentClass())) {
0 ignored issues
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...
88
            $parentMetadata = $this->loadClassMetadata($parent);
89
            if (!$parentMetadata instanceof ResourceMetadataInterface) {
90
                throw new \RuntimeException(sprintf(
91
                    "Failed to merge metadata from parent class '%s'",
92
                    $parent->name
93
                ));
94
            }
95
        }
96
97
        return $metadata;
98
    }
99
100
    /**
101
     * Parse JSON API document metadata
102
     *
103
     * @param ApiDocument $document
104
     * @param \ReflectionClass $class
105
     * @return DocumentMetadata
106
     */
107
    private function loadDocumentMetadata(ApiDocument $document, \ReflectionClass $class)
0 ignored issues
show
Unused Code introduced by
The parameter $document is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
108
    {
109
        $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...
110
111
112
113
        return $metadata;
114
    }
115
116
    /**
117
     * @param \ReflectionClass $class
118
     * @return ObjectMetadata
119
     */
120 1
    private function loadObjectMetadata(\ReflectionClass $class)
121
    {
122 1
        $metadata = new ObjectMetadata($class->name);
123
124 1
        $properties = $class->getProperties();
125 1
        foreach ($properties as $property) {
126 1
            foreach ($this->reader->getPropertyAnnotations($property) as $annotation) {
127 1
                if ($annotation instanceof Property) {
128 1
                    $metadata->addProperty($this->loadPropertyMetadata($annotation, $property));
129
                }
130
            }
131
        }
132
133 1 View Code Duplication
        if (false !== ($parent = $class->getParentClass())) {
0 ignored issues
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...
134 1
            $parentMetadata = $this->loadClassMetadata($parent);
135 1
            if (!$parentMetadata instanceof ObjectMetadataInterface) {
136
                throw new \RuntimeException(sprintf(
137
                    "Failed to merge metadata from parent class '%s'",
138
                    $parent->name
139
                ));
140
            }
141
142 1
            $metadata->mergeMetadata($parentMetadata);
143
        }
144
145 1
        return $metadata;
146
    }
147
148
    /**
149
     * Parse property metadata
150
     *
151
     * @param Property $annotation
152
     * @param \ReflectionProperty $property
153
     * @return PropertyMetadata
154
     */
155 1
    private function loadPropertyMetadata(Property $annotation, \ReflectionProperty $property)
156
    {
157 1
        $metadata = new PropertyMetadata($property->name, $property->class);
158
159 1
        list($dataType, $dataTypeParams) = $this->parseDataType($annotation, $property);
160
        $metadata
161 1
            ->setDataType($dataType)
162 1
            ->setDataTypeParams($dataTypeParams);
163
164 1
        if ($annotation->setter) {
165
            $metadata->setSetter($annotation->setter);
166 1
        } elseif (false === $property->isPublic()) {
167 1
            $setter = 'set' . ucfirst($property->name);
168 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...
169
                throw new \RuntimeException(sprintf(
170
                    "Couldn't find setter for non public property: %s:%s",
171
                    $property->class,
172
                    $property->name
173
                ));
174
            }
175
176 1
            $metadata->setSetter($setter);
177
        }
178
179 1
        return $metadata;
180
    }
181
182
    /**
183
     * Parse property data type
184
     *
185
     * @param Property $annotation
186
     * @param \ReflectionProperty $property
187
     * @return array
188
     */
189 1
    private function parseDataType(Property $annotation, \ReflectionProperty $property)
190
    {
191 1
        if (!empty($annotation->parser)) {
192 1
            if (!$property->getDeclaringClass()->hasMethod($annotation->parser)) {
193
                throw new \InvalidArgumentException(sprintf(
194
                    "Custom parser function %s:%s() for property '%s' does not exist",
195
                    $property->class,
196
                    $annotation->parser,
197
                    $property->name
198
                ));
199
            }
200 1
            return ['custom', $annotation->parser];
201 1
        } elseif (!empty($annotation->type)) {
202 1
            return $this->parseDataTypeString($annotation->type);
203 1
        } elseif (preg_match('~@var\s(.*?)\s~si', $property->getDocComment(), $matches)) {
204 1
            return $this->parseDataTypeString($matches[1]);
205
        } else {
206 1
            return ['raw', null];
207
        }
208
    }
209
210
    /**
211
     * Parse data type string
212
     *
213
     * @param string $type
214
     * @return array
215
     */
216 1
    private function parseDataTypeString($type)
217
    {
218 1
        $params = null;
219
220 1
        if ($this->isScalarDataType($type)) {
221 1
            $dataType = 'scalar';
222 1
            $params = $type;
223 1
        } elseif (preg_match('~^DateTime(<(.*?)>)?$~', $type, $matches)) {
224 1
            $dataType = 'datetime';
225 1
            if (3 === count($matches)) {
226 1
                $params = $matches[2];
227
            }
228
        } elseif (
229 1
            (preg_match('~Array(<(.*?)>)?$~si', $type, $matches)) ||
230 1
            (preg_match('~^(.*?)\[\]$~si', $type, $matches))
231
        ) {
232 1
            $dataType = 'array';
233 1
            if (3 === count($matches)) {
234 1
                $params = $this->parseDataTypeString($matches[2]);
235 1
            } elseif (2 === count($matches)) {
236 1
                $params = $this->parseDataTypeString($matches[1]);
237
            } else {
238 1
                $params = ['raw', null];
239
            }
240
        } else {
241 1
            $type = ltrim($type, '\\');
242
243 1
            if (!class_exists($type) && !interface_exists($type)) {
244
                throw new \InvalidArgumentException(sprintf(
245
                    "Unknown object type '%s' specified",
246
                    $type
247
                ));
248
            }
249
250 1
            $dataType = 'object';
251 1
            $params = $type;
252
        }
253
254 1
        return [$dataType, $params];
255
    }
256
257
    /**
258
     * Returns true if specified type scalar. False otherwise.
259
     *
260
     * @param string $type
261
     * @return bool
262
     */
263 1
    private function isScalarDataType($type)
264
    {
265 1
        return in_array($type, ['string', 'bool', 'boolean', 'int', 'integer', 'float', 'double']);
266
    }
267
}