SetPreferenceAction.php (2342B)
1 <?php 2 3 namespace PartKeepr\AuthBundle\Action; 4 5 use Dunglas\ApiBundle\Action\ActionUtilTrait; 6 use Dunglas\ApiBundle\Api\ResourceInterface; 7 use Dunglas\ApiBundle\Exception\RuntimeException; 8 use PartKeepr\AuthBundle\Services\UserPreferenceService; 9 use PartKeepr\AuthBundle\Services\UserService; 10 use PartKeepr\CategoryBundle\Exception\RootNodeNotFoundException; 11 use Symfony\Component\HttpFoundation\JsonResponse; 12 use Symfony\Component\HttpFoundation\Request; 13 use Symfony\Component\Serializer\Serializer; 14 15 /** 16 * Returns the tree root node. 17 */ 18 class SetPreferenceAction 19 { 20 use ActionUtilTrait; 21 22 /** 23 * @var UserService 24 */ 25 private $userService; 26 27 /** 28 * @var UserPreferenceService 29 */ 30 private $userPreferenceService; 31 32 /** 33 * @var Serializer 34 */ 35 private $serializer; 36 37 public function __construct( 38 UserService $userService, 39 UserPreferenceService $userPreferenceService, 40 Serializer $serializer 41 ) { 42 $this->userService = $userService; 43 $this->userPreferenceService = $userPreferenceService; 44 $this->serializer = $serializer; 45 } 46 47 /** 48 * Retrieves a collection of resources. 49 * 50 * @param Request $request 51 * 52 * @throws \Exception If the format is invalid 53 * @throws RuntimeException|RootNodeNotFoundException 54 * 55 * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable 56 */ 57 public function __invoke(Request $request) 58 { 59 $user = $this->userService->getUser(); 60 61 $data = json_decode($request->getContent()); 62 63 if (property_exists($data, 'preferenceKey') && property_exists($data, 'preferenceValue')) { 64 $preference = $this->userPreferenceService->setPreference( 65 $user, 66 $data->preferenceKey, 67 $data->preferenceValue 68 ); 69 } else { 70 throw new \Exception('Invalid format'); 71 } 72 73 list($resourceType) = $this->extractAttributes($request); 74 75 /* 76 * @var ResourceInterface $resourceType 77 */ 78 79 $serializedData = $this->serializer->normalize( 80 $preference, 81 'json', 82 $resourceType->getNormalizationContext() 83 ); 84 85 return new JsonResponse($serializedData); 86 } 87 }