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

fix: handle class name collision while parsing types inside a class #398

Merged
merged 1 commit into from
Aug 8, 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
4 changes: 3 additions & 1 deletion src/Type/Parser/Lexer/AliasLexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ public function tokenize(string $symbol): Token

private function resolve(string $symbol): string
{
if (Reflection::classOrInterfaceExists($symbol)) {
// Matches the case where a class extends a class with the same name but
// in a different namespace.
if ($symbol === $this->reflection->getShortName() && Reflection::classOrInterfaceExists($symbol)) {
return $symbol;
}

Expand Down
33 changes: 33 additions & 0 deletions tests/Integration/Mapping/ClassNameCollisionTestCollision.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace CuyZ\Valinor\Tests\Integration\Mapping;

use CuyZ\Valinor\Mapper\MappingError;
use CuyZ\Valinor\MapperBuilder;
use CuyZ\Valinor\Tests\Integration\IntegrationTest;
use CuyZ\Valinor\Tests\Integration\Mapping\Fixture\Error;

final class ClassNameCollisionTestCollision extends IntegrationTest
{
public function test_mapping_to_class_with_same_class_name_as_native_class_works_properly(): void
{
try {
$result = (new MapperBuilder())
->mapper()
->map(ObjectWithErrorsClassNameCollision::class, ['foo', 'bar']);
} catch (MappingError $error) {
$this->mappingFail($error);
}

self::assertSame('foo', $result->errors[0]->message);
self::assertSame('bar', $result->errors[1]->message);
}
}

final class ObjectWithErrorsClassNameCollision
{
public function __construct(
/** @var list<Error> */
public array $errors
) {}
}
13 changes: 13 additions & 0 deletions tests/Integration/Mapping/Fixture/Error.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace CuyZ\Valinor\Tests\Integration\Mapping\Fixture;

/**
* Has the same name of the native class `Error` on purpose.
*/
final class Error
{
public function __construct(
public string $message
) {}
}