Passed
Pull Request — master (#41)
by Thomas
02:55
created

EntityManager::getDbal()   C

Complexity

Conditions 8
Paths 17

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 14
cts 14
cp 1
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 14
nc 17
nop 0
crap 8
1
<?php
2
3
namespace ORM;
4
5
use ORM\Dbal\Dbal;
6
use ORM\Dbal\Column;
7
use ORM\Dbal\Other;
8
use ORM\Dbal\Table;
9
use ORM\Exception\IncompletePrimaryKey;
10
use ORM\Exception\InvalidConfiguration;
11
use ORM\Exception\NoConnection;
12
use ORM\Exception\NoEntity;
13
use ORM\Exception\NotScalar;
14
use ORM\Exception\UnsupportedDriver;
15
16
/**
17
 * The EntityManager that manages the instances of Entities.
18
 *
19
 * @package ORM
20
 * @author Thomas Flori <[email protected]>
21
 */
22
class EntityManager
23
{
24
    const OPT_CONNECTION = 'connection';
25
    const OPT_TABLE_NAME_TEMPLATE = 'tableNameTemplate';
26
    const OPT_NAMING_SCHEME_TABLE = 'namingSchemeTable';
27
    const OPT_NAMING_SCHEME_COLUMN = 'namingSchemeColumn';
28
    const OPT_NAMING_SCHEME_METHODS = 'namingSchemeMethods';
29
    const OPT_QUOTING_CHARACTER = 'quotingChar';
30
    const OPT_IDENTIFIER_DIVIDER = 'identifierDivider';
31
    const OPT_BOOLEAN_TRUE = 'true';
32
    const OPT_BOOLEAN_FALSE = 'false';
33
    const OPT_DBAL_CLASS = 'dbalClass';
34
35
    /** @deprecated */
36
    const OPT_MYSQL_BOOLEAN_TRUE = 'mysqlTrue';
37
    /** @deprecated */
38
    const OPT_MYSQL_BOOLEAN_FALSE = 'mysqlFalse';
39
    /** @deprecated */
40
    const OPT_SQLITE_BOOLEAN_TRUE = 'sqliteTrue';
41
    /** @deprecated */
42
    const OPT_SQLITE_BOOLEAN_FASLE = 'sqliteFalse';
43
    /** @deprecated */
44
    const OPT_PGSQL_BOOLEAN_TRUE = 'pgsqlTrue';
45
    /** @deprecated */
46
    const OPT_PGSQL_BOOLEAN_FALSE = 'pgsqlFalse';
47
48
    /** Connection to database
49
     * @var \PDO|callable|DbConfig */
50
    protected $connection;
51
52
    /** The Database Abstraction Layer
53
     * @var Dbal */
54
    protected $dbal;
55
56
    /** The Namer instance
57
     * @var Namer */
58
    protected $namer;
59
60
    /** The Entity map
61
     * @var Entity[][] */
62
    protected $map = [];
63
64
    /** The options set for this instance
65
     * @var array */
66
    protected $options = [];
67
68
    /** Already fetched column descriptions
69
     * @var Table[]|Column[][] */
70
    protected $descriptions = [];
71
72
    /** Mapping for EntityManager instances
73
     * @var EntityManager[string]|EntityManager[string][string] */
74
    protected static $emMapping = [
75
        'byClass' => [],
76
        'byNameSpace' => [],
77
        'byParent' => [],
78
        'last' => null,
79
    ];
80
81
    /**
82
     * Constructor
83
     *
84
     * @param array $options Options for the new EntityManager
85
     * @throws InvalidConfiguration
86
     */
87 735
    public function __construct($options = [])
88
    {
89 735
        foreach ($options as $option => $value) {
90 5
            $this->setOption($option, $value);
91
        }
92
93 735
        self::$emMapping['last'] = $this;
94 735
    }
95
96
    /**
97
     * Get an instance of the EntityManager.
98
     *
99
     * If no class is given it gets $class from backtrace.
100
     *
101
     * It first gets tries the EntityManager for the Namespace of $class, then for the parents of $class. If no
102
     * EntityManager is found it returns the last created EntityManager (null if no EntityManager got created).
103
     *
104
     * @param string $class
105
     * @return EntityManager
106
     */
107 289
    public static function getInstance($class = null)
108
    {
109 289
        if (empty($class)) {
110 41
            $trace = debug_backtrace();
111 41
            if (empty($trace[1]['class'])) {
112 1
                return self::$emMapping['last'];
113
            }
114 40
            $class = $trace[1]['class'];
115
        }
116
117 288
        if (!isset(self::$emMapping['byClass'][$class])) {
118 288
            if (!($em = self::getInstanceByParent($class)) && !($em = self::getInstanceByNameSpace($class))) {
119 286
                $em = self::$emMapping['last'];
120
            }
121
122 288
            self::$emMapping['byClass'][$class] = $em;
123
        }
124
125 288
        return self::$emMapping['byClass'][$class];
126
    }
127
128
    /**
129
     * Get the instance by NameSpace mapping
130
     *
131
     * @param $class
132
     * @return EntityManager
133
     */
134 287
    private static function getInstanceByNameSpace($class)
135
    {
136 287
        foreach (self::$emMapping['byNameSpace'] as $nameSpace => $em) {
137 2
            if (strpos($class, $nameSpace) === 0) {
138 2
                return $em;
139
            }
140
        }
141
142 286
        return null;
143
    }
144
145
    /**
146
     * Get the instance by Parent class mapping
147
     *
148
     * @param $class
149
     * @return EntityManager
150
     */
151 288
    private static function getInstanceByParent($class)
152
    {
153
        // we don't need a reflection when we don't have mapping byParent
154 288
        if (empty(self::$emMapping['byParent'])) {
155 286
            return null;
156
        }
157
158 2
        $reflection = new \ReflectionClass($class);
159 2
        foreach (self::$emMapping['byParent'] as $parentClass => $em) {
160 2
            if ($reflection->isSubclassOf($parentClass)) {
161 2
                return $em;
162
            }
163
        }
164
165 1
        return null;
166
    }
167
168
    /**
169
     * Define $this EntityManager as the default EntityManager for $nameSpace
170
     *
171
     * @param $nameSpace
172
     * @return self
173
     */
174 2
    public function defineForNamespace($nameSpace)
175
    {
176 2
        self::$emMapping['byNameSpace'][$nameSpace] = $this;
177 2
        return $this;
178
    }
179
180
    /**
181
     * Define $this EntityManager as the default EntityManager for subClasses of $class
182
     *
183
     * @param $class
184
     * @return self
185
     */
186 2
    public function defineForParent($class)
187
    {
188 2
        self::$emMapping['byParent'][$class] = $this;
189 2
        return $this;
190
    }
191
192
    /**
193
     * Set $option to $value
194
     *
195
     * @param string $option One of OPT_* constants
196
     * @param mixed  $value
197
     * @return self
198
     */
199 9
    public function setOption($option, $value)
200
    {
201
        switch ($option) {
202 9
            case self::OPT_CONNECTION:
203 1
                $this->setConnection($value);
204 1
                break;
205
        }
206
207 9
        $this->options[$option] = $value;
208 9
        return $this;
209
    }
210
211
    /**
212
     * Get $option
213
     *
214
     * @param $option
215
     * @return mixed
216
     */
217 4
    public function getOption($option)
218
    {
219 4
        return isset($this->options[$option]) ? $this->options[$option] : null;
220
    }
221
222
    /**
223
     * Add connection after instantiation
224
     *
225
     * The connection can be an array of parameters for DbConfig::__construct(), a callable function that returns a PDO
226
     * instance, an instance of DbConfig or a PDO instance itself.
227
     *
228
     * When it is not a PDO instance the connection get established on first use.
229
     *
230
     * @param mixed $connection A configuration for (or a) PDO instance
231
     * @throws InvalidConfiguration
232
     */
233 10
    public function setConnection($connection)
234
    {
235 10
        if (is_callable($connection) || $connection instanceof DbConfig) {
236 6
            $this->connection = $connection;
237
        } else {
238 4
            if ($connection instanceof \PDO) {
239 1
                $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
240 1
                $this->connection = $connection;
241 3
            } elseif (is_array($connection)) {
242 2
                $dbConfigReflection = new \ReflectionClass(DbConfig::class);
243 2
                $this->connection   = $dbConfigReflection->newInstanceArgs($connection);
244
            } else {
245 1
                throw new InvalidConfiguration(
246 1
                    'Connection must be callable, DbConfig, PDO or an array of parameters for DbConfig::__constructor'
247
                );
248
            }
249
        }
250 9
    }
251
252
    /**
253
     * Get the pdo connection.
254
     *
255
     * @return \PDO
256
     * @throws NoConnection
257
     */
258 9
    public function getConnection()
259
    {
260 9
        if (!$this->connection) {
261 1
            throw new NoConnection('No database connection');
262
        }
263
264 8
        if (!$this->connection instanceof \PDO) {
265 7
            if ($this->connection instanceof DbConfig) {
266
                /** @var DbConfig $dbConfig */
267 4
                $dbConfig = $this->connection;
268 4
                $this->connection = new \PDO(
269 4
                    $dbConfig->getDsn(),
270 4
                    $dbConfig->user,
271 4
                    $dbConfig->pass,
272 4
                    $dbConfig->attributes
273
                );
274
            } else {
275 3
                $pdo = call_user_func($this->connection);
276 3
                if (!$pdo instanceof \PDO) {
277 1
                    throw new NoConnection('Getter does not return PDO instance');
278
                }
279 2
                $this->connection = $pdo;
280
            }
281 6
            $this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
282
        }
283
284 7
        return $this->connection;
285
    }
286
287
    /**
288
     * Get the Datbase Abstraction Layer
289
     *
290
     * @return Dbal
291
     */
292 11
    public function getDbal()
293
    {
294 11
        if (!$this->dbal) {
295 11
            $connectionType = $this->getConnection()->getAttribute(\PDO::ATTR_DRIVER_NAME);
296
297 11
            $options = &$this->options;
298
            // backward compatibility - deprecated
299 11
            if (isset($options[$connectionType . 'True']) && !isset($options[self::OPT_BOOLEAN_TRUE])) {
300 1
                $options[self::OPT_BOOLEAN_TRUE] = $options[$connectionType . 'True'];
301
            }
302 11
            if (isset($options[$connectionType . 'False']) && !isset($options[self::OPT_BOOLEAN_FALSE])) {
303 1
                $options[self::OPT_BOOLEAN_FALSE] = $options[$connectionType . 'False'];
304
            }
305
306 11
            $dbalClass = isset($options[self::OPT_DBAL_CLASS]) ?
307 11
                $options[self::OPT_DBAL_CLASS] : __NAMESPACE__ . '\\Dbal\\' . ucfirst($connectionType);
308 11
            if (!class_exists($dbalClass)) {
309 2
                $dbalClass = Other::class;
310
            }
311
312 11
            $this->dbal = new $dbalClass($this, $options);
313
        }
314
315 11
        return $this->dbal;
316
    }
317
318
    /**
319
     * Get the Namer instance
320
     *
321
     * @return Namer
322
     * @codeCoverageIgnore trivial code...
323
     */
324
    public function getNamer()
325
    {
326
        if (!$this->namer) {
327
            $this->namer = new Namer($this->options);
328
        }
329
330
        return $this->namer;
331
    }
332
333
    /**
334
     * Synchronizing $entity with database
335
     *
336
     * If $reset is true it also calls reset() on $entity.
337
     *
338
     * @param Entity $entity
339
     * @param bool   $reset Reset entities current data
340
     * @return bool
341
     * @throws IncompletePrimaryKey
342
     * @throws InvalidConfiguration
343
     * @throws NoConnection
344
     * @throws NoEntity
345
     */
346 13
    public function sync(Entity $entity, $reset = false)
347
    {
348 13
        $this->map($entity, true);
349
350
        /** @var EntityFetcher $fetcher */
351 10
        $fetcher = $this->fetch(get_class($entity));
352 10
        foreach ($entity->getPrimaryKey() as $attribute => $value) {
353 10
            $fetcher->where($attribute, $value);
354
        }
355
356 10
        $result = $this->getConnection()->query($fetcher->getQuery());
357 7
        if ($originalData = $result->fetch(\PDO::FETCH_ASSOC)) {
358 5
            $entity->setOriginalData($originalData);
359 5
            if ($reset) {
360 2
                $entity->reset();
361
            }
362 5
            return true;
363
        }
364 2
        return false;
365
    }
366
367
    /**
368
     * Insert $entity in database
369
     *
370
     * Returns boolean if it is not auto incremented or the value of auto incremented column otherwise.
371
     *
372
     * @param Entity $entity
373
     * @param bool   $useAutoIncrement
374
     * @return mixed
375
     * @internal
376
     */
377 11
    public function insert(Entity $entity, $useAutoIncrement = true)
378
    {
379 11
        return $this->getDbal()->insert($entity, $useAutoIncrement);
380
    }
381
382
    /**
383
     * Update $entity in database
384
     *
385
     * @param Entity $entity
386
     * @return bool
387
     * @internal
388
     */
389 6
    public function update(Entity $entity)
390
    {
391 6
        $this->getDbal()->update($entity);
392 3
        $this->sync($entity, true);
393 3
        return true;
394
    }
395
396
    /**
397
     * Delete $entity from database
398
     *
399
     * This method does not delete from the map - you can still receive the entity via fetch.
400
     *
401
     * @param Entity $entity
402
     * @return bool
403
     */
404 6
    public function delete(Entity $entity)
405
    {
406 6
        $this->getDbal()->delete($entity);
407 4
        $entity->setOriginalData([]);
408 4
        return true;
409
    }
410
411
    /**
412
     * Map $entity in the entity map
413
     *
414
     * Returns the given entity or an entity that previously got mapped. This is useful to work in every function with
415
     * the same object.
416
     *
417
     * ```php?start_inline=true
418
     * $user = $enitityManager->map(new User(['id' => 42]));
419
     * ```
420
     *
421
     * @param Entity $entity
422
     * @param bool   $update Update the entity map
423
     * @return Entity
424
     * @throws IncompletePrimaryKey
425
     */
426 26
    public function map(Entity $entity, $update = false)
427
    {
428 26
        $class = get_class($entity);
429 26
        $key = md5(serialize($entity->getPrimaryKey()));
430
431 22
        if ($update || !isset($this->map[$class][$key])) {
432 22
            $this->map[$class][$key] = $entity;
433
        }
434
435 22
        return $this->map[$class][$key];
436
    }
437
438
    /**
439
     * Fetch one or more entities
440
     *
441
     * With $primaryKey it tries to find this primary key in the entity map (carefully: mostly the database returns a
442
     * string and we do not convert them). If there is no entity in the entity map it tries to fetch the entity from
443
     * the database. The return value is then null (not found) or the entity.
444
     *
445
     * Without $primaryKey it creates an entityFetcher and returns this.
446
     *
447
     * @param string|Entity $class      The entity class you want to fetch
448
     * @param mixed         $primaryKey The primary key of the entity you want to fetch
449
     * @return Entity|EntityFetcher
450
     * @throws IncompletePrimaryKey
451
     * @throws InvalidConfiguration
452
     * @throws NoConnection
453
     * @throws NoEntity
454
     */
455 61
    public function fetch($class, $primaryKey = null)
456
    {
457 61
        $reflection = new \ReflectionClass($class);
458 61
        if (!$reflection->isSubclassOf(Entity::class)) {
459 1
            throw new NoEntity($class . ' is not a subclass of Entity');
460
        }
461
462 60
        if ($primaryKey === null) {
463 52
            return new EntityFetcher($this, $class);
464
        }
465
466 9
        if (!is_array($primaryKey)) {
467 7
            $primaryKey = [$primaryKey];
468
        }
469
470 9
        $primaryKeyVars = $class::getPrimaryKeyVars();
471 9
        if (count($primaryKeyVars) !== count($primaryKey)) {
472 1
            throw new IncompletePrimaryKey(
473 1
                'Primary key consist of [' . implode(',', $primaryKeyVars) . '] only ' . count($primaryKey) . ' given'
474
            );
475
        }
476
477 8
        $primaryKey = array_combine($primaryKeyVars, $primaryKey);
478
479 8
        if (isset($this->map[$class][md5(serialize($primaryKey))])) {
480 7
            return $this->map[$class][md5(serialize($primaryKey))];
481
        }
482
483 1
        $fetcher = new EntityFetcher($this, $class);
484 1
        foreach ($primaryKey as $attribute => $value) {
485 1
            $fetcher->where($attribute, $value);
486
        }
487
488 1
        return $fetcher->one();
489
    }
490
491
    /**
492
     * Returns $value formatted to use in a sql statement.
493
     *
494
     * @param  mixed  $value      The variable that should be returned in SQL syntax
495
     * @return string
496
     * @codeCoverageIgnore This is just a proxy
497
     */
498
    public function escapeValue($value)
499
    {
500
        return $this->getDbal()->escapeValue($value);
501
    }
502
503
    /**
504
     * Returns $identifier quoted for use in a sql statement
505
     *
506
     * @param string $identifier Identifier to quote
507
     * @return string
508
     * @codeCoverageIgnore This is just a proxy
509
     */
510
    public function escapeIdentifier($identifier)
511
    {
512
        return $this->getDbal()->escapeIdentifier($identifier);
513
    }
514
515
    /**
516
     * Returns an array of columns from $table.
517
     *
518
     * @param string $table
519
     * @return Column[]|Table
520
     */
521 2
    public function describe($table)
522
    {
523 2
        if (!isset($this->descriptions[$table])) {
524 2
            $this->descriptions[$table] = $this->getDbal()->describe($table);
525
        }
526 2
        return $this->descriptions[$table];
527
    }
528
}
529