Passed
Push — master ( 9a1311...88d100 )
by Borislav
06:30
created

SortingDefinition::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 2
rs 10
1
<?php namespace App\Entity\Query;
2
3
use Doctrine\ORM\QueryBuilder;
4
5
class SortingDefinition {
6
7
	const FIELDS_SEPARATOR = ',';
8
9
	public $input;
10
	public $sortableFields = [];
11
	/** @var SortingItem[] */
12
	public $items = [];
13
14
	public function __construct(?string $input, string $entityAlias = null, array $sortableFields = []) {
15
		$this->input = $input;
16
		$this->sortableFields = $sortableFields;
17
18
		foreach (array_filter(explode(self::FIELDS_SEPARATOR, $input)) as $fieldWithDirection) {
0 ignored issues
show
Bug introduced by
It seems like $input can also be of type null; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

18
		foreach (array_filter(explode(self::FIELDS_SEPARATOR, /** @scrutinizer ignore-type */ $input)) as $fieldWithDirection) {
Loading history...
19
			$this->items[] = new SortingItem($fieldWithDirection, $entityAlias);
20
		}
21
		if ($this->sortableFields) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->sortableFields of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
22
			$this->items = array_values(array_filter($this->items, function(SortingItem $item) {
23
				return !in_array($item->field, $this->sortableFields);
24
			}));
25
		}
26
	}
27
28
	public function __toString() {
29
		return implode(', ', $this->items);
30
	}
31
32
	public function equals(string $input): bool {
33
		return $this->input === $input;
34
	}
35
36
	public function isActive(): bool {
37
		return count($this->items) > 0;
38
	}
39
40
	public function addToQueryBuilder(QueryBuilder $qb) {
41
		foreach ($this->items as $item) {
42
			$qb->addOrderBy($item->field, $item->direction);
43
		}
44
	}
45
}
46