Completed
Push — feature/external-media ( 7123dd )
by
unknown
06:53
created

WPCOM_REST_API_V2_Endpoint_External_Media   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 25 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 10
loc 40
rs 10
c 0
b 0
f 0
wmc 4
lcom 0
cbo 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A register_routes() 10 10 1
A get_external_media() 0 15 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * REST API endpoint for the External Media connections.
4
 *
5
 * @package Jetpack
6
 * @since 8.5.0
7
 */
8
9
use Automattic\Jetpack\Connection\Client;
10
11
/**
12
 * External Medie connections helper API.
13
 *
14
 * @since 8.5
15
 */
16
class WPCOM_REST_API_V2_Endpoint_External_Media extends WP_REST_Controller {
17
	/**
18
	 * Constructor.
19
	 */
20
	public function __construct() {
21
		$this->namespace = 'wpcom/v2';
22
		$this->rest_base = 'external-media';
23
		add_action( 'rest_api_init', array( $this, 'register_routes' ) );
24
	}
25
26
	/**
27
	 * Register the route.
28
	 */
29 View Code Duplication
	public function register_routes() {
30
		register_rest_route(
31
			$this->namespace,
32
			$this->rest_base . '/list/(?P<service>google_photos|pexels)',
33
			array(
34
				'methods'  => WP_REST_Server::READABLE,
35
				'callback' => array( $this, 'get_external_media' ),
36
			)
37
		);
38
	}
39
40
	public function get_external_media( \WP_REST_Request $request ) {
41
		$params = $request->get_params();
42
43
		$path = add_query_arg(
44
			$request->get_params(),
45
			'/meta/external-media/' . urlencode( $params['service'] )
46
		);
47
48
		$response = Client::wpcom_json_api_request_as_blog( $path );
49
		if ( is_wp_error( $response ) ) {
50
			return $response;
51
		}
52
53
		return json_decode( wp_remote_retrieve_body( $response ) );
54
	}
55
}
56
57
wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Endpoint_External_Media' );
58