CombiningQuery::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 12
ccs 8
cts 8
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace QB\MySQL\Clause;
6
7
use InvalidArgumentException;
8
use QB\Generic\IQueryPart;
9
10
class CombiningQuery
11
{
12
    public const TYPE_UNION = 'UNION';
13
14
    public const MODIFIER_ALL      = 'ALL';
15
    public const MODIFIER_DISTINCT = 'DISTINCT';
16
17
    protected const VALID_TYPE      = [null, self::TYPE_UNION];
18
    protected const VALID_MODIFIERS = [null, self::MODIFIER_ALL, self::MODIFIER_DISTINCT];
19
20
    protected string $type;
21
22
    protected IQueryPart $queryPart;
23
24
    protected ?string $modifier = null;
25
26
    /**
27
     * CombiningQuery constructor.
28
     *
29
     * @param string      $type
30
     * @param IQueryPart  $queryPart
31
     * @param string|null $modifier
32
     */
33 23
    public function __construct(string $type, IQueryPart $queryPart, ?string $modifier = null)
34
    {
35 23
        if (!$this->isValid($type, $modifier)) {
36 5
            $data = (string)print_r([$type, $modifier], true);
37 5
            throw new InvalidArgumentException(
38 5
                sprintf('invalid arguments for %s. arguments: %s', __CLASS__, $data)
39
            );
40
        }
41
42 18
        $this->type      = $type;
43 18
        $this->queryPart = $queryPart;
44 18
        $this->modifier  = $modifier;
45 18
    }
46
47
    /**
48
     * @param string      $type
49
     * @param string|null $modifier
50
     *
51
     * @return bool
52
     */
53 23
    private function isValid(string $type, ?string $modifier = null): bool
54
    {
55 23
        if (!in_array($type, static::VALID_TYPE, true)) {
56 2
            return false;
57
        }
58
59 21
        if (!in_array($modifier, static::VALID_MODIFIERS, true)) {
60 3
            return false;
61
        }
62
63 18
        return true;
64
    }
65
66
    /**
67
     * @return string
68
     */
69 18
    public function __toString(): string
70
    {
71 18
        $modifier = '';
72 18
        if ($this->modifier) {
73 5
            $modifier = ' ' . $this->modifier;
74
        }
75
76 18
        $parts   = [];
77 18
        $parts[] = $this->type . $modifier;
78 18
        $parts[] = (string)$this->queryPart;
79
80 18
        return implode(PHP_EOL, $parts);
81
    }
82
}
83