partkeepr

fork of partkeepr
git clone https://git.e1e0.net/partkeepr.git
Log | Files | Refs | Submodules | README | LICENSE

SetPreferenceAction.php (2061B)


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