Skip to content

Instantly share code, notes, and snippets.

@atillay
Last active November 11, 2021 17:03
Show Gist options
  • Save atillay/a7316b6366df3481944a930d236b9faf to your computer and use it in GitHub Desktop.
Save atillay/a7316b6366df3481944a930d236b9faf to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App\Validator;
use Symfony\Component\HttpFoundation\RequestStack;
final class ValidationGroupsGenerator
{
private $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function __invoke($object): array
{
$groups = ['Default'];
$currentRequest = $this->requestStack->getCurrentRequest();
$entityName = (new \ReflectionClass($object))->getShortName();
$entitySlug = strtolower(preg_replace('/[A-Z]/', '-\\0', lcfirst($entityName)));
$operationName = $currentRequest->attributes->get('_api_item_operation_name')
?? $currentRequest->attributes->get('_api_collection_operation_name');
/* Generate entity validation group "entity:operationName" (ex: account:post) */
$groups[] = sprintf('%s:%s', $entitySlug, $operationName);
return $groups;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment