/** * @param EntityInterface[] $entities * @param int $batchLimit default to 10 */ public function batchPersistAndFlush(array $entities, $batchLimit = 10) { $manager = $this->managerRegistry->getManagerForClass($this->repository->getClassName()); $counter = 0; $entitiesToFlush = array(); foreach ($entities as $entity) { $manager->persist($entity); $entitiesToFlush[] = $entity; if (0 === ++$counter % $batchLimit) { $manager->flush($entitiesToFlush); $entitiesToFlush = array(); } } if (0 !== $counter % $batchLimit) { $manager->flush($entitiesToFlush); } }
/** * @dataProvider getTestBatchPersistAndFlushData * @param int $batchLimit * @param array $entityList * @param array $entitiesToFlushList */ public function testBatchPersistAndFlush($batchLimit, array $entityList, array $entitiesToFlushList) { $className = 'AppBundle\\Entity\\EntityInterface'; /** @var DoctrineObjectManager|ObjectProphecy $manager */ $manager = $this->prophesize('Doctrine\\Common\\Persistence\\ObjectManager'); $this->repository->getClassName()->willReturn($className)->shouldBeCalledTimes(1); $this->managerRegistry->getManagerForClass($className)->willReturn($manager->reveal())->shouldBeCalledTimes(1); foreach ($entityList as $entity) { $manager->persist($entity)->shouldBeCalledTimes(1); } foreach ($entitiesToFlushList as $entitiesToFlush) { $manager->flush($entitiesToFlush)->shouldBeCalledTimes(1); } $this->manager->batchPersistAndFlush($entityList, $batchLimit); }