AbstractHasParentRepository   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 19
c 1
b 0
f 0
dl 0
loc 48
ccs 22
cts 22
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getFullNames() 0 20 2
A getSelfAndDescendantsSubQuery() 0 16 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Repository;
6
7
use Application\Enum\Site;
8
use Application\Model\AbstractModel;
9
use Application\Traits\HasParentInterface;
10
11
/**
12
 * @template T of HasParentInterface & AbstractModel
13
 *
14
 * @extends AbstractRepository<T>
15
 */
16
abstract class AbstractHasParentRepository extends AbstractRepository
17
{
18
    /**
19
     * Native query to return the IDs of myself and all recursive descendants
20
     * of the one passed as parameter.
21
     */
22 5
    public function getSelfAndDescendantsSubQuery(int $itemId): string
23
    {
24 5
        $table = $this->getClassMetadata()->table['name'];
25
26 5
        $connection = $this->getEntityManager()->getConnection();
27 5
        $table = $connection->quoteIdentifier($table);
28
29 5
        $entireHierarchySql = "
30
            WITH RECURSIVE parent AS (
31 5
                    SELECT $table.id, $table.parent_id FROM $table WHERE $table.id IN ($itemId)
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 entries in the DB for
42
     * the given site.
43
     */
44 7
    public function getFullNames(Site $site): array
45
    {
46 7
        $connection = $this->getEntityManager()->getConnection();
47 7
        $table = $this->getClassMetadata()->getTableName();
48 7
        $table = $connection->quoteIdentifier($table);
49
50 7
        $sql = 'WITH RECURSIVE parent AS (
51 7
    SELECT id, parent_id, name AS fullName FROM ' . $table . ' WHERE parent_id IS NULL and site = :site
52
    UNION
53 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
54 7
) SELECT id, fullName FROM parent ORDER BY fullName ASC';
55
56 7
        $records = $connection->executeQuery($sql, ['site' => $site->value])->fetchAllAssociative();
57
58 7
        $result = [];
59 7
        foreach ($records as $r) {
60 7
            $result[$r['fullName']] = $r['id'];
61
        }
62
63 7
        return $result;
64
    }
65
}
66