ReflectionMethods   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 0
dl 0
loc 52
c 0
b 0
f 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A callProtectedMethod() 0 6 1
A getMethod() 0 7 1
A getProperty() 0 10 3
1
<?php
2
declare(strict_types=1);
3
/**
4
 * Created by PhpStorm.
5
 * User: benedikt
6
 * Date: 1/6/18
7
 * Time: 7:07 PM
8
 */
9
10
namespace Tfboe\FmLib\TestHelpers;
11
12
/**
13
 * Trait ReflectionMethods
14
 * @package Tfboe\FmLib\TestHelpers
15
 */
16
trait ReflectionMethods
17
{
18
//<editor-fold desc="Protected Methods">
19
  /** @noinspection PhpDocMissingThrowsInspection */ //ReflectionException
20
  /**
21
   * Calls the given protected method on the given object with the given arguments
22
   * @param mixed $object the object to call on
23
   * @param string $method the method name
24
   * @param mixed[] $args the arguments for the method
25
   * @return mixed the return value of the method
26
   */
27
  protected static function callProtectedMethod($object, string $method, array $args = [])
28
  {
29
    // ReflectionException => get_class is a valid class
30
    /** @noinspection PhpUnhandledExceptionInspection */
31
    return self::getMethod(get_class($object), $method)->invokeArgs($object, $args);
32
  }
33
34
  /**
35
   * Gets a protected or private method and makes it accessible
36
   * @param string $class the class name
37
   * @param string $name the method name
38
   * @return \ReflectionMethod the accessible method object
39
   * @throws \ReflectionException the given class does not exist
40
   */
41
  protected static function getMethod(string $class, string $name): \ReflectionMethod
42
  {
43
    $class = new \ReflectionClass($class);
44
    $method = $class->getMethod($name);
45
    $method->setAccessible(true);
46
    return $method;
47
  }
48
49
  /**
50
   * Gets a protected or private property and makes it accessible
51
   * @param string $class the class name
52
   * @param string $name the method name
53
   * @return \ReflectionProperty the accessible property object
54
   * @throws \ReflectionException the given class does not exist
55
   */
56
  protected static function getProperty(string $class, string $name): \ReflectionProperty
57
  {
58
    $class = new \ReflectionClass($class);
59
    /** @noinspection PhpStatementHasEmptyBodyInspection */
60
    while (!$class->hasProperty($name) && ($class = $class->getParentClass()) !== null) {
61
    }
62
    $property = $class->getProperty($name);
63
    $property->setAccessible(true);
64
    return $property;
65
  }
66
//</editor-fold desc="Protected Methods">
67
}