-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBaseController.php
More file actions
112 lines (95 loc) · 2.79 KB
/
BaseController.php
File metadata and controls
112 lines (95 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
/**
* Controller which handels general quering, such as pagination.
*/
namespace OWC\PDC\Base\RestAPI\Controllers;
use OWC\PDC\Base\Foundation\Plugin;
use WP_Query;
use WP_REST_Request;
/**
* Controller which handels general quering, such as pagination.
*/
abstract class BaseController
{
/**
* Instance of the plugin.
*/
protected Plugin $plugin;
/**
* Construction, with dependency injection of the BasePlugin.
*
* @return void
*/
public function __construct(Plugin $plugin)
{
$this->plugin = $plugin;
}
/**
* Merges a paginator, based on a WP_Query, inside a data arary.
*/
protected function addPaginator(array $data, WP_Query $query): array
{
$page = $query->get('paged');
$page = 0 == $page ? 1 : $page;
return array_merge([
'data' => $data,
], [
'pagination' => [
'total_count' => (int) $query->found_posts,
'total_pages' => $query->max_num_pages,
'current_page' => $page,
'limit' => $query->get('posts_per_page'),
],
]);
}
/**
* Get the paginator query params for a given query.
*/
protected function getPaginatorParams(WP_REST_Request $request, int $limit = 10): array
{
$params = array_merge($request->get_params(), [
'posts_per_page' => $request->get_param('limit') ?: $limit,
'paged' => $request->get_param('page') ?: 0,
]);
return $this->validateQueryParams($params);
}
protected function validateQueryParams(array $params): array
{
$allowedQueryParams = [
'include-connected',
'tax_query',
'meta_query',
'posts_per_page',
'paged',
'post_type',
'post_status',
];
return array_filter($params, function ($param) use ($allowedQueryParams) {
return in_array($param, $allowedQueryParams);
}, ARRAY_FILTER_USE_KEY);
}
/**
* Return the post status to query on.
*/
protected function getPostStatus(\WP_REST_Request $request): array
{
$preview = filter_var($request->get_param('draft-preview'), FILTER_VALIDATE_BOOLEAN);
if (! \is_user_logged_in()) {
$preview = false;
}
return $preview ? ['publish', 'draft', 'future'] : ['publish'];
}
/**
* Check if the source parameter is valid.
*/
protected function showOnParamIsValid(\WP_REST_Request $request): bool
{
if (empty($request->get_param('source'))) {
return false;
}
if (! is_numeric($request->get_param('source'))) {
return false;
}
return true;
}
}