Issues (5)

src/QueryPredicate.php (1 issue)

Severity
1
<?php
2
3
/**
4
 * This file is part of the miBadger package.
5
 *
6
 * @author Michael Webbers <[email protected]>
7
 * @license http://opensource.org/licenses/Apache-2.0 Apache v2 License
8
 */
9
namespace miBadger\Query;
10
11
/**
12
 *
13
 * @since 2.0.0
14
 */
15
class QueryPredicate implements QueryExpression
16
{
17
	/* @var string The kind of predicate (AND or OR) */
18
	private $type;
19
20
	/* @var array The list of subclauses that are combined by this predicate. */
21
	private $conditions;
22
23
	/**
24
	 * Constructs a new query predicate of the given type
25
	 * @param string $type the predicate type. either 'AND', 'OR' or 'NOT'
26
	 * @param QueryExpression $left the first query expression to be used by this predicate
27
	 * @param QueryExpression ...$others the remaining query expressions, if applicable
28
	 */
29
	public function __construct(string $type, QueryExpression $left, QueryExpression ...$others)
30
	{
31
		$type = strtoupper($type);
32
		switch ($type) {
33
			case 'AND':
34
			case 'OR':
35
				if (empty($others)) {
36
					throw new QueryException(sprintf("%s Operator needs at least two arguments", $type));
37
				}
38
				$this->type = $type;
39
				break;
40
41
			case 'NOT':
42
				if (!empty($others)) {
43
					throw new QueryException("NOT Operator can only accept 1 argument");
44
				}
45
				$this->type = $type;
46
				break;
47
				
48
			default:
49
				throw new QueryException(sprintf("Invalid predicate operator \"%s\"", $type));
50
		}
51
52
		$this->conditions = array_merge([$left], $others);
53
	}
54
55
	/**
56
	 * {@inheritdoc}
57
	 */
58
	public function getFlattenedConditions()
59
	{
60
		$conditions = [];
61
62
		foreach ($this->conditions as $condition) {
63
			$conditions = array_merge($conditions, $condition->getFlattenedConditions());
64
		}
65
66
		return $conditions;
67
	}
68
69
	/**
70
	 * {@inheritdoc}
71
	 */
72
	public function __toString()
73
	{
74
		$conditionSql = [];
75
		foreach ($this->conditions as $cond) {
76
			$conditionSql[] = sprintf('( %s )', (string) $cond);
77
		}
78
		
79
		$sql = '';
0 ignored issues
show
The assignment to $sql is dead and can be removed.
Loading history...
80
		switch ($this->type) {
81
			case 'AND':
82
				return join(' AND ', $conditionSql);
83
			case 'OR':
84
				return join(' OR ', $conditionSql);
85
			case 'NOT':
86
				return sprintf('NOT %s', $conditionSql[0]);
87
			default:
88
				// return ''; // This case can never happen
89
		}
90
	}
91
}
92