aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/SQLUnionQuery.php
blob: 8587a42926729d284733537d902defd63b6f4e48 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
 * This class is to be used in combination with SQLQuery if you need to
 * combine many SQLQuery objets into one single query using UNION.
 */
class SQLUnionQuery
{
    /**
     * @var SQLQuery[]
     */
    protected array $queries;
    protected bool $unionAll = false;

    public function __construct(SQLQuery ...$queries)
    {
        $this->queries = $queries;
    }

    /**
     * Adds a query to the union.
     */
    public function add(SQLQuery $query): void
    {
        $this->queries[] = $query;
    }

    /**
     * Whether UNION ALL should be used or not
     */
    public function setUnionAll(bool $unionAll): void
    {
        $this->unionAll = $unionAll;
    }

    /**
     * Returns the combined query
     */
    public function getQuery(): string
    {
        $queries    = [];
        foreach ($this->queries as $query) {
            $queries[] = $query->show();
        }

        $query = implode(
            $this->unionAll ? ' UNION ALL ' : ' UNION ',
            $queries
        );

        return $query;
    }

    /**
     * Returns the used parameters
     */
    public function getParameters(): array
    {
        $parameters = [];
        foreach ($this->queries as $query) {
            $parameters = array_merge($parameters, $query->settings['parameter'] ?? []);
        }

        return $parameters;
    }

    /**
     * Fetches all rows from the combined query
     */
    public function fetchAll(?callable $callable = null): array
    {
        return DBManager::get()->fetchAll(
            $this->getQuery(),
            $this->getParameters(),
            $callable
        );
    }

    /**
     * Fetches a single column from all rows of the combined query
     */
    public function fetchFirst(int $columnNumber = 0): array
    {
        return $this->fetchAll(function ($row) use ($columnNumber) {
            return array_values($row)[$columnNumber];
        });
    }
}