Skip to content

Refactor expose properties to avoid catching exceptions on private properties of parent classes #206

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions src/Resources/AbstractUnzerResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
namespace UnzerSDK\Resources;

use DateTime;
use ReflectionClass;
use ReflectionException;
use ReflectionProperty;
use RuntimeException;
Expand Down Expand Up @@ -495,10 +496,21 @@ public function getExternalId(): ?string
*/
private function exposeProperties(): array
{
$properties = get_object_vars($this);
foreach ($properties as $property => $value) {
if (self::propertyShouldBeSkipped($property, $value)) {
unset($properties[$property]);
$reflectionClass = new ReflectionClass(static::class);
$reflectionProperties = $reflectionClass->getProperties(ReflectionProperty::IS_PROTECTED); // only send protected properties

$properties = [];
foreach ($reflectionProperties as $propertyObject) {
$property = $propertyObject->getName();
$value = $propertyObject->getValue($this);

// do not send properties that are set to null
if ($value === null) {
continue;
}

// do not send id property if it is empty
if ($property === 'id' && empty($value)) {
continue;
}

Expand All @@ -516,7 +528,6 @@ private function exposeProperties(): array
// handle additional values
if ($property === 'additionalAttributes') {
if (!is_array($value) || empty($value)) {
unset($properties[$property]);
continue;
}
$value = $this->exposeAdditionalAttributes($value);
Expand Down
13 changes: 13 additions & 0 deletions test/unit/Resources/AbstractUnzerResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,19 @@ public function additionalAttributesShouldBeSettable(): void
$this->assertEquals(1234.567, $paypage->expose()['additionalAttributes']['effectiveInterestRate']);
}

/**
* @test
*/
public function parentPrivatePropertiesShouldNotCauseAnException(): void
{
$metadata = new Metadata();
$metadata->setParentResource(new Unzer('s-priv-123'));
$metadata->setSpecialParams(['something' => 'special']);

$result = $metadata->jsonSerialize();
$this->assertEquals('{"something":"special"}', $result);
}

//<editor-fold desc="Data Providers">

/**
Expand Down