MapperFactory::create()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 14
c 0
b 0
f 0
ccs 8
cts 8
cp 1
rs 10
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Palladium\Component;
4
5
use RuntimeException;
6
use PDO;
7
use Palladium\Contract\CanCreateMapper;
8
9
class MapperFactory implements CanCreateMapper
10
{
11
12
    private $connection;
13
    private $cache = [];
14
    private $table;
15
16
    /**
17
     * Creates new factory instance
18
     *
19
     * @param PDO $connection
20
     * @param string $table A list of table name aliases
21
     */
22 27
    public function __construct(PDO $connection, string $table)
23
    {
24 27
        $this->connection = $connection;
25 27
        $this->table = $table;
26 27
    }
27
28
29
    /**
30
     * Method for retrieving an SQL data mapper instance
31
     *
32
     * @param string $className Fully qualified class name of the mapper
33
     *
34
     * @throws RuntimeException if mapper's class can't be found
35
     *
36
     * @return DataMapper
37
     */
38 27
    public function create(string $className)
39
    {
40 27
        if (array_key_exists($className, $this->cache)) {
41 11
            return $this->cache[$className];
42
        }
43
44 27
        if (!class_exists($className)) {
45 1
            throw new RuntimeException("Mapper not found. Attempted to load '{$className}'.");
46
        }
47
48 26
        $instance = new $className($this->connection, $this->table);
49 26
        $this->cache[$className] = $instance;
50
51 26
        return $instance;
52
    }
53
54
}
55