AttributeExtractor::extractAttributes()   C
last analyzed

Complexity

Conditions 8
Paths 9

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 8.0093

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 33
ccs 18
cts 19
cp 0.9474
rs 5.3846
cc 8
eloc 17
nc 9
nop 1
crap 8.0093
1
<?php
2
3
namespace Happyr\SerializerBundle\PropertyManager;
4
5
/**
6
 * Extract attributes from object.
7
 *
8
 * @author Tobias Nyholm <[email protected]>
9
 */
10
class AttributeExtractor
11
{
12
    /**
13
     * @var array
14
     */
15
    private $attributesCache = [];
16
17
    /**
18
     * Gets and caches attributes for this class and context.
19
     *
20
     * @param object|string $object
21
     *
22
     * @return string[]
23
     */
24 23
    public function getAttributes($object)
25
    {
26 23
        if (is_string($object)) {
27 23
            $class = $object;
28 23
        } else {
29 11
            $class = get_class($object);
30
        }
31
32
        // get cache key
33 23
        if (false !== $key = $this->getCacheKey($class)) {
34 23
            if (isset($this->attributesCache[$key])) {
35 1
                return $this->attributesCache[$key];
36
            }
37 23
        }
38
39 23
        return $this->attributesCache[$key] = $this->extractAttributes($class);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->attributes...ractAttributes($class); (array<string,array>) is incompatible with the return type documented by Happyr\SerializerBundle\...xtractor::getAttributes of type 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...
40
    }
41
42
    /**
43
     * Extracts attributes for this class and context.
44
     *
45
     * @param string $class
46
     *
47
     * @return string[]
48
     */
49 23
    private function extractAttributes($class)
50
    {
51
        // If not using groups, detect manually
52 23
        $attributes = ['property' => [], 'method' => []];
53
54
        // methods
55 23
        $reflClass = new \ReflectionClass($class);
56 23
        foreach ($reflClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflMethod) {
57
            if (
58 23
                $reflMethod->getNumberOfRequiredParameters() !== 0 ||
59 23
                $reflMethod->isStatic() ||
60 23
                $reflMethod->isConstructor() ||
61 23
                $reflMethod->isDestructor()
62 23
            ) {
63 23
                continue;
64
            }
65
66 23
            $name = $reflMethod->name;
67
68 23
            $attributes['method'][$name] = true;
69 23
        }
70
71
        // properties
72 23
        foreach ($reflClass->getProperties() as $reflProperty) {
73 23
            if ($reflProperty->isStatic()) {
74
                continue;
75
            }
76
77 23
            $attributes['property'][$reflProperty->name] = true;
78 23
        }
79
80 23
        return $attributes;
81
    }
82
83
    /**
84
     * Get a good cache key for this class.
85
     *
86
     * @param $class
87
     *
88
     * @return bool|string
89
     */
90 23
    private function getCacheKey($class)
91
    {
92
        try {
93 23
            return md5($class);
94
        } catch (\Exception $e) {
95
            // The context cannot be serialized, skip the cache
96
            return false;
97
        }
98
    }
99
}
100