Passed
Pull Request — master (#43)
by David
03:10
created

DbRow::_attach()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
3
namespace TheCodingMachine\TDBM;
4
5
/*
6
 Copyright (C) 2006-2017 David Négrier - THE CODING MACHINE
7
8
 This program is free software; you can redistribute it and/or modify
9
 it under the terms of the GNU General Public License as published by
10
 the Free Software Foundation; either version 2 of the License, or
11
 (at your option) any later version.
12
13
 This program is distributed in the hope that it will be useful,
14
 but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 GNU General Public License for more details.
17
18
 You should have received a copy of the GNU General Public License
19
 along with this program; if not, write to the Free Software
20
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21
 */
22
23
/**
24
 * Instances of this class represent a row in a database.
25
 *
26
 * @author David Negrier
27
 */
28
class DbRow
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
            list($sql_where, $parameters) = $this->tdbmService->buildFilterFromFilterBag($this->primaryKeys, $connection->getDatabasePlatform());
163
164
            $sql = 'SELECT * FROM '.$connection->quoteIdentifier($this->dbTableName).' WHERE '.$sql_where;
0 ignored issues
show
Security introduced by
'SELECT * FROM ' . $conn... ' WHERE ' . $sql_where is used as a query on line 165. If $sql_where can contain user-input, it is usually preferable to use a parameter placeholder like :paramName and pass the dynamic input as second argument array('param' => $sql_where).

Instead of embedding dynamic parameters in SQL, Doctrine also allows you to pass them separately and insert a placeholder instead:

function findUser(Doctrine\DBAL\Connection $con, $email) {
    // Unsafe
    $con->executeQuery("SELECT * FROM users WHERE email = '".$email."'");

    // Safe
    $con->executeQuery(
        "SELECT * FROM users WHERE email = :email",
        array('email' => $email)
    );
}
Loading history...
165
            $result = $connection->executeQuery($sql, $parameters);
166
167
            $row = $result->fetch(\PDO::FETCH_ASSOC);
168
169
            if ($row === false) {
170
                throw new TDBMException("Could not retrieve object from table \"$this->dbTableName\" using filter \".$sql_where.\" with data \"".var_export($parameters, true)."\".");
171
            }
172
173
            $this->dbRow = [];
174
            $types = $this->tdbmService->_getColumnTypesForTable($this->dbTableName);
175
176
            foreach ($row as $key => $value) {
177
                $this->dbRow[$key] = $types[$key]->convertToPHPValue($value, $connection->getDatabasePlatform());
178
            }
179
180
            $result->closeCursor();
181
182
            $this->status = TDBMObjectStateEnum::STATE_LOADED;
183
        }
184
    }
185
186
    public function get($var)
187
    {
188
        $this->_dbLoadIfNotLoaded();
189
190
        return $this->dbRow[$var] ?? null;
191
    }
192
193
    /**
194
     * Returns true if a column is set, false otherwise.
195
     *
196
     * @param string $var
197
     *
198
     * @return bool
199
     */
200
    /*public function has($var) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
201
        $this->_dbLoadIfNotLoaded();
202
203
        return isset($this->dbRow[$var]);
204
    }*/
205
206 View Code Duplication
    public function set($var, $value)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
207
    {
208
        $this->_dbLoadIfNotLoaded();
209
210
        /*
211
        // Ok, let's start by checking the column type
212
        $type = $this->db_connection->getColumnType($this->dbTableName, $var);
213
214
        // Throws an exception if the type is not ok.
215
        if (!$this->db_connection->checkType($value, $type)) {
216
            throw new TDBMException("Error! Invalid value passed for attribute '$var' of table '$this->dbTableName'. Passed '$value', but expecting '$type'");
217
        }
218
        */
219
220
        /*if ($var == $this->getPrimaryKey() && isset($this->dbRow[$var]))
0 ignored issues
show
Unused Code Comprehensibility introduced by
66% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
221
            throw new TDBMException("Error! Changing primary key value is forbidden.");*/
222
        $this->dbRow[$var] = $value;
223
        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
224
            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
225
            $this->tdbmService->_addToToSaveObjectList($this);
226
        }
227
    }
228
229
    /**
230
     * @param string             $foreignKeyName
231
     * @param AbstractTDBMObject $bean
232
     */
233 View Code Duplication
    public function setRef($foreignKeyName, AbstractTDBMObject $bean = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
234
    {
235
        $this->references[$foreignKeyName] = $bean;
236
237
        if ($this->tdbmService !== null && $this->status === TDBMObjectStateEnum::STATE_LOADED) {
238
            $this->status = TDBMObjectStateEnum::STATE_DIRTY;
239
            $this->tdbmService->_addToToSaveObjectList($this);
240
        }
241
    }
242
243
    /**
244
     * @param string $foreignKeyName A unique name for this reference
245
     *
246
     * @return AbstractTDBMObject|null
247
     */
248
    public function getRef($foreignKeyName)
249
    {
250
        if (array_key_exists($foreignKeyName, $this->references)) {
251
            return $this->references[$foreignKeyName];
252
        } elseif ($this->status === TDBMObjectStateEnum::STATE_NEW || $this->tdbmService === null) {
253
            // If the object is new and has no property, then it has to be empty.
254
            return;
255
        } else {
256
            $this->_dbLoadIfNotLoaded();
257
258
            // Let's match the name of the columns to the primary key values
259
            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
260
261
            $values = [];
262
            foreach ($fk->getUnquotedLocalColumns() as $column) {
263
                if (!isset($this->dbRow[$column])) {
264
                    return;
265
                }
266
                $values[] = $this->dbRow[$column];
267
            }
268
269
            $filter = array_combine($fk->getUnquotedForeignColumns(), $values);
270
271
            // If the foreign key points to the primary key, let's use findObjectByPk
272
            if ($this->tdbmService->getPrimaryKeyColumns($fk->getForeignTableName()) === $fk->getUnquotedForeignColumns()) {
273
                return $this->tdbmService->findObjectByPk($fk->getForeignTableName(), $filter, [], true);
274
            } else {
275
                return $this->tdbmService->findObject($fk->getForeignTableName(), $filter);
276
            }
277
        }
278
    }
279
280
    /**
281
     * Returns the name of the table this object comes from.
282
     *
283
     * @return string
284
     */
285
    public function _getDbTableName()
286
    {
287
        return $this->dbTableName;
288
    }
289
290
    /**
291
     * Method used internally by TDBM. You should not use it directly.
292
     * This method returns the status of the TDBMObject.
293
     * This is one of TDBMObjectStateEnum::STATE_NEW, TDBMObjectStateEnum::STATE_NOT_LOADED, TDBMObjectStateEnum::STATE_LOADED, TDBMObjectStateEnum::STATE_DELETED.
294
     * $status = TDBMObjectStateEnum::STATE_NEW when a new object is created with DBMObject:getNewObject.
295
     * $status = TDBMObjectStateEnum::STATE_NOT_LOADED when the object has been retrieved with getObject but when no data has been accessed in it yet.
296
     * $status = TDBMObjectStateEnum::STATE_LOADED when the object is cached in memory.
297
     *
298
     * @return string
299
     */
300
    public function _getStatus()
301
    {
302
        return $this->status;
303
    }
304
305
    /**
306
     * Override the native php clone function for TDBMObjects.
307
     */
308
    public function __clone()
309
    {
310
        // Let's load the row (before we lose the ID!)
311
        $this->_dbLoadIfNotLoaded();
312
313
        //Let's set the status to detached
314
        $this->status = TDBMObjectStateEnum::STATE_DETACHED;
315
316
        $this->primaryKeys = [];
317
318
        //Now unset the PK from the row
319
        if ($this->tdbmService) {
320
            $pk_array = $this->tdbmService->getPrimaryKeyColumns($this->dbTableName);
321
            foreach ($pk_array as $pk) {
322
                unset($this->dbRow[$pk]);
323
            }
324
        }
325
    }
326
327
    /**
328
     * Returns raw database row.
329
     *
330
     * @return array
331
     *
332
     * @throws TDBMMissingReferenceException
333
     */
334
    public function _getDbRow()
335
    {
336
        // Let's merge $dbRow and $references
337
        $dbRow = $this->dbRow;
338
339
        foreach ($this->references as $foreignKeyName => $reference) {
340
            // Let's match the name of the columns to the primary key values
341
            $fk = $this->tdbmService->_getForeignKeyByName($this->dbTableName, $foreignKeyName);
342
            $localColumns = $fk->getUnquotedLocalColumns();
343
344
            if ($reference !== null) {
345
                $refDbRows = $reference->_getDbRows();
346
                $firstRefDbRow = reset($refDbRows);
347
                if ($firstRefDbRow->_getStatus() == TDBMObjectStateEnum::STATE_DELETED) {
348
                    throw TDBMMissingReferenceException::referenceDeleted($this->dbTableName, $reference);
349
                }
350
                $pkValues = array_values($firstRefDbRow->_getPrimaryKeys());
351 View Code Duplication
                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
352
                    $dbRow[$localColumns[$i]] = $pkValues[$i];
353
                }
354
            } else {
355 View Code Duplication
                for ($i = 0, $count = count($localColumns); $i < $count; ++$i) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
356
                    $dbRow[$localColumns[$i]] = null;
357
                }
358
            }
359
        }
360
361
        return $dbRow;
362
    }
363
364
    /**
365
     * Returns references array.
366
     *
367
     * @return AbstractTDBMObject[]
368
     */
369
    public function _getReferences()
370
    {
371
        return $this->references;
372
    }
373
374
    /**
375
     * Returns the values of the primary key.
376
     * This is set when the object is in "loaded" state.
377
     *
378
     * @return array
379
     */
380
    public function _getPrimaryKeys()
381
    {
382
        return $this->primaryKeys;
383
    }
384
385
    /**
386
     * Sets the values of the primary key.
387
     * This is set when the object is in "loaded" state.
388
     *
389
     * @param array $primaryKeys
390
     */
391
    public function _setPrimaryKeys(array $primaryKeys)
392
    {
393
        $this->primaryKeys = $primaryKeys;
394
        foreach ($this->primaryKeys as $column => $value) {
395
            $this->dbRow[$column] = $value;
396
        }
397
    }
398
399
    /**
400
     * Returns the TDBMObject this bean is associated to.
401
     *
402
     * @return AbstractTDBMObject
403
     */
404
    public function getTDBMObject()
405
    {
406
        return $this->object;
407
    }
408
409
    /**
410
     * Sets the TDBMObject this bean is associated to.
411
     * Only used when cloning.
412
     *
413
     * @param AbstractTDBMObject $object
414
     */
415
    public function setTDBMObject(AbstractTDBMObject $object)
416
    {
417
        $this->object = $object;
418
    }
419
}
420