GetPartsAction.php (1914B)
1 <?php 2 3 namespace PartKeepr\PartBundle\Action; 4 5 use Doctrine\ORM\EntityManager; 6 use Dunglas\ApiBundle\Action\ActionUtilTrait; 7 use Dunglas\ApiBundle\Exception\RuntimeException; 8 use Dunglas\ApiBundle\Model\DataProviderInterface; 9 use PartKeepr\PartBundle\Entity\Part; 10 use PartKeepr\PartBundle\Services\PartService; 11 use Symfony\Component\HttpFoundation\Request; 12 13 /** 14 * Default API action retrieving a collection of resources. 15 * 16 * @author Kévin Dunglas <dunglas@gmail.com> 17 */ 18 class GetPartsAction 19 { 20 use ActionUtilTrait; 21 22 /** 23 * @var DataProviderInterface 24 */ 25 private $dataProvider; 26 27 /** 28 * @var EntityManager 29 */ 30 private $em; 31 32 /** 33 * @var PartService 34 */ 35 private $partService; 36 37 public function __construct(DataProviderInterface $dataProvider, EntityManager $em, PartService $partService) 38 { 39 $this->dataProvider = $dataProvider; 40 $this->em = $em; 41 $this->partService = $partService; 42 } 43 44 /** 45 * Retrieves a collection of resources. 46 * 47 * @param Request $request 48 * 49 * @throws RuntimeException 50 * 51 * @return array|\Dunglas\ApiBundle\Model\PaginatorInterface|\Traversable 52 */ 53 public function __invoke(Request $request) 54 { 55 list($resourceType) = $this->extractAttributes($request); 56 57 $items = $this->dataProvider->getCollection($resourceType); 58 59 /** 60 * @var Part 61 */ 62 foreach ($items as $part) { 63 if ($part->isMetaPart()) { 64 $sum = 0; 65 66 $parts = $this->partService->getMatchingMetaParts($part); 67 68 foreach ($parts as $matchingPart) { 69 /** 70 * @var Part 71 */ 72 $sum += $matchingPart->getStockLevel(); 73 } 74 75 $part->setStockLevel($sum); 76 } 77 } 78 79 return $items; 80 } 81 }