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

Commit

Permalink
Merge pull request #239 from simPod/strict-child
Browse files Browse the repository at this point in the history
Read `#[Strict]` also from parent classes
  • Loading branch information
brendt committed Sep 17, 2021
2 parents 7960781 + 6a9ccb4 commit 38bda92
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

All notable changes to `data-transfer-object` will be documented in this file

## Unreleased

- `#[Strict]` is passed down the inheritance chain so children are strict when parent is strict (#239)

## 3.7.1 - 2021-09-09

- Cast properties with self or parent type (#236)
Expand Down
16 changes: 15 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,19 @@ public function validate(): void

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

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

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

$this->isStrict = $attribute !== null;
}

return $this->isStrict;
}
}
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 38bda92

Please sign in to comment.