NSA::getReflectionClassWithProperty()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 17

Duplication

Lines 17
Ratio 100 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 17
loc 17
ccs 9
cts 9
cp 1
rs 9.7
c 0
b 0
f 0
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
namespace Nyholm;
4
5
use Webmozart\Assert\Assert;
6
7
/**
8
 * Warning: This class should only be used with tests, fixtures or debug.
9
 *
10
 * @author Tobias Nyholm <[email protected]>
11
 */
12
class NSA
13
{
14
    /**
15
     * Get a constant of an object. You may provide the class name (including namespace) instead of an object.
16
     *
17
     * @param object|string $objectOrClass
18
     * @param string        $constantName
19
     *
20
     * @return mixed
21
     *
22
     * @throws \InvalidArgumentException
23
     * @throws \LogicException
24
     */
25 3
    public static function getConstant($objectOrClass, $constantName)
26
    {
27 3
        $class = $objectOrClass;
28
29 3
        if (!is_string($objectOrClass)) {
30 2
            Assert::object($objectOrClass, 'Can not get a constant of a non object. Variable of type "%s" was given.');
31 2
            $class = get_class($objectOrClass);
32
        }
33
34 3
        $refl = static::getReflectionClassWithConstant($class, $constantName);
0 ignored issues
show
Bug introduced by
It seems like $class defined by $objectOrClass on line 27 can also be of type object; however, Nyholm\NSA::getReflectionClassWithConstant() does only seem to accept string, 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...
35
36 3
        if (null === $refl) {
37 1
            throw new \LogicException(sprintf('The constant %s does not exist on %s or any of its parents.', $constantName, $class));
38
        }
39
40 2
        return $refl->getConstant($constantName);
41
    }
42
43
    /**
44
     * Get a property of an object. If the property is static you may provide the class name (including namespace)
45
     * instead of an object.
46
     *
47
     * @param object|string $objectOrClass
48
     * @param string        $propertyName
49
     *
50
     * @return mixed
51
     *
52
     * @throws \InvalidArgumentException
53
     * @throws \LogicException
54
     */
55 25 View Code Duplication
    public static function getProperty($objectOrClass, $propertyName)
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...
56
    {
57 25
        $reflectionProperty = static::getAccessibleReflectionProperty($objectOrClass, $propertyName);
58
59 18
        $object = $objectOrClass;
60 18
        if (is_string($objectOrClass)) {
61 4
            $object = (new \ReflectionClass($objectOrClass))->newInstanceWithoutConstructor();
62
        }
63
64 18
        return $reflectionProperty->getValue($object);
65
    }
66
67
    /**
68
     * Set a property to an object. If the property is static you may provide the class name (including namespace)
69
     * instead of an object.
70
     *
71
     * @param object|string $objectOrClass
72
     * @param string        $propertyName
73
     * @param mixed         $value
74
     *
75
     * @throws \InvalidArgumentException
76
     * @throws \LogicException
77
     */
78 9 View Code Duplication
    public static function setProperty($objectOrClass, $propertyName, $value)
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...
79
    {
80 9
        $reflectionProperty = static::getAccessibleReflectionProperty($objectOrClass, $propertyName);
81
82 9
        $object = $objectOrClass;
83 9
        if (is_string($objectOrClass)) {
84 2
            $object = (new \ReflectionClass($objectOrClass))->newInstanceWithoutConstructor();
85
        }
86
87 9
        $reflectionProperty->setValue($object, $value);
88 9
    }
89
90
    /**
91
     * Invoke a method on a object and get the return values. If the method is static you may provide the class
92
     * name (including namespace) instead of an object.
93
     *
94
     * @param object|string $objectOrClass
95
     * @param string        $methodName
96
     * @param mixed         ...$params
97
     *
98
     * @return mixed
99
     *
100
     * @throws \InvalidArgumentException
101
     * @throws \LogicException
102
     */
103 16
    public static function invokeMethod()
104
    {
105 16
        if (func_num_args() < 2) {
106 2
            throw new \LogicException('The method Reflection::invokeMethod need at least two arguments.');
107
        }
108
109 14
        $arguments = func_get_args();
110 14
        $objectOrClass = array_shift($arguments);
111 14
        $methodName = array_shift($arguments);
112
113 14
        Assert::string($methodName, 'Method name has to be a string. Variable of type "%s" was given.');
114 11 View Code Duplication
        if (is_string($objectOrClass)) {
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...
115 4
            Assert::classExists($objectOrClass, 'Could not find class "%s"');
116
        } else {
117 7
            Assert::notInstanceOf($objectOrClass, '\stdClass', 'Can not get a method of \stdClass.');
118 6
            Assert::object($objectOrClass, 'Can not get a property of a non object. Variable of type "%s" was given.');
119
        }
120
121 8
        $refl = new \ReflectionClass($objectOrClass);
122 8
        if (!$refl->hasMethod($methodName)) {
123 1
            throw new \LogicException(sprintf('The method %s::%s does not exist.', get_class($objectOrClass), $methodName));
124
        }
125
126 7
        $method = $refl->getMethod($methodName);
127 7
        $method->setAccessible(true);
128
129
        // If it is a static call we should pass null as first parameter to \ReflectionMethod::invokeArgs
130 7
        $object = null;
131 7
        if (!$method->isStatic()) {
132 4
            $object = $objectOrClass;
133 4
            Assert::object($object, 'Can not access non-static method without an object.');
134
        }
135
136 6
        return $method->invokeArgs($object, $arguments);
137
    }
138
139
    /**
140
     * Get a reflection class that has this constant.
141
     *
142
     * @param string $class
143
     * @param string $constantName
144
     *
145
     * @return \ReflectionClass|null
146
     *
147
     * @throws \InvalidArgumentException
148
     */
149 3 View Code Duplication
    protected static function getReflectionClassWithConstant($class, $constantName)
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...
150
    {
151 3
        Assert::string($class, 'First argument to Reflection::getReflectionClassWithConstant must be string. Variable of type "%s" was given.');
152 3
        Assert::classExists($class, 'Could not find class "%s"');
153
154 3
        $refl = new \ReflectionClass($class);
155 3
        if ($refl->hasConstant($constantName)) {
156 2
            return $refl;
157
        }
158
159 1
        if (false === $parent = get_parent_class($class)) {
160
            // No more parents
161 1
            return null;
162
        }
163
164 1
        return self::getReflectionClassWithConstant($parent, $constantName);
165
    }
166
167
    /**
168
     * Get a reflection class that has this property.
169
     *
170
     * @param string $class
171
     * @param string $propertyName
172
     *
173
     * @return \ReflectionClass|null
174
     *
175
     * @throws \InvalidArgumentException
176
     */
177 21 View Code Duplication
    protected static function getReflectionClassWithProperty($class, $propertyName)
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...
178
    {
179 21
        Assert::string($class, 'First argument to Reflection::getReflectionClassWithProperty must be string. Variable of type "%s" was given.');
180 21
        Assert::classExists($class, 'Could not find class "%s"');
181
182 20
        $refl = new \ReflectionClass($class);
183 20
        if ($refl->hasProperty($propertyName)) {
184 19
            return $refl;
185
        }
186
187 9
        if (false === $parent = get_parent_class($class)) {
188
            // No more parents
189 1
            return null;
190
        }
191
192 9
        return self::getReflectionClassWithProperty($parent, $propertyName);
193
    }
194
195
    /**
196
     * Get an reflection property that you can access directly.
197
     *
198
     * @param object|string $objectOrClass
199
     * @param string        $propertyName
200
     *
201
     * @return \ReflectionProperty
202
     *
203
     * @throws \InvalidArgumentException
204
     * @throws \LogicException           if the property is not found on the object
205
     */
206 25
    protected static function getAccessibleReflectionProperty($objectOrClass, $propertyName)
207
    {
208 25
        Assert::string($propertyName, 'Property name must be a string. Variable of type "%s" was given.');
209
210 23
        $class = $objectOrClass;
211 23 View Code Duplication
        if (!is_string($objectOrClass)) {
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...
212 18
            Assert::object($objectOrClass, 'Can not get a property of a non object. Variable of type "%s" was given.');
213 16
            Assert::notInstanceOf($objectOrClass, '\stdClass', 'Can not get a property of \stdClass.');
214 15
            $class = get_class($objectOrClass);
215
        }
216
217 20
        if (null === $refl = static::getReflectionClassWithProperty($class, $propertyName)) {
0 ignored issues
show
Bug introduced by
It seems like $class defined by $objectOrClass on line 210 can also be of type object; however, Nyholm\NSA::getReflectionClassWithProperty() does only seem to accept string, 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...
218 1
            throw new \LogicException(sprintf('The property %s does not exist on %s or any of its parents.', $propertyName, $class));
219
        }
220
221 19
        $property = $refl->getProperty($propertyName);
222 19
        $property->setAccessible(true);
223
224 19
        if (!$property->isStatic()) {
225 11
            Assert::object($objectOrClass, 'Can not access non-static property without an object.');
226
        }
227
228 18
        return $property;
229
    }
230
231
    /**
232
     * Get all property names on a class or object.
233
     *
234
     * @param object|string $objectOrClass
235
     *
236
     * @return array of strings
237
     *
238
     * @throws \InvalidArgumentException
239
     */
240 18
    public static function getProperties($objectOrClass)
241
    {
242 18
        $class = $objectOrClass;
243 18 View Code Duplication
        if (!is_string($objectOrClass)) {
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...
244 10
            Assert::object($objectOrClass, 'Can not get a property of a non object. Variable of type "%s" was given.');
245 9
            Assert::notInstanceOf($objectOrClass, '\stdClass', 'Can not get a property of \stdClass.');
246 8
            $class = get_class($objectOrClass);
247
        }
248
249 16
        $refl = new \ReflectionClass($class);
250 16
        $properties = $refl->getProperties();
251
252
        // check parents
253 16
        while (false !== $parent = get_parent_class($class)) {
254 16
            $parentRefl = new \ReflectionClass($parent);
255 16
            $properties = array_merge($properties, $parentRefl->getProperties());
256 16
            $class = $parent;
257
        }
258
259
        return array_map(function ($reflectionProperty) {
260 16
            return $reflectionProperty->name;
261 16
        }, $properties);
262
    }
263
}
264