Skip to content

Commit

Permalink
Add ValueResolver
Browse files Browse the repository at this point in the history
  • Loading branch information
ulrichsg committed Jan 10, 2024
1 parent f064130 commit fff7dfe
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions ValueResolver/PropelValueResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

namespace Propel\Bundle\PropelBundle\ValueResolver;

use Propel\Runtime\ActiveRecord\ActiveRecordInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Attribute\AsTargetedValueResolver;
use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

#[AsTargetedValueResolver('propel')]
class PropelValueResolver implements ValueResolverInterface
{
public function resolve(Request $request, ArgumentMetadata $argument): iterable
{
$className = $argument->getType();
if (!is_subclass_of($className, ActiveRecordInterface::class)) {
return [];
}

$idParam = lcfirst($this->baseName($className) . 'Id');
$id = $request->attributes->get($idParam);
if ($id === null) {
return [];
}

$queryClass = $className . 'Query';
if (!class_exists($queryClass)) {
return [];
}

$entity = $queryClass::create()->findPk($id);

if (!$entity) {
$msg = sprintf(
'Could not resolve entity (%s: %s) for class: %s',
$idParam,
$id,
$className,
);
throw new NotFoundHttpException($msg);
}

return [$entity];
}

private function baseName(string $className): string
{
$parts = explode('\\', $className);
return end($parts);
}
}

0 comments on commit fff7dfe

Please sign in to comment.