Completed
Pull Request — master (#437)
by Anton
04:37
created

CompositeBuilder::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 6
ccs 5
cts 5
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link      https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Db\Query;
12
13
/**
14
 * Class Expression Builder
15
 *
16
 * @package Bluz\Db\Query
17
 */
18
class CompositeBuilder implements \Countable
19
{
20
    /**
21
     * @var string type AND|OR
22
     */
23
    private $type;
24
25
    /**
26
     * @var array parts of the composite expression
27
     */
28
    private $parts = [];
29
30
    /**
31
     * Constructor
32
     *
33
     * @param array  $parts parts of the composite expression
34
     * @param string $type  AND|OR
35
     */
36 3
    public function __construct(array $parts = [], $type = 'AND')
37
    {
38 3
        $type = strtoupper($type);
39 3
        $this->type = $type === 'OR' ? 'OR' : 'AND';
40 3
        $this->add($parts);
41 3
    }
42
43
    /**
44
     * Adds an expression to composite expression.
45
     *
46
     * @param  mixed $parts
47
     *
48
     * @return CompositeBuilder
49
     */
50 3
    public function add($parts)
51
    {
52 3
        foreach ((array)$parts as $part) {
53 3
            if (!empty($part) || ($part instanceof self && $part->count() > 0)) {
54 3
                $this->parts[] = $part;
55
            }
56
        }
57
58 3
        return $this;
59
    }
60
61
    /**
62
     * Return type of this composite
63
     *
64
     * @return string
65
     */
66 3
    public function getType()
67
    {
68 3
        return $this->type;
69
    }
70
71
    /**
72
     * Retrieves the amount of expressions on composite expression.
73
     *
74
     * @return integer
75
     */
76
    public function count()
77
    {
78
        return count($this->parts);
79
    }
80
81
    /**
82
     * Retrieve the string representation of this composite expression.
83
     *
84
     * @return string
85
     */
86 3
    public function __toString()
87
    {
88 3
        if (count($this->parts) === 1) {
89
            return (string)$this->parts[0];
90
        }
91 3
        return '(' . implode(') ' . $this->type . ' (', $this->parts) . ')';
92
    }
93
}
94