Completed
Push — master ( 83aa6c...801091 )
by Mārtiņš
02:12
created

MapperFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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