Failed Conditions
Push — master ( 27554e...857869 )
by Luca
09:08
created

AbstractHasParentRepository::getFullNames()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 20
ccs 13
cts 13
cp 1
rs 9.9
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Repository;
6
7
use Application\Model\AbstractModel;
8
use Application\Traits\HasParentInterface;
9
10
/**
11
 * @template T of HasParentInterface & AbstractModel
12
 *
13
 * @extends AbstractRepository<T>
14
 */
15
abstract class AbstractHasParentRepository extends AbstractRepository
16
{
17
    /**
18
     * Native query to return the IDs of myself and all recursive descendants
19
     * of the one passed as parameter.
20
     */
21 5
    public function getSelfAndDescendantsSubQuery(int $itemId): string
22
    {
23 5
        $table = $this->getClassMetadata()->table['name'];
24
25 5
        $connection = $this->getEntityManager()->getConnection();
26 5
        $table = $connection->quoteIdentifier($table);
27 5
        $id = $connection->quote($itemId);
28
29 5
        $entireHierarchySql = "
30
            WITH RECURSIVE parent AS (
31 5
                    SELECT $table.id, $table.parent_id FROM $table WHERE $table.id IN ($id)
32
                    UNION
33 5
                    SELECT $table.id, $table.parent_id FROM $table JOIN parent ON $table.parent_id = parent.id
34
                )
35 5
            SELECT id FROM parent ORDER BY id";
36
37 5
        return trim($entireHierarchySql);
38
    }
39
40
    /**
41
     * Returns an array of fullNames and their ID for all domains.
42
     */
43 7
    public function getFullNames(): array
44
    {
45 7
        $connection = $this->getEntityManager()->getConnection();
46 7
        $table = $this->getClassMetadata()->getTableName();
47 7
        $table = $connection->quoteIdentifier($table);
48
49 7
        $sql = 'WITH RECURSIVE parent AS (
50 7
    SELECT id, parent_id, name AS fullName FROM ' . $table . ' WHERE parent_id IS NULL
51
    UNION
52 7
    SELECT child.id, child.parent_id, CONCAT(parent.fullName, " > ", child.name) AS fullName FROM ' . $table . ' AS child JOIN parent ON child.parent_id = parent.id
53 7
) SELECT id, fullName FROM parent ORDER BY fullName ASC';
54
55 7
        $records = $connection->executeQuery($sql)->fetchAllAssociative();
56
57 7
        $result = [];
58 7
        foreach ($records as $r) {
59 7
            $result[$r['fullName']] = $r['id'];
60
        }
61
62 7
        return $result;
63
    }
64
}
65