Created
September 3, 2020 17:12
-
-
Save tamert/767670ed97815a78de1f44fad2f945c6 to your computer and use it in GitHub Desktop.
UserContextBuilder.php
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 characters
<?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