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 59422d5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
12 changes: 11 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,15 @@ public function validate(): void

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

$reflectionClass = $this->reflectionClass;
while ($attribute === null && $reflectionClass !== false) {
$attribute = $reflectionClass->getAttributes(Strict::class)[0] ?? null;

$reflectionClass = $reflectionClass->getParentClass();
}

return $this->isStrict ??= $attribute !== null;
}
}
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 59422d5

Please sign in to comment.