-
Notifications
You must be signed in to change notification settings - Fork 25
/
DbRow.php
436 lines (373 loc) · 14.5 KB
/
DbRow.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
<?php
namespace Mouf\Database\TDBM;
/*
Copyright (C) 2006-2016 David Négrier - THE CODING MACHINE
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* Instances of this class represent a row in a database.
*
* @author David Negrier
*/
class DbRow
{
/**
* The service this object is bound to.
*
* @var TDBMService
*/
protected $tdbmService;
/**
* The object containing this db row.
*
* @var AbstractTDBMObject
*/
private $object;
/**
* The name of the table the object if issued from.
*
* @var string
*/
private $dbTableName;
/**
* The array of columns returned from database.
*
* @var array
*/
private $dbRow = array();
/**
* @var AbstractTDBMObject[]
*/
private $references = array();
/**
* One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
* $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
* $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
* $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
*
* @var string
*/
private $status;
/**
* The values of the primary key.
* This is set when the object is in "loaded" state.
*
* @var array An array of column => value
*/
private $primaryKeys;
/**
* You should never call the constructor directly. Instead, you should use the
* TDBMService class that will create TDBMObjects for you.
*
* Used with id!=false when we want to retrieve an existing object
* and id==false if we want a new object
*
* @param AbstractTDBMObject $object The object containing this db row.
* @param string $table_name
* @param array $primaryKeys
* @param TDBMService $tdbmService
*
* @throws TDBMException
* @throws TDBMInvalidOperationException
*/
public function __construct(AbstractTDBMObject $object, $table_name, array $primaryKeys = array(), TDBMService $tdbmService = null, array $dbRow = array())
{
$this->object = $object;
$this->dbTableName = $table_name;
$this->status = TDBMObjectStateEnum::STATE_DETACHED;
if ($tdbmService === null) {
if (!empty($primaryKeys)) {
throw new TDBMException('You cannot pass an id to the DbRow constructor without passing also a TDBMService.');
}
} else {
$this->tdbmService = $tdbmService;
if (!empty($primaryKeys)) {
$this->_setPrimaryKeys($primaryKeys);
if (!empty($dbRow)) {
$this->dbRow = $dbRow;
$this->status = TDBMObjectStateEnum::STATE_LOADED;
} else {
$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
}
$tdbmService->_addToCache($this);
} else {
$this->status = TDBMObjectStateEnum::STATE_NEW;
$this->tdbmService->_addToToSaveObjectList($this);
}
}
}
public function _attach(TDBMService $tdbmService)
{
if ($this->status !== TDBMObjectStateEnum::STATE_DETACHED) {
throw new TDBMInvalidOperationException('Cannot attach an object that is already attached to TDBM.');
}
$this->tdbmService = $tdbmService;
$this->status = TDBMObjectStateEnum::STATE_NEW;
$this->tdbmService->_addToToSaveObjectList($this);
}
/**
* Sets the state of the TDBM Object
* One of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
* $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
* $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
* $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
*
* @param string $state
*/
public function _setStatus($state)
{
$this->status = $state;
}
/**
* This is an internal method. You should not call this method yourself. The TDBM library will do it for you.
* If the object is in state 'not loaded', this method performs a query in database to load the object.
*
* A TDBMException is thrown is no object can be retrieved (for instance, if the primary key specified
* cannot be found).
*/
public function _dbLoadIfNotLoaded()
{
if ($this->status == TDBMObjectStateEnum::STATE_NOT_LOADED) {
$connection = $this->tdbmService->getConnection();
/// buildFilterFromFilterBag($filter_bag)
list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys);
$sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
$result = $connection->executeQuery($sql, $parameters);
if ($result->rowCount() === 0) {
throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \"\".");
}
$row = $result->fetch(\PDO::FETCH_ASSOC);
$this->dbRow = [];
$types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
foreach ($row as $key => $value) {
$this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
}
$result->closeCursor();
$this->status = TDBMObjectStateEnum::STATE_LOADED;
}
}
public function get($var)
{
$this->_dbLoadIfNotLoaded();
// Let's first check if the key exist.
if (!isset($this->dbRow[$var])) {
/*
// Unable to find column.... this is an error if the object has been retrieved from database.
// If it's a new object, well, that may not be an error after all!
// Let's check if the column does exist in the table
$column_exist = $this->db_connection->checkColumnExist($this->dbTableName, $var);
// If the column DOES exist, then the object is new, and therefore, we should
// return null.
if ($column_exist === true) {
return null;
}
// Let's try to be accurate in error reporting. The checkColumnExist returns an array of closest matches.
$result_array = $column_exist;
if (count($result_array)==1)
$str = "Could not find column \"$var\" in table \"$this->dbTableName\". Maybe you meant this column: '".$result_array[0]."'";
else
$str = "Could not find column \"$var\" in table \"$this->dbTableName\". Maybe you meant one of those columns: '".implode("', '",$result_array)."'";
throw new TDBMException($str);*/
return;
}
$value = $this->dbRow[$var];
if ($value instanceof \DateTime) {
if (method_exists('DateTimeImmutable', 'createFromMutable')) { // PHP 5.6+ only
return \DateTimeImmutable::createFromMutable($value);
} else {
return new \DateTimeImmutable($value->format('c'));
}
}
return $this->dbRow[$var];
}
/**
* Returns true if a column is set, false otherwise.
*
* @param string $var
*
* @return bool
*/
/*public function has($var) {
$this->_dbLoadIfNotLoaded();
return isset($this->dbRow[$var]);
}*/
public function set($var, $value)
{
$this->_dbLoadIfNotLoaded();
/*
// Ok, let's start by checking the column type
$type = $this->db_connection->getColumnType($this->dbTableName, $var);
// Throws an exception if the type is not ok.
if (!$this->db_connection->checkType($value, $type)) {
throw new TDBMException("Error! Invalid value passed for attribute '$var' of table '$this->dbTableName'. Passed '$value', but expecting '$type'");
}
*/
/*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
throw new TDBMException("Error! Changing primary key value is forbidden.");*/
$this->dbRow[$var] = $value;
if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
$this->status = TDBMObjectStateEnum::STATE_DIRTY;
$this->tdbmService->_addToToSaveObjectList($this);
}
}
/**
* @param string $foreignKeyName
* @param AbstractTDBMObject $bean
*/
public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
{
$this->references[$foreignKeyName] = $bean;
if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
$this->status = TDBMObjectStateEnum::STATE_DIRTY;
$this->tdbmService->_addToToSaveObjectList($this);
}
}
/**
* @param string $foreignKeyName A unique name for this reference
*
* @return AbstractTDBMObject|null
*/
public function getRef($foreignKeyName)
{
if (isset($this->references[$foreignKeyName])) {
return $this->references[$foreignKeyName];
} elseif ($this->status === TDBMObjectStateEnum::STATE_NEW) {
// If the object is new and has no property, then it has to be empty.
return;
} else {
$this->_dbLoadIfNotLoaded();
// Let's match the name of the columns to the primary key values
$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
$values = [];
foreach ($fk->getLocalColumns() as $column) {
$values[] = $this->dbRow[$column];
}
$filter = array_combine($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()), $values);
return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
}
}
/**
* Returns the name of the table this object comes from.
*
* @return string
*/
public function _getDbTableName()
{
return $this->dbTableName;
}
/**
* Method used internally by TDBM. You should not use it directly.
* This method returns the status of the TDBMObject.
* This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
* $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
* $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
* $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
*
* @return string
*/
public function _getStatus()
{
return $this->status;
}
/**
* Override the native php clone function for TDBMObjects.
*/
public function __clone()
{
// Let's load the row (before we lose the ID!)
$this->_dbLoadIfNotLoaded();
//Let's set the status to detached
$this->status = TDBMObjectStateEnum::STATE_DETACHED;
$this->primaryKeys = [];
//Now unset the PK from the row
if ($this->tdbmService) {
$pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
foreach ($pk_array as $pk) {
$this->dbRow[$pk] = null;
}
}
}
/**
* Returns raw database row.
*
* @return array
*/
public function _getDbRow()
{
// Let's merge $dbRow and $references
$dbRow = $this->dbRow;
foreach ($this->references as $foreignKeyName => $reference) {
// Let's match the name of the columns to the primary key values
$fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
$refDbRows = $reference->_getDbRows();
$firstRefDbRow = reset($refDbRows);
$pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
$localColumns = $fk->getLocalColumns();
for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
$dbRow[$localColumns[$i]] = $pkValues[$i];
}
}
return $dbRow;
}
/**
* Returns references array.
*
* @return AbstractTDBMObject[]
*/
public function _getReferences()
{
return $this->references;
}
/**
* Returns the values of the primary key.
* This is set when the object is in "loaded" state.
*
* @return array
*/
public function _getPrimaryKeys()
{
return $this->primaryKeys;
}
/**
* Sets the values of the primary key.
* This is set when the object is in "loaded" state.
*
* @param array $primaryKeys
*/
public function _setPrimaryKeys(array $primaryKeys)
{
$this->primaryKeys = $primaryKeys;
foreach ($this->primaryKeys as $column => $value) {
$this->dbRow[$column] = $value;
}
}
/**
* Returns the TDBMObject this bean is associated to.
*
* @return AbstractTDBMObject
*/
public function getTDBMObject()
{
return $this->object;
}
/**
* Sets the TDBMObject this bean is associated to.
* Only used when cloning.
*
* @param AbstractTDBMObject $object
*/
public function setTDBMObject(AbstractTDBMObject $object)
{
$this->object = $object;
}
}