Skip to content

Instantly share code, notes, and snippets.

@atillay
Created November 11, 2021 12:09
Show Gist options
  • Select an option

  • Save atillay/494a3073849c2319a0a9352d5fd1d7ad to your computer and use it in GitHub Desktop.

Select an option

Save atillay/494a3073849c2319a0a9352d5fd1d7ad to your computer and use it in GitHub Desktop.

Revisions

  1. atillay created this gist Nov 11, 2021.
    49 changes: 49 additions & 0 deletions api-platform-groups-context-builder.php
    Original 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);
    }
    }