1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @package WPEmerge |
4
|
|
|
* @author Atanas Angelov <[email protected]> |
5
|
|
|
* @copyright 2017-2019 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\CanFilterQueryInterface; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Represent an object which has a WordPress query filter attribute. |
18
|
|
|
*/ |
19
|
|
|
trait HasQueryFilterTrait { |
20
|
|
|
/** |
21
|
|
|
* Query filter. |
22
|
|
|
* |
23
|
|
|
* @var callable|null |
24
|
|
|
*/ |
25
|
|
|
protected $query_filter = null; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Get attribute. |
29
|
|
|
* |
30
|
|
|
* @param string $attribute |
31
|
|
|
* @param mixed $default |
32
|
|
|
* @return mixed |
33
|
|
|
*/ |
34
|
|
|
abstract public function getAttribute( $attribute, $default = '' ); |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Apply the query filter, if any. |
38
|
|
|
* |
39
|
|
|
* @param RequestInterface $request |
40
|
|
|
* @param array $query_vars |
41
|
|
|
* @return array |
42
|
|
|
*/ |
43
|
3 |
|
public function applyQueryFilter( $request, $query_vars ) { |
44
|
3 |
|
$query = $this->getAttribute( 'query' ); |
45
|
3 |
|
$condition = $this->getAttribute( 'condition' ); |
46
|
|
|
|
47
|
3 |
|
if ( $query === null ) { |
48
|
1 |
|
return $query_vars; |
49
|
|
|
} |
50
|
|
|
|
51
|
2 |
|
if ( ! $condition instanceof CanFilterQueryInterface ) { |
52
|
1 |
|
throw new ConfigurationException( |
53
|
|
|
'Only routes with a condition implementing the ' . CanFilterQueryInterface::class . ' ' . |
54
|
|
|
'interface can apply query filters. ' . |
55
|
1 |
|
'Make sure your route has a URL condition and it is not in a non-URL route group.' |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
return call_user_func_array( |
60
|
1 |
|
$query, |
61
|
1 |
|
array_merge( |
62
|
1 |
|
[$query_vars], |
63
|
1 |
|
array_values( $condition->getArguments( $request ) ) |
64
|
|
|
) |
65
|
|
|
); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|