Skip to content

Commit

Permalink
✨ Added trait for accessing values of private properties
Browse files Browse the repository at this point in the history
  • Loading branch information
yoan-myparcel committed Feb 2, 2024
1 parent ada36a3 commit 6c364e3
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Support/GetPrivatePropertyValue.php
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);
}
}
29 changes: 29 additions & 0 deletions tests/Support/GetPrivatePropertyValueTest.php
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'));
}
}

0 comments on commit 6c364e3

Please sign in to comment.