PartPutAction.php (2728B)
1 <?php 2 3 namespace PartKeepr\PartBundle\Action; 4 5 use Dunglas\ApiBundle\Action\ActionUtilTrait; 6 use Dunglas\ApiBundle\Api\ResourceInterface; 7 use Dunglas\ApiBundle\Exception\RuntimeException; 8 use Dunglas\ApiBundle\Model\DataProviderInterface; 9 use PartKeepr\AuthBundle\Exceptions\UserLimitReachedException; 10 use PartKeepr\AuthBundle\Exceptions\UserProtectedException; 11 use PartKeepr\PartBundle\Entity\Part; 12 use PartKeepr\PartBundle\Exceptions\InternalPartNumberNotUniqueException; 13 use PartKeepr\PartBundle\Services\PartService; 14 use Symfony\Component\HttpFoundation\Request; 15 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; 16 use Symfony\Component\Serializer\SerializerInterface; 17 18 class PartPutAction 19 { 20 use ActionUtilTrait; 21 22 /** 23 * @var DataProviderInterface 24 */ 25 private $dataProvider; 26 27 /** 28 * @var SerializerInterface 29 */ 30 private $serializer; 31 32 /** 33 * @var PartService 34 */ 35 private $partService; 36 37 public function __construct( 38 DataProviderInterface $dataProvider, 39 SerializerInterface $serializer, 40 PartService $partService 41 ) { 42 $this->dataProvider = $dataProvider; 43 $this->serializer = $serializer; 44 $this->partService = $partService; 45 } 46 47 /** 48 * Create a new item. 49 * 50 * @param Request $request 51 * @param string|int $id 52 * 53 * @throws NotFoundHttpException 54 * @throws RuntimeException 55 * @throws UserProtectedException 56 * @throws UserLimitReachedException 57 * 58 * @return mixed 59 */ 60 public function __invoke(Request $request, $id) 61 { 62 /** 63 * @var ResourceInterface 64 */ 65 list($resourceType, $format) = $this->extractAttributes($request); 66 67 /* 68 * Workaround to ensure stockLevels are not overwritten in a PUT request. 69 * @see https://github.com/partkeepr/PartKeepr/issues/551 70 */ 71 $data = json_decode($request->getContent(), true); 72 73 if (array_key_exists('stockLevels', $data)) { 74 unset($data['stockLevels']); 75 } 76 77 $requestData = json_encode($data); 78 79 $data = $this->getItem($this->dataProvider, $resourceType, $id); 80 81 $context = $resourceType->getDenormalizationContext(); 82 $context['object_to_populate'] = $data; 83 84 /** 85 * @var Part 86 */ 87 $part = $this->serializer->deserialize( 88 $requestData, 89 $resourceType->getEntityClass(), 90 $format, 91 $context 92 ); 93 94 if (!$this->partService->isInternalPartNumberUnique($part->getInternalPartNumber(), $part)) { 95 throw new InternalPartNumberNotUniqueException(); 96 } 97 98 return $part; 99 } 100 }