-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
✨ Added trait for accessing values of private properties
- Loading branch information
1 parent
ada36a3
commit 6c364e3
Showing
2 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace MyParcelCom\Payments\Providers\Support; | ||
|
||
use ReflectionClass; | ||
use ReflectionException; | ||
|
||
trait GetPrivatePropertyValue | ||
{ | ||
/** | ||
* @throws ReflectionException | ||
*/ | ||
private function getPrivatePropertyValue(object $object, string $property): mixed | ||
{ | ||
$classReflection = new ReflectionClass($object); | ||
$propertyReflection = $classReflection->getProperty($property); | ||
/** @noinspection PhpExpressionResultUnusedInspection */ | ||
$propertyReflection->setAccessible(true); | ||
|
||
return $propertyReflection->getValue($object); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Tests\Support; | ||
|
||
use MyParcelCom\Payments\Providers\Support\GetPrivatePropertyValue; | ||
use PHPUnit\Framework\TestCase; | ||
|
||
use ReflectionException; | ||
|
||
use function PHPUnit\Framework\assertSame; | ||
|
||
class GetPrivatePropertyValueTest extends TestCase | ||
{ | ||
use GetPrivatePropertyValue; | ||
|
||
/** | ||
* @throws ReflectionException | ||
*/ | ||
public function test_it_gets_private_property_value(): void | ||
{ | ||
$object = new class { | ||
private string $property = 'value'; | ||
}; | ||
|
||
assertSame('value', $this->getPrivatePropertyValue($object, 'property')); | ||
} | ||
} |