Completed
Push — 4.0 ( 75904a...fd4ff6 )
by David
02:59
created
src/Mouf/Database/TDBM/DbRow.php 1 patch
Indentation   +379 added lines, -379 removed lines patch added patch discarded remove patch
@@ -27,170 +27,170 @@  discard block
 block discarded – undo
27 27
  */
28 28
 class DbRow
29 29
 {
30
-    /**
31
-     * The service this object is bound to.
32
-     *
33
-     * @var TDBMService
34
-     */
35
-    protected $tdbmService;
36
-
37
-    /**
38
-     * The object containing this db row.
39
-     *
40
-     * @var AbstractTDBMObject
41
-     */
42
-    private $object;
43
-
44
-    /**
45
-     * The name of the table the object if issued from.
46
-     *
47
-     * @var string
48
-     */
49
-    private $dbTableName;
50
-
51
-    /**
52
-     * The array of columns returned from database.
53
-     *
54
-     * @var array
55
-     */
56
-    private $dbRow = array();
57
-
58
-    /**
59
-     * @var AbstractTDBMObject[]
60
-     */
61
-    private $references = array();
62
-
63
-    /**
64
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
65
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
66
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
67
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
68
-     *
69
-     * @var string
70
-     */
71
-    private $status;
72
-
73
-    /**
74
-     * The values of the primary key.
75
-     * This is set when the object is in "loaded" state.
76
-     *
77
-     * @var array An array of column => value
78
-     */
79
-    private $primaryKeys;
80
-
81
-    /**
82
-     * You should never call the constructor directly. Instead, you should use the
83
-     * TDBMService class that will create TDBMObjects for you.
84
-     *
85
-     * Used with id!=false when we want to retrieve an existing object
86
-     * and id==false if we want a new object
87
-     *
88
-     * @param AbstractTDBMObject $object      The object containing this db row.
89
-     * @param string             $table_name
90
-     * @param array              $primaryKeys
91
-     * @param TDBMService        $tdbmService
92
-     *
93
-     * @throws TDBMException
94
-     * @throws TDBMInvalidOperationException
95
-     */
96
-    public function __construct(AbstractTDBMObject $object, $table_name, array $primaryKeys = array(), TDBMService $tdbmService = null, array $dbRow = array())
97
-    {
98
-        $this->object = $object;
99
-        $this->dbTableName = $table_name;
100
-
101
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
102
-
103
-        if ($tdbmService === null) {
104
-            if (!empty($primaryKeys)) {
105
-                throw new TDBMException('You cannot pass an id to the DbRow constructor without passing also a TDBMService.');
106
-            }
107
-        } else {
108
-            $this->tdbmService = $tdbmService;
109
-
110
-            if (!empty($primaryKeys)) {
111
-                $this->_setPrimaryKeys($primaryKeys);
112
-                if (!empty($dbRow)) {
113
-                    $this->dbRow = $dbRow;
114
-                    $this->status = TDBMObjectStateEnum::STATE_LOADED;
115
-                } else {
116
-                    $this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
117
-                }
118
-                $tdbmService->_addToCache($this);
119
-            } else {
120
-                $this->status = TDBMObjectStateEnum::STATE_NEW;
121
-                $this->tdbmService->_addToToSaveObjectList($this);
122
-            }
123
-        }
124
-    }
125
-
126
-    public function _attach(TDBMService $tdbmService)
127
-    {
128
-        if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
129
-            throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
130
-        }
131
-        $this->tdbmService = $tdbmService;
132
-        $this->status = TDBMObjectStateEnum::STATE_NEW;
133
-        $this->tdbmService->_addToToSaveObjectList($this);
134
-    }
135
-
136
-    /**
137
-     * Sets the state of the TDBM Object
138
-     * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
139
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
140
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
141
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
142
-     *
143
-     * @param string $state
144
-     */
145
-    public function _setStatus($state)
146
-    {
147
-        $this->status = $state;
148
-    }
149
-
150
-    /**
151
-     * This is an internal method. You should not call this method yourself. The TDBM library will do it for you.
152
-     * If the object is in state 'not loaded', this method performs a query in database to load the object.
153
-     *
154
-     * A TDBMException is thrown is no object can be retrieved (for instance, if the primary key specified
155
-     * cannot be found).
156
-     */
157
-    public function _dbLoadIfNotLoaded()
158
-    {
159
-        if ($this->status == TDBMObjectStateEnum::STATE_NOT_LOADED) {
160
-            $connection = $this->tdbmService->getConnection();
161
-
162
-            /// buildFilterFromFilterBag($filter_bag)
163
-            list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys);
164
-
165
-            $sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
166
-            $result = $connection->executeQuery($sql, $parameters);
167
-
168
-            if ($result->rowCount() === 0) {
169
-                throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \"\".");
170
-            }
171
-
172
-            $row = $result->fetch(\PDO::FETCH_ASSOC);
173
-
174
-            $this->dbRow = [];
175
-            $types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
176
-
177
-            foreach ($row as $key => $value) {
178
-                $this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
179
-            }
180
-
181
-            $result->closeCursor();
182
-
183
-            $this->status = TDBMObjectStateEnum::STATE_LOADED;
184
-        }
185
-    }
186
-
187
-    public function get($var)
188
-    {
189
-        $this->_dbLoadIfNotLoaded();
190
-
191
-        // Let's first check if the key exist.
192
-        if (!isset($this->dbRow[$var])) {
193
-            /*
30
+	/**
31
+	 * The service this object is bound to.
32
+	 *
33
+	 * @var TDBMService
34
+	 */
35
+	protected $tdbmService;
36
+
37
+	/**
38
+	 * The object containing this db row.
39
+	 *
40
+	 * @var AbstractTDBMObject
41
+	 */
42
+	private $object;
43
+
44
+	/**
45
+	 * The name of the table the object if issued from.
46
+	 *
47
+	 * @var string
48
+	 */
49
+	private $dbTableName;
50
+
51
+	/**
52
+	 * The array of columns returned from database.
53
+	 *
54
+	 * @var array
55
+	 */
56
+	private $dbRow = array();
57
+
58
+	/**
59
+	 * @var AbstractTDBMObject[]
60
+	 */
61
+	private $references = array();
62
+
63
+	/**
64
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
65
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
66
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
67
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
68
+	 *
69
+	 * @var string
70
+	 */
71
+	private $status;
72
+
73
+	/**
74
+	 * The values of the primary key.
75
+	 * This is set when the object is in "loaded" state.
76
+	 *
77
+	 * @var array An array of column => value
78
+	 */
79
+	private $primaryKeys;
80
+
81
+	/**
82
+	 * You should never call the constructor directly. Instead, you should use the
83
+	 * TDBMService class that will create TDBMObjects for you.
84
+	 *
85
+	 * Used with id!=false when we want to retrieve an existing object
86
+	 * and id==false if we want a new object
87
+	 *
88
+	 * @param AbstractTDBMObject $object      The object containing this db row.
89
+	 * @param string             $table_name
90
+	 * @param array              $primaryKeys
91
+	 * @param TDBMService        $tdbmService
92
+	 *
93
+	 * @throws TDBMException
94
+	 * @throws TDBMInvalidOperationException
95
+	 */
96
+	public function __construct(AbstractTDBMObject $object, $table_name, array $primaryKeys = array(), TDBMService $tdbmService = null, array $dbRow = array())
97
+	{
98
+		$this->object = $object;
99
+		$this->dbTableName = $table_name;
100
+
101
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
102
+
103
+		if ($tdbmService === null) {
104
+			if (!empty($primaryKeys)) {
105
+				throw new TDBMException('You cannot pass an id to the DbRow constructor without passing also a TDBMService.');
106
+			}
107
+		} else {
108
+			$this->tdbmService = $tdbmService;
109
+
110
+			if (!empty($primaryKeys)) {
111
+				$this->_setPrimaryKeys($primaryKeys);
112
+				if (!empty($dbRow)) {
113
+					$this->dbRow = $dbRow;
114
+					$this->status = TDBMObjectStateEnum::STATE_LOADED;
115
+				} else {
116
+					$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
117
+				}
118
+				$tdbmService->_addToCache($this);
119
+			} else {
120
+				$this->status = TDBMObjectStateEnum::STATE_NEW;
121
+				$this->tdbmService->_addToToSaveObjectList($this);
122
+			}
123
+		}
124
+	}
125
+
126
+	public function _attach(TDBMService $tdbmService)
127
+	{
128
+		if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
129
+			throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
130
+		}
131
+		$this->tdbmService = $tdbmService;
132
+		$this->status = TDBMObjectStateEnum::STATE_NEW;
133
+		$this->tdbmService->_addToToSaveObjectList($this);
134
+	}
135
+
136
+	/**
137
+	 * Sets the state of the TDBM Object
138
+	 * One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
139
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
140
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
141
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
142
+	 *
143
+	 * @param string $state
144
+	 */
145
+	public function _setStatus($state)
146
+	{
147
+		$this->status = $state;
148
+	}
149
+
150
+	/**
151
+	 * This is an internal method. You should not call this method yourself. The TDBM library will do it for you.
152
+	 * If the object is in state 'not loaded', this method performs a query in database to load the object.
153
+	 *
154
+	 * A TDBMException is thrown is no object can be retrieved (for instance, if the primary key specified
155
+	 * cannot be found).
156
+	 */
157
+	public function _dbLoadIfNotLoaded()
158
+	{
159
+		if ($this->status == TDBMObjectStateEnum::STATE_NOT_LOADED) {
160
+			$connection = $this->tdbmService->getConnection();
161
+
162
+			/// buildFilterFromFilterBag($filter_bag)
163
+			list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys);
164
+
165
+			$sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
166
+			$result = $connection->executeQuery($sql, $parameters);
167
+
168
+			if ($result->rowCount() === 0) {
169
+				throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \"\".");
170
+			}
171
+
172
+			$row = $result->fetch(\PDO::FETCH_ASSOC);
173
+
174
+			$this->dbRow = [];
175
+			$types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
176
+
177
+			foreach ($row as $key => $value) {
178
+				$this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
179
+			}
180
+
181
+			$result->closeCursor();
182
+
183
+			$this->status = TDBMObjectStateEnum::STATE_LOADED;
184
+		}
185
+	}
186
+
187
+	public function get($var)
188
+	{
189
+		$this->_dbLoadIfNotLoaded();
190
+
191
+		// Let's first check if the key exist.
192
+		if (!isset($this->dbRow[$var])) {
193
+			/*
194 194
             // Unable to find column.... this is an error if the object has been retrieved from database.
195 195
             // If it's a new object, well, that may not be an error after all!
196 196
             // Let's check if the column does exist in the table
@@ -210,39 +210,39 @@  discard block
 block discarded – undo
210 210
             $str = "Could not find column \"$var\" in table \"$this->dbTableName\". Maybe you meant one of those columns: '".implode("', '",$result_array)."'";
211 211
 
212 212
             throw new TDBMException($str);*/
213
-            return;
214
-        }
215
-
216
-        $value = $this->dbRow[$var];
217
-        if ($value instanceof \DateTime) {
218
-            if (method_exists('DateTimeImmutable', 'createFromMutable')) { // PHP 5.6+ only
219
-                return \DateTimeImmutable::createFromMutable($value);
220
-            } else {
221
-                return new \DateTimeImmutable($value->format('c'));
222
-            }
223
-        }
224
-
225
-        return $this->dbRow[$var];
226
-    }
227
-
228
-    /**
229
-     * Returns true if a column is set, false otherwise.
230
-     *
231
-     * @param string $var
232
-     *
233
-     * @return bool
234
-     */
235
-    /*public function has($var) {
213
+			return;
214
+		}
215
+
216
+		$value = $this->dbRow[$var];
217
+		if ($value instanceof \DateTime) {
218
+			if (method_exists('DateTimeImmutable', 'createFromMutable')) { // PHP 5.6+ only
219
+				return \DateTimeImmutable::createFromMutable($value);
220
+			} else {
221
+				return new \DateTimeImmutable($value->format('c'));
222
+			}
223
+		}
224
+
225
+		return $this->dbRow[$var];
226
+	}
227
+
228
+	/**
229
+	 * Returns true if a column is set, false otherwise.
230
+	 *
231
+	 * @param string $var
232
+	 *
233
+	 * @return bool
234
+	 */
235
+	/*public function has($var) {
236 236
         $this->_dbLoadIfNotLoaded();
237 237
 
238 238
         return isset($this->dbRow[$var]);
239 239
     }*/
240 240
 
241
-    public function set($var, $value)
242
-    {
243
-        $this->_dbLoadIfNotLoaded();
241
+	public function set($var, $value)
242
+	{
243
+		$this->_dbLoadIfNotLoaded();
244 244
 
245
-        /*
245
+		/*
246 246
         // Ok, let's start by checking the column type
247 247
         $type = $this->db_connection->getColumnType($this->dbTableName, $var);
248 248
 
@@ -252,193 +252,193 @@  discard block
 block discarded – undo
252 252
         }
253 253
         */
254 254
 
255
-        /*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
255
+		/*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
256 256
             throw new TDBMException("Error! Changing primary key value is forbidden.");*/
257
-        $this->dbRow[$var] = $value;
258
-        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
259
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
260
-            $this->tdbmService->_addToToSaveObjectList($this);
261
-        }
262
-    }
263
-
264
-    /**
265
-     * @param string             $foreignKeyName
266
-     * @param AbstractTDBMObject $bean
267
-     */
268
-    public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
269
-    {
270
-        $this->references[$foreignKeyName] = $bean;
271
-
272
-        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
273
-            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
274
-            $this->tdbmService->_addToToSaveObjectList($this);
275
-        }
276
-    }
277
-
278
-    /**
279
-     * @param string $foreignKeyName A unique name for this reference
280
-     *
281
-     * @return AbstractTDBMObject|null
282
-     */
283
-    public function getRef($foreignKeyName)
284
-    {
285
-        if (array_key_exists($foreignKeyName, $this->references)) {
286
-            return $this->references[$foreignKeyName];
287
-        } elseif ($this->status === TDBMObjectStateEnum::STATE_NEW) {
288
-            // If the object is new and has no property, then it has to be empty.
289
-            return;
290
-        } else {
291
-            $this->_dbLoadIfNotLoaded();
292
-
293
-            // Let's match the name of the columns to the primary key values
294
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
295
-
296
-            $values = [];
297
-            foreach ($fk->getLocalColumns() as $column) {
298
-                if (!isset($this->dbRow[$column])) {
299
-                    return;
300
-                }
301
-                $values[] = $this->dbRow[$column];
302
-            }
303
-
304
-            $filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
305
-
306
-            return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
307
-        }
308
-    }
309
-
310
-    /**
311
-     * Returns the name of the table this object comes from.
312
-     *
313
-     * @return string
314
-     */
315
-    public function _getDbTableName()
316
-    {
317
-        return $this->dbTableName;
318
-    }
319
-
320
-    /**
321
-     * Method used internally by TDBM. You should not use it directly.
322
-     * This method returns the status of the TDBMObject.
323
-     * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
324
-     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
325
-     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
326
-     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
327
-     *
328
-     * @return string
329
-     */
330
-    public function _getStatus()
331
-    {
332
-        return $this->status;
333
-    }
334
-
335
-    /**
336
-     * Override the native php clone function for TDBMObjects.
337
-     */
338
-    public function __clone()
339
-    {
340
-        // Let's load the row (before we lose the ID!)
341
-        $this->_dbLoadIfNotLoaded();
342
-
343
-        //Let's set the status to detached
344
-        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
345
-
346
-        $this->primaryKeys = [];
347
-
348
-        //Now unset the PK from the row
349
-        if ($this->tdbmService) {
350
-            $pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
351
-            foreach ($pk_array as $pk) {
352
-                $this->dbRow[$pk] = null;
353
-            }
354
-        }
355
-    }
356
-
357
-    /**
358
-     * Returns raw database row.
359
-     *
360
-     * @return array
361
-     */
362
-    public function _getDbRow()
363
-    {
364
-        // Let's merge $dbRow and $references
365
-        $dbRow = $this->dbRow;
366
-
367
-        foreach ($this->references as $foreignKeyName => $reference) {
368
-            // Let's match the name of the columns to the primary key values
369
-            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
370
-            $localColumns = $fk->getLocalColumns();
371
-
372
-            if ($reference !== null) {
373
-                $refDbRows = $reference->_getDbRows();
374
-                $firstRefDbRow = reset($refDbRows);
375
-                $pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
376
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
377
-                    $dbRow[$localColumns[$i]] = $pkValues[$i];
378
-                }
379
-            } else {
380
-                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
381
-                    $dbRow[$localColumns[$i]] = null;
382
-                }
383
-            }
384
-        }
385
-
386
-        return $dbRow;
387
-    }
388
-
389
-    /**
390
-     * Returns references array.
391
-     *
392
-     * @return AbstractTDBMObject[]
393
-     */
394
-    public function _getReferences()
395
-    {
396
-        return $this->references;
397
-    }
398
-
399
-    /**
400
-     * Returns the values of the primary key.
401
-     * This is set when the object is in "loaded" state.
402
-     *
403
-     * @return array
404
-     */
405
-    public function _getPrimaryKeys()
406
-    {
407
-        return $this->primaryKeys;
408
-    }
409
-
410
-    /**
411
-     * Sets the values of the primary key.
412
-     * This is set when the object is in "loaded" state.
413
-     *
414
-     * @param array $primaryKeys
415
-     */
416
-    public function _setPrimaryKeys(array $primaryKeys)
417
-    {
418
-        $this->primaryKeys = $primaryKeys;
419
-        foreach ($this->primaryKeys as $column => $value) {
420
-            $this->dbRow[$column] = $value;
421
-        }
422
-    }
423
-
424
-    /**
425
-     * Returns the TDBMObject this bean is associated to.
426
-     *
427
-     * @return AbstractTDBMObject
428
-     */
429
-    public function getTDBMObject()
430
-    {
431
-        return $this->object;
432
-    }
433
-
434
-    /**
435
-     * Sets the TDBMObject this bean is associated to.
436
-     * Only used when cloning.
437
-     *
438
-     * @param AbstractTDBMObject $object
439
-     */
440
-    public function setTDBMObject(AbstractTDBMObject $object)
441
-    {
442
-        $this->object = $object;
443
-    }
257
+		$this->dbRow[$var] = $value;
258
+		if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
259
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
260
+			$this->tdbmService->_addToToSaveObjectList($this);
261
+		}
262
+	}
263
+
264
+	/**
265
+	 * @param string             $foreignKeyName
266
+	 * @param AbstractTDBMObject $bean
267
+	 */
268
+	public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
269
+	{
270
+		$this->references[$foreignKeyName] = $bean;
271
+
272
+		if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
273
+			$this->status = TDBMObjectStateEnum::STATE_DIRTY;
274
+			$this->tdbmService->_addToToSaveObjectList($this);
275
+		}
276
+	}
277
+
278
+	/**
279
+	 * @param string $foreignKeyName A unique name for this reference
280
+	 *
281
+	 * @return AbstractTDBMObject|null
282
+	 */
283
+	public function getRef($foreignKeyName)
284
+	{
285
+		if (array_key_exists($foreignKeyName, $this->references)) {
286
+			return $this->references[$foreignKeyName];
287
+		} elseif ($this->status === TDBMObjectStateEnum::STATE_NEW) {
288
+			// If the object is new and has no property, then it has to be empty.
289
+			return;
290
+		} else {
291
+			$this->_dbLoadIfNotLoaded();
292
+
293
+			// Let's match the name of the columns to the primary key values
294
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
295
+
296
+			$values = [];
297
+			foreach ($fk->getLocalColumns() as $column) {
298
+				if (!isset($this->dbRow[$column])) {
299
+					return;
300
+				}
301
+				$values[] = $this->dbRow[$column];
302
+			}
303
+
304
+			$filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
305
+
306
+			return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
307
+		}
308
+	}
309
+
310
+	/**
311
+	 * Returns the name of the table this object comes from.
312
+	 *
313
+	 * @return string
314
+	 */
315
+	public function _getDbTableName()
316
+	{
317
+		return $this->dbTableName;
318
+	}
319
+
320
+	/**
321
+	 * Method used internally by TDBM. You should not use it directly.
322
+	 * This method returns the status of the TDBMObject.
323
+	 * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
324
+	 * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
325
+	 * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
326
+	 * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
327
+	 *
328
+	 * @return string
329
+	 */
330
+	public function _getStatus()
331
+	{
332
+		return $this->status;
333
+	}
334
+
335
+	/**
336
+	 * Override the native php clone function for TDBMObjects.
337
+	 */
338
+	public function __clone()
339
+	{
340
+		// Let's load the row (before we lose the ID!)
341
+		$this->_dbLoadIfNotLoaded();
342
+
343
+		//Let's set the status to detached
344
+		$this->status = TDBMObjectStateEnum::STATE_DETACHED;
345
+
346
+		$this->primaryKeys = [];
347
+
348
+		//Now unset the PK from the row
349
+		if ($this->tdbmService) {
350
+			$pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
351
+			foreach ($pk_array as $pk) {
352
+				$this->dbRow[$pk] = null;
353
+			}
354
+		}
355
+	}
356
+
357
+	/**
358
+	 * Returns raw database row.
359
+	 *
360
+	 * @return array
361
+	 */
362
+	public function _getDbRow()
363
+	{
364
+		// Let's merge $dbRow and $references
365
+		$dbRow = $this->dbRow;
366
+
367
+		foreach ($this->references as $foreignKeyName => $reference) {
368
+			// Let's match the name of the columns to the primary key values
369
+			$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
370
+			$localColumns = $fk->getLocalColumns();
371
+
372
+			if ($reference !== null) {
373
+				$refDbRows = $reference->_getDbRows();
374
+				$firstRefDbRow = reset($refDbRows);
375
+				$pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
376
+				for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
377
+					$dbRow[$localColumns[$i]] = $pkValues[$i];
378
+				}
379
+			} else {
380
+				for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
381
+					$dbRow[$localColumns[$i]] = null;
382
+				}
383
+			}
384
+		}
385
+
386
+		return $dbRow;
387
+	}
388
+
389
+	/**
390
+	 * Returns references array.
391
+	 *
392
+	 * @return AbstractTDBMObject[]
393
+	 */
394
+	public function _getReferences()
395
+	{
396
+		return $this->references;
397
+	}
398
+
399
+	/**
400
+	 * Returns the values of the primary key.
401
+	 * This is set when the object is in "loaded" state.
402
+	 *
403
+	 * @return array
404
+	 */
405
+	public function _getPrimaryKeys()
406
+	{
407
+		return $this->primaryKeys;
408
+	}
409
+
410
+	/**
411
+	 * Sets the values of the primary key.
412
+	 * This is set when the object is in "loaded" state.
413
+	 *
414
+	 * @param array $primaryKeys
415
+	 */
416
+	public function _setPrimaryKeys(array $primaryKeys)
417
+	{
418
+		$this->primaryKeys = $primaryKeys;
419
+		foreach ($this->primaryKeys as $column => $value) {
420
+			$this->dbRow[$column] = $value;
421
+		}
422
+	}
423
+
424
+	/**
425
+	 * Returns the TDBMObject this bean is associated to.
426
+	 *
427
+	 * @return AbstractTDBMObject
428
+	 */
429
+	public function getTDBMObject()
430
+	{
431
+		return $this->object;
432
+	}
433
+
434
+	/**
435
+	 * Sets the TDBMObject this bean is associated to.
436
+	 * Only used when cloning.
437
+	 *
438
+	 * @param AbstractTDBMObject $object
439
+	 */
440
+	public function setTDBMObject(AbstractTDBMObject $object)
441
+	{
442
+		$this->object = $object;
443
+	}
444 444
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Controllers/TdbmInstallController.php 1 patch
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -15,168 +15,168 @@
 block discarded – undo
15 15
  */
16 16
 class TdbmInstallController extends Controller
17 17
 {
18
-    /**
19
-     * @var HtmlBlock
20
-     */
21
-    public $content;
22
-
23
-    public $selfedit;
24
-
25
-    /**
26
-     * The active MoufManager to be edited/viewed.
27
-     *
28
-     * @var MoufManager
29
-     */
30
-    public $moufManager;
31
-
32
-    /**
33
-     * The template used by the main page for mouf.
34
-     *
35
-     * @Property
36
-     * @Compulsory
37
-     *
38
-     * @var TemplateInterface
39
-     */
40
-    public $template;
41
-
42
-    /**
43
-     * Displays the first install screen.
44
-     *
45
-     * @Action
46
-     * @Logged
47
-     *
48
-     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
49
-     */
50
-    public function defaultAction($selfedit = 'false')
51
-    {
52
-        $this->selfedit = $selfedit;
53
-
54
-        if ($selfedit == 'true') {
55
-            $this->moufManager = MoufManager::getMoufManager();
56
-        } else {
57
-            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
58
-        }
59
-
60
-        $this->content->addFile(dirname(__FILE__).'/../../../../views/installStep1.php', $this);
61
-        $this->template->toHtml();
62
-    }
63
-
64
-    /**
65
-     * Skips the install process.
66
-     *
67
-     * @Action
68
-     * @Logged
69
-     *
70
-     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
71
-     */
72
-    public function skip($selfedit = 'false')
73
-    {
74
-        InstallUtils::continueInstall($selfedit == 'true');
75
-    }
76
-
77
-    protected $daoNamespace;
78
-    protected $beanNamespace;
79
-    protected $autoloadDetected;
80
-    protected $storeInUtc;
81
-    protected $useCustomComposer = false;
82
-
83
-    /**
84
-     * Displays the second install screen.
85
-     *
86
-     * @Action
87
-     * @Logged
88
-     *
89
-     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
90
-     */
91
-    public function configure($selfedit = 'false')
92
-    {
93
-        $this->selfedit = $selfedit;
94
-
95
-        if ($selfedit == 'true') {
96
-            $this->moufManager = MoufManager::getMoufManager();
97
-        } else {
98
-            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
99
-        }
100
-
101
-        // Let's start by performing basic checks about the instances we assume to exist.
102
-        if (!$this->moufManager->instanceExists('dbalConnection')) {
103
-            $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.");
104
-
105
-            return;
106
-        }
107
-
108
-        $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_tdbmService');
109
-        $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_tdbmService');
110
-
111
-        if ($this->daoNamespace == null && $this->beanNamespace == null) {
112
-            $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
113
-
114
-            $autoloadNamespaces = $classNameMapper->getManagedNamespaces();
115
-            if ($autoloadNamespaces) {
116
-                $this->autoloadDetected = true;
117
-                $rootNamespace = $autoloadNamespaces[0];
118
-                $this->daoNamespace = $rootNamespace.'Model\\Dao';
119
-                $this->beanNamespace = $rootNamespace.'Model\\Bean';
120
-            } else {
121
-                $this->autoloadDetected = false;
122
-                $this->daoNamespace = 'YourApplication\\Model\\Dao';
123
-                $this->beanNamespace = 'YourApplication\\Model\\Bean';
124
-            }
125
-        } else {
126
-            $this->autoloadDetected = true;
127
-        }
128
-        $this->defaultPath = true;
129
-        $this->storePath = '';
130
-
131
-        $this->castDatesToDateTime = true;
132
-
133
-        $this->content->addFile(dirname(__FILE__).'/../../../../views/installStep2.php', $this);
134
-        $this->template->toHtml();
135
-    }
136
-
137
-    /**
138
-     * This action generates the TDBM instance, then the DAOs and Beans.
139
-     *
140
-     * @Action
141
-     *
142
-     * @param string $daonamespace
143
-     * @param string $beannamespace
144
-     * @param int    $storeInUtc
145
-     * @param string $selfedit
146
-     *
147
-     * @throws \Mouf\MoufException
148
-     */
149
-    public function generate($daonamespace, $beannamespace, $storeInUtc = 0, $selfedit = 'false', $defaultPath = false, $storePath = '')
150
-    {
151
-        $this->selfedit = $selfedit;
152
-
153
-        if ($selfedit == 'true') {
154
-            $this->moufManager = MoufManager::getMoufManager();
155
-        } else {
156
-            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
157
-        }
158
-
159
-        $doctrineCache = $this->moufManager->getInstanceDescriptor('defaultDoctrineCache');
160
-
161
-        if (!$this->moufManager->instanceExists('tdbmService')) {
162
-            $tdbmService = $this->moufManager->createInstance('Mouf\\Database\\TDBM\\TDBMService')->setName('tdbmService');
163
-            $tdbmService->getConstructorArgumentProperty('connection')->setValue($this->moufManager->getInstanceDescriptor('dbalConnection'));
164
-            $tdbmService->getConstructorArgumentProperty('cache')->setValue($doctrineCache);
165
-        }
166
-
167
-        $this->moufManager->rewriteMouf();
168
-
169
-        TdbmController::generateDaos($this->moufManager, 'tdbmService', $daonamespace, $beannamespace, 'DaoFactory', 'daoFactory', $selfedit, $storeInUtc, $defaultPath, $storePath);
170
-
171
-        InstallUtils::continueInstall($selfedit == 'true');
172
-    }
173
-
174
-    protected $errorMsg;
175
-
176
-    private function displayErrorMsg($msg)
177
-    {
178
-        $this->errorMsg = $msg;
179
-        $this->content->addFile(dirname(__FILE__).'/../../../../views/installError.php', $this);
180
-        $this->template->toHtml();
181
-    }
18
+	/**
19
+	 * @var HtmlBlock
20
+	 */
21
+	public $content;
22
+
23
+	public $selfedit;
24
+
25
+	/**
26
+	 * The active MoufManager to be edited/viewed.
27
+	 *
28
+	 * @var MoufManager
29
+	 */
30
+	public $moufManager;
31
+
32
+	/**
33
+	 * The template used by the main page for mouf.
34
+	 *
35
+	 * @Property
36
+	 * @Compulsory
37
+	 *
38
+	 * @var TemplateInterface
39
+	 */
40
+	public $template;
41
+
42
+	/**
43
+	 * Displays the first install screen.
44
+	 *
45
+	 * @Action
46
+	 * @Logged
47
+	 *
48
+	 * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
49
+	 */
50
+	public function defaultAction($selfedit = 'false')
51
+	{
52
+		$this->selfedit = $selfedit;
53
+
54
+		if ($selfedit == 'true') {
55
+			$this->moufManager = MoufManager::getMoufManager();
56
+		} else {
57
+			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
58
+		}
59
+
60
+		$this->content->addFile(dirname(__FILE__).'/../../../../views/installStep1.php', $this);
61
+		$this->template->toHtml();
62
+	}
63
+
64
+	/**
65
+	 * Skips the install process.
66
+	 *
67
+	 * @Action
68
+	 * @Logged
69
+	 *
70
+	 * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
71
+	 */
72
+	public function skip($selfedit = 'false')
73
+	{
74
+		InstallUtils::continueInstall($selfedit == 'true');
75
+	}
76
+
77
+	protected $daoNamespace;
78
+	protected $beanNamespace;
79
+	protected $autoloadDetected;
80
+	protected $storeInUtc;
81
+	protected $useCustomComposer = false;
82
+
83
+	/**
84
+	 * Displays the second install screen.
85
+	 *
86
+	 * @Action
87
+	 * @Logged
88
+	 *
89
+	 * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
90
+	 */
91
+	public function configure($selfedit = 'false')
92
+	{
93
+		$this->selfedit = $selfedit;
94
+
95
+		if ($selfedit == 'true') {
96
+			$this->moufManager = MoufManager::getMoufManager();
97
+		} else {
98
+			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
99
+		}
100
+
101
+		// Let's start by performing basic checks about the instances we assume to exist.
102
+		if (!$this->moufManager->instanceExists('dbalConnection')) {
103
+			$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.");
104
+
105
+			return;
106
+		}
107
+
108
+		$this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_tdbmService');
109
+		$this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_tdbmService');
110
+
111
+		if ($this->daoNamespace == null && $this->beanNamespace == null) {
112
+			$classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
113
+
114
+			$autoloadNamespaces = $classNameMapper->getManagedNamespaces();
115
+			if ($autoloadNamespaces) {
116
+				$this->autoloadDetected = true;
117
+				$rootNamespace = $autoloadNamespaces[0];
118
+				$this->daoNamespace = $rootNamespace.'Model\\Dao';
119
+				$this->beanNamespace = $rootNamespace.'Model\\Bean';
120
+			} else {
121
+				$this->autoloadDetected = false;
122
+				$this->daoNamespace = 'YourApplication\\Model\\Dao';
123
+				$this->beanNamespace = 'YourApplication\\Model\\Bean';
124
+			}
125
+		} else {
126
+			$this->autoloadDetected = true;
127
+		}
128
+		$this->defaultPath = true;
129
+		$this->storePath = '';
130
+
131
+		$this->castDatesToDateTime = true;
132
+
133
+		$this->content->addFile(dirname(__FILE__).'/../../../../views/installStep2.php', $this);
134
+		$this->template->toHtml();
135
+	}
136
+
137
+	/**
138
+	 * This action generates the TDBM instance, then the DAOs and Beans.
139
+	 *
140
+	 * @Action
141
+	 *
142
+	 * @param string $daonamespace
143
+	 * @param string $beannamespace
144
+	 * @param int    $storeInUtc
145
+	 * @param string $selfedit
146
+	 *
147
+	 * @throws \Mouf\MoufException
148
+	 */
149
+	public function generate($daonamespace, $beannamespace, $storeInUtc = 0, $selfedit = 'false', $defaultPath = false, $storePath = '')
150
+	{
151
+		$this->selfedit = $selfedit;
152
+
153
+		if ($selfedit == 'true') {
154
+			$this->moufManager = MoufManager::getMoufManager();
155
+		} else {
156
+			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
157
+		}
158
+
159
+		$doctrineCache = $this->moufManager->getInstanceDescriptor('defaultDoctrineCache');
160
+
161
+		if (!$this->moufManager->instanceExists('tdbmService')) {
162
+			$tdbmService = $this->moufManager->createInstance('Mouf\\Database\\TDBM\\TDBMService')->setName('tdbmService');
163
+			$tdbmService->getConstructorArgumentProperty('connection')->setValue($this->moufManager->getInstanceDescriptor('dbalConnection'));
164
+			$tdbmService->getConstructorArgumentProperty('cache')->setValue($doctrineCache);
165
+		}
166
+
167
+		$this->moufManager->rewriteMouf();
168
+
169
+		TdbmController::generateDaos($this->moufManager, 'tdbmService', $daonamespace, $beannamespace, 'DaoFactory', 'daoFactory', $selfedit, $storeInUtc, $defaultPath, $storePath);
170
+
171
+		InstallUtils::continueInstall($selfedit == 'true');
172
+	}
173
+
174
+	protected $errorMsg;
175
+
176
+	private function displayErrorMsg($msg)
177
+	{
178
+		$this->errorMsg = $msg;
179
+		$this->content->addFile(dirname(__FILE__).'/../../../../views/installError.php', $this);
180
+		$this->template->toHtml();
181
+	}
182 182
 }
Please login to merge, or discard this patch.