protected function createAndPersistData()
 {
     foreach ($this->getReferences('product') as $product) {
         $productStock = new ProductStock();
         $productStock->setProduct($product)->setQuantity(rand(0, 1000));
         $warehouse = $this->getReference(sprintf('warehouse_%s', rand(1, 10)));
         $productStock->setWarehouse($warehouse);
         $this->manager->persist($productStock);
     }
 }
 private function updateStock(Income $income)
 {
     $em = $this->getDoctrine()->getManager();
     $stockRepo = $em->getRepository('AppBundle:ProductStock');
     $elements = $income->getElements();
     $productsStock = array();
     /** @var IncomeElement $element */
     foreach ($elements as $element) {
         $pId = $element->getProduct()->getId();
         if (!isset($productsStock[$pId])) {
             $productsStock[$pId] = 0;
         }
         $productsStock[$pId] += $element->getQuantity();
     }
     $currentProducts = $stockRepo->findCurrentForMany(array_keys($productsStock));
     foreach ($elements as $element) {
         $pId = $element->getProduct()->getId();
         // prevent saving stock if there are multiple elements for one product
         if (!isset($productsStock[$pId])) {
             continue;
         }
         if (isset($currentProducts[$pId])) {
             /** @var ProductStock $oldStock */
             $oldStock = $currentProducts[$pId];
             $newStockValue = $oldStock->getStock() + $productsStock[$pId];
         } else {
             $newStockValue = $productsStock[$pId];
         }
         $newStock = new ProductStock();
         $newStock->setProduct($element->getProduct())->setStock($newStockValue);
         $em->persist($newStock);
         unset($productsStock[$pId]);
     }
     $em->flush();
 }