Failed Conditions
Push — master ( 5de32f...4f0134 )
by Atanas
01:47
created

HasQueryFilterTrait::query()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 0
cts 0
cp 0
crap 2
1
<?php
2
/**
3
 * @package   WPEmerge
4
 * @author    Atanas Angelov <[email protected]>
5
 * @copyright 2018 Atanas Angelov
6
 * @license   https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0
7
 * @link      https://wpemerge.com/
8
 */
9
10
namespace WPEmerge\Routing;
11
12
use WPEmerge\Exceptions\ConfigurationException;
13
use WPEmerge\Requests\RequestInterface;
14
use WPEmerge\Routing\Conditions\UrlCondition;
15
16
/**
17
 * Represent an object which has a WordPress query filter.
18
 */
19
trait HasQueryFilterTrait {
20
	use HasConditionTrait;
21
22
	/**
23
	 * Query filter.
24
	 *
25
	 * @var callable|null
26
	 */
27
	protected $query_filter = null;
28
29
	/**
30
	 * Get the main WordPress query vars filter, if any.
31
	 *
32
	 * @codeCoverageIgnore
33
	 * @return callable|null
34
	 */
35
	public function getQueryFilter() {
36
		return $this->query_filter;
37
	}
38
39
	/**
40
	 * Set the main WordPress query vars filter.
41
	 *
42
	 * @codeCoverageIgnore
43
	 * @param  callable|null $query_filter
44
	 * @return void
45
	 */
46
	public function setQueryFilter( $query_filter ) {
47
		$this->query_filter = $query_filter;
48
	}
49
50
	/**
51
	 * Apply the query filter, if any.
52
	 *
53
	 * @param  RequestInterface $request
54
	 * @param  array            $query_vars
55
	 * @return array
56
	 */
57 3
	public function applyQueryFilter( $request, $query_vars ) {
58 3
		$condition = $this->getCondition();
59
60 3
		if ( $this->getQueryFilter() === null ) {
61 1
			return $query_vars;
62
		}
63
64 2
		if ( ! $condition instanceof UrlCondition ) {
65 1
			throw new ConfigurationException(
66
				'Only routes with URL condition can use queries. ' .
67 1
				'Make sure your route has a URL condition and it is not in a non-URL route group.'
68
			);
69
		}
70
71 1
		$arguments = $this->getCondition()->getArguments( $request );
72
73 1
		return call_user_func_array( $this->getQueryFilter(), array_merge( [$query_vars], array_values( $arguments ) ) );
74
	}
75
}
76