From 4db549c48bd839de38e6f55c9c92797bdd59e5bd Mon Sep 17 00:00:00 2001 From: Niki Zakariassen Date: Mon, 27 Feb 2023 11:44:57 +0100 Subject: [PATCH] Fixed array for data collections bug --- src/SpatieLaravelData/Rules/ValidTypeRule.php | 5 +++- .../DataCollectionSpatieLaravelData.php | 27 +++++++++++++++++++ test/SpatieLaravelData/ValidTypeRuleTest.php | 8 ++++++ 3 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 test/Samples/DataCollectionSpatieLaravelData.php diff --git a/src/SpatieLaravelData/Rules/ValidTypeRule.php b/src/SpatieLaravelData/Rules/ValidTypeRule.php index 7be593d..cdceb21 100644 --- a/src/SpatieLaravelData/Rules/ValidTypeRule.php +++ b/src/SpatieLaravelData/Rules/ValidTypeRule.php @@ -10,6 +10,7 @@ use PHPStan\Rules\RuleErrorBuilder; use PHPStan\ShouldNotHappenException; use Cego\phpstan\TypeSystem\UnionType; +use Spatie\LaravelData\DataCollection; use Cego\phpstan\TypeSystem\TypeSystem; use Cego\phpstan\SpatieLaravelData\Data\Call; use Cego\phpstan\SpatieLaravelData\Data\Constructor; @@ -180,7 +181,9 @@ public static function getErrorMessage(string $property, string $class, string $ */ private function expectedTypesMatchesExactlyCast(array $casts, UnionType $expectedTypes): bool { - foreach ($casts as $castType) { + $systemCasts = [UnionType::fromString(DataCollection::class)]; + + foreach ([...$casts, ...$systemCasts] as $castType) { if (TypeSystem::isSubtypeOf($expectedTypes, $castType)) { return true; } diff --git a/test/Samples/DataCollectionSpatieLaravelData.php b/test/Samples/DataCollectionSpatieLaravelData.php new file mode 100644 index 0000000..f7040a4 --- /dev/null +++ b/test/Samples/DataCollectionSpatieLaravelData.php @@ -0,0 +1,27 @@ + $collectionProperty + */ + public function __construct( + public readonly DataCollection $collectionProperty, + ) { + } + + public function initDefault(): self + { + return self::from( + [ + 'collectionProperty' => [], + ], + ); + } +} diff --git a/test/SpatieLaravelData/ValidTypeRuleTest.php b/test/SpatieLaravelData/ValidTypeRuleTest.php index a5e7fe6..fbc03da 100644 --- a/test/SpatieLaravelData/ValidTypeRuleTest.php +++ b/test/SpatieLaravelData/ValidTypeRuleTest.php @@ -100,6 +100,14 @@ public function it_does_not_care_about_generics(): void ], []); } + /** @test */ + public function it_accepts_arrays_for_data_collections(): void + { + $this->analyse([ + __DIR__ . '/../Samples/DataCollectionSpatieLaravelData.php', + ], []); + } + private function expectError(int $line, string $property, string $class, string $expectedType, string $actualType): array { return [