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

MapperFactory   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 0
dl 0
loc 46
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A create() 0 15 3
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