Passed
Pull Request — master (#380)
by Wilmer
04:10 queued 01:20
created

Assert   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 17
c 2
b 0
f 0
dl 0
loc 55
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A invokeMethod() 0 7 1
A getInaccessibleProperty() 0 19 3
A equalsWithoutLE() 0 6 1
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
     * Asserting two strings equality ignoring line endings.
16
     */
17
    public static function equalsWithoutLE(string $expected, string $actual, string $message = ''): void
18
    {
19
        $expected = str_replace("\r\n", "\n", $expected);
20
        $actual = str_replace("\r\n", "\n", $actual);
21
22
        self::assertEquals($expected, $actual, $message);
23
    }
24
25
    /**
26
     * Gets an inaccessible object property.
27
     *
28
     * @param bool $revoke whether to make property inaccessible after getting.
29
     */
30
    public static function getInaccessibleProperty(object $object, string $propertyName, bool $revoke = true): mixed
31
    {
32
        $class = new ReflectionClass($object);
33
34
        while (!$class->hasProperty($propertyName)) {
35
            $class = $class->getParentClass();
36
        }
37
38
        $property = $class->getProperty($propertyName);
39
40
        $property->setAccessible(true);
41
42
        $result = $property->getValue($object);
43
44
        if ($revoke) {
45
            $property->setAccessible(false);
46
        }
47
48
        return $result;
49
    }
50
51
    /**
52
     * Invokes an inaccessible method.
53
     *
54
     * @param object $object The object to invoke the method on.
55
     * @param string $method The name of the method to invoke.
56
     * @param array $args The arguments to pass to the method.
57
     *
58
     * @throws ReflectionException
59
     */
60
    public static function invokeMethod(object $object, string $method, array $args = []): mixed
61
    {
62
        $reflection = new ReflectionObject($object);
63
        $method = $reflection->getMethod($method);
64
        $method->setAccessible(true);
65
66
        return $method->invokeArgs($object, $args);
67
    }
68
}
69