Completed
Push — master ( ee4a1a...944d90 )
by Gary
01:58
created

WP_REST_React_Controller::prepare_links()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 25
rs 8.5806
cc 4
eloc 16
nc 4
nop 1
1
<?php
2
3
/**
4
 * Class WP_REST_React_Controller
5
 */
6
class WP_REST_React_Controller {
7
	/**
8
	 * The namespace of this controller's route.
9
	 *
10
	 * @var string
11
	 */
12
	protected $namespace;
13
14
	/**
15
	 * The base of this controller's route.
16
	 *
17
	 * @var string
18
	 */
19
	protected $rest_base;
20
21
	/**
22
	 * Constructor.
23
	 */
24
	public function __construct() {
25
		$this->namespace = 'wp/v2';
26
		$this->rest_base = 'react';
27
	}
28
29
	/**
30
	 * Register the routes for the objects of the controller.
31
	 */
32
	public function register_routes() {
33
		register_rest_route( $this->namespace, $this->rest_base, array(
34
			array(
35
				'methods'             => WP_Rest_Server::READABLE,
36
				'callback'            => array( $this, 'get_items' ),
37
				'permission_callback' => array( $this, 'get_items_permission_callback' ),
38
				'args'                => $this->get_collection_params(),
39
			),
40
			array(
41
				'methods'             => WP_Rest_Server::CREATABLE,
42
				'callback'            => array( $this, 'create_item' ),
43
				'permission_callback' => array( $this, 'create_item_permission_callback' ),
44
				'args'                => $this->get_creation_params(),
45
			),
46
			'schema' => array( $this, 'get_public_item_schema' ),
47
		) );
48
	}
49
50
	/**
51
	 * Check if a given request has access to read reactions.
52
	 *
53
	 * @param  WP_REST_Request $request Full details about the request.
54
	 * @return WP_Error|boolean
55
	 */
56
	public function get_items_permissions_check( $request ) {
57
		if ( ! empty( $request['post'] ) ) {
58
			foreach ( (array) $request['post'] as $post_id ) {
59
				$post = get_post( $post_id );
60
				if ( ! empty( $post_id ) && $post && ! $this->check_read_post_permission( $post ) ) {
61
					return new WP_Error( 'rest_cannot_read_post', __( 'Sorry, you cannot read the post for this reaction.' ), array( 'status' => rest_authorization_required_code() ) );
62
				} else if ( 0 === $post_id && ! current_user_can( 'moderate_comments' ) ) {
63
					return new WP_Error( 'rest_cannot_read', __( 'Sorry, you cannot read reactions without a post.' ), array( 'status' => rest_authorization_required_code() ) );
64
				}
65
			}
66
		}
67
68
		return true;
69
	}
70
71
	/**
72
	 * Get a list of reactions.
73
	 *
74
	 * @param  WP_REST_Request $request Full details about the request.
75
	 * @return WP_Error|WP_REST_Response
76
	 */
77
	public function get_items( $request ) {
78
		$prepared_args = array(
79
			'post__in' => $request['post'],
80
			'type'     => 'reaction',
81
		);
82
83
		/**
84
		 * Filter arguments, before passing to WP_Comment_Query, when querying reactions via the REST API.
85
		 *
86
		 * @see https://developer.wordpress.org/reference/classes/wp_comment_query/
87
		 *
88
		 * @param array           $prepared_args Array of arguments for WP_Comment_Query.
89
		 * @param WP_REST_Request $request       The current request.
90
		 */
91
		$prepared_args = apply_filters( 'rest_reaction_query', $prepared_args, $request );
92
93
		$query = new WP_Comment_Query;
94
		$query_result = $query->query( $prepared_args );
95
96
		$reactions_count = array();
97
		foreach ( $query_result as $reaction ) {
98
			if ( empty( $reactions_count[ $reaction->comment_content ] ) ) {
99
				$reactions_count[ $reaction->comment_content ] = array(
100
					'count'   => 0,
101
					'post_id' => $reaction->comment_post_ID,
102
				);
103
			}
104
105
			$reactions_count[ $reaction->comment_content ]++;
106
		}
107
108
		$reactions = array();
109
		foreach ( $reactions_count as $emoji => $data ) {
110
			$reaction = array(
111
				'emoji'   => $emoji,
112
				'count'   => $data['count'],
113
				'post_id' => $data['post_id'],
114
			);
115
116
			$data = $this->prepare_item_for_response( $reaction, $request );
117
			$reactions[] = $this->prepare_response_for_collection( $data );
118
		}
119
120
		$total_reactions = (int) $query->found_comments;
121
		$reaction_groups = count( $reactions );
122
123
		$response = rest_ensure_response( $reactions );
124
		$response->header( 'X-WP-Total', $total_reactions );
125
		$response->header( 'X-WP-TotalGroups', $reaction_groups );
126
127
		return $response;
128
	}
129
130
	/**
131
	 * Check if a given request has access to create a reaction
132
	 *
133
	 * @param  WP_REST_Request $request Full details about the request.
134
	 * @return WP_Error|boolean
135
	 */
136
	public function create_item_permissions_check( $request ) {
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
137
		return true;
138
	}
139
140
	/**
141
	 * Create a reaction.
142
	 *
143
	 * @param  WP_REST_Request $request Full details about the request.
144
	 * @return WP_Error|WP_REST_Response
145
	 */
146
	public function create_item( $request ) {
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
147
	}
148
149
	/**
150
	 * Check if we can read a post.
151
	 *
152
	 * Correctly handles posts with the inherit status.
153
	 *
154
	 * @param object $post Post object.
155
	 * @return boolean Can we read it?
156
	 */
157
	public function check_read_post_permission( $post ) {
158
		$posts_controller = new WP_REST_Posts_Controller( $post->post_type );
159
160
		return $posts_controller->check_read_permission( $post );
161
	}
162
163
	/**
164
	 * Prepare a reaction group output for response.
165
	 *
166
	 * @param  array            $reaction Reaction data.
167
	 * @param  WP_REST_Request  $request  Request object.
168
	 * @return WP_REST_Response $response
169
	 */
170
	public function prepare_item_for_response( $reaction, $request ) {
171
		$data = array(
172
			'emoji'   => $reaction['emoji'],
173
			'count'   => (int) $reaction['count'],
174
			'post_id' => (int) $reaction['post_id'],
175
		);
176
177
		// Wrap the data in a response object
178
		$response = rest_ensure_response( $data );
179
180
		$response->add_links( $this->prepare_links( $reaction ) );
181
182
		/**
183
		 * Filter a reaction group returned from the API.
184
		 *
185
		 * Allows modification of the reaction right before it is returned.
186
		 *
187
		 * @param WP_REST_Response  $response   The response object.
188
		 * @param array             $reaction   The original reaction data.
189
		 * @param WP_REST_Request   $request    Request used to generate the response.
190
		 */
191
		return apply_filters( 'rest_prepare_comment', $response, $reaction, $request );
192
	}
193
194
	/**
195
	 * Prepare a response for inserting into a collection.
196
	 *
197
	 * @param WP_REST_Response $response Response object.
198
	 * @return array Response data, ready for insertion into collection data.
199
	 */
200
	public function prepare_response_for_collection( $response ) {
201
		if ( ! ( $response instanceof WP_REST_Response ) ) {
0 ignored issues
show
Bug introduced by
The class WP_REST_Response does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
202
			return $response;
203
		}
204
205
		$data = (array) $response->get_data();
206
		$links = WP_REST_Server::get_response_links( $response );
207
		if ( ! empty( $links ) ) {
208
			$data['_links'] = $links;
209
		}
210
211
		return $data;
212
	}
213
214
	/**
215
	 * Prepare links for the request.
216
	 *
217
	 * @param array $reaction Reaction.
218
	 * @return array Links for the given reaction.
219
	 */
220
	protected function prepare_links( $reaction ) {
221
		$links = array(
222
			'self' => array(
223
				'href' => rest_url( sprintf( '/%s/%s/%s', $this->namespace, $this->rest_base, $reaction->emoji ) ),
224
			),
225
			'collection' => array(
226
				'href' => rest_url( sprintf( '/%s/%s', $this->namespace, $this->rest_base ) ),
227
			),
228
		);
229
230
		if ( 0 !== (int) $reaction['post_id'] ) {
231
			$post = get_post( $reaction['post_id'] );
232
			if ( ! empty( $post->ID ) ) {
233
				$obj = get_post_type_object( $post->post_type );
234
				$base = ! empty( $obj->rest_base ) ? $obj->rest_base : $obj->name;
235
				$links['up'] = array(
236
					'href'       => rest_url( '/wp/v2/' . $base . '/' . $reaction['post_id'] ),
237
					'embeddable' => true,
238
					'post_type'  => $post->post_type,
239
				);
240
			}
241
		}
242
243
		return $links;
244
	}
245
246
	/**
247
	 * Get the query params for collections
248
	 *
249
	 * @return array
250
	 */
251
	public function get_collection_params() {
252
		$query_params = array();
253
254
		$query_params['post']   = array(
255
			'default'           => array(),
256
			'description'       => __( 'Limit result set to resources assigned to specific post ids.' ),
257
			'type'              => 'array',
258
			'sanitize_callback' => 'wp_parse_id_list',
259
			'validate_callback' => 'rest_validate_request_arg',
260
		);
261
262
		return $query_params;
263
	}
264
	/**
265
	 * Get the query params for collections
266
	 *
267
	 * @return array
268
	 */
269
	public function get_creation_params() {
270
		$query_params = array();
271
272
		$query_params['post']   = array(
273
			'default'           => array(),
274
			'description'       => __( 'The post ID to add a reaction to.' ),
275
			'type'              => 'integer',
276
			'sanitize_callback' => 'absint',
277
			'validate_callback' => 'rest_validate_request_arg',
278
		);
279
280
		$query_params['emoji']  = array(
281
			'default'           => array(),
282
			'description'       => __( 'The reaction emoji.' ),
283
			'type'              => 'string',
284
			'validate_callback' => 'rest_validate_request_arg',
285
		);
286
287
		return $query_params;
288
	}
289
}