Passed
Pull Request — master (#380)
by Wilmer
02:36
created

Assert::getInaccessibleProperty()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 1
b 0
f 0
nc 4
nop 3
dl 0
loc 19
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Tests\Support;
6
7
use PHPUnit\Framework\TestCase;
8
use ReflectionClass;
9
use ReflectionException;
10
use ReflectionObject;
11
12
final class Assert extends TestCase
13
{
14
    /**
15
     * Gets an inaccessible object property.
16
     *
17
     * @param bool $revoke whether to make property inaccessible after getting.
18
     */
19
    public static function getInaccessibleProperty(object $object, string $propertyName, bool $revoke = true): mixed
20
    {
21
        $class = new ReflectionClass($object);
22
23
        while (!$class->hasProperty($propertyName)) {
24
            $class = $class->getParentClass();
25
        }
26
27
        $property = $class->getProperty($propertyName);
28
29
        $property->setAccessible(true);
30
31
        $result = $property->getValue($object);
32
33
        if ($revoke) {
34
            $property->setAccessible(false);
35
        }
36
37
        return $result;
38
    }
39
40
    /**
41
     * Invokes an inaccessible method.
42
     *
43
     * @param object $object The object to invoke the method on.
44
     * @param string $method The name of the method to invoke.
45
     * @param array $args The arguments to pass to the method.
46
     *
47
     * @throws ReflectionException
48
     */
49
    public static function invokeMethod(object $object, string $method, array $args = []): mixed
50
    {
51
        $reflection = new ReflectionObject($object);
52
        $method = $reflection->getMethod($method);
53
        $method->setAccessible(true);
54
55
        return $method->invokeArgs($object, $args);
56
    }
57
}
58