Passed
Pull Request — master (#172)
by David
02:33
created

ManyToOneDataLoader::load()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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