Passed
Push — 2.x ( 0f4623...13490d )
by Aleksei
33:35 queued 13:35
created

SubQuery::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cycle ORM package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Cycle\Database\Injection;
13
14
use Cycle\Database\Driver\CompilerInterface;
15
use Cycle\Database\Query\Interpolator;
16
use Cycle\Database\Query\QueryParameters;
17
use Cycle\Database\Query\SelectQuery;
18
19
/**
20
 * This fragment is used to inject a whole select statement into
21
 * FROM and SELECT parts of the query.
22
 *
23
 * Examples:
24
 *
25
 * ```
26
 *  $subQuery = new SubQuery($queryBuilder->select()->from(['users']),'u');
27
 *  $query = $queryBuilder->select()->from($subQuery);
28
 * ```
29
 *
30
 * Will provide SQL like this: SELECT * FROM (SELECT * FROM users) AS u
31
 *
32
 * ```
33
 *  $subQuery = new SubQuery($queryBuilder->select()->from(['users']),'u');
34
 *  $query = $queryBuilder->select($subQuery)->from(['employee']);
35
 * ```
36
 *
37
 * Will provide SQL like this: SELECT *, (SELECT * FROM users) AS u FROM employee
38
 */
39
class SubQuery implements FragmentInterface
40
{
41
    private SelectQuery $query;
42
    private string $alias;
43
44
    /** @var ParameterInterface[] */
45
    private array $parameters;
46
47
    public function __construct(SelectQuery $query, string $alias)
48
    {
49
        $this->query = $query;
50
        $this->alias = $alias;
51
52
        $parameters = new QueryParameters();
53
        $this->query->sqlStatement($parameters);
54
        $this->parameters = $parameters->getParameters();
55
    }
56
57
    public function getType(): int
58
    {
59
        return CompilerInterface::SUBQUERY;
60
    }
61
62
    public function getTokens(): array
63
    {
64
        return \array_merge(
65
            [
66
                'alias' => $this->alias,
67
                'parameters' => $this->parameters,
68
            ],
69
            $this->query->getTokens(),
70
        );
71
    }
72
73
    public function getQuery(): SelectQuery
74
    {
75
        return $this->query;
76
    }
77
78
    public function __toString(): string
79
    {
80
        $parameters = new QueryParameters();
81
82
        return Interpolator::interpolate(
83
            $this->query->sqlStatement($parameters),
84
            $parameters->getParameters(),
85
        );
86
    }
87
}
88