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

OneToManyDataLoader   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 18
c 1
b 0
f 0
dl 0
loc 59
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 10 2
A __construct() 0 5 1
A get() 0 10 3
1
<?php
2
3
4
namespace TheCodingMachine\TDBM\QueryFactory\SmartEagerLoad;
5
6
use Doctrine\DBAL\Connection;
7
use TheCodingMachine\TDBM\TDBMException;
8
9
class OneToManyDataLoader
10
{
11
    /**
12
     * @var Connection
13
     */
14
    private $connection;
15
    /**
16
     * @var string
17
     */
18
    private $sql;
19
    /**
20
     * @var string
21
     */
22
    private $fkColumn;
23
    /**
24
     * @var array<string, array<int, array<string, mixed>>> Array of rows, indexed by foreign key.
25
     */
26
    private $data;
27
28
    public function __construct(Connection $connection, string $sql, string $fkColumn)
29
    {
30
        $this->connection = $connection;
31
        $this->sql = $sql;
32
        $this->fkColumn = $fkColumn;
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
42
        $data = [];
43
        foreach ($results as $row) {
44
            $data[$row[$this->fkColumn]][] = $row;
45
        }
46
47
        return $data;
48
    }
49
50
    /**
51
     * Returns the DB row with the given ID.
52
     * Loads all rows if necessary.
53
     * Throws an exception if nothing found.
54
     *
55
     * @param string $id
56
     * @return array<string, mixed>
57
     */
58
    public function get(string $id): array
59
    {
60
        if ($this->data === null) {
61
            $this->data = $this->load();
62
        }
63
64
        if (!isset($this->data[$id])) {
65
            return [];
66
        }
67
        return $this->data[$id];
68
    }
69
}
70