Completed
Pull Request — master (#38)
by Thomas
02:53
created

EntityManager::setConnection()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

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