|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * This file is part of the EcommitUtilBundle package. |
| 5 | + * |
| 6 | + * (c) E-commit <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Ecommit\UtilBundle\Doctrine; |
| 13 | + |
| 14 | +use Doctrine\Bundle\DoctrineBundle\Registry; |
| 15 | + |
| 16 | +class ClearEntityManager |
| 17 | +{ |
| 18 | + /** |
| 19 | + * @var Registry |
| 20 | + */ |
| 21 | + protected $doctrine; |
| 22 | + |
| 23 | + /** |
| 24 | + * @var array |
| 25 | + */ |
| 26 | + protected $snapshots = array(); |
| 27 | + |
| 28 | + public function __construct(Registry $registry) |
| 29 | + { |
| 30 | + $this->doctrine = $registry; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * EntityManager snapshot |
| 35 | + * @param string|null $managerName |
| 36 | + */ |
| 37 | + public function snapshotEntityManager($managerName = null) |
| 38 | + { |
| 39 | + if (null === $managerName) { |
| 40 | + $managerName = $this->doctrine->getDefaultConnectionName(); |
| 41 | + } |
| 42 | + $this->snapshots[$managerName] = $this->doctrine->getManager($managerName)->getUnitOfWork()->getIdentityMap(); |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Detach all objects in EntityManager persisted since snapshot |
| 47 | + * @param string|null $managerName |
| 48 | + */ |
| 49 | + public function clearEntityManager($managerName = null) |
| 50 | + { |
| 51 | + if (null === $managerName) { |
| 52 | + $managerName = $this->doctrine->getDefaultConnectionName(); |
| 53 | + } |
| 54 | + if (!array_key_exists($managerName, $this->snapshots)) { |
| 55 | + throw new \Exception('The snapshot was not done'); |
| 56 | + } |
| 57 | + $snapshot = $this->snapshots[$managerName]; |
| 58 | + |
| 59 | + $em = $this->doctrine->getManager($managerName); |
| 60 | + $identityMap = $em->getUnitOfWork()->getIdentityMap(); |
| 61 | + foreach ($identityMap as $class => $objects) { |
| 62 | + foreach ($objects as $id => $object) { |
| 63 | + if (!array_key_exists($class, $snapshot) || !array_key_exists($id, $snapshot[$class])) { |
| 64 | + $em->detach($object); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments