Created
November 11, 2021 12:09
-
-
Save atillay/494a3073849c2319a0a9352d5fd1d7ad to your computer and use it in GitHub Desktop.
Revisions
-
atillay created this gist
Nov 11, 2021 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,49 @@ <?php namespace App\Serializer; use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; final class GroupsContextBuilder implements SerializerContextBuilderInterface { private $decorated; private $authorizationChecker; public function __construct(SerializerContextBuilderInterface $decorated, AuthorizationCheckerInterface $authorizationChecker) { $this->decorated = $decorated; $this->authorizationChecker = $authorizationChecker; } public function createFromRequest(Request $request, bool $normalization, ?array $extractedAttributes = null): array { $context = $this->decorated->createFromRequest($request, $normalization, $extractedAttributes); $resourceClass = $context['resource_class'] ?? null; $entityName = (new \ReflectionClass($resourceClass))->getShortName(); $entitySlug = strtolower(preg_replace('/[A-Z]/', '-\\0', lcfirst($entityName))); $operationName = $this->extractOperationName($context); $serializeType = true === $normalization ? 'out' : 'in'; // in=input=denormalization, out=output=normalization /* Generate entity group "entity:operationName" */ $context['groups'][] = sprintf('%s:%s', $entitySlug, $operationName); /* Generate entity group "entity:operationName:serializeType" */ $context['groups'][] = sprintf('%s:%s:%s', $entitySlug, $operationName, $serializeType); return $context; } private function extractOperationName(array $context): string { if (!empty($context['item_operation_name']) { return $context['item_operation_name'] === 'get' ? 'get_item' : $context['item_operation_name']; } if (!empty($context['collection_operation_name']) { return $context['collection_operation_name'] === 'get' ? 'get_col' : $context['collection_operation_name']; } throw new \Exception(get_class() . ' : unsupported request); } }