Passed
Branch refactor/kernels (b754ed)
by Atanas
01:59
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
	 * @internal
54
	 * @throws ConfigurationException
55
	 * @param RequestInterface            $request
56
	 * @param  array<string, mixed>       $query_vars
57
	 * @return array<string, mixed>|false
58
	 */
59 4
	public function applyQueryFilter( $request, $query_vars ) {
60 4
		$condition = $this->getCondition();
61
62 4
		if ( $this->getQueryFilter() === null ) {
63 1
			return false;
64
		}
65
66 3
		if ( ! $condition instanceof UrlCondition ) {
67 1
			throw new ConfigurationException(
68
				'Only routes with URL condition can use queries. ' .
69 1
				'Make sure your route has a URL condition and it is not in a non-URL route group.'
70
			);
71
		}
72
73 2
		if ( ! $this->getCondition()->isSatisfied( $request ) ) {
74 1
			return false;
75
		}
76
77 1
		$arguments = $this->getCondition()->getArguments( $request );
78
79 1
		return call_user_func_array( $this->getQueryFilter(), array_merge( [$query_vars], array_values( $arguments ) ) );
80
	}
81
82
	/**
83
	 * Fluent alias for setQueryFilter().
84
	 *
85
	 * @codeCoverageIgnore
86
	 * @param  callable $query_filter
87
	 * @return static   $this
88
	 */
89
	public function query( $query_filter ) {
90
		$this->setQueryFilter( $query_filter );
91
92
		return $this;
93
	}
94
}
95