Test Failed
Pull Request — 4.2 (#140)
by David
04:46
created
src/Mouf/Database/TDBM/MoufConfiguration.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -17,21 +17,21 @@
 block discarded – undo
17 17
  */
18 18
 class MoufConfiguration extends Configuration
19 19
 {
20
-    private $daoFactoryInstanceName = 'daoFactory';
20
+	private $daoFactoryInstanceName = 'daoFactory';
21 21
 
22
-    /**
23
-     * @return string
24
-     */
25
-    public function getDaoFactoryInstanceName() : string
26
-    {
27
-        return $this->daoFactoryInstanceName;
28
-    }
22
+	/**
23
+	 * @return string
24
+	 */
25
+	public function getDaoFactoryInstanceName() : string
26
+	{
27
+		return $this->daoFactoryInstanceName;
28
+	}
29 29
 
30
-    /**
31
-     * @param string $daoFactoryInstanceName
32
-     */
33
-    public function setDaoFactoryInstanceName(string $daoFactoryInstanceName)
34
-    {
35
-        $this->daoFactoryInstanceName = $daoFactoryInstanceName;
36
-    }
30
+	/**
31
+	 * @param string $daoFactoryInstanceName
32
+	 */
33
+	public function setDaoFactoryInstanceName(string $daoFactoryInstanceName)
34
+	{
35
+		$this->daoFactoryInstanceName = $daoFactoryInstanceName;
36
+	}
37 37
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMObject.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -33,42 +33,42 @@
 block discarded – undo
33 33
  */
34 34
 class TDBMObject extends AbstractTDBMObject
35 35
 {
36
-    public function getProperty($var, $tableName = null)
37
-    {
38
-        return $this->get($var, $tableName);
39
-    }
36
+	public function getProperty($var, $tableName = null)
37
+	{
38
+		return $this->get($var, $tableName);
39
+	}
40 40
 
41
-    public function setProperty($var, $value, $tableName = null)
42
-    {
43
-        $this->set($var, $value, $tableName);
44
-    }
41
+	public function setProperty($var, $value, $tableName = null)
42
+	{
43
+		$this->set($var, $value, $tableName);
44
+	}
45 45
 
46
-    /**
47
-     * Specify data which should be serialized to JSON.
48
-     *
49
-     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
50
-     *
51
-     * @return mixed data which can be serialized by <b>json_encode</b>,
52
-     *               which is a value of any type other than a resource
53
-     *
54
-     * @since 5.4.0
55
-     */
56
-    public function jsonSerialize()
57
-    {
58
-        throw new TDBMException('Json serialization is only implemented for generated beans.');
59
-    }
46
+	/**
47
+	 * Specify data which should be serialized to JSON.
48
+	 *
49
+	 * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
50
+	 *
51
+	 * @return mixed data which can be serialized by <b>json_encode</b>,
52
+	 *               which is a value of any type other than a resource
53
+	 *
54
+	 * @since 5.4.0
55
+	 */
56
+	public function jsonSerialize()
57
+	{
58
+		throw new TDBMException('Json serialization is only implemented for generated beans.');
59
+	}
60 60
 
61
-    /**
62
-     * Returns an array of used tables by this bean (from parent to child relationship).
63
-     *
64
-     * @return string[]
65
-     */
66
-    protected function getUsedTables() : array
67
-    {
68
-        $tableNames = array_keys($this->dbRows);
69
-        $tableNames = $this->tdbmService->_getLinkBetweenInheritedTables($tableNames);
70
-        $tableNames = array_reverse($tableNames);
61
+	/**
62
+	 * Returns an array of used tables by this bean (from parent to child relationship).
63
+	 *
64
+	 * @return string[]
65
+	 */
66
+	protected function getUsedTables() : array
67
+	{
68
+		$tableNames = array_keys($this->dbRows);
69
+		$tableNames = $this->tdbmService->_getLinkBetweenInheritedTables($tableNames);
70
+		$tableNames = array_reverse($tableNames);
71 71
 
72
-        return $tableNames;
73
-    }
72
+		return $tableNames;
73
+	}
74 74
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/AbstractTDBMObject.php 1 patch
Indentation   +606 added lines, -606 removed lines patch added patch discarded remove patch
@@ -31,615 +31,615 @@
 block discarded – undo
31 31
  */
32 32
 abstract class AbstractTDBMObject implements JsonSerializable
33 33
 {
34
-    /**
35
-     * The service this object is bound to.
36
-     *
37
-     * @var TDBMService
38
-     */
39
-    protected $tdbmService;
40
-
41
-    /**
42
-     * An array of DbRow, indexed by table name.
43
-     *
44
-     * @var DbRow[]
45
-     */
46
-    protected $dbRows = [];
47
-
48
-    /**
49
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
50
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
51
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
52
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
53
-     *
54
-     * @var string
55
-     */
56
-    private $status;
57
-
58
-    /**
59
-     * Array storing beans related via many to many relationships (pivot tables).
60
-     *
61
-     * @var \SplObjectStorage[] Key: pivot table name, value: SplObjectStorage
62
-     */
63
-    private $relationships = [];
64
-
65
-    /**
66
-     * @var bool[] Key: pivot table name, value: whether a query was performed to load the data
67
-     */
68
-    private $loadedRelationships = [];
69
-
70
-    /**
71
-     * Array storing beans related via many to one relationships (this bean is pointed by external beans).
72
-     *
73
-     * @var AlterableResultIterator[] Key: [external_table]___[external_column], value: SplObjectStorage
74
-     */
75
-    private $manyToOneRelationships = [];
76
-
77
-    /**
78
-     * Used with $primaryKeys when we want to retrieve an existing object
79
-     * and $primaryKeys=[] if we want a new object.
80
-     *
81
-     * @param string      $tableName
82
-     * @param array       $primaryKeys
83
-     * @param TDBMService $tdbmService
84
-     *
85
-     * @throws TDBMException
86
-     * @throws TDBMInvalidOperationException
87
-     */
88
-    public function __construct($tableName = null, array $primaryKeys = [], TDBMService $tdbmService = null)
89
-    {
90
-        // FIXME: lazy loading should be forbidden on tables with inheritance and dynamic type assignation...
91
-        if (!empty($tableName)) {
92
-            $this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
93
-        }
94
-
95
-        if ($tdbmService === null) {
96
-            $this->_setStatus(TDBMObjectStateEnum::STATE_DETACHED);
97
-        } else {
98
-            $this->_attach($tdbmService);
99
-            if (!empty($primaryKeys)) {
100
-                $this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
101
-            } else {
102
-                $this->_setStatus(TDBMObjectStateEnum::STATE_NEW);
103
-            }
104
-        }
105
-    }
106
-
107
-    /**
108
-     * Alternative constructor called when data is fetched from database via a SELECT.
109
-     *
110
-     * @param array       $beanData    array<table, array<column, value>>
111
-     * @param TDBMService $tdbmService
112
-     */
113
-    public function _constructFromData(array $beanData, TDBMService $tdbmService)
114
-    {
115
-        $this->tdbmService = $tdbmService;
116
-
117
-        foreach ($beanData as $table => $columns) {
118
-            $this->dbRows[$table] = new DbRow($this, $table, $tdbmService->_getPrimaryKeysFromObjectData($table, $columns), $tdbmService, $columns);
119
-        }
120
-
121
-        $this->status = TDBMObjectStateEnum::STATE_LOADED;
122
-    }
123
-
124
-    /**
125
-     * Alternative constructor called when bean is lazily loaded.
126
-     *
127
-     * @param string      $tableName
128
-     * @param array       $primaryKeys
129
-     * @param TDBMService $tdbmService
130
-     */
131
-    public function _constructLazy($tableName, array $primaryKeys, TDBMService $tdbmService)
132
-    {
133
-        $this->tdbmService = $tdbmService;
134
-
135
-        $this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
136
-
137
-        $this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
138
-    }
139
-
140
-    public function _attach(TDBMService $tdbmService)
141
-    {
142
-        if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
143
-            throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
144
-        }
145
-        $this->tdbmService = $tdbmService;
146
-
147
-        // If we attach this object, we must work to make sure the tables are in ascending order (from low level to top level)
148
-        $tableNames = $this->getUsedTables();
149
-
150
-        $newDbRows = [];
151
-
152
-        foreach ($tableNames as $table) {
153
-            if (!isset($this->dbRows[$table])) {
154
-                $this->registerTable($table);
155
-            }
156
-            $newDbRows[$table] = $this->dbRows[$table];
157
-        }
158
-        $this->dbRows = $newDbRows;
159
-
160
-        $this->status = TDBMObjectStateEnum::STATE_NEW;
161
-        foreach ($this->dbRows as $dbRow) {
162
-            $dbRow->_attach($tdbmService);
163
-        }
164
-    }
165
-
166
-    /**
167
-     * Sets the state of the TDBM Object
168
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
169
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
170
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
171
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
172
-     *
173
-     * @param string $state
174
-     */
175
-    public function _setStatus($state)
176
-    {
177
-        $this->status = $state;
178
-
179
-        // TODO: we might ignore the loaded => dirty state here! dirty status comes from the db_row itself.
180
-        foreach ($this->dbRows as $dbRow) {
181
-            $dbRow->_setStatus($state);
182
-        }
183
-
184
-        if ($state === TDBMObjectStateEnum::STATE_DELETED) {
185
-            $this->onDelete();
186
-        }
187
-    }
188
-
189
-    /**
190
-     * Checks that $tableName is ok, or returns the only possible table name if "$tableName = null"
191
-     * or throws an error.
192
-     *
193
-     * @param string $tableName
194
-     *
195
-     * @return string
196
-     */
197
-    private function checkTableName($tableName = null)
198
-    {
199
-        if ($tableName === null) {
200
-            if (count($this->dbRows) > 1) {
201
-                throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
202
-            } elseif (count($this->dbRows) === 1) {
203
-                $tableName = array_keys($this->dbRows)[0];
204
-            }
205
-        }
206
-
207
-        return $tableName;
208
-    }
209
-
210
-    protected function get($var, $tableName = null)
211
-    {
212
-        $tableName = $this->checkTableName($tableName);
213
-
214
-        if (!isset($this->dbRows[$tableName])) {
215
-            return;
216
-        }
217
-
218
-        return $this->dbRows[$tableName]->get($var);
219
-    }
220
-
221
-    protected function set($var, $value, $tableName = null)
222
-    {
223
-        if ($tableName === null) {
224
-            if (count($this->dbRows) > 1) {
225
-                throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
226
-            } elseif (count($this->dbRows) === 1) {
227
-                $tableName = array_keys($this->dbRows)[0];
228
-            } else {
229
-                throw new TDBMException('Please specify a table for this object.');
230
-            }
231
-        }
232
-
233
-        if (!isset($this->dbRows[$tableName])) {
234
-            $this->registerTable($tableName);
235
-        }
236
-
237
-        $this->dbRows[$tableName]->set($var, $value);
238
-        if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
239
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
240
-        }
241
-    }
242
-
243
-    /**
244
-     * @param string             $foreignKeyName
245
-     * @param AbstractTDBMObject $bean
246
-     */
247
-    protected function setRef($foreignKeyName, AbstractTDBMObject $bean = null, $tableName = null)
248
-    {
249
-        if ($tableName === null) {
250
-            if (count($this->dbRows) > 1) {
251
-                throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
252
-            } elseif (count($this->dbRows) === 1) {
253
-                $tableName = array_keys($this->dbRows)[0];
254
-            } else {
255
-                throw new TDBMException('Please specify a table for this object.');
256
-            }
257
-        }
258
-
259
-        if (!isset($this->dbRows[$tableName])) {
260
-            $this->registerTable($tableName);
261
-        }
262
-
263
-        $oldLinkedBean = $this->dbRows[$tableName]->getRef($foreignKeyName);
264
-        if ($oldLinkedBean !== null) {
265
-            $oldLinkedBean->removeManyToOneRelationship($tableName, $foreignKeyName, $this);
266
-        }
267
-
268
-        $this->dbRows[$tableName]->setRef($foreignKeyName, $bean);
269
-        if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
270
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
271
-        }
272
-
273
-        if ($bean !== null) {
274
-            $bean->setManyToOneRelationship($tableName, $foreignKeyName, $this);
275
-        }
276
-    }
277
-
278
-    /**
279
-     * @param string $foreignKeyName A unique name for this reference
280
-     *
281
-     * @return AbstractTDBMObject|null
282
-     */
283
-    protected function getRef($foreignKeyName, $tableName = null)
284
-    {
285
-        $tableName = $this->checkTableName($tableName);
286
-
287
-        if (!isset($this->dbRows[$tableName])) {
288
-            return;
289
-        }
290
-
291
-        return $this->dbRows[$tableName]->getRef($foreignKeyName);
292
-    }
293
-
294
-    /**
295
-     * Adds a many to many relationship to this bean.
296
-     *
297
-     * @param string             $pivotTableName
298
-     * @param AbstractTDBMObject $remoteBean
299
-     */
300
-    protected function addRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
301
-    {
302
-        $this->setRelationship($pivotTableName, $remoteBean, 'new');
303
-    }
304
-
305
-    /**
306
-     * Returns true if there is a relationship to this bean.
307
-     *
308
-     * @param string             $pivotTableName
309
-     * @param AbstractTDBMObject $remoteBean
310
-     *
311
-     * @return bool
312
-     */
313
-    protected function hasRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
314
-    {
315
-        $storage = $this->retrieveRelationshipsStorage($pivotTableName);
316
-
317
-        if ($storage->contains($remoteBean)) {
318
-            if ($storage[$remoteBean]['status'] !== 'delete') {
319
-                return true;
320
-            }
321
-        }
322
-
323
-        return false;
324
-    }
325
-
326
-    /**
327
-     * Internal TDBM method. Removes a many to many relationship from this bean.
328
-     *
329
-     * @param string             $pivotTableName
330
-     * @param AbstractTDBMObject $remoteBean
331
-     */
332
-    public function _removeRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
333
-    {
334
-        if (isset($this->relationships[$pivotTableName][$remoteBean]) && $this->relationships[$pivotTableName][$remoteBean]['status'] === 'new') {
335
-            unset($this->relationships[$pivotTableName][$remoteBean]);
336
-            unset($remoteBean->relationships[$pivotTableName][$this]);
337
-        } else {
338
-            $this->setRelationship($pivotTableName, $remoteBean, 'delete');
339
-        }
340
-    }
341
-
342
-    /**
343
-     * Sets many to many relationships for this bean.
344
-     * Adds new relationships and removes unused ones.
345
-     *
346
-     * @param $pivotTableName
347
-     * @param array $remoteBeans
348
-     */
349
-    protected function setRelationships($pivotTableName, array $remoteBeans)
350
-    {
351
-        $storage = $this->retrieveRelationshipsStorage($pivotTableName);
352
-
353
-        foreach ($storage as $oldRemoteBean) {
354
-            if (!in_array($oldRemoteBean, $remoteBeans, true)) {
355
-                // $oldRemoteBean must be removed
356
-                $this->_removeRelationship($pivotTableName, $oldRemoteBean);
357
-            }
358
-        }
359
-
360
-        foreach ($remoteBeans as $remoteBean) {
361
-            if (!$storage->contains($remoteBean) || $storage[$remoteBean]['status'] === 'delete') {
362
-                // $remoteBean must be added
363
-                $this->addRelationship($pivotTableName, $remoteBean);
364
-            }
365
-        }
366
-    }
367
-
368
-    /**
369
-     * Returns the list of objects linked to this bean via $pivotTableName.
370
-     *
371
-     * @param $pivotTableName
372
-     *
373
-     * @return \SplObjectStorage
374
-     */
375
-    private function retrieveRelationshipsStorage($pivotTableName)
376
-    {
377
-        $storage = $this->getRelationshipStorage($pivotTableName);
378
-        if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->loadedRelationships[$pivotTableName]) && $this->loadedRelationships[$pivotTableName])) {
379
-            return $storage;
380
-        }
381
-
382
-        $beans = $this->tdbmService->_getRelatedBeans($pivotTableName, $this);
383
-        $this->loadedRelationships[$pivotTableName] = true;
384
-
385
-        foreach ($beans as $bean) {
386
-            if (isset($storage[$bean])) {
387
-                $oldStatus = $storage[$bean]['status'];
388
-                if ($oldStatus === 'delete') {
389
-                    // Keep deleted things deleted
390
-                    continue;
391
-                }
392
-            }
393
-            $this->setRelationship($pivotTableName, $bean, 'loaded');
394
-        }
395
-
396
-        return $storage;
397
-    }
398
-
399
-    /**
400
-     * Internal TDBM method. Returns the list of objects linked to this bean via $pivotTableName.
401
-     *
402
-     * @param $pivotTableName
403
-     *
404
-     * @return AbstractTDBMObject[]
405
-     */
406
-    public function _getRelationships($pivotTableName)
407
-    {
408
-        return $this->relationshipStorageToArray($this->retrieveRelationshipsStorage($pivotTableName));
409
-    }
410
-
411
-    private function relationshipStorageToArray(\SplObjectStorage $storage)
412
-    {
413
-        $beans = [];
414
-        foreach ($storage as $bean) {
415
-            $statusArr = $storage[$bean];
416
-            if ($statusArr['status'] !== 'delete') {
417
-                $beans[] = $bean;
418
-            }
419
-        }
420
-
421
-        return $beans;
422
-    }
423
-
424
-    /**
425
-     * Declares a relationship between.
426
-     *
427
-     * @param string             $pivotTableName
428
-     * @param AbstractTDBMObject $remoteBean
429
-     * @param string             $status
430
-     */
431
-    private function setRelationship($pivotTableName, AbstractTDBMObject $remoteBean, $status)
432
-    {
433
-        $storage = $this->getRelationshipStorage($pivotTableName);
434
-        $storage->attach($remoteBean, ['status' => $status, 'reverse' => false]);
435
-        if ($this->status === TDBMObjectStateEnum::STATE_LOADED) {
436
-            $this->_setStatus(TDBMObjectStateEnum::STATE_DIRTY);
437
-        }
438
-
439
-        $remoteStorage = $remoteBean->getRelationshipStorage($pivotTableName);
440
-        $remoteStorage->attach($this, ['status' => $status, 'reverse' => true]);
441
-    }
442
-
443
-    /**
444
-     * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
445
-     *
446
-     * @param string $pivotTableName
447
-     *
448
-     * @return \SplObjectStorage
449
-     */
450
-    private function getRelationshipStorage(string $pivotTableName) : \SplObjectStorage
451
-    {
452
-        return $this->relationships[$pivotTableName] ?? $this->relationships[$pivotTableName] = new \SplObjectStorage();
453
-    }
454
-
455
-    /**
456
-     * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
457
-     *
458
-     * @param string $tableName
459
-     * @param string $foreignKeyName
460
-     *
461
-     * @return AlterableResultIterator
462
-     */
463
-    private function getManyToOneAlterableResultIterator(string $tableName, string $foreignKeyName) : AlterableResultIterator
464
-    {
465
-        $key = $tableName.'___'.$foreignKeyName;
466
-
467
-        return $this->manyToOneRelationships[$key] ?? $this->manyToOneRelationships[$key] = new AlterableResultIterator();
468
-    }
469
-
470
-    /**
471
-     * Declares a relationship between this bean and the bean pointing to it.
472
-     *
473
-     * @param string             $tableName
474
-     * @param string             $foreignKeyName
475
-     * @param AbstractTDBMObject $remoteBean
476
-     */
477
-    private function setManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
478
-    {
479
-        $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
480
-        $alterableResultIterator->add($remoteBean);
481
-    }
482
-
483
-    /**
484
-     * Declares a relationship between this bean and the bean pointing to it.
485
-     *
486
-     * @param string             $tableName
487
-     * @param string             $foreignKeyName
488
-     * @param AbstractTDBMObject $remoteBean
489
-     */
490
-    private function removeManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
491
-    {
492
-        $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
493
-        $alterableResultIterator->remove($remoteBean);
494
-    }
495
-
496
-    /**
497
-     * Returns the list of objects linked to this bean via a given foreign key.
498
-     *
499
-     * @param string $tableName
500
-     * @param string $foreignKeyName
501
-     * @param string $searchTableName
502
-     * @param array  $searchFilter
503
-     * @param string $orderString     The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column). WARNING : This parameter is not kept when there is an additionnal or removal object !
504
-     *
505
-     * @return AlterableResultIterator
506
-     */
507
-    protected function retrieveManyToOneRelationshipsStorage(string $tableName, string $foreignKeyName, string $searchTableName, array $searchFilter, $orderString = null) : AlterableResultIterator
508
-    {
509
-        $key = $tableName.'___'.$foreignKeyName;
510
-        $alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
511
-        if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->manyToOneRelationships[$key]) && $this->manyToOneRelationships[$key]->getUnderlyingResultIterator() !== null)) {
512
-            return $alterableResultIterator;
513
-        }
514
-
515
-        $unalteredResultIterator = $this->tdbmService->findObjects($searchTableName, $searchFilter, [], $orderString);
516
-
517
-        $alterableResultIterator->setResultIterator($unalteredResultIterator->getIterator());
518
-
519
-        return $alterableResultIterator;
520
-    }
521
-
522
-    /**
523
-     * Reverts any changes made to the object and resumes it to its DB state.
524
-     * This can only be called on objects that come from database and that have not been deleted.
525
-     * Otherwise, this will throw an exception.
526
-     *
527
-     * @throws TDBMException
528
-     */
529
-    public function discardChanges()
530
-    {
531
-        if ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->status === TDBMObjectStateEnum::STATE_DETACHED) {
532
-            throw new TDBMException("You cannot call discardChanges() on an object that has been created with the 'new' keyword and that has not yet been saved.");
533
-        }
534
-
535
-        if ($this->status === TDBMObjectStateEnum::STATE_DELETED) {
536
-            throw new TDBMException('You cannot call discardChanges() on an object that has been deleted.');
537
-        }
538
-
539
-        $this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
540
-    }
541
-
542
-    /**
543
-     * Method used internally by TDBM. You should not use it directly.
544
-     * This method returns the status of the TDBMObject.
545
-     * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
546
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
547
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
548
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
549
-     *
550
-     * @return string
551
-     */
552
-    public function _getStatus()
553
-    {
554
-        return $this->status;
555
-    }
556
-
557
-    /**
558
-     * Override the native php clone function for TDBMObjects.
559
-     */
560
-    public function __clone()
561
-    {
562
-        // Let's clone the many to many relationships
563
-        if ($this->status === TDBMObjectStateEnum::STATE_DETACHED) {
564
-            $pivotTableList = array_keys($this->relationships);
565
-        } else {
566
-            $pivotTableList = $this->tdbmService->_getPivotTablesLinkedToBean($this);
567
-        }
568
-
569
-        foreach ($pivotTableList as $pivotTable) {
570
-            $storage = $this->retrieveRelationshipsStorage($pivotTable);
571
-
572
-            // Let's duplicate the reverse side of the relationship // This is useless: already done by "retrieveRelationshipsStorage"!!!
573
-            /*foreach ($storage as $remoteBean) {
34
+	/**
35
+	 * The service this object is bound to.
36
+	 *
37
+	 * @var TDBMService
38
+	 */
39
+	protected $tdbmService;
40
+
41
+	/**
42
+	 * An array of DbRow, indexed by table name.
43
+	 *
44
+	 * @var DbRow[]
45
+	 */
46
+	protected $dbRows = [];
47
+
48
+	/**
49
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
50
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
51
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
52
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
53
+	 *
54
+	 * @var string
55
+	 */
56
+	private $status;
57
+
58
+	/**
59
+	 * Array storing beans related via many to many relationships (pivot tables).
60
+	 *
61
+	 * @var \SplObjectStorage[] Key: pivot table name, value: SplObjectStorage
62
+	 */
63
+	private $relationships = [];
64
+
65
+	/**
66
+	 * @var bool[] Key: pivot table name, value: whether a query was performed to load the data
67
+	 */
68
+	private $loadedRelationships = [];
69
+
70
+	/**
71
+	 * Array storing beans related via many to one relationships (this bean is pointed by external beans).
72
+	 *
73
+	 * @var AlterableResultIterator[] Key: [external_table]___[external_column], value: SplObjectStorage
74
+	 */
75
+	private $manyToOneRelationships = [];
76
+
77
+	/**
78
+	 * Used with $primaryKeys when we want to retrieve an existing object
79
+	 * and $primaryKeys=[] if we want a new object.
80
+	 *
81
+	 * @param string      $tableName
82
+	 * @param array       $primaryKeys
83
+	 * @param TDBMService $tdbmService
84
+	 *
85
+	 * @throws TDBMException
86
+	 * @throws TDBMInvalidOperationException
87
+	 */
88
+	public function __construct($tableName = null, array $primaryKeys = [], TDBMService $tdbmService = null)
89
+	{
90
+		// FIXME: lazy loading should be forbidden on tables with inheritance and dynamic type assignation...
91
+		if (!empty($tableName)) {
92
+			$this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
93
+		}
94
+
95
+		if ($tdbmService === null) {
96
+			$this->_setStatus(TDBMObjectStateEnum::STATE_DETACHED);
97
+		} else {
98
+			$this->_attach($tdbmService);
99
+			if (!empty($primaryKeys)) {
100
+				$this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
101
+			} else {
102
+				$this->_setStatus(TDBMObjectStateEnum::STATE_NEW);
103
+			}
104
+		}
105
+	}
106
+
107
+	/**
108
+	 * Alternative constructor called when data is fetched from database via a SELECT.
109
+	 *
110
+	 * @param array       $beanData    array<table, array<column, value>>
111
+	 * @param TDBMService $tdbmService
112
+	 */
113
+	public function _constructFromData(array $beanData, TDBMService $tdbmService)
114
+	{
115
+		$this->tdbmService = $tdbmService;
116
+
117
+		foreach ($beanData as $table => $columns) {
118
+			$this->dbRows[$table] = new DbRow($this, $table, $tdbmService->_getPrimaryKeysFromObjectData($table, $columns), $tdbmService, $columns);
119
+		}
120
+
121
+		$this->status = TDBMObjectStateEnum::STATE_LOADED;
122
+	}
123
+
124
+	/**
125
+	 * Alternative constructor called when bean is lazily loaded.
126
+	 *
127
+	 * @param string      $tableName
128
+	 * @param array       $primaryKeys
129
+	 * @param TDBMService $tdbmService
130
+	 */
131
+	public function _constructLazy($tableName, array $primaryKeys, TDBMService $tdbmService)
132
+	{
133
+		$this->tdbmService = $tdbmService;
134
+
135
+		$this->dbRows[$tableName] = new DbRow($this, $tableName, $primaryKeys, $tdbmService);
136
+
137
+		$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
138
+	}
139
+
140
+	public function _attach(TDBMService $tdbmService)
141
+	{
142
+		if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
143
+			throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
144
+		}
145
+		$this->tdbmService = $tdbmService;
146
+
147
+		// If we attach this object, we must work to make sure the tables are in ascending order (from low level to top level)
148
+		$tableNames = $this->getUsedTables();
149
+
150
+		$newDbRows = [];
151
+
152
+		foreach ($tableNames as $table) {
153
+			if (!isset($this->dbRows[$table])) {
154
+				$this->registerTable($table);
155
+			}
156
+			$newDbRows[$table] = $this->dbRows[$table];
157
+		}
158
+		$this->dbRows = $newDbRows;
159
+
160
+		$this->status = TDBMObjectStateEnum::STATE_NEW;
161
+		foreach ($this->dbRows as $dbRow) {
162
+			$dbRow->_attach($tdbmService);
163
+		}
164
+	}
165
+
166
+	/**
167
+	 * Sets the state of the TDBM Object
168
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
169
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
170
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
171
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
172
+	 *
173
+	 * @param string $state
174
+	 */
175
+	public function _setStatus($state)
176
+	{
177
+		$this->status = $state;
178
+
179
+		// TODO: we might ignore the loaded => dirty state here! dirty status comes from the db_row itself.
180
+		foreach ($this->dbRows as $dbRow) {
181
+			$dbRow->_setStatus($state);
182
+		}
183
+
184
+		if ($state === TDBMObjectStateEnum::STATE_DELETED) {
185
+			$this->onDelete();
186
+		}
187
+	}
188
+
189
+	/**
190
+	 * Checks that $tableName is ok, or returns the only possible table name if "$tableName = null"
191
+	 * or throws an error.
192
+	 *
193
+	 * @param string $tableName
194
+	 *
195
+	 * @return string
196
+	 */
197
+	private function checkTableName($tableName = null)
198
+	{
199
+		if ($tableName === null) {
200
+			if (count($this->dbRows) > 1) {
201
+				throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
202
+			} elseif (count($this->dbRows) === 1) {
203
+				$tableName = array_keys($this->dbRows)[0];
204
+			}
205
+		}
206
+
207
+		return $tableName;
208
+	}
209
+
210
+	protected function get($var, $tableName = null)
211
+	{
212
+		$tableName = $this->checkTableName($tableName);
213
+
214
+		if (!isset($this->dbRows[$tableName])) {
215
+			return;
216
+		}
217
+
218
+		return $this->dbRows[$tableName]->get($var);
219
+	}
220
+
221
+	protected function set($var, $value, $tableName = null)
222
+	{
223
+		if ($tableName === null) {
224
+			if (count($this->dbRows) > 1) {
225
+				throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
226
+			} elseif (count($this->dbRows) === 1) {
227
+				$tableName = array_keys($this->dbRows)[0];
228
+			} else {
229
+				throw new TDBMException('Please specify a table for this object.');
230
+			}
231
+		}
232
+
233
+		if (!isset($this->dbRows[$tableName])) {
234
+			$this->registerTable($tableName);
235
+		}
236
+
237
+		$this->dbRows[$tableName]->set($var, $value);
238
+		if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
239
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
240
+		}
241
+	}
242
+
243
+	/**
244
+	 * @param string             $foreignKeyName
245
+	 * @param AbstractTDBMObject $bean
246
+	 */
247
+	protected function setRef($foreignKeyName, AbstractTDBMObject $bean = null, $tableName = null)
248
+	{
249
+		if ($tableName === null) {
250
+			if (count($this->dbRows) > 1) {
251
+				throw new TDBMException('This object is based on several tables. You must specify which table you are retrieving data from.');
252
+			} elseif (count($this->dbRows) === 1) {
253
+				$tableName = array_keys($this->dbRows)[0];
254
+			} else {
255
+				throw new TDBMException('Please specify a table for this object.');
256
+			}
257
+		}
258
+
259
+		if (!isset($this->dbRows[$tableName])) {
260
+			$this->registerTable($tableName);
261
+		}
262
+
263
+		$oldLinkedBean = $this->dbRows[$tableName]->getRef($foreignKeyName);
264
+		if ($oldLinkedBean !== null) {
265
+			$oldLinkedBean->removeManyToOneRelationship($tableName, $foreignKeyName, $this);
266
+		}
267
+
268
+		$this->dbRows[$tableName]->setRef($foreignKeyName, $bean);
269
+		if ($this->dbRows[$tableName]->_getStatus() === TDBMObjectStateEnum::STATE_DIRTY) {
270
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
271
+		}
272
+
273
+		if ($bean !== null) {
274
+			$bean->setManyToOneRelationship($tableName, $foreignKeyName, $this);
275
+		}
276
+	}
277
+
278
+	/**
279
+	 * @param string $foreignKeyName A unique name for this reference
280
+	 *
281
+	 * @return AbstractTDBMObject|null
282
+	 */
283
+	protected function getRef($foreignKeyName, $tableName = null)
284
+	{
285
+		$tableName = $this->checkTableName($tableName);
286
+
287
+		if (!isset($this->dbRows[$tableName])) {
288
+			return;
289
+		}
290
+
291
+		return $this->dbRows[$tableName]->getRef($foreignKeyName);
292
+	}
293
+
294
+	/**
295
+	 * Adds a many to many relationship to this bean.
296
+	 *
297
+	 * @param string             $pivotTableName
298
+	 * @param AbstractTDBMObject $remoteBean
299
+	 */
300
+	protected function addRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
301
+	{
302
+		$this->setRelationship($pivotTableName, $remoteBean, 'new');
303
+	}
304
+
305
+	/**
306
+	 * Returns true if there is a relationship to this bean.
307
+	 *
308
+	 * @param string             $pivotTableName
309
+	 * @param AbstractTDBMObject $remoteBean
310
+	 *
311
+	 * @return bool
312
+	 */
313
+	protected function hasRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
314
+	{
315
+		$storage = $this->retrieveRelationshipsStorage($pivotTableName);
316
+
317
+		if ($storage->contains($remoteBean)) {
318
+			if ($storage[$remoteBean]['status'] !== 'delete') {
319
+				return true;
320
+			}
321
+		}
322
+
323
+		return false;
324
+	}
325
+
326
+	/**
327
+	 * Internal TDBM method. Removes a many to many relationship from this bean.
328
+	 *
329
+	 * @param string             $pivotTableName
330
+	 * @param AbstractTDBMObject $remoteBean
331
+	 */
332
+	public function _removeRelationship($pivotTableName, AbstractTDBMObject $remoteBean)
333
+	{
334
+		if (isset($this->relationships[$pivotTableName][$remoteBean]) && $this->relationships[$pivotTableName][$remoteBean]['status'] === 'new') {
335
+			unset($this->relationships[$pivotTableName][$remoteBean]);
336
+			unset($remoteBean->relationships[$pivotTableName][$this]);
337
+		} else {
338
+			$this->setRelationship($pivotTableName, $remoteBean, 'delete');
339
+		}
340
+	}
341
+
342
+	/**
343
+	 * Sets many to many relationships for this bean.
344
+	 * Adds new relationships and removes unused ones.
345
+	 *
346
+	 * @param $pivotTableName
347
+	 * @param array $remoteBeans
348
+	 */
349
+	protected function setRelationships($pivotTableName, array $remoteBeans)
350
+	{
351
+		$storage = $this->retrieveRelationshipsStorage($pivotTableName);
352
+
353
+		foreach ($storage as $oldRemoteBean) {
354
+			if (!in_array($oldRemoteBean, $remoteBeans, true)) {
355
+				// $oldRemoteBean must be removed
356
+				$this->_removeRelationship($pivotTableName, $oldRemoteBean);
357
+			}
358
+		}
359
+
360
+		foreach ($remoteBeans as $remoteBean) {
361
+			if (!$storage->contains($remoteBean) || $storage[$remoteBean]['status'] === 'delete') {
362
+				// $remoteBean must be added
363
+				$this->addRelationship($pivotTableName, $remoteBean);
364
+			}
365
+		}
366
+	}
367
+
368
+	/**
369
+	 * Returns the list of objects linked to this bean via $pivotTableName.
370
+	 *
371
+	 * @param $pivotTableName
372
+	 *
373
+	 * @return \SplObjectStorage
374
+	 */
375
+	private function retrieveRelationshipsStorage($pivotTableName)
376
+	{
377
+		$storage = $this->getRelationshipStorage($pivotTableName);
378
+		if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->loadedRelationships[$pivotTableName]) && $this->loadedRelationships[$pivotTableName])) {
379
+			return $storage;
380
+		}
381
+
382
+		$beans = $this->tdbmService->_getRelatedBeans($pivotTableName, $this);
383
+		$this->loadedRelationships[$pivotTableName] = true;
384
+
385
+		foreach ($beans as $bean) {
386
+			if (isset($storage[$bean])) {
387
+				$oldStatus = $storage[$bean]['status'];
388
+				if ($oldStatus === 'delete') {
389
+					// Keep deleted things deleted
390
+					continue;
391
+				}
392
+			}
393
+			$this->setRelationship($pivotTableName, $bean, 'loaded');
394
+		}
395
+
396
+		return $storage;
397
+	}
398
+
399
+	/**
400
+	 * Internal TDBM method. Returns the list of objects linked to this bean via $pivotTableName.
401
+	 *
402
+	 * @param $pivotTableName
403
+	 *
404
+	 * @return AbstractTDBMObject[]
405
+	 */
406
+	public function _getRelationships($pivotTableName)
407
+	{
408
+		return $this->relationshipStorageToArray($this->retrieveRelationshipsStorage($pivotTableName));
409
+	}
410
+
411
+	private function relationshipStorageToArray(\SplObjectStorage $storage)
412
+	{
413
+		$beans = [];
414
+		foreach ($storage as $bean) {
415
+			$statusArr = $storage[$bean];
416
+			if ($statusArr['status'] !== 'delete') {
417
+				$beans[] = $bean;
418
+			}
419
+		}
420
+
421
+		return $beans;
422
+	}
423
+
424
+	/**
425
+	 * Declares a relationship between.
426
+	 *
427
+	 * @param string             $pivotTableName
428
+	 * @param AbstractTDBMObject $remoteBean
429
+	 * @param string             $status
430
+	 */
431
+	private function setRelationship($pivotTableName, AbstractTDBMObject $remoteBean, $status)
432
+	{
433
+		$storage = $this->getRelationshipStorage($pivotTableName);
434
+		$storage->attach($remoteBean, ['status' => $status, 'reverse' => false]);
435
+		if ($this->status === TDBMObjectStateEnum::STATE_LOADED) {
436
+			$this->_setStatus(TDBMObjectStateEnum::STATE_DIRTY);
437
+		}
438
+
439
+		$remoteStorage = $remoteBean->getRelationshipStorage($pivotTableName);
440
+		$remoteStorage->attach($this, ['status' => $status, 'reverse' => true]);
441
+	}
442
+
443
+	/**
444
+	 * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
445
+	 *
446
+	 * @param string $pivotTableName
447
+	 *
448
+	 * @return \SplObjectStorage
449
+	 */
450
+	private function getRelationshipStorage(string $pivotTableName) : \SplObjectStorage
451
+	{
452
+		return $this->relationships[$pivotTableName] ?? $this->relationships[$pivotTableName] = new \SplObjectStorage();
453
+	}
454
+
455
+	/**
456
+	 * Returns the SplObjectStorage associated to this relationship (creates it if it does not exists).
457
+	 *
458
+	 * @param string $tableName
459
+	 * @param string $foreignKeyName
460
+	 *
461
+	 * @return AlterableResultIterator
462
+	 */
463
+	private function getManyToOneAlterableResultIterator(string $tableName, string $foreignKeyName) : AlterableResultIterator
464
+	{
465
+		$key = $tableName.'___'.$foreignKeyName;
466
+
467
+		return $this->manyToOneRelationships[$key] ?? $this->manyToOneRelationships[$key] = new AlterableResultIterator();
468
+	}
469
+
470
+	/**
471
+	 * Declares a relationship between this bean and the bean pointing to it.
472
+	 *
473
+	 * @param string             $tableName
474
+	 * @param string             $foreignKeyName
475
+	 * @param AbstractTDBMObject $remoteBean
476
+	 */
477
+	private function setManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
478
+	{
479
+		$alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
480
+		$alterableResultIterator->add($remoteBean);
481
+	}
482
+
483
+	/**
484
+	 * Declares a relationship between this bean and the bean pointing to it.
485
+	 *
486
+	 * @param string             $tableName
487
+	 * @param string             $foreignKeyName
488
+	 * @param AbstractTDBMObject $remoteBean
489
+	 */
490
+	private function removeManyToOneRelationship(string $tableName, string $foreignKeyName, AbstractTDBMObject $remoteBean)
491
+	{
492
+		$alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
493
+		$alterableResultIterator->remove($remoteBean);
494
+	}
495
+
496
+	/**
497
+	 * Returns the list of objects linked to this bean via a given foreign key.
498
+	 *
499
+	 * @param string $tableName
500
+	 * @param string $foreignKeyName
501
+	 * @param string $searchTableName
502
+	 * @param array  $searchFilter
503
+	 * @param string $orderString     The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column). WARNING : This parameter is not kept when there is an additionnal or removal object !
504
+	 *
505
+	 * @return AlterableResultIterator
506
+	 */
507
+	protected function retrieveManyToOneRelationshipsStorage(string $tableName, string $foreignKeyName, string $searchTableName, array $searchFilter, $orderString = null) : AlterableResultIterator
508
+	{
509
+		$key = $tableName.'___'.$foreignKeyName;
510
+		$alterableResultIterator = $this->getManyToOneAlterableResultIterator($tableName, $foreignKeyName);
511
+		if ($this->status === TDBMObjectStateEnum::STATE_DETACHED || $this->status === TDBMObjectStateEnum::STATE_NEW || (isset($this->manyToOneRelationships[$key]) && $this->manyToOneRelationships[$key]->getUnderlyingResultIterator() !== null)) {
512
+			return $alterableResultIterator;
513
+		}
514
+
515
+		$unalteredResultIterator = $this->tdbmService->findObjects($searchTableName, $searchFilter, [], $orderString);
516
+
517
+		$alterableResultIterator->setResultIterator($unalteredResultIterator->getIterator());
518
+
519
+		return $alterableResultIterator;
520
+	}
521
+
522
+	/**
523
+	 * Reverts any changes made to the object and resumes it to its DB state.
524
+	 * This can only be called on objects that come from database and that have not been deleted.
525
+	 * Otherwise, this will throw an exception.
526
+	 *
527
+	 * @throws TDBMException
528
+	 */
529
+	public function discardChanges()
530
+	{
531
+		if ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->status === TDBMObjectStateEnum::STATE_DETACHED) {
532
+			throw new TDBMException("You cannot call discardChanges() on an object that has been created with the 'new' keyword and that has not yet been saved.");
533
+		}
534
+
535
+		if ($this->status === TDBMObjectStateEnum::STATE_DELETED) {
536
+			throw new TDBMException('You cannot call discardChanges() on an object that has been deleted.');
537
+		}
538
+
539
+		$this->_setStatus(TDBMObjectStateEnum::STATE_NOT_LOADED);
540
+	}
541
+
542
+	/**
543
+	 * Method used internally by TDBM. You should not use it directly.
544
+	 * This method returns the status of the TDBMObject.
545
+	 * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
546
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
547
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
548
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
549
+	 *
550
+	 * @return string
551
+	 */
552
+	public function _getStatus()
553
+	{
554
+		return $this->status;
555
+	}
556
+
557
+	/**
558
+	 * Override the native php clone function for TDBMObjects.
559
+	 */
560
+	public function __clone()
561
+	{
562
+		// Let's clone the many to many relationships
563
+		if ($this->status === TDBMObjectStateEnum::STATE_DETACHED) {
564
+			$pivotTableList = array_keys($this->relationships);
565
+		} else {
566
+			$pivotTableList = $this->tdbmService->_getPivotTablesLinkedToBean($this);
567
+		}
568
+
569
+		foreach ($pivotTableList as $pivotTable) {
570
+			$storage = $this->retrieveRelationshipsStorage($pivotTable);
571
+
572
+			// Let's duplicate the reverse side of the relationship // This is useless: already done by "retrieveRelationshipsStorage"!!!
573
+			/*foreach ($storage as $remoteBean) {
574 574
                 $metadata = $storage[$remoteBean];
575 575
 
576 576
                 $remoteStorage = $remoteBean->getRelationshipStorage($pivotTable);
577 577
                 $remoteStorage->attach($this, ['status' => $metadata['status'], 'reverse' => !$metadata['reverse']]);
578 578
             }*/
579
-        }
580
-
581
-        // Let's clone each row
582
-        foreach ($this->dbRows as $key => &$dbRow) {
583
-            $dbRow = clone $dbRow;
584
-            $dbRow->setTDBMObject($this);
585
-        }
586
-
587
-        $this->manyToOneRelationships = [];
588
-
589
-        // Let's set the status to new (to enter the save function)
590
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
591
-    }
592
-
593
-    /**
594
-     * Returns raw database rows.
595
-     *
596
-     * @return DbRow[] Key: table name, Value: DbRow object
597
-     */
598
-    public function _getDbRows()
599
-    {
600
-        return $this->dbRows;
601
-    }
602
-
603
-    private function registerTable($tableName)
604
-    {
605
-        $dbRow = new DbRow($this, $tableName);
606
-
607
-        if (in_array($this->status, [TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DIRTY])) {
608
-            // Let's get the primary key for the new table
609
-            $anotherDbRow = array_values($this->dbRows)[0];
610
-            /* @var $anotherDbRow DbRow */
611
-            $indexedPrimaryKeys = array_values($anotherDbRow->_getPrimaryKeys());
612
-            $primaryKeys = $this->tdbmService->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $indexedPrimaryKeys);
613
-            $dbRow->_setPrimaryKeys($primaryKeys);
614
-        }
615
-
616
-        $dbRow->_setStatus($this->status);
617
-
618
-        $this->dbRows[$tableName] = $dbRow;
619
-        // TODO: look at status (if not new)=> get primary key from tdbmservice
620
-    }
621
-
622
-    /**
623
-     * Internal function: return the list of relationships.
624
-     *
625
-     * @return \SplObjectStorage[]
626
-     */
627
-    public function _getCachedRelationships()
628
-    {
629
-        return $this->relationships;
630
-    }
631
-
632
-    /**
633
-     * Returns an array of used tables by this bean (from parent to child relationship).
634
-     *
635
-     * @return string[]
636
-     */
637
-    abstract protected function getUsedTables() : array;
638
-
639
-    /**
640
-     * Method called when the bean is removed from database.
641
-     */
642
-    protected function onDelete() : void
643
-    {
644
-    }
579
+		}
580
+
581
+		// Let's clone each row
582
+		foreach ($this->dbRows as $key => &$dbRow) {
583
+			$dbRow = clone $dbRow;
584
+			$dbRow->setTDBMObject($this);
585
+		}
586
+
587
+		$this->manyToOneRelationships = [];
588
+
589
+		// Let's set the status to new (to enter the save function)
590
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
591
+	}
592
+
593
+	/**
594
+	 * Returns raw database rows.
595
+	 *
596
+	 * @return DbRow[] Key: table name, Value: DbRow object
597
+	 */
598
+	public function _getDbRows()
599
+	{
600
+		return $this->dbRows;
601
+	}
602
+
603
+	private function registerTable($tableName)
604
+	{
605
+		$dbRow = new DbRow($this, $tableName);
606
+
607
+		if (in_array($this->status, [TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DIRTY])) {
608
+			// Let's get the primary key for the new table
609
+			$anotherDbRow = array_values($this->dbRows)[0];
610
+			/* @var $anotherDbRow DbRow */
611
+			$indexedPrimaryKeys = array_values($anotherDbRow->_getPrimaryKeys());
612
+			$primaryKeys = $this->tdbmService->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $indexedPrimaryKeys);
613
+			$dbRow->_setPrimaryKeys($primaryKeys);
614
+		}
615
+
616
+		$dbRow->_setStatus($this->status);
617
+
618
+		$this->dbRows[$tableName] = $dbRow;
619
+		// TODO: look at status (if not new)=> get primary key from tdbmservice
620
+	}
621
+
622
+	/**
623
+	 * Internal function: return the list of relationships.
624
+	 *
625
+	 * @return \SplObjectStorage[]
626
+	 */
627
+	public function _getCachedRelationships()
628
+	{
629
+		return $this->relationships;
630
+	}
631
+
632
+	/**
633
+	 * Returns an array of used tables by this bean (from parent to child relationship).
634
+	 *
635
+	 * @return string[]
636
+	 */
637
+	abstract protected function getUsedTables() : array;
638
+
639
+	/**
640
+	 * Method called when the bean is removed from database.
641
+	 */
642
+	protected function onDelete() : void
643
+	{
644
+	}
645 645
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Controllers/TdbmController.php 1 patch
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -18,129 +18,129 @@
 block discarded – undo
18 18
  */
19 19
 class TdbmController extends AbstractMoufInstanceController
20 20
 {
21
-    /**
22
-     * @var HtmlBlock
23
-     */
24
-    public $content;
25
-
26
-    protected $daoNamespace;
27
-    protected $beanNamespace;
28
-    protected $daoFactoryInstanceName;
29
-    protected $autoloadDetected;
30
-    ///protected $storeInUtc;
31
-    protected $useCustomComposer;
32
-    protected $composerFile;
33
-
34
-    /**
35
-     * Admin page used to display the DAO generation form.
36
-     *
37
-     * @Action
38
-     */
39
-    public function defaultAction($name, $selfedit = 'false')
40
-    {
41
-        $this->initController($name, $selfedit);
42
-
43
-        // Fill variables
44
-        $this->daoNamespace = self::getFromConfiguration($this->moufManager, $name, 'daoNamespace');
45
-        $this->beanNamespace = self::getFromConfiguration($this->moufManager, $name, 'beanNamespace');
46
-        $this->daoFactoryInstanceName = self::getFromConfiguration($this->moufManager, $name, 'daoFactoryInstanceName');
47
-        //$this->storeInUtc = self::getFromConfiguration($this->moufManager, $name, 'storeInUtc');
48
-        $this->composerFile = self::getFromConfiguration($this->moufManager, $name, 'customComposerFile');
49
-        $this->useCustomComposer = $this->composerFile ? true : false;
50
-
51
-        if ($this->daoNamespace == null && $this->beanNamespace == null) {
52
-            $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
53
-
54
-            $autoloadNamespaces = $classNameMapper->getManagedNamespaces();
55
-            if ($autoloadNamespaces) {
56
-                $this->autoloadDetected = true;
57
-                $rootNamespace = $autoloadNamespaces[0];
58
-                $this->daoNamespace = $rootNamespace.'Dao';
59
-                $this->beanNamespace = $rootNamespace.'Dao\\Bean';
60
-            } else {
61
-                $this->autoloadDetected = false;
62
-                $this->daoNamespace = 'YourApplication\\Dao';
63
-                $this->beanNamespace = 'YourApplication\\Dao\\Bean';
64
-            }
65
-        } else {
66
-            $this->autoloadDetected = true;
67
-        }
68
-
69
-        $this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
70
-        $this->template->toHtml();
71
-    }
72
-
73
-    /**
74
-     * This action generates the DAOs and Beans for the TDBM service passed in parameter.
75
-     *
76
-     * @Action
77
-     *
78
-     * @param string $name
79
-     * @param bool   $selfedit
80
-     */
81
-    public function generate($name, $daonamespace, $beannamespace, $daofactoryinstancename, /*$storeInUtc = 0,*/ $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
82
-    {
83
-        $this->initController($name, $selfedit);
84
-
85
-        self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit, /*$storeInUtc,*/ $useCustomComposer, $composerFile);
86
-
87
-        // TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
88
-        header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
89
-    }
90
-
91
-    /**
92
-     * This function generates the DAOs and Beans for the TDBM service passed in parameter.
93
-     *
94
-     * @param MoufManager $moufManager
95
-     * @param string      $name
96
-     * @param string      $daonamespace
97
-     * @param string      $beannamespace
98
-     * @param string      $daofactoryclassname
99
-     * @param string      $daofactoryinstancename
100
-     * @param string      $selfedit
101
-     *
102
-     * @throws \Mouf\MoufException
103
-     */
104
-    public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit = 'false', /*$storeInUtc = null,*/ $useCustomComposer = null, $composerFile = null)
105
-    {
106
-        self::setInConfiguration($moufManager, $name, 'daoNamespace', $daonamespace);
107
-        self::setInConfiguration($moufManager, $name, 'beanNamespace', $beannamespace);
108
-        self::setInConfiguration($moufManager, $name, 'daoFactoryInstanceName', $daofactoryinstancename);
109
-        //self::setInConfiguration($moufManager, $name, 'storeInUtc', $storeInUtc);
110
-        if ($useCustomComposer) {
111
-            self::setInConfiguration($moufManager, $name, 'customComposerFile', $composerFile);
112
-        } else {
113
-            self::setInConfiguration($moufManager, $name, 'customComposerFile', null);
114
-        }
115
-        // Let's rewrite before calling the DAO generator
116
-        $moufManager->rewriteMouf();
117
-
118
-
119
-        $tdbmService = new InstanceProxy($name);
120
-        /* @var $tdbmService TDBMService */
121
-        $tdbmService->generateAllDaosAndBeans(($useCustomComposer ? $composerFile : null));
122
-    }
123
-
124
-    private static function getConfigurationDescriptor(MoufManager $moufManager, string $tdbmInstanceName)
125
-    {
126
-        return $moufManager->getInstanceDescriptor($tdbmInstanceName)->getConstructorArgumentProperty('configuration')->getValue();
127
-    }
128
-
129
-    private static function getFromConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property)
130
-    {
131
-        $configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
132
-        if ($configuration === null) {
133
-            throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
134
-        }
135
-        return $configuration->getProperty($property)->getValue();
136
-    }
137
-
138
-    private static function setInConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property, ?string $value)
139
-    {
140
-        $configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
141
-        if ($configuration === null) {
142
-            throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
143
-        }
144
-        $configuration->getProperty($property)->setValue($value);
145
-    }
21
+	/**
22
+	 * @var HtmlBlock
23
+	 */
24
+	public $content;
25
+
26
+	protected $daoNamespace;
27
+	protected $beanNamespace;
28
+	protected $daoFactoryInstanceName;
29
+	protected $autoloadDetected;
30
+	///protected $storeInUtc;
31
+	protected $useCustomComposer;
32
+	protected $composerFile;
33
+
34
+	/**
35
+	 * Admin page used to display the DAO generation form.
36
+	 *
37
+	 * @Action
38
+	 */
39
+	public function defaultAction($name, $selfedit = 'false')
40
+	{
41
+		$this->initController($name, $selfedit);
42
+
43
+		// Fill variables
44
+		$this->daoNamespace = self::getFromConfiguration($this->moufManager, $name, 'daoNamespace');
45
+		$this->beanNamespace = self::getFromConfiguration($this->moufManager, $name, 'beanNamespace');
46
+		$this->daoFactoryInstanceName = self::getFromConfiguration($this->moufManager, $name, 'daoFactoryInstanceName');
47
+		//$this->storeInUtc = self::getFromConfiguration($this->moufManager, $name, 'storeInUtc');
48
+		$this->composerFile = self::getFromConfiguration($this->moufManager, $name, 'customComposerFile');
49
+		$this->useCustomComposer = $this->composerFile ? true : false;
50
+
51
+		if ($this->daoNamespace == null && $this->beanNamespace == null) {
52
+			$classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
53
+
54
+			$autoloadNamespaces = $classNameMapper->getManagedNamespaces();
55
+			if ($autoloadNamespaces) {
56
+				$this->autoloadDetected = true;
57
+				$rootNamespace = $autoloadNamespaces[0];
58
+				$this->daoNamespace = $rootNamespace.'Dao';
59
+				$this->beanNamespace = $rootNamespace.'Dao\\Bean';
60
+			} else {
61
+				$this->autoloadDetected = false;
62
+				$this->daoNamespace = 'YourApplication\\Dao';
63
+				$this->beanNamespace = 'YourApplication\\Dao\\Bean';
64
+			}
65
+		} else {
66
+			$this->autoloadDetected = true;
67
+		}
68
+
69
+		$this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
70
+		$this->template->toHtml();
71
+	}
72
+
73
+	/**
74
+	 * This action generates the DAOs and Beans for the TDBM service passed in parameter.
75
+	 *
76
+	 * @Action
77
+	 *
78
+	 * @param string $name
79
+	 * @param bool   $selfedit
80
+	 */
81
+	public function generate($name, $daonamespace, $beannamespace, $daofactoryinstancename, /*$storeInUtc = 0,*/ $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
82
+	{
83
+		$this->initController($name, $selfedit);
84
+
85
+		self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit, /*$storeInUtc,*/ $useCustomComposer, $composerFile);
86
+
87
+		// TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
88
+		header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
89
+	}
90
+
91
+	/**
92
+	 * This function generates the DAOs and Beans for the TDBM service passed in parameter.
93
+	 *
94
+	 * @param MoufManager $moufManager
95
+	 * @param string      $name
96
+	 * @param string      $daonamespace
97
+	 * @param string      $beannamespace
98
+	 * @param string      $daofactoryclassname
99
+	 * @param string      $daofactoryinstancename
100
+	 * @param string      $selfedit
101
+	 *
102
+	 * @throws \Mouf\MoufException
103
+	 */
104
+	public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryinstancename, $selfedit = 'false', /*$storeInUtc = null,*/ $useCustomComposer = null, $composerFile = null)
105
+	{
106
+		self::setInConfiguration($moufManager, $name, 'daoNamespace', $daonamespace);
107
+		self::setInConfiguration($moufManager, $name, 'beanNamespace', $beannamespace);
108
+		self::setInConfiguration($moufManager, $name, 'daoFactoryInstanceName', $daofactoryinstancename);
109
+		//self::setInConfiguration($moufManager, $name, 'storeInUtc', $storeInUtc);
110
+		if ($useCustomComposer) {
111
+			self::setInConfiguration($moufManager, $name, 'customComposerFile', $composerFile);
112
+		} else {
113
+			self::setInConfiguration($moufManager, $name, 'customComposerFile', null);
114
+		}
115
+		// Let's rewrite before calling the DAO generator
116
+		$moufManager->rewriteMouf();
117
+
118
+
119
+		$tdbmService = new InstanceProxy($name);
120
+		/* @var $tdbmService TDBMService */
121
+		$tdbmService->generateAllDaosAndBeans(($useCustomComposer ? $composerFile : null));
122
+	}
123
+
124
+	private static function getConfigurationDescriptor(MoufManager $moufManager, string $tdbmInstanceName)
125
+	{
126
+		return $moufManager->getInstanceDescriptor($tdbmInstanceName)->getConstructorArgumentProperty('configuration')->getValue();
127
+	}
128
+
129
+	private static function getFromConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property)
130
+	{
131
+		$configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
132
+		if ($configuration === null) {
133
+			throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
134
+		}
135
+		return $configuration->getProperty($property)->getValue();
136
+	}
137
+
138
+	private static function setInConfiguration(MoufManager $moufManager, string $tdbmInstanceName, string $property, ?string $value)
139
+	{
140
+		$configuration = self::getConfigurationDescriptor($moufManager, $tdbmInstanceName);
141
+		if ($configuration === null) {
142
+			throw new \RuntimeException('Unable to find the configuration object linked to TDBMService.');
143
+		}
144
+		$configuration->getProperty($property)->setValue($value);
145
+	}
146 146
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/MoufDiListener.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -11,58 +11,58 @@
 block discarded – undo
11 11
 class MoufDiListener implements GeneratorListenerInterface
12 12
 {
13 13
 
14
-    /**
15
-     * @param ConfigurationInterface $configuration
16
-     * @param BeanDescriptorInterface[] $beanDescriptors
17
-     */
18
-    public function onGenerate(ConfigurationInterface $configuration, array $beanDescriptors): void
19
-    {
20
-        // Let's generate the needed instance in Mouf.
21
-        $moufManager = MoufManager::getMoufManager();
14
+	/**
15
+	 * @param ConfigurationInterface $configuration
16
+	 * @param BeanDescriptorInterface[] $beanDescriptors
17
+	 */
18
+	public function onGenerate(ConfigurationInterface $configuration, array $beanDescriptors): void
19
+	{
20
+		// Let's generate the needed instance in Mouf.
21
+		$moufManager = MoufManager::getMoufManager();
22 22
 
23
-        $daoFactoryInstanceName = null;
24
-        if ($configuration instanceof MoufConfiguration) {
25
-            $daoFactoryInstanceName = $configuration->getDaoFactoryInstanceName();
26
-            $daoFactoryClassName = $configuration->getDaoNamespace().'\\Generated\\'.$configuration->getNamingStrategy()->getDaoFactoryClassName();
27
-            $moufManager->declareComponent($daoFactoryInstanceName, $daoFactoryClassName, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS);
28
-        }
23
+		$daoFactoryInstanceName = null;
24
+		if ($configuration instanceof MoufConfiguration) {
25
+			$daoFactoryInstanceName = $configuration->getDaoFactoryInstanceName();
26
+			$daoFactoryClassName = $configuration->getDaoNamespace().'\\Generated\\'.$configuration->getNamingStrategy()->getDaoFactoryClassName();
27
+			$moufManager->declareComponent($daoFactoryInstanceName, $daoFactoryClassName, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS);
28
+		}
29 29
 
30
-        $tdbmServiceInstanceName = $this->getTdbmInstanceName($configuration);
30
+		$tdbmServiceInstanceName = $this->getTdbmInstanceName($configuration);
31 31
 
32
-        foreach ($beanDescriptors as $beanDescriptor) {
33
-            $daoName = $beanDescriptor->getDaoClassName();
32
+		foreach ($beanDescriptors as $beanDescriptor) {
33
+			$daoName = $beanDescriptor->getDaoClassName();
34 34
 
35
-            $instanceName = TDBMDaoGenerator::toVariableName($daoName);
36
-            if (!$moufManager->instanceExists($instanceName)) {
37
-                $moufManager->declareComponent($instanceName, $configuration->getDaoNamespace().'\\'.$daoName);
38
-            }
39
-            $moufManager->setParameterViaConstructor($instanceName, 0, $tdbmServiceInstanceName, 'object');
40
-            if ($daoFactoryInstanceName !== null) {
41
-                $moufManager->bindComponentViaSetter($daoFactoryInstanceName, 'set'.$daoName, $instanceName);
42
-            }
43
-        }
35
+			$instanceName = TDBMDaoGenerator::toVariableName($daoName);
36
+			if (!$moufManager->instanceExists($instanceName)) {
37
+				$moufManager->declareComponent($instanceName, $configuration->getDaoNamespace().'\\'.$daoName);
38
+			}
39
+			$moufManager->setParameterViaConstructor($instanceName, 0, $tdbmServiceInstanceName, 'object');
40
+			if ($daoFactoryInstanceName !== null) {
41
+				$moufManager->bindComponentViaSetter($daoFactoryInstanceName, 'set'.$daoName, $instanceName);
42
+			}
43
+		}
44 44
 
45
-        $moufManager->rewriteMouf();
46
-    }
45
+		$moufManager->rewriteMouf();
46
+	}
47 47
 
48
-    private function getTdbmInstanceName(ConfigurationInterface $configuration) : string
49
-    {
50
-        $moufManager = MoufManager::getMoufManager();
48
+	private function getTdbmInstanceName(ConfigurationInterface $configuration) : string
49
+	{
50
+		$moufManager = MoufManager::getMoufManager();
51 51
 
52
-        $configurationInstanceName = $moufManager->findInstanceName($configuration);
53
-        if (!$configurationInstanceName) {
54
-            throw new \TDBMException('Could not find TDBM instance for configuration object.');
55
-        }
52
+		$configurationInstanceName = $moufManager->findInstanceName($configuration);
53
+		if (!$configurationInstanceName) {
54
+			throw new \TDBMException('Could not find TDBM instance for configuration object.');
55
+		}
56 56
 
57
-        // Let's find the configuration
58
-        $tdbmServicesNames = $moufManager->findInstances(TDBMService::class);
57
+		// Let's find the configuration
58
+		$tdbmServicesNames = $moufManager->findInstances(TDBMService::class);
59 59
 
60
-        foreach ($tdbmServicesNames as $name) {
61
-            if ($moufManager->getInstanceDescriptor($name)->getConstructorArgumentProperty('configuration')->getValue()->getName() === $configurationInstanceName) {
62
-                return $name;
63
-            }
64
-        }
60
+		foreach ($tdbmServicesNames as $name) {
61
+			if ($moufManager->getInstanceDescriptor($name)->getConstructorArgumentProperty('configuration')->getValue()->getName() === $configurationInstanceName) {
62
+				return $name;
63
+			}
64
+		}
65 65
 
66
-        throw new \TDBMException('Could not find TDBMService instance.');
67
-    }
66
+		throw new \TDBMException('Could not find TDBMService instance.');
67
+	}
68 68
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/DefaultNamingStrategy.php 1 patch
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -7,168 +7,168 @@
 block discarded – undo
7 7
 
8 8
 class DefaultNamingStrategy implements NamingStrategyInterface
9 9
 {
10
-    private $beanPrefix = '';
11
-    private $beanSuffix = '';
12
-    private $baseBeanPrefix = 'Abstract';
13
-    private $baseBeanSuffix = '';
14
-    private $daoPrefix = '';
15
-    private $daoSuffix = 'Dao';
16
-    private $baseDaoPrefix = 'Abstract';
17
-    private $baseDaoSuffix = 'Dao';
18
-
19
-    /**
20
-     * Sets the string prefix to any bean class name.
21
-     *
22
-     * @param string $beanPrefix
23
-     */
24
-    public function setBeanPrefix(string $beanPrefix)
25
-    {
26
-        $this->beanPrefix = $beanPrefix;
27
-    }
28
-
29
-    /**
30
-     * Sets the string suffix to any bean class name.
31
-     *
32
-     * @param string $beanSuffix
33
-     */
34
-    public function setBeanSuffix(string $beanSuffix)
35
-    {
36
-        $this->beanSuffix = $beanSuffix;
37
-    }
38
-
39
-    /**
40
-     * Sets the string prefix to any base bean class name.
41
-     *
42
-     * @param string $baseBeanPrefix
43
-     */
44
-    public function setBaseBeanPrefix(string $baseBeanPrefix)
45
-    {
46
-        $this->baseBeanPrefix = $baseBeanPrefix;
47
-    }
48
-
49
-    /**
50
-     * Sets the string suffix to any base bean class name.
51
-     *
52
-     * @param string $baseBeanSuffix
53
-     */
54
-    public function setBaseBeanSuffix(string $baseBeanSuffix)
55
-    {
56
-        $this->baseBeanSuffix = $baseBeanSuffix;
57
-    }
58
-
59
-    /**
60
-     * Sets the string prefix to any DAO class name.
61
-     *
62
-     * @param string $daoPrefix
63
-     */
64
-    public function setDaoPrefix(string $daoPrefix)
65
-    {
66
-        $this->daoPrefix = $daoPrefix;
67
-    }
68
-
69
-    /**
70
-     * Sets the string suffix to any DAO class name.
71
-     *
72
-     * @param string $daoSuffix
73
-     */
74
-    public function setDaoSuffix(string $daoSuffix)
75
-    {
76
-        $this->daoSuffix = $daoSuffix;
77
-    }
78
-
79
-    /**
80
-     * Sets the string prefix to any base DAO class name.
81
-     *
82
-     * @param string $baseDaoPrefix
83
-     */
84
-    public function setBaseDaoPrefix(string $baseDaoPrefix)
85
-    {
86
-        $this->baseDaoPrefix = $baseDaoPrefix;
87
-    }
88
-
89
-    /**
90
-     * Sets the string suffix to any base DAO class name.
91
-     *
92
-     * @param string $baseDaoSuffix
93
-     */
94
-    public function setBaseDaoSuffix(string $baseDaoSuffix)
95
-    {
96
-        $this->baseDaoSuffix = $baseDaoSuffix;
97
-    }
98
-
99
-
100
-    /**
101
-     * Returns the bean class name from the table name (excluding the namespace).
102
-     *
103
-     * @param string $tableName
104
-     * @return string
105
-     */
106
-    public function getBeanClassName(string $tableName): string
107
-    {
108
-        return $this->beanPrefix.self::toSingularCamelCase($tableName).$this->beanSuffix;
109
-    }
110
-
111
-    /**
112
-     * Returns the base bean class name from the table name (excluding the namespace).
113
-     *
114
-     * @param string $tableName
115
-     * @return string
116
-     */
117
-    public function getBaseBeanClassName(string $tableName): string
118
-    {
119
-        return $this->baseBeanPrefix.self::toSingularCamelCase($tableName).$this->baseBeanSuffix;
120
-    }
121
-
122
-    /**
123
-     * Returns the name of the DAO class from the table name (excluding the namespace).
124
-     *
125
-     * @param string $tableName
126
-     * @return string
127
-     */
128
-    public function getDaoClassName(string $tableName): string
129
-    {
130
-        return $this->daoPrefix.self::toSingularCamelCase($tableName).$this->daoSuffix;
131
-    }
132
-
133
-    /**
134
-     * Returns the name of the base DAO class from the table name (excluding the namespace).
135
-     *
136
-     * @param string $tableName
137
-     * @return string
138
-     */
139
-    public function getBaseDaoClassName(string $tableName): string
140
-    {
141
-        return $this->baseDaoPrefix.self::toSingularCamelCase($tableName).$this->baseDaoSuffix;
142
-    }
143
-
144
-    /**
145
-     * Tries to put string to the singular form (if it is plural) and camel case form.
146
-     * We assume the table names are in english.
147
-     *
148
-     * @param $str string
149
-     *
150
-     * @return string
151
-     */
152
-    private static function toSingularCamelCase(string $str): string
153
-    {
154
-        $tokens = preg_split("/[_ ]+/", $str);
155
-        $tokens = array_map([Inflector::class, 'singularize'], $tokens);
156
-
157
-        $str = '';
158
-        foreach ($tokens as $token) {
159
-            $str .= ucfirst(Inflector::singularize($token));
160
-        }
161
-
162
-        return $str;
163
-    }
164
-
165
-    /**
166
-     * Returns the class name for the DAO factory.
167
-     *
168
-     * @return string
169
-     */
170
-    public function getDaoFactoryClassName(): string
171
-    {
172
-        return 'DaoFactory';
173
-    }
10
+	private $beanPrefix = '';
11
+	private $beanSuffix = '';
12
+	private $baseBeanPrefix = 'Abstract';
13
+	private $baseBeanSuffix = '';
14
+	private $daoPrefix = '';
15
+	private $daoSuffix = 'Dao';
16
+	private $baseDaoPrefix = 'Abstract';
17
+	private $baseDaoSuffix = 'Dao';
18
+
19
+	/**
20
+	 * Sets the string prefix to any bean class name.
21
+	 *
22
+	 * @param string $beanPrefix
23
+	 */
24
+	public function setBeanPrefix(string $beanPrefix)
25
+	{
26
+		$this->beanPrefix = $beanPrefix;
27
+	}
28
+
29
+	/**
30
+	 * Sets the string suffix to any bean class name.
31
+	 *
32
+	 * @param string $beanSuffix
33
+	 */
34
+	public function setBeanSuffix(string $beanSuffix)
35
+	{
36
+		$this->beanSuffix = $beanSuffix;
37
+	}
38
+
39
+	/**
40
+	 * Sets the string prefix to any base bean class name.
41
+	 *
42
+	 * @param string $baseBeanPrefix
43
+	 */
44
+	public function setBaseBeanPrefix(string $baseBeanPrefix)
45
+	{
46
+		$this->baseBeanPrefix = $baseBeanPrefix;
47
+	}
48
+
49
+	/**
50
+	 * Sets the string suffix to any base bean class name.
51
+	 *
52
+	 * @param string $baseBeanSuffix
53
+	 */
54
+	public function setBaseBeanSuffix(string $baseBeanSuffix)
55
+	{
56
+		$this->baseBeanSuffix = $baseBeanSuffix;
57
+	}
58
+
59
+	/**
60
+	 * Sets the string prefix to any DAO class name.
61
+	 *
62
+	 * @param string $daoPrefix
63
+	 */
64
+	public function setDaoPrefix(string $daoPrefix)
65
+	{
66
+		$this->daoPrefix = $daoPrefix;
67
+	}
68
+
69
+	/**
70
+	 * Sets the string suffix to any DAO class name.
71
+	 *
72
+	 * @param string $daoSuffix
73
+	 */
74
+	public function setDaoSuffix(string $daoSuffix)
75
+	{
76
+		$this->daoSuffix = $daoSuffix;
77
+	}
78
+
79
+	/**
80
+	 * Sets the string prefix to any base DAO class name.
81
+	 *
82
+	 * @param string $baseDaoPrefix
83
+	 */
84
+	public function setBaseDaoPrefix(string $baseDaoPrefix)
85
+	{
86
+		$this->baseDaoPrefix = $baseDaoPrefix;
87
+	}
88
+
89
+	/**
90
+	 * Sets the string suffix to any base DAO class name.
91
+	 *
92
+	 * @param string $baseDaoSuffix
93
+	 */
94
+	public function setBaseDaoSuffix(string $baseDaoSuffix)
95
+	{
96
+		$this->baseDaoSuffix = $baseDaoSuffix;
97
+	}
98
+
99
+
100
+	/**
101
+	 * Returns the bean class name from the table name (excluding the namespace).
102
+	 *
103
+	 * @param string $tableName
104
+	 * @return string
105
+	 */
106
+	public function getBeanClassName(string $tableName): string
107
+	{
108
+		return $this->beanPrefix.self::toSingularCamelCase($tableName).$this->beanSuffix;
109
+	}
110
+
111
+	/**
112
+	 * Returns the base bean class name from the table name (excluding the namespace).
113
+	 *
114
+	 * @param string $tableName
115
+	 * @return string
116
+	 */
117
+	public function getBaseBeanClassName(string $tableName): string
118
+	{
119
+		return $this->baseBeanPrefix.self::toSingularCamelCase($tableName).$this->baseBeanSuffix;
120
+	}
121
+
122
+	/**
123
+	 * Returns the name of the DAO class from the table name (excluding the namespace).
124
+	 *
125
+	 * @param string $tableName
126
+	 * @return string
127
+	 */
128
+	public function getDaoClassName(string $tableName): string
129
+	{
130
+		return $this->daoPrefix.self::toSingularCamelCase($tableName).$this->daoSuffix;
131
+	}
132
+
133
+	/**
134
+	 * Returns the name of the base DAO class from the table name (excluding the namespace).
135
+	 *
136
+	 * @param string $tableName
137
+	 * @return string
138
+	 */
139
+	public function getBaseDaoClassName(string $tableName): string
140
+	{
141
+		return $this->baseDaoPrefix.self::toSingularCamelCase($tableName).$this->baseDaoSuffix;
142
+	}
143
+
144
+	/**
145
+	 * Tries to put string to the singular form (if it is plural) and camel case form.
146
+	 * We assume the table names are in english.
147
+	 *
148
+	 * @param $str string
149
+	 *
150
+	 * @return string
151
+	 */
152
+	private static function toSingularCamelCase(string $str): string
153
+	{
154
+		$tokens = preg_split("/[_ ]+/", $str);
155
+		$tokens = array_map([Inflector::class, 'singularize'], $tokens);
156
+
157
+		$str = '';
158
+		foreach ($tokens as $token) {
159
+			$str .= ucfirst(Inflector::singularize($token));
160
+		}
161
+
162
+		return $str;
163
+	}
164
+
165
+	/**
166
+	 * Returns the class name for the DAO factory.
167
+	 *
168
+	 * @return string
169
+	 */
170
+	public function getDaoFactoryClassName(): string
171
+	{
172
+		return 'DaoFactory';
173
+	}
174 174
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Commands/GenerateCommand.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -13,48 +13,48 @@
 block discarded – undo
13 13
 class GenerateCommand extends Command
14 14
 {
15 15
 
16
-    /**
17
-     * @var TDBMService
18
-     */
19
-    private $configuration;
16
+	/**
17
+	 * @var TDBMService
18
+	 */
19
+	private $configuration;
20 20
 
21
-    public function __construct(ConfigurationInterface $configuration)
22
-    {
23
-        parent::__construct();
24
-        $this->configuration = $configuration;
25
-    }
21
+	public function __construct(ConfigurationInterface $configuration)
22
+	{
23
+		parent::__construct();
24
+		$this->configuration = $configuration;
25
+	}
26 26
 
27
-    protected function configure()
28
-    {
29
-        $this->setName('tdbm:generate')
30
-            ->setDescription('Generates DAOs and beans.')
31
-            ->setHelp('Use this command to generate or regenerate the DAOs and beans for your project.')
32
-        ;
33
-    }
27
+	protected function configure()
28
+	{
29
+		$this->setName('tdbm:generate')
30
+			->setDescription('Generates DAOs and beans.')
31
+			->setHelp('Use this command to generate or regenerate the DAOs and beans for your project.')
32
+		;
33
+	}
34 34
 
35
-    protected function execute(InputInterface $input, OutputInterface $output)
36
-    {
37
-        // TODO: externalize composer.json file for autoloading (no more parameters for generateAllDaosAndBeans)
35
+	protected function execute(InputInterface $input, OutputInterface $output)
36
+	{
37
+		// TODO: externalize composer.json file for autoloading (no more parameters for generateAllDaosAndBeans)
38 38
 
39
-        $alteredConf = new AlteredConfiguration($this->configuration);
39
+		$alteredConf = new AlteredConfiguration($this->configuration);
40 40
 
41 41
 
42
-        $loggers = [ new ConsoleLogger($output) ];
42
+		$loggers = [ new ConsoleLogger($output) ];
43 43
 
44
-        $logger = $alteredConf->getLogger();
45
-        if ($logger) {
46
-            $loggers[] = $logger;
47
-        }
44
+		$logger = $alteredConf->getLogger();
45
+		if ($logger) {
46
+			$loggers[] = $logger;
47
+		}
48 48
 
49
-        $multiLogger = new MultiLogger($loggers);
49
+		$multiLogger = new MultiLogger($loggers);
50 50
 
51
-        $alteredConf->setLogger($multiLogger);
51
+		$alteredConf->setLogger($multiLogger);
52 52
 
53
-        $multiLogger->notice('Starting regenerating DAOs and beans');
53
+		$multiLogger->notice('Starting regenerating DAOs and beans');
54 54
 
55
-        $tdbmService = new TDBMService($this->configuration);
56
-        $tdbmService->generateAllDaosAndBeans();
55
+		$tdbmService = new TDBMService($this->configuration);
56
+		$tdbmService->generateAllDaosAndBeans();
57 57
 
58
-        $multiLogger->notice('Finished regenerating DAOs and beans');
59
-    }
58
+		$multiLogger->notice('Finished regenerating DAOs and beans');
59
+	}
60 60
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Controllers/TdbmInstallController.php 1 patch
Indentation   +215 added lines, -215 removed lines patch added patch discarded remove patch
@@ -21,219 +21,219 @@
 block discarded – undo
21 21
  */
22 22
 class TdbmInstallController extends Controller
23 23
 {
24
-    /**
25
-     * @var HtmlBlock
26
-     */
27
-    public $content;
28
-
29
-    public $selfedit;
30
-
31
-    /**
32
-     * The active MoufManager to be edited/viewed.
33
-     *
34
-     * @var MoufManager
35
-     */
36
-    public $moufManager;
37
-
38
-    /**
39
-     * The template used by the main page for mouf.
40
-     *
41
-     * @Property
42
-     * @Compulsory
43
-     *
44
-     * @var TemplateInterface
45
-     */
46
-    public $template;
47
-
48
-    /**
49
-     * Displays the first install screen.
50
-     *
51
-     * @Action
52
-     * @Logged
53
-     *
54
-     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
55
-     */
56
-    public function defaultAction($selfedit = 'false')
57
-    {
58
-        $this->selfedit = $selfedit;
59
-
60
-        if ($selfedit == 'true') {
61
-            $this->moufManager = MoufManager::getMoufManager();
62
-        } else {
63
-            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
64
-        }
65
-
66
-        $this->content->addFile(dirname(__FILE__).'/../../../../views/installStep1.php', $this);
67
-        $this->template->toHtml();
68
-    }
69
-
70
-    /**
71
-     * Skips the install process.
72
-     *
73
-     * @Action
74
-     * @Logged
75
-     *
76
-     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
77
-     */
78
-    public function skip($selfedit = 'false')
79
-    {
80
-        InstallUtils::continueInstall($selfedit == 'true');
81
-    }
82
-
83
-    protected $daoNamespace;
84
-    protected $beanNamespace;
85
-    protected $autoloadDetected;
86
-    //protected $storeInUtc;
87
-    protected $useCustomComposer = false;
88
-    protected $composerFile;
89
-
90
-    /**
91
-     * Displays the second install screen.
92
-     *
93
-     * @Action
94
-     * @Logged
95
-     *
96
-     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
97
-     */
98
-    public function configure($selfedit = 'false')
99
-    {
100
-        $this->selfedit = $selfedit;
101
-
102
-        if ($selfedit == 'true') {
103
-            $this->moufManager = MoufManager::getMoufManager();
104
-        } else {
105
-            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
106
-        }
107
-
108
-        // Let's start by performing basic checks about the instances we assume to exist.
109
-        if (!$this->moufManager->instanceExists('dbalConnection')) {
110
-            $this->displayErrorMsg("The TDBM install process assumes your database connection instance is already created, and that the name of this instance is 'dbalConnection'. Could not find the 'dbalConnection' instance.");
111
-
112
-            return;
113
-        }
114
-
115
-        if ($this->moufManager->has('tdbmConfiguration')) {
116
-            $tdbmConfiguration = $this->moufManager->getInstanceDescriptor('tdbmConfiguration');
117
-
118
-            $this->beanNamespace = $tdbmConfiguration->getConstructorArgumentProperty('beanNamespace')->getValue();
119
-            $this->daoNamespace = $tdbmConfiguration->getConstructorArgumentProperty('daoNamespace')->getValue();
120
-        } else {
121
-            // Old TDBM 4.2 fallback
122
-            $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_tdbmService');
123
-            $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_tdbmService');
124
-        }
125
-
126
-        if ($this->daoNamespace == null && $this->beanNamespace == null) {
127
-            $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
128
-
129
-            $autoloadNamespaces = $classNameMapper->getManagedNamespaces();
130
-            if ($autoloadNamespaces) {
131
-                $this->autoloadDetected = true;
132
-                $rootNamespace = $autoloadNamespaces[0];
133
-                $this->daoNamespace = $rootNamespace.'Dao';
134
-                $this->beanNamespace = $rootNamespace.'Model';
135
-            } else {
136
-                $this->autoloadDetected = false;
137
-                $this->daoNamespace = 'YourApplication\\Dao';
138
-                $this->beanNamespace = 'YourApplication\\Model';
139
-            }
140
-        } else {
141
-            $this->autoloadDetected = true;
142
-        }
143
-        $this->defaultPath = true;
144
-        $this->storePath = '';
145
-
146
-        $this->castDatesToDateTime = true;
147
-
148
-        $this->content->addFile(__DIR__.'/../../../../views/installStep2.php', $this);
149
-        $this->template->toHtml();
150
-    }
151
-
152
-    /**
153
-     * This action generates the TDBM instance, then the DAOs and Beans.
154
-     *
155
-     * @Action
156
-     *
157
-     * @param string $daonamespace
158
-     * @param string $beannamespace
159
-     * @param string $selfedit
160
-     *
161
-     * @throws \Mouf\MoufException
162
-     */
163
-    public function generate($daonamespace, $beannamespace, /*$storeInUtc = 0,*/ $selfedit = 'false', $defaultPath = false, $storePath = '')
164
-    {
165
-        $this->selfedit = $selfedit;
166
-
167
-        if ($selfedit == 'true') {
168
-            $this->moufManager = MoufManager::getMoufManager();
169
-        } else {
170
-            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
171
-        }
172
-
173
-        $doctrineCache = $this->moufManager->getInstanceDescriptor('defaultDoctrineCache');
174
-
175
-        $migratingFrom42 = false;
176
-        if ($this->moufManager->has('tdbmService') && !$this->moufManager->has('tdbmConfiguration')) {
177
-            $migratingFrom42 = true;
178
-        }
179
-
180
-        $namingStrategy = InstallUtils::getOrCreateInstance('namingStrategy', DefaultNamingStrategy::class, $this->moufManager);
181
-        if ($migratingFrom42) {
182
-            // Let's setup the naming strategy for compatibility
183
-            $namingStrategy->getSetterProperty('setBeanPrefix')->setValue('');
184
-            $namingStrategy->getSetterProperty('setBeanSuffix')->setValue('Bean');
185
-            $namingStrategy->getSetterProperty('setBaseBeanPrefix')->setValue('');
186
-            $namingStrategy->getSetterProperty('setBaseBeanSuffix')->setValue('BaseBean');
187
-            $namingStrategy->getSetterProperty('setDaoPrefix')->setValue('');
188
-            $namingStrategy->getSetterProperty('setDaoSuffix')->setValue('Dao');
189
-            $namingStrategy->getSetterProperty('setBaseDaoPrefix')->setValue('');
190
-            $namingStrategy->getSetterProperty('setBaseDaoSuffix')->setValue('BaseDao');
191
-        }
192
-
193
-        if (!$this->moufManager->instanceExists('tdbmConfiguration')) {
194
-            $moufListener = InstallUtils::getOrCreateInstance(MoufDiListener::class, MoufDiListener::class, $this->moufManager);
195
-
196
-            $tdbmConfiguration = $this->moufManager->createInstance(MoufConfiguration::class)->setName('tdbmConfiguration');
197
-            $tdbmConfiguration->getConstructorArgumentProperty('connection')->setValue($this->moufManager->getInstanceDescriptor('dbalConnection'));
198
-            $tdbmConfiguration->getConstructorArgumentProperty('cache')->setValue($doctrineCache);
199
-            $tdbmConfiguration->getConstructorArgumentProperty('namingStrategy')->setValue($namingStrategy);
200
-            $tdbmConfiguration->getProperty('daoFactoryInstanceName')->setValue('daoFactory');
201
-            $tdbmConfiguration->getConstructorArgumentProperty('generatorListeners')->setValue([$moufListener]);
202
-
203
-            // Let's also delete the tdbmService if migrating versions <= 4.2
204
-            if ($migratingFrom42) {
205
-                $this->moufManager->removeComponent('tdbmService');
206
-            }
207
-        } else {
208
-            $tdbmConfiguration = $this->moufManager->getInstanceDescriptor('tdbmConfiguration');
209
-        }
210
-
211
-        if (!$this->moufManager->instanceExists('tdbmService')) {
212
-            $tdbmService = $this->moufManager->createInstance('Mouf\\Database\\TDBM\\TDBMService')->setName('tdbmService');
213
-            $tdbmService->getConstructorArgumentProperty('configuration')->setValue($tdbmConfiguration);
214
-        }
215
-
216
-        // We declare our instance of the Symfony command as a Mouf instance
217
-        $generateCommand = InstallUtils::getOrCreateInstance('generateCommand', GenerateCommand::class, $this->moufManager);
218
-        $generateCommand->getConstructorArgumentProperty('tdbmConfiguration')->setValue($tdbmConfiguration);
219
-
220
-        // We register that instance descriptor using "ConsoleUtils"
221
-        $consoleUtils = new ConsoleUtils($this->moufManager);
222
-        $consoleUtils->registerCommand($generateCommand);
223
-
224
-        $this->moufManager->rewriteMouf();
225
-
226
-        TdbmController::generateDaos($this->moufManager, 'tdbmService', $daonamespace, $beannamespace, 'daoFactory', $selfedit, /*$storeInUtc,*/ $defaultPath, $storePath);
227
-
228
-        InstallUtils::continueInstall($selfedit == 'true');
229
-    }
230
-
231
-    protected $errorMsg;
232
-
233
-    private function displayErrorMsg($msg)
234
-    {
235
-        $this->errorMsg = $msg;
236
-        $this->content->addFile(__DIR__.'/../../../../views/installError.php', $this);
237
-        $this->template->toHtml();
238
-    }
24
+	/**
25
+	 * @var HtmlBlock
26
+	 */
27
+	public $content;
28
+
29
+	public $selfedit;
30
+
31
+	/**
32
+	 * The active MoufManager to be edited/viewed.
33
+	 *
34
+	 * @var MoufManager
35
+	 */
36
+	public $moufManager;
37
+
38
+	/**
39
+	 * The template used by the main page for mouf.
40
+	 *
41
+	 * @Property
42
+	 * @Compulsory
43
+	 *
44
+	 * @var TemplateInterface
45
+	 */
46
+	public $template;
47
+
48
+	/**
49
+	 * Displays the first install screen.
50
+	 *
51
+	 * @Action
52
+	 * @Logged
53
+	 *
54
+	 * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
55
+	 */
56
+	public function defaultAction($selfedit = 'false')
57
+	{
58
+		$this->selfedit = $selfedit;
59
+
60
+		if ($selfedit == 'true') {
61
+			$this->moufManager = MoufManager::getMoufManager();
62
+		} else {
63
+			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
64
+		}
65
+
66
+		$this->content->addFile(dirname(__FILE__).'/../../../../views/installStep1.php', $this);
67
+		$this->template->toHtml();
68
+	}
69
+
70
+	/**
71
+	 * Skips the install process.
72
+	 *
73
+	 * @Action
74
+	 * @Logged
75
+	 *
76
+	 * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
77
+	 */
78
+	public function skip($selfedit = 'false')
79
+	{
80
+		InstallUtils::continueInstall($selfedit == 'true');
81
+	}
82
+
83
+	protected $daoNamespace;
84
+	protected $beanNamespace;
85
+	protected $autoloadDetected;
86
+	//protected $storeInUtc;
87
+	protected $useCustomComposer = false;
88
+	protected $composerFile;
89
+
90
+	/**
91
+	 * Displays the second install screen.
92
+	 *
93
+	 * @Action
94
+	 * @Logged
95
+	 *
96
+	 * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
97
+	 */
98
+	public function configure($selfedit = 'false')
99
+	{
100
+		$this->selfedit = $selfedit;
101
+
102
+		if ($selfedit == 'true') {
103
+			$this->moufManager = MoufManager::getMoufManager();
104
+		} else {
105
+			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
106
+		}
107
+
108
+		// Let's start by performing basic checks about the instances we assume to exist.
109
+		if (!$this->moufManager->instanceExists('dbalConnection')) {
110
+			$this->displayErrorMsg("The TDBM install process assumes your database connection instance is already created, and that the name of this instance is 'dbalConnection'. Could not find the 'dbalConnection' instance.");
111
+
112
+			return;
113
+		}
114
+
115
+		if ($this->moufManager->has('tdbmConfiguration')) {
116
+			$tdbmConfiguration = $this->moufManager->getInstanceDescriptor('tdbmConfiguration');
117
+
118
+			$this->beanNamespace = $tdbmConfiguration->getConstructorArgumentProperty('beanNamespace')->getValue();
119
+			$this->daoNamespace = $tdbmConfiguration->getConstructorArgumentProperty('daoNamespace')->getValue();
120
+		} else {
121
+			// Old TDBM 4.2 fallback
122
+			$this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_tdbmService');
123
+			$this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_tdbmService');
124
+		}
125
+
126
+		if ($this->daoNamespace == null && $this->beanNamespace == null) {
127
+			$classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
128
+
129
+			$autoloadNamespaces = $classNameMapper->getManagedNamespaces();
130
+			if ($autoloadNamespaces) {
131
+				$this->autoloadDetected = true;
132
+				$rootNamespace = $autoloadNamespaces[0];
133
+				$this->daoNamespace = $rootNamespace.'Dao';
134
+				$this->beanNamespace = $rootNamespace.'Model';
135
+			} else {
136
+				$this->autoloadDetected = false;
137
+				$this->daoNamespace = 'YourApplication\\Dao';
138
+				$this->beanNamespace = 'YourApplication\\Model';
139
+			}
140
+		} else {
141
+			$this->autoloadDetected = true;
142
+		}
143
+		$this->defaultPath = true;
144
+		$this->storePath = '';
145
+
146
+		$this->castDatesToDateTime = true;
147
+
148
+		$this->content->addFile(__DIR__.'/../../../../views/installStep2.php', $this);
149
+		$this->template->toHtml();
150
+	}
151
+
152
+	/**
153
+	 * This action generates the TDBM instance, then the DAOs and Beans.
154
+	 *
155
+	 * @Action
156
+	 *
157
+	 * @param string $daonamespace
158
+	 * @param string $beannamespace
159
+	 * @param string $selfedit
160
+	 *
161
+	 * @throws \Mouf\MoufException
162
+	 */
163
+	public function generate($daonamespace, $beannamespace, /*$storeInUtc = 0,*/ $selfedit = 'false', $defaultPath = false, $storePath = '')
164
+	{
165
+		$this->selfedit = $selfedit;
166
+
167
+		if ($selfedit == 'true') {
168
+			$this->moufManager = MoufManager::getMoufManager();
169
+		} else {
170
+			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
171
+		}
172
+
173
+		$doctrineCache = $this->moufManager->getInstanceDescriptor('defaultDoctrineCache');
174
+
175
+		$migratingFrom42 = false;
176
+		if ($this->moufManager->has('tdbmService') && !$this->moufManager->has('tdbmConfiguration')) {
177
+			$migratingFrom42 = true;
178
+		}
179
+
180
+		$namingStrategy = InstallUtils::getOrCreateInstance('namingStrategy', DefaultNamingStrategy::class, $this->moufManager);
181
+		if ($migratingFrom42) {
182
+			// Let's setup the naming strategy for compatibility
183
+			$namingStrategy->getSetterProperty('setBeanPrefix')->setValue('');
184
+			$namingStrategy->getSetterProperty('setBeanSuffix')->setValue('Bean');
185
+			$namingStrategy->getSetterProperty('setBaseBeanPrefix')->setValue('');
186
+			$namingStrategy->getSetterProperty('setBaseBeanSuffix')->setValue('BaseBean');
187
+			$namingStrategy->getSetterProperty('setDaoPrefix')->setValue('');
188
+			$namingStrategy->getSetterProperty('setDaoSuffix')->setValue('Dao');
189
+			$namingStrategy->getSetterProperty('setBaseDaoPrefix')->setValue('');
190
+			$namingStrategy->getSetterProperty('setBaseDaoSuffix')->setValue('BaseDao');
191
+		}
192
+
193
+		if (!$this->moufManager->instanceExists('tdbmConfiguration')) {
194
+			$moufListener = InstallUtils::getOrCreateInstance(MoufDiListener::class, MoufDiListener::class, $this->moufManager);
195
+
196
+			$tdbmConfiguration = $this->moufManager->createInstance(MoufConfiguration::class)->setName('tdbmConfiguration');
197
+			$tdbmConfiguration->getConstructorArgumentProperty('connection')->setValue($this->moufManager->getInstanceDescriptor('dbalConnection'));
198
+			$tdbmConfiguration->getConstructorArgumentProperty('cache')->setValue($doctrineCache);
199
+			$tdbmConfiguration->getConstructorArgumentProperty('namingStrategy')->setValue($namingStrategy);
200
+			$tdbmConfiguration->getProperty('daoFactoryInstanceName')->setValue('daoFactory');
201
+			$tdbmConfiguration->getConstructorArgumentProperty('generatorListeners')->setValue([$moufListener]);
202
+
203
+			// Let's also delete the tdbmService if migrating versions <= 4.2
204
+			if ($migratingFrom42) {
205
+				$this->moufManager->removeComponent('tdbmService');
206
+			}
207
+		} else {
208
+			$tdbmConfiguration = $this->moufManager->getInstanceDescriptor('tdbmConfiguration');
209
+		}
210
+
211
+		if (!$this->moufManager->instanceExists('tdbmService')) {
212
+			$tdbmService = $this->moufManager->createInstance('Mouf\\Database\\TDBM\\TDBMService')->setName('tdbmService');
213
+			$tdbmService->getConstructorArgumentProperty('configuration')->setValue($tdbmConfiguration);
214
+		}
215
+
216
+		// We declare our instance of the Symfony command as a Mouf instance
217
+		$generateCommand = InstallUtils::getOrCreateInstance('generateCommand', GenerateCommand::class, $this->moufManager);
218
+		$generateCommand->getConstructorArgumentProperty('tdbmConfiguration')->setValue($tdbmConfiguration);
219
+
220
+		// We register that instance descriptor using "ConsoleUtils"
221
+		$consoleUtils = new ConsoleUtils($this->moufManager);
222
+		$consoleUtils->registerCommand($generateCommand);
223
+
224
+		$this->moufManager->rewriteMouf();
225
+
226
+		TdbmController::generateDaos($this->moufManager, 'tdbmService', $daonamespace, $beannamespace, 'daoFactory', $selfedit, /*$storeInUtc,*/ $defaultPath, $storePath);
227
+
228
+		InstallUtils::continueInstall($selfedit == 'true');
229
+	}
230
+
231
+	protected $errorMsg;
232
+
233
+	private function displayErrorMsg($msg)
234
+	{
235
+		$this->errorMsg = $msg;
236
+		$this->content->addFile(__DIR__.'/../../../../views/installError.php', $this);
237
+		$this->template->toHtml();
238
+	}
239 239
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Configuration.php 1 patch
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -17,171 +17,171 @@
 block discarded – undo
17 17
 class Configuration implements ConfigurationInterface
18 18
 {
19 19
 
20
-    /**
21
-     * @var string
22
-     */
23
-    private $beanNamespace;
24
-    /**
25
-     * @var string
26
-     */
27
-    private $daoNamespace;
28
-    /**
29
-     * @var Connection
30
-     */
31
-    private $connection;
32
-    /**
33
-     * @var Cache
34
-     */
35
-    private $cache;
36
-    /**
37
-     * @var SchemaAnalyzer
38
-     */
39
-    private $schemaAnalyzer;
40
-    /**
41
-     * @var LoggerInterface
42
-     */
43
-    private $logger;
44
-    /**
45
-     * @var GeneratorListenerInterface
46
-     */
47
-    private $generatorEventDispatcher;
48
-    /**
49
-     * @var NamingStrategyInterface
50
-     */
51
-    private $namingStrategy;
52
-    /**
53
-     * @var PathFinderInterface
54
-     */
55
-    private $pathFinder;
56
-    /**
57
-     * The Composer file used to detect the path where files should be written.
58
-     *
59
-     * @var string
60
-     */
61
-    private $composerFile;
62
-
63
-    /**
64
-     * @param string $beanNamespace The namespace hosting the beans
65
-     * @param string $daoNamespace The namespace hosting the DAOs
66
-     * @param Connection $connection The connection to the database
67
-     * @param Cache|null $cache The Doctrine cache to store database metadata
68
-     * @param SchemaAnalyzer|null $schemaAnalyzer The schema analyzer that will be used to find shortest paths... Will be automatically created if not passed
69
-     * @param LoggerInterface|null $logger The logger
70
-     * @param GeneratorListenerInterface[] $generatorListeners A list of listeners that will be triggered when beans/daos are generated
71
-     */
72
-    public function __construct(string $beanNamespace, string $daoNamespace, Connection $connection, NamingStrategyInterface $namingStrategy, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null, array $generatorListeners = [])
73
-    {
74
-        $this->beanNamespace = rtrim($beanNamespace, '\\');
75
-        $this->daoNamespace = rtrim($daoNamespace, '\\');
76
-        $this->connection = $connection;
77
-        $this->namingStrategy = $namingStrategy;
78
-        if ($cache !== null) {
79
-            $this->cache = $cache;
80
-        } else {
81
-            $this->cache = new VoidCache();
82
-        }
83
-        if ($schemaAnalyzer !== null) {
84
-            $this->schemaAnalyzer = $schemaAnalyzer;
85
-        } else {
86
-            $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
87
-        }
88
-        $this->logger = $logger;
89
-        $this->generatorEventDispatcher = new GeneratorEventDispatcher($generatorListeners);
90
-        $this->pathFinder = new PathFinder();
91
-    }
92
-
93
-    /**
94
-     * @return string
95
-     */
96
-    public function getBeanNamespace(): string
97
-    {
98
-        return $this->beanNamespace;
99
-    }
100
-
101
-    /**
102
-     * @return string
103
-     */
104
-    public function getDaoNamespace(): string
105
-    {
106
-        return $this->daoNamespace;
107
-    }
108
-
109
-    /**
110
-     * @return Connection
111
-     */
112
-    public function getConnection(): Connection
113
-    {
114
-        return $this->connection;
115
-    }
116
-
117
-    /**
118
-     * @return NamingStrategyInterface
119
-     */
120
-    public function getNamingStrategy(): NamingStrategyInterface
121
-    {
122
-        return $this->namingStrategy;
123
-    }
124
-
125
-    /**
126
-     * @return Cache
127
-     */
128
-    public function getCache(): Cache
129
-    {
130
-        return $this->cache;
131
-    }
132
-
133
-    /**
134
-     * @return SchemaAnalyzer
135
-     */
136
-    public function getSchemaAnalyzer(): SchemaAnalyzer
137
-    {
138
-        return $this->schemaAnalyzer;
139
-    }
140
-
141
-    /**
142
-     * @return LoggerInterface
143
-     */
144
-    public function getLogger(): ?LoggerInterface
145
-    {
146
-        return $this->logger;
147
-    }
148
-
149
-    /**
150
-     * @return GeneratorListenerInterface
151
-     */
152
-    public function getGeneratorEventDispatcher(): GeneratorListenerInterface
153
-    {
154
-        return $this->generatorEventDispatcher;
155
-    }
156
-
157
-
158
-
159
-    /**
160
-     * Creates a unique cache key for the current connection.
161
-     *
162
-     * @return string
163
-     */
164
-    private function getConnectionUniqueId(): string
165
-    {
166
-        return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
167
-    }
168
-
169
-    /**
170
-     * Returns a class able to find the place of a PHP file based on the class name.
171
-     * Useful to find the path where DAOs and beans should be written to.
172
-     *
173
-     * @return PathFinderInterface
174
-     */
175
-    public function getPathFinder(): PathFinderInterface
176
-    {
177
-        return $this->pathFinder;
178
-    }
179
-
180
-    /**
181
-     * @param PathFinderInterface $pathFinder
182
-     */
183
-    public function setPathFinder(PathFinderInterface $pathFinder)
184
-    {
185
-        $this->pathFinder = $pathFinder;
186
-    }
20
+	/**
21
+	 * @var string
22
+	 */
23
+	private $beanNamespace;
24
+	/**
25
+	 * @var string
26
+	 */
27
+	private $daoNamespace;
28
+	/**
29
+	 * @var Connection
30
+	 */
31
+	private $connection;
32
+	/**
33
+	 * @var Cache
34
+	 */
35
+	private $cache;
36
+	/**
37
+	 * @var SchemaAnalyzer
38
+	 */
39
+	private $schemaAnalyzer;
40
+	/**
41
+	 * @var LoggerInterface
42
+	 */
43
+	private $logger;
44
+	/**
45
+	 * @var GeneratorListenerInterface
46
+	 */
47
+	private $generatorEventDispatcher;
48
+	/**
49
+	 * @var NamingStrategyInterface
50
+	 */
51
+	private $namingStrategy;
52
+	/**
53
+	 * @var PathFinderInterface
54
+	 */
55
+	private $pathFinder;
56
+	/**
57
+	 * The Composer file used to detect the path where files should be written.
58
+	 *
59
+	 * @var string
60
+	 */
61
+	private $composerFile;
62
+
63
+	/**
64
+	 * @param string $beanNamespace The namespace hosting the beans
65
+	 * @param string $daoNamespace The namespace hosting the DAOs
66
+	 * @param Connection $connection The connection to the database
67
+	 * @param Cache|null $cache The Doctrine cache to store database metadata
68
+	 * @param SchemaAnalyzer|null $schemaAnalyzer The schema analyzer that will be used to find shortest paths... Will be automatically created if not passed
69
+	 * @param LoggerInterface|null $logger The logger
70
+	 * @param GeneratorListenerInterface[] $generatorListeners A list of listeners that will be triggered when beans/daos are generated
71
+	 */
72
+	public function __construct(string $beanNamespace, string $daoNamespace, Connection $connection, NamingStrategyInterface $namingStrategy, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null, array $generatorListeners = [])
73
+	{
74
+		$this->beanNamespace = rtrim($beanNamespace, '\\');
75
+		$this->daoNamespace = rtrim($daoNamespace, '\\');
76
+		$this->connection = $connection;
77
+		$this->namingStrategy = $namingStrategy;
78
+		if ($cache !== null) {
79
+			$this->cache = $cache;
80
+		} else {
81
+			$this->cache = new VoidCache();
82
+		}
83
+		if ($schemaAnalyzer !== null) {
84
+			$this->schemaAnalyzer = $schemaAnalyzer;
85
+		} else {
86
+			$this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
87
+		}
88
+		$this->logger = $logger;
89
+		$this->generatorEventDispatcher = new GeneratorEventDispatcher($generatorListeners);
90
+		$this->pathFinder = new PathFinder();
91
+	}
92
+
93
+	/**
94
+	 * @return string
95
+	 */
96
+	public function getBeanNamespace(): string
97
+	{
98
+		return $this->beanNamespace;
99
+	}
100
+
101
+	/**
102
+	 * @return string
103
+	 */
104
+	public function getDaoNamespace(): string
105
+	{
106
+		return $this->daoNamespace;
107
+	}
108
+
109
+	/**
110
+	 * @return Connection
111
+	 */
112
+	public function getConnection(): Connection
113
+	{
114
+		return $this->connection;
115
+	}
116
+
117
+	/**
118
+	 * @return NamingStrategyInterface
119
+	 */
120
+	public function getNamingStrategy(): NamingStrategyInterface
121
+	{
122
+		return $this->namingStrategy;
123
+	}
124
+
125
+	/**
126
+	 * @return Cache
127
+	 */
128
+	public function getCache(): Cache
129
+	{
130
+		return $this->cache;
131
+	}
132
+
133
+	/**
134
+	 * @return SchemaAnalyzer
135
+	 */
136
+	public function getSchemaAnalyzer(): SchemaAnalyzer
137
+	{
138
+		return $this->schemaAnalyzer;
139
+	}
140
+
141
+	/**
142
+	 * @return LoggerInterface
143
+	 */
144
+	public function getLogger(): ?LoggerInterface
145
+	{
146
+		return $this->logger;
147
+	}
148
+
149
+	/**
150
+	 * @return GeneratorListenerInterface
151
+	 */
152
+	public function getGeneratorEventDispatcher(): GeneratorListenerInterface
153
+	{
154
+		return $this->generatorEventDispatcher;
155
+	}
156
+
157
+
158
+
159
+	/**
160
+	 * Creates a unique cache key for the current connection.
161
+	 *
162
+	 * @return string
163
+	 */
164
+	private function getConnectionUniqueId(): string
165
+	{
166
+		return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
167
+	}
168
+
169
+	/**
170
+	 * Returns a class able to find the place of a PHP file based on the class name.
171
+	 * Useful to find the path where DAOs and beans should be written to.
172
+	 *
173
+	 * @return PathFinderInterface
174
+	 */
175
+	public function getPathFinder(): PathFinderInterface
176
+	{
177
+		return $this->pathFinder;
178
+	}
179
+
180
+	/**
181
+	 * @param PathFinderInterface $pathFinder
182
+	 */
183
+	public function setPathFinder(PathFinderInterface $pathFinder)
184
+	{
185
+		$this->pathFinder = $pathFinder;
186
+	}
187 187
 }
Please login to merge, or discard this patch.