Completed
Branch BETA-4.9-messages-queue-fixed (941081)
by
unknown
30:24 queued 05:56
created

Base   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 143
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 3
Bugs 2 Features 0
Metric Value
wmc 22
lcom 1
cbo 1
dl 0
loc 143
rs 10
c 3
b 2
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A _set_debug_info() 0 3 1
A __construct() 0 3 2
A set_requested_version() 0 3 1
B parse_route() 0 22 5
C send_response() 0 48 13
1
<?php
2
namespace EventEspresso\core\libraries\rest_api\controllers;
3
4
if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
5
	exit( 'No direct script access allowed' );
6
}
7
8
/**
9
 *
10
 * Base
11
 *
12
 * Base controller for EE REST API
13
 *
14
 * @package			Event Espresso
15
 * @subpackage
16
 * @author				Mike Nelson
17
 *
18
 */
19
class Base {
20
	/**
21
	 * Contains debug info we'll send back in the response headers
22
	 * @var array
23
	 */
24
	protected $_debug_info = array();
25
26
	/**
27
	 * Indicates whether or not the API is in debug mode
28
	 * @var boolean
29
	 */
30
	protected $_debug_mode = false;
31
32
	/**
33
	 * Indicates the version that was requested
34
	 * @var string
35
	 */
36
	protected $_requested_version;
37
38
	public function __construct() {
39
		$this->_debug_mode = defined( 'EE_REST_API_DEBUG_MODE' ) ? EE_REST_API_DEBUG_MODE : false;
40
	}
41
42
43
	/**
44
	 * Sets the version the user requested
45
	 * @param string $version eg '4.8'
46
	 */
47
	public function set_requested_version( $version ) {
48
		$this->_requested_version = $version;
49
	}
50
51
	/**
52
	 * Sets some debug info that we'll send back in headers
53
	 * @param string $key
54
	 * @param string|array $info
55
	 */
56
	protected function _set_debug_info( $key, $info ){
57
		$this->_debug_info[ $key ] = $info;
58
	}
59
60
61
62
	/**
63
	 * Sends a response, but also makes sure to attach headers that
64
	 * are handy for debugging.
65
	 * Specifically, we assume folks will want to know what exactly was the DB query that got run,
66
	 * what exactly was the Models query that got run, what capabilities came into play, what fields were omitted from
67
	 * the response, others?
68
	 *
69
	 * @param array|\WP_Error|\Exception $response
70
	 * @return \WP_REST_Response
71
	 */
72
	public function send_response( $response ) {
73
		if( $response instanceof \Exception ) {
74
			$response = new \WP_Error( $response->getCode(), $response->getMessage() );
75
		}
76
		if( $response instanceof \WP_Error ) {
0 ignored issues
show
Bug introduced by
The class WP_Error 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...
77
			//we want to send a "normal"-looking WP error response, but we also
78
			//want to add headers. It doesn't seem WP API 1.2 supports this.
79
			//I'd like to use WP_JSON_Server::error_to_response() but its protected
80
			//so here's most of it copy-and-pasted :P
81
			$error_data = $response->get_error_data();
82
			if ( is_array( $error_data ) && isset( $error_data['status'] ) ) {
83
				$status = $error_data['status'];
84
			} else {
85
				$status = 500;
86
			}
87
88
			$errors = array();
89
			foreach ( (array) $response->errors as $code => $messages ) {
90
				foreach ( (array) $messages as $message ) {
91
					$errors[] = array(
92
						'code'    => $code,
93
						'message' => $message,
94
						'data'    => $response->get_error_data( $code )
95
					);
96
				}
97
			}
98
			$data = isset( $errors[0] ) ? $errors[0] : array();
99
			if ( count( $errors ) > 1 ) {
100
				// Remove the primary error.
101
				array_shift( $errors );
102
				$data['additional_errors'] = $errors;
103
			}
104
			$rest_response = new \WP_REST_Response( $data, $status );
105
		}else{
106
			$rest_response = new \WP_REST_Response( $response, 200 );
107
		}
108
		$headers = array();
109
		if( $this->_debug_mode && is_array( $this->_debug_info ) ) {
110
			foreach( $this->_debug_info  as $debug_key => $debug_info ) {
111
				if( is_array( $debug_info ) ) {
112
					$debug_info = json_encode( $debug_info );
113
				}
114
				$headers[ 'X-EE4-Debug-' . ucwords( $debug_key ) ] = $debug_info;
115
			}
116
		}
117
		$rest_response->set_headers( $headers );
118
		return $rest_response;
119
	}
120
121
122
123
	/**
124
	 * Applies the regex to the route, then creates an array using the values of
125
	 * $match_keys as keys (but ignores the full pattern match). Returns the array of matches.
126
	 * For example, if you call
127
	 * parse_route( '/ee/v4.8/events', '~\/ee\/v([^/]*)\/(.*)~', array( 'version', 'model' ) )
128
	 * it will return array( 'version' => '4.8', 'model' => 'events' )
129
	 *
130
	 * @param string $route
131
	 * @param string $regex
132
	 * @param array  $match_keys EXCLUDING matching the entire regex
133
	 * @return array where  $match_keys are the keys (the first value of $match_keys
134
	 * becomes the first key of the return value, etc. Eg passing in $match_keys of
135
	 * array( 'model', 'id' ), will, if the regex is successful, will return
136
	 * array( 'model' => 'foo', 'id' => 'bar' )
137
	 * @throws \EE_Error if it couldn't be parsed
138
	 */
139
	public function parse_route( $route, $regex, $match_keys ) {
140
		$indexed_matches = array();
141
		$success = preg_match( $regex, $route, $matches );
142
		if(
143
			is_array( $matches ) ) {
144
			//skip the overall regex match. Who cares
145
			for( $i = 1; $i <= count( $match_keys ); $i++ ) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
146
				if( ! isset( $matches[ $i ] ) ) {
147
					$success = false;
148
				} else {
149
					$indexed_matches[ $match_keys[ $i - 1 ] ] = $matches[ $i ];
150
				}
151
			}
152
		}
153
		if( ! $success ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $success of type integer|false is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
154
			throw new \EE_Error(
155
				__( 'We could not parse the URL. Please contact Event Espresso Support', 'event_espresso' ),
156
				'endpoint_parsing_error'
157
			);
158
		}
159
		return $indexed_matches;
160
	}
161
}
162
163
// End of file Base.php