Skip to content

Instantly share code, notes, and snippets.

@tamert
Created September 3, 2020 17:12
Show Gist options
  • Save tamert/767670ed97815a78de1f44fad2f945c6 to your computer and use it in GitHub Desktop.
Save tamert/767670ed97815a78de1f44fad2f945c6 to your computer and use it in GitHub Desktop.
UserContextBuilder.php
<?php
// src/Serializer/UserContextBuilder.php
namespace App\Serializer;
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\User;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
final class UserContextBuilder 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;
if ($resourceClass === User::class && $this->authorizationChecker->isGranted('ROLE_ADMIN')) {
$context['groups'][] = 'admin';
}
return $context;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment