Passed
Pull Request — master (#172)
by David
06:43
created

ManyToOneDataLoader::get()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 3
nc 4
nop 1
1
<?php
2
3
4
namespace TheCodingMachine\TDBM\QueryFactory\SmartEagerLoad;
5
6
7
use Doctrine\DBAL\Connection;
8
use TheCodingMachine\TDBM\TDBMException;
9
10
class ManyToOneDataLoader
11
{
12
    /**
13
     * @var Connection
14
     */
15
    private $connection;
16
    /**
17
     * @var string
18
     */
19
    private $sql;
20
    /**
21
     * @var string
22
     */
23
    private $idColumn;
24
    /**
25
     * @var array<string, array<string, mixed>> Rows, indexed by ID.
26
     */
27
    private $data;
28
29
    public function __construct(Connection $connection, string $sql, string $idColumn)
30
    {
31
        $this->connection = $connection;
32
        $this->sql = $sql;
33
        $this->idColumn = $idColumn;
34
    }
35
36
    /**
37
     * @return array<string, array<string, mixed>> Rows, indexed by ID.
38
     */
39
    private function load(): array
40
    {
41
        $results = $this->connection->fetchAll($this->sql);
42
        $results = array_column($results, null, $this->idColumn);
43
44
        return $results;
45
    }
46
47
    /**
48
     * Returns the DB row with the given ID.
49
     * Loads all rows if necessary.
50
     * Throws an exception if nothing found.
51
     *
52
     * @param string $id
53
     * @return array<string, mixed>
54
     */
55
    public function get(string $id): array
56
    {
57
        if ($this->data === null) {
58
            $this->data = $this->load();
59
        }
60
61
        if (!isset($this->data[$id])) {
62
            throw new TDBMException('The loaded dataset does not contain row with ID "'.$id.'"');
63
        }
64
        return $this->data[$id];
65
    }
66
}
67