Skip to content

Commit da52478

Browse files
committed
Add ClearEntityManager
1 parent 88cf8e8 commit da52478

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

Doctrine/ClearEntityManager.php

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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+
}

Resources/config/services.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,5 +13,9 @@
1313
<service id="ecommit_util.cache" class="Ecommit\UtilBundle\Cache\Cache" abstract="true" public="false">
1414
<argument /> <!-- Options -->
1515
</service>
16+
17+
<service id="ecommit_util.clear_entity_manager" class="Ecommit\UtilBundle\Doctrine\ClearEntityManager">
18+
<argument type="service" id="doctrine" />
19+
</service>
1620
</services>
1721
</container>

0 commit comments

Comments
 (0)