Skip to content

Commit

Permalink
refactor: move proxy to real class converter to ClassUtil (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
priyadi authored Feb 19, 2024
1 parent 685af2f commit 7a6c521
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use Rekalogika\Mapper\Transformer\ObjectToObjectMetadata\ObjectToObjectMetadata;
use Rekalogika\Mapper\Transformer\ObjectToObjectMetadata\ObjectToObjectMetadataFactoryInterface;
use Rekalogika\Mapper\Util\ClassUtil;

/**
* @internal
Expand All @@ -31,31 +32,10 @@ public function createObjectToObjectMetadata(
string $targetClass,
): ObjectToObjectMetadata {
$metadata = $this->decorated->createObjectToObjectMetadata(
$this->resolveRealClass($sourceClass),
ClassUtil::determineRealClassFromPossibleProxy($sourceClass),
$targetClass,
);

return $metadata;
}

/**
* @param class-string $class
* @return class-string
*/
private function resolveRealClass(string $class): string
{
$pos = strrpos($class, '\\__CG__\\');

if ($pos === false) {
$pos = strrpos($class, '\\__PM__\\');
}

if ($pos !== false) {
$class = substr($class, $pos + 8);
}

assert(class_exists($class), sprintf('Class "%s" does not exist', $class));

return $class;
}
}
45 changes: 45 additions & 0 deletions src/Util/ClassUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

namespace Rekalogika\Mapper\Util;

use Rekalogika\Mapper\Exception\UnexpectedValueException;
use Symfony\Component\VarExporter\Internal\Hydrator;

/**
Expand All @@ -24,6 +25,50 @@ private function __construct()
{
}

/**
* @template T of object
* @param class-string<T> $class
* @return class-string<T>
*/
public static function determineRealClassFromPossibleProxy(string $class): string
{
$inputClass = $class;

$pos = strrpos($class, '\\__CG__\\');

if ($pos === false) {
$pos = strrpos($class, '\\__PM__\\');
}

if ($pos !== false) {
$class = substr($class, $pos + 8);
}

if (!class_exists($class)) {
throw new UnexpectedValueException(sprintf(
'Trying to resolve the real class from possible proxy class "%s", got "%s", but the class does not exist',
$inputClass,
$class
));
}

/** @psalm-suppress DocblockTypeContradiction */
if (!is_a($inputClass, $class, true)) {
/** @psalm-suppress NoValue */
throw new UnexpectedValueException(sprintf(
'Trying to resolve the real class from possible proxy class "%s", got "%s", but the proxy "%s" is not a subclass of "%s"',
$inputClass,
$class,
$inputClass,
$class,
));
}

/** @var class-string<T> $class */

return $class;
}

/**
* @param class-string|\ReflectionClass<object> $class
* @return int
Expand Down

0 comments on commit 7a6c521

Please sign in to comment.