Passed
Push — master ( 60258a...f4db75 )
by Nicolaas
02:16
created

ReflectionHelper::allowAccessToProperty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 13
rs 10
1
<?php
2
3
namespace Sunnysideup\DashboardWelcomeQuicklinks\Api;
4
5
use ReflectionClass;
6
7
/**
8
 * usage
9
 * ```php
10
 *     $myObject = ReflectionHelper::allowAccessToProperty(MyClass::class, 'myProtectedProperty');
11
 *     $myObject->myProtectedProperty = 'new value';
12
 * ```
13
 */
14
15
class ReflectionHelper
16
{
17
    /**
18
     * returns a new instance of a class with the protected property available for changing.
19
     *
20
     * @param string $className
21
     * @param string $propertyName
22
     * @return object object of the classname provded
23
     */
24
    public static function allowAccessToProperty(string $className, string $propertyName)
25
    {
26
        // Create a reflection object for the class
27
        $reflectionClass = new ReflectionClass($className);
28
29
        // Get the protected property
30
        $property = $reflectionClass->getProperty($propertyName);
31
32
        // Make the property accessible
33
        $property->setAccessible(true);
34
35
        // Set the value of the protected property
36
        return new $className();
37
    }
38
}
39