Skip to content
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

Validate derived types in collections #74

Merged
merged 2 commits into from
Jul 10, 2023
Merged
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
3 changes: 3 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@ parameters:
polluteScopeWithLoopInitialAssignments: false
paths:
- src
reportUnmatchedIgnoredErrors: false
ignoreErrors:
- '/^Parameter #1 \$[A-Za-z_0-9]+ of function is_subclass_of expects object\|string, mixed given.$/'
2 changes: 1 addition & 1 deletion src/Types/TypeUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static function validateCollectionValues($values, string $type): void
if (is_array($values)) {
foreach ($values as $value) {
$debugType = get_debug_type($value);
if ($type !== $debugType) {
if ($type !== $debugType && !is_subclass_of($value, $type)) {
throw new UnexpectedValueException("Collection of type=$type contains value of type=$debugType");
}
}
Expand Down
15 changes: 15 additions & 0 deletions tests/Types/TypeUtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,23 @@ public function testInvalidValueThrowsException(): void
}
}
}

public function testValidationWithChildClasses(): void
{
$this->expectNotToPerformAssertions();
TypeUtils::validateCollectionValues([new ChildCustomType(), new ChildCustomType()], TestCustomType::class);
TypeUtils::validateCollectionValues([new ChildCustomType(), new ChildCustomType()], TestInterface::class);
}
}

class TestCustomType {

}

class ChildCustomType extends TestCustomType implements TestInterface {

}

interface TestInterface {

}