Skip to content
This repository has been archived by the owner on Nov 1, 2022. It is now read-only.

Commit

Permalink
Read #[Strict] also from parent classes
Browse files Browse the repository at this point in the history
  • Loading branch information
simPod committed Sep 14, 2021
1 parent 7960781 commit e326b46
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/Reflection/DataTransferObjectClass.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Spatie\DataTransferObject\Reflection;

use ReflectionAttribute;
use ReflectionClass;
use ReflectionProperty;
use Spatie\DataTransferObject\Attributes\Strict;
Expand Down Expand Up @@ -66,6 +67,22 @@ public function validate(): void

public function isStrict(): bool
{
return $this->isStrict ??= ! empty($this->reflectionClass->getAttributes(Strict::class));
return $this->isStrict ??= ! empty($this->getStrictAttributesWithParent($this->reflectionClass));
}

/**
* @param array<ReflectionAttribute> $attributes
*
* @return array<ReflectionAttribute>
*/
private function getStrictAttributesWithParent(ReflectionClass $reflectionClass, array $attributes = []): array
{
$attributes = array_merge($attributes, $reflectionClass->getAttributes(Strict::class));
$parent = $reflectionClass->getParentClass();
if ($parent === false) {
return $attributes;
}

return $this->getStrictAttributesWithParent($parent, $attributes);
}
}
14 changes: 14 additions & 0 deletions tests/StrictDtoTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@ public function strict_test()
$this->expectException(UnknownProperties::class);

$dto = new StrictDto(
name: 'name',
unknown: 'unknown'
);
}

/** @test */
public function strict_child_test()
{
$this->expectException(UnknownProperties::class);

$dto = new ChildStrictDto(
name: 'name',
unknown: 'unknown'
);
Expand All @@ -37,6 +48,9 @@ class StrictDto extends DataTransferObject
public string $name;
}

final class ChildStrictDto extends StrictDto {}


class NonStrictDto extends DataTransferObject
{
public string $name;
Expand Down

0 comments on commit e326b46

Please sign in to comment.