Completed
Push — master ( 017835...f95b3f )
by Sergey
02:43
created

ExtensionTrait::setInaccessibleProperty()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 1
nop 3
1
<?php
2
/**
3
 * Common tests stuff
4
 *
5
 * @see       https://github.com/sergeymakinen/tests
6
 * @copyright Copyright (c) 2017 Sergey Makinen (https://makinen.ru)
7
 * @license   https://github.com/sergeymakinen/tests/blob/master/LICENSE MIT License
8
 */
9
10
namespace SergeyMakinen\Tests\Util;
11
12
trait ExtensionTrait
13
{
14
    /**
15
     * Returns the reflected property.
16
     *
17
     * @param object|string $object
18
     * @param string $name
19
     * @return \ReflectionProperty
20
     */
21
    protected function getProperty($object, $name)
22
    {
23
        $class = new \ReflectionClass($object);
24
        while (!$class->hasProperty($name)) {
25
            $class = $class->getParentClass();
26
        }
27
        return $class->getProperty($name);
28
    }
29
30
    /**
31
     * Returns the private/protected property by its name.
32
     *
33
     * @param object|string $object
34
     * @param string $name
35
     * @return mixed
36
     */
37
    protected function getInaccessibleProperty($object, $name)
38
    {
39
        $property = $this->getProperty($object, $name);
40
        $property->setAccessible(true);
41
        return $property->getValue(is_object($object) ? $object : null);
42
    }
43
44
    /**
45
     * Sets the private/protected property value by its name.
46
     *
47
     * @param object|string $object
48
     * @param string $name
49
     * @param mixed $value
50
     */
51
    protected function setInaccessibleProperty($object, $name, $value)
52
    {
53
        $property = $this->getProperty($object, $name);
54
        $property->setAccessible(true);
55
        $property->setValue(is_object($object) ? $object : null, $value);
56
    }
57
58
    /**
59
     * Invokes the private/protected method by its name and returns its result.
60
     *
61
     * @param object|string $object
62
     * @param string $name
63
     * @param array $args
64
     * @return mixed
65
     */
66
    protected function invokeInaccessibleMethod($object, $name, array $args = [])
67
    {
68
        $method = new \ReflectionMethod($object, $name);
69
        $method->setAccessible(true);
70
        return $method->invokeArgs(is_object($object) ? $object : null, $args);
71
    }
72
}
73