|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace SmrTest; |
|
4
|
|
|
|
|
5
|
|
|
use ReflectionClass; |
|
6
|
|
|
use ReflectionMethod; |
|
7
|
|
|
|
|
8
|
|
|
class TestUtils { |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Get a private or protected method for testing/documentation purposes. |
|
12
|
|
|
* Note that this function should only be used as a last resort! Its use |
|
13
|
|
|
* indicates that the input class is a good candidate for refactoring. |
|
14
|
|
|
* |
|
15
|
|
|
* How to use for MyClass->foo(): |
|
16
|
|
|
* $cls = new MyClass(); |
|
17
|
|
|
* $foo = SmrTest\TestUtils::getPrivateMethod($cls, 'foo'); |
|
18
|
|
|
* $foo->invoke($cls, $args, ...); |
|
19
|
|
|
* |
|
20
|
|
|
* @param object $obj The instance of your class |
|
21
|
|
|
* @param string $name The name of your private/protected method |
|
22
|
|
|
* @return \ReflectionMethod The method you want to test |
|
23
|
|
|
*/ |
|
24
|
|
|
public static function getPrivateMethod(object $obj, string $name): ReflectionMethod { |
|
25
|
|
|
$method = new ReflectionMethod($obj, $name); |
|
26
|
|
|
$method->setAccessible(true); |
|
27
|
|
|
return $method; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Construct an instance of a class with a protected constructor for test |
|
32
|
|
|
* purposes. Note that this function should only beused as a last resort! |
|
33
|
|
|
* Its use indicates that the input class is a candidate for refactoring. |
|
34
|
|
|
* |
|
35
|
|
|
* @template T of object |
|
36
|
|
|
* @param class-string<T> $name The name of the class to construct |
|
|
|
|
|
|
37
|
|
|
* @param mixed ...$args The arguments to pass to the constructor |
|
38
|
|
|
* @return T |
|
39
|
|
|
*/ |
|
40
|
|
|
public static function constructPrivateClass(string $name, ...$args): object { |
|
41
|
|
|
$class = new ReflectionClass($name); |
|
42
|
|
|
$constructor = $class->getConstructor(); |
|
43
|
|
|
$constructor->setAccessible(true); |
|
44
|
|
|
$object = $class->newInstanceWithoutConstructor(); |
|
45
|
|
|
$constructor->invoke($object, ...$args); |
|
46
|
|
|
return $object; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
} |
|
50
|
|
|
|