-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathEntityManager.php
More file actions
318 lines (271 loc) · 10.2 KB
/
Copy pathEntityManager.php
File metadata and controls
318 lines (271 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
<?php
namespace Mouf\Doctrine\ORM;
use Doctrine\Common\Cache\CacheProvider;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Tools\SchemaTool;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Configuration;
use Doctrine\Common\EventManager;
use Doctrine\ORM\ORMException;
use Mouf\Composer\ClassNameMapper;
use Mouf\Validator\MoufValidatorInterface;
use Mouf\Validator\MoufValidatorResult;
use Mouf\MoufManager;
/**
* This is a very simple wrapper around Doctrine's EntityManager that exposes its contructor as "public".
* This allows calling the constructor directly using Mouf.
*
* @author David Négrier <[email protected]>
* @ExtendedAction {"name":"Generate DAOs", "url":"entityManagerInstall/", "default":false}
* @ExtendedAction {"name":"Update DB schema", "url":"entityManagerInstall/generate_schema", "default":false}
*/
class EntityManager extends \Doctrine\ORM\EntityManager implements MoufValidatorInterface,MoufEntityManagerInterface
{
private $entitiesNamespace;
private $proxyNamespace;
private $daoNamespace;
/**
* Creates a new EntityManager that operates on the given database connection
* and uses the given Configuration and EventManager implementations.
*
* @param \Doctrine\DBAL\Connection $conn
* @param \Doctrine\ORM\Configuration $config
* @param \Doctrine\Common\EventManager $eventManager
*/
public function __construct(Connection $conn, Configuration $config, EventManager $eventManager)
{
// Those security checks are usually performed in EntityManager::create
if (! $config->getMetadataDriverImpl()) {
throw ORMException::missingMappingDriverImpl();
}
if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
throw ORMException::mismatchedEventManager();
}
parent::__construct($conn, $config, $eventManager);
}
public function updateSchema()
{
$metadata = $this->getMetadataFactory()->getAllMetadata();
if (! empty($metadata)) {
$tool = new SchemaTool($this);
$fileName = ROOT_PATH.'dump.sql';
$sqls = $tool->getCreateSchemaSql($metadata);
$dump = '';
foreach ($sqls as $sql) {
$dump .= $sql.";\n";
}
file_put_contents($fileName, $dump);
$tool->updateSchema($metadata);
}
return $fileName;
}
public function getSchemaUpdateSQL()
{
$doctrineCache = $this->getConfiguration()->getMetadataCacheImpl();
if ($doctrineCache instanceof CacheProvider) {
$doctrineCache->deleteAll();
} else {
$doctrineCache->delete("*");
}
$metadata = $this->getMetadataFactory()->getAllMetadata();
$sql = array();
if (! empty($metadata)) {
$tool = new SchemaTool($this);
$sql = $tool->getUpdateSchemaSql($metadata);
}
return $sql;
}
public function generateDAOs()
{
//Get Bean / Table list
$metadata = $this->getMetadataFactory()->getAllMetadata();
$daos = array();
foreach ($metadata as $data) {
// we should check that we generate DAOs only for the root package (not the other entities of other packages)
$refClass = new \ReflectionClass($data->name);
$vendorDir = realpath(__DIR__.'/../../../');
$classFile = $refClass->getFileName();
if (strpos($classFile, $vendorDir) === 0) {
continue;
}
list($fullClassName, $className) = $this->generateDAO($data);
$daos[$fullClassName] = $className;
}
return $daos;
}
private function generateDAO($data)
{
//Get Path where to generate dao files
$classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../composer.json');
/* @var $data ClassMetaData */
$entityClass = $data->name;
$entityName = basename(str_replace("\\", '/', $data->name));
$tableName = $data->table['name'];
$daoClassName = $entityName.'Dao';
$daoBaseClassName = $entityName.'BaseDao';
$daoPath = ROOT_PATH.'/'.$classNameMapper->getPossibleFileNames(rtrim($this->daoNamespace, '\\').'\\'.$daoClassName)[0];
$daoBasePath = ROOT_PATH.'/'.$classNameMapper->getPossibleFileNames(rtrim($this->daoNamespace, '\\').'\\'.$daoBaseClassName)[0];
$daoDir = dirname($daoPath);
if (!is_dir($daoDir)) {
$oldUmask = umask();
umask(0);
$dirCreate = mkdir($daoDir, 0775, true);
umask($oldUmask);
}
//generate magic _call functions : findOne & find By field
$magicCallsStr = '';
$magicCallMethodAnnotation = '';
foreach ($data->fieldNames as $fieldName) {
if (array_search($fieldName, $data->identifier) === false) {
$field = \Doctrine\Common\Util\Inflector::classify(str_replace('.', ' ', $fieldName));
$magicCallMethodAnnotation .=" * @method $entityName findBy$field(\$fieldValue, \$orderBy = null, \$limit = null, \$offset = null)
* @method $entityName findOneBy$field(\$fieldValue, \$orderBy = null)
";
$magicCallsStr .= " /**
* Finds only one entity by $field.
* Throw an exception if more than one entity was found.
*
* @param mixed \$fieldValue the value of the filtered field
*
* @return $entityName
*/
public function findUniqueBy$field(\$fieldValue)
{
return \$this->findUniqueBy(array(".var_export($fieldName, true)." => \$fieldValue));
}
";
}
}
$str = "<?php
/*
* This file has been automatically generated by Mouf/ORM.
* DO NOT edit this file, as it might be overwritten.
* If you need to perform changes, edit the $daoClassName class instead!
*/
namespace $this->daoNamespace;
use Doctrine\\ORM\\EntityManagerInterface;
use Doctrine\\ORM\\EntityRepository;
use Doctrine\\ORM\\NonUniqueResultException;
use Mouf\\Doctrine\\ORM\\Event\\SaveListenerInterface;
use $entityClass;
/**
* The $daoBaseClassName class will maintain the persistence of $entityName class into the $tableName table.
*
$magicCallMethodAnnotation
*/
class $daoBaseClassName extends EntityRepository
{
/**
* @var SaveListenerInterface[]
*/
private \$saveListenerCollection;
/**
* @param EntityManagerInterface \$entityManager
* @param SaveListenerInterface[] \$saveListenerCollection
*/
public function __construct(EntityManagerInterface \$entityManager, array \$saveListenerCollection = [])
{
parent::__construct(\$entityManager, \$entityManager->getClassMetadata('$entityClass'));
\$this->saveListenerCollection = \$saveListenerCollection;
}
/**
* Get a new persistent entity
* @param ...\$params
* @return $entityName
*/
public function create(...\$params) : $entityName
{
\$entity = new $entityName(...\$params);
\$this->getEntityManager()->persist(\$entity);
return \$entity;
}
/**
* Peforms a flush on the entity.
*
* @param $entityName
* @throws \\Exception
*/
public function save($entityName \$entity)
{
foreach (\$this->saveListenerCollection as \$saveListener) {
\$saveListener->preSave(\$entity);
}
\$this->getEntityManager()->flush(\$entity);
foreach (\$this->saveListenerCollection as \$saveListener) {
\$saveListener->postSave(\$entity);
}
}
/**
* Peforms remove on the entity.
*
* @param $entityName \$entity
*/
public function remove($entityName \$entity)
{
\$this->getEntityManager()->remove(\$entity);
}
/**
* Finds only one entity. The criteria must contain all the elements needed to find a unique entity.
* Throw an exception if more than one entity was found.
*
* @param array \$criteria
*
* @return $entityName|null
*/
public function findUniqueBy(array \$criteria) : ?$entityName
{
\$result = \$this->findBy(\$criteria);
if (count(\$result) === 1) {
return \$result[0];
} elseif (count(\$result) > 1) {
throw new NonUniqueResultException('More than one $entityName was found');
} else {
return null;
}
}
$magicCallsStr}
";
file_put_contents($daoBasePath, $str);
@chmod($daoBasePath, 0664);
$str = "<?php
namespace $this->daoNamespace;
/**
* The $daoClassName class will maintain the persistence of $entityName class into the $tableName table.
*/
class $daoClassName extends $daoBaseClassName {
/*** PUT YOUR SPECIFIC QUERIES HERE !! ***/
}";
if (!file_exists($daoPath)) {
file_put_contents($daoPath, $str);
chmod($daoPath, 0664);
}
return array($this->daoNamespace."\\".$daoClassName , $daoClassName);
}
public function setEntitiesNamespace($entitiesNamespace)
{
$this->entitiesNamespace = $entitiesNamespace;
}
public function setProxyNamespace($proxyNamespace)
{
$this->proxyNamespace = $proxyNamespace;
}
public function setDaoNamespace($daoNamespace)
{
$this->daoNamespace = $daoNamespace;
}
/**
* (non-PHPdoc).
*
* @see \Mouf\Validator\MoufValidatorInterface::validateInstance()
*/
public function validateInstance()
{
$instanceName = MoufManager::getMoufManager()->findInstanceName($this);
$sql = $this->getSchemaUpdateSQL();
// Let's validate that the schema and the entities do match
if (! empty($sql)) {
return new MoufValidatorResult(MoufValidatorResult::ERROR, "<b>Doctrine ORM:</b> Your database schema does not match the Doctrine entities in your code. <a href='".ROOT_URL.'vendor/mouf/mouf/entityManagerInstall/generate_schema?name='.$instanceName."&selfedit=false' class='btn btn-danger'><i class='icon icon-white icon-wrench'></i> Fix database schema to match entities</a>");
}
return new MoufValidatorResult(MoufValidatorResult::SUCCESS, '<b>Doctrine ORM:</b> Your database schema matches your entities.');
}
}