Skip to content

Commit

Permalink
fix: Backport Normalize class names #300 (#301)
Browse files Browse the repository at this point in the history
Co-authored-by: Grégoire Paris <[email protected]>
  • Loading branch information
Tofandel and greg0ire committed Aug 6, 2022
1 parent d7edf27 commit b73e83d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/Persistence/Mapping/AbstractClassMetadataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use function class_exists;
use function explode;
use function is_array;
use function ltrim;
use function str_replace;
use function strpos;
use function strrpos;
Expand Down Expand Up @@ -214,6 +215,18 @@ abstract protected function initializeReflection(ClassMetadata $class, Reflectio
*/
abstract protected function isEntity(ClassMetadata $class);

/**
* Removes the prepended backslash of a class string to conform with how php outputs class names
*
* @param string $className
*
* @return string
*/
private function normalizeClassName($className)
{
return ltrim($className, '\\');
}

/**
* {@inheritDoc}
*
Expand All @@ -222,6 +235,8 @@ abstract protected function isEntity(ClassMetadata $class);
*/
public function getMetadataFor($className)
{
$className = $this->normalizeClassName($className);

if (isset($this->loadedMetadata[$className])) {
return $this->loadedMetadata[$className];
}
Expand Down Expand Up @@ -307,6 +322,8 @@ public function getMetadataFor($className)
*/
public function hasMetadataFor($className)
{
$className = $this->normalizeClassName($className);

return isset($this->loadedMetadata[$className]);
}

Expand All @@ -321,7 +338,7 @@ public function hasMetadataFor($className)
*/
public function setMetadataFor($className, $class)
{
$this->loadedMetadata[$className] = $class;
$this->loadedMetadata[$this->normalizeClassName($className)] = $class;
}

/**
Expand Down
17 changes: 17 additions & 0 deletions tests/Persistence/Mapping/AbstractClassMetadataFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,19 @@ public function testAnonymousClassIsNotMistakenForShortAlias(): void
self::assertFalse($cmf->isTransient(get_class(new class () {
})));
}

public function testItGetsTheSameMetadataForBackslashedClassName(): void
{
$cmf = $this->getMockForAbstractClass(AbstractClassMetadataFactory::class);
$cmf
->method('newClassMetadataInstance')
->with(SomeOtherEntity::class)
->willReturn(
$this->createMock(ClassMetadata::class)
);

self::assertSame($cmf->getMetadataFor(SomeOtherEntity::class), $cmf->getMetadataFor('\\' . SomeOtherEntity::class));
}
}

class SomeGrandParentEntity
Expand All @@ -97,3 +110,7 @@ class SomeParentEntity extends SomeGrandParentEntity
final class SomeEntity extends SomeParentEntity
{
}

final class SomeOtherEntity
{
}

0 comments on commit b73e83d

Please sign in to comment.