Completed
Pull Request — master (#378)
by Darren
19:13
created
core/libraries/rest_api/changes/ChangesIn40834.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -10,38 +10,38 @@
 block discarded – undo
10 10
 class ChangesIn40834 extends ChangesInBase
11 11
 {
12 12
 
13
-    /**
14
-     * Adds hooks so requests to 4.8.29 don't have the checkin endpoints
15
-     */
16
-    public function setHooks()
17
-    {
18
-        // set a hook to remove the checkout/checkout endpoints if the request
19
-        // is for lower than 4.8.33
20
-        add_filter(
21
-            'FHEE__EventEspresso\core\libraries\rest_api\controllers\Base___get_response_headers',
22
-            array($this, 'removeResponseHeaders'),
23
-            10,
24
-            3
25
-        );
26
-    }
13
+	/**
14
+	 * Adds hooks so requests to 4.8.29 don't have the checkin endpoints
15
+	 */
16
+	public function setHooks()
17
+	{
18
+		// set a hook to remove the checkout/checkout endpoints if the request
19
+		// is for lower than 4.8.33
20
+		add_filter(
21
+			'FHEE__EventEspresso\core\libraries\rest_api\controllers\Base___get_response_headers',
22
+			array($this, 'removeResponseHeaders'),
23
+			10,
24
+			3
25
+		);
26
+	}
27 27
 
28 28
 
29
-    /**
30
-     * Removes the checkin and checkout endpoints from the index for requests
31
-     * to api versions lowers than 4.8.33
32
-     *
33
-     * @param array  $response_headers
34
-     * @param Base   $controller
35
-     * @param string $requested_version
36
-     * @return array like $routes_on_this_version
37
-     */
38
-    public function removeResponseHeaders($response_headers, $controller, $requested_version)
39
-    {
40
-        if ($controller instanceof Base
41
-            && $this->appliesToVersion($requested_version)
42
-        ) {
43
-            return array();
44
-        }
45
-        return $response_headers;
46
-    }
29
+	/**
30
+	 * Removes the checkin and checkout endpoints from the index for requests
31
+	 * to api versions lowers than 4.8.33
32
+	 *
33
+	 * @param array  $response_headers
34
+	 * @param Base   $controller
35
+	 * @param string $requested_version
36
+	 * @return array like $routes_on_this_version
37
+	 */
38
+	public function removeResponseHeaders($response_headers, $controller, $requested_version)
39
+	{
40
+		if ($controller instanceof Base
41
+			&& $this->appliesToVersion($requested_version)
42
+		) {
43
+			return array();
44
+		}
45
+		return $response_headers;
46
+	}
47 47
 }
Please login to merge, or discard this patch.
core/libraries/rest_api/changes/ChangesIn40833.php 1 patch
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -7,57 +7,57 @@
 block discarded – undo
7 7
 class ChangesIn40833 extends ChangesInBase
8 8
 {
9 9
 
10
-    /**
11
-     * Adds hooks so requests to 4.8.29 don't have the checkin endpoints
12
-     */
13
-    public function setHooks()
14
-    {
15
-        // set a hook to remove the checkout/checkout endpoints if the request
16
-        // is for lower than 4.8.33
17
-        add_filter(
18
-            'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
19
-            array($this, 'removeCheckinRoutesEarlierThan4833'),
20
-            10,
21
-            2
22
-        );
23
-        add_filter(
24
-            'FHEE__EventEspresso\core\libraries\rest_api\controllers\Base___get_headers_from_ee_notices__return',
25
-            array($this, 'dontAddHeadersFromEeNotices'),
26
-            10,
27
-            2
28
-        );
29
-    }
10
+	/**
11
+	 * Adds hooks so requests to 4.8.29 don't have the checkin endpoints
12
+	 */
13
+	public function setHooks()
14
+	{
15
+		// set a hook to remove the checkout/checkout endpoints if the request
16
+		// is for lower than 4.8.33
17
+		add_filter(
18
+			'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
19
+			array($this, 'removeCheckinRoutesEarlierThan4833'),
20
+			10,
21
+			2
22
+		);
23
+		add_filter(
24
+			'FHEE__EventEspresso\core\libraries\rest_api\controllers\Base___get_headers_from_ee_notices__return',
25
+			array($this, 'dontAddHeadersFromEeNotices'),
26
+			10,
27
+			2
28
+		);
29
+	}
30 30
 
31 31
 
32
-    /**
33
-     * Removes the checkin and checkout endpoints from the index for requests
34
-     * to api versions lowers than 4.8.33
35
-     *
36
-     * @param array  $routes_on_this_version
37
-     * @param string $version
38
-     * @return array like $routes_on_this_version
39
-     */
40
-    public function removeCheckinRoutesEarlierThan4833($routes_on_this_version, $version)
41
-    {
42
-        if ($this->appliesToVersion($version)) {
43
-            unset($routes_on_this_version['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)']);
44
-        }
45
-        return $routes_on_this_version;
46
-    }
32
+	/**
33
+	 * Removes the checkin and checkout endpoints from the index for requests
34
+	 * to api versions lowers than 4.8.33
35
+	 *
36
+	 * @param array  $routes_on_this_version
37
+	 * @param string $version
38
+	 * @return array like $routes_on_this_version
39
+	 */
40
+	public function removeCheckinRoutesEarlierThan4833($routes_on_this_version, $version)
41
+	{
42
+		if ($this->appliesToVersion($version)) {
43
+			unset($routes_on_this_version['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)']);
44
+		}
45
+		return $routes_on_this_version;
46
+	}
47 47
 
48 48
 
49
-    /**
50
-     * We just added headers for notices in this version
51
-     *
52
-     * @param array  $headers_from_ee_notices
53
-     * @param string $requested_version
54
-     * @return array
55
-     */
56
-    public function dontAddHeadersFromEeNotices($headers_from_ee_notices, $requested_version)
57
-    {
58
-        if ($this->appliesToVersion($requested_version)) {
59
-            return array();
60
-        }
61
-        return $headers_from_ee_notices;
62
-    }
49
+	/**
50
+	 * We just added headers for notices in this version
51
+	 *
52
+	 * @param array  $headers_from_ee_notices
53
+	 * @param string $requested_version
54
+	 * @return array
55
+	 */
56
+	public function dontAddHeadersFromEeNotices($headers_from_ee_notices, $requested_version)
57
+	{
58
+		if ($this->appliesToVersion($requested_version)) {
59
+			return array();
60
+		}
61
+		return $headers_from_ee_notices;
62
+	}
63 63
 }
Please login to merge, or discard this patch.
core/libraries/rest_api/changes/ChangesIn40836.php 1 patch
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -14,174 +14,174 @@
 block discarded – undo
14 14
 class ChangesIn40836 extends ChangesInBase
15 15
 {
16 16
 
17
-    /**
18
-     * Adds hooks so requests to 4.8.29 don't have the checkin endpoints
19
-     */
20
-    public function setHooks()
21
-    {
22
-        // set a hook to remove the "calculate" query param
23
-        add_filter(
24
-            'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
25
-            array($this, 'removeCalculateQueryParam'),
26
-            10,
27
-            3
28
-        );
29
-        // don't add the _calculated_fields either
30
-        add_filter(
31
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
32
-            array($this, 'removeCalculatedFieldsFromResponse'),
33
-            10,
34
-            5
35
-        );
36
-        // and also don't add the count headers
37
-        add_filter(
38
-            'FHEE__EventEspresso\core\libraries\rest_api\controllers\Base___get_response_headers',
39
-            array($this, 'removeHeadersNewInThisVersion'),
40
-            10,
41
-            3
42
-        );
43
-        // remove the old featured_image part of the response...
44
-        add_filter(
45
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
46
-            array($this, 'addOldFeaturedImagePartOfCptEntities'),
47
-            10,
48
-            5
49
-        );
50
-        // assuming ticket 9425's change gets pushed with 9406, we don't need to
51
-        // remove it from the calculated fields on older requests (because this will
52
-        // be the first version with calculated fields)
53
-        // before this, infinity was -1, now it's null
54
-        add_filter(
55
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
56
-            array($this, 'useNegativeOneForInfinityBeforeThisVersion'),
57
-            10,
58
-            4
59
-        );
60
-    }
17
+	/**
18
+	 * Adds hooks so requests to 4.8.29 don't have the checkin endpoints
19
+	 */
20
+	public function setHooks()
21
+	{
22
+		// set a hook to remove the "calculate" query param
23
+		add_filter(
24
+			'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
25
+			array($this, 'removeCalculateQueryParam'),
26
+			10,
27
+			3
28
+		);
29
+		// don't add the _calculated_fields either
30
+		add_filter(
31
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
32
+			array($this, 'removeCalculatedFieldsFromResponse'),
33
+			10,
34
+			5
35
+		);
36
+		// and also don't add the count headers
37
+		add_filter(
38
+			'FHEE__EventEspresso\core\libraries\rest_api\controllers\Base___get_response_headers',
39
+			array($this, 'removeHeadersNewInThisVersion'),
40
+			10,
41
+			3
42
+		);
43
+		// remove the old featured_image part of the response...
44
+		add_filter(
45
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
46
+			array($this, 'addOldFeaturedImagePartOfCptEntities'),
47
+			10,
48
+			5
49
+		);
50
+		// assuming ticket 9425's change gets pushed with 9406, we don't need to
51
+		// remove it from the calculated fields on older requests (because this will
52
+		// be the first version with calculated fields)
53
+		// before this, infinity was -1, now it's null
54
+		add_filter(
55
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
56
+			array($this, 'useNegativeOneForInfinityBeforeThisVersion'),
57
+			10,
58
+			4
59
+		);
60
+	}
61 61
 
62 62
 
63
-    /**
64
-     * Don't show "calculate" as an query param option in the index
65
-     *
66
-     * @param array    $query_params
67
-     * @param EEM_Base $model
68
-     * @param string   $version
69
-     * @return array
70
-     */
71
-    public function removeCalculateQueryParam($query_params, EEM_Base $model, $version)
72
-    {
73
-        if ($this->appliesToVersion($version)) {
74
-            unset($query_params['calculate']);
75
-        }
76
-        return $query_params;
77
-    }
63
+	/**
64
+	 * Don't show "calculate" as an query param option in the index
65
+	 *
66
+	 * @param array    $query_params
67
+	 * @param EEM_Base $model
68
+	 * @param string   $version
69
+	 * @return array
70
+	 */
71
+	public function removeCalculateQueryParam($query_params, EEM_Base $model, $version)
72
+	{
73
+		if ($this->appliesToVersion($version)) {
74
+			unset($query_params['calculate']);
75
+		}
76
+		return $query_params;
77
+	}
78 78
 
79 79
 
80
-    /**
81
-     * Removes the "_calculate_fields" part of entity responses before 4.8.36
82
-     *
83
-     * @param array           $entity_response_array
84
-     * @param EEM_Base        $model
85
-     * @param string          $request_context
86
-     * @param WP_REST_Request $request
87
-     * @param Read            $controller
88
-     * @return array
89
-     */
90
-    public function removeCalculatedFieldsFromResponse(
91
-        $entity_response_array,
92
-        EEM_Base $model,
93
-        $request_context,
94
-        WP_REST_Request $request,
95
-        Read $controller
96
-    ) {
97
-        if ($this->appliesToVersion($controller->getModelVersionInfo()->requestedVersion())) {
98
-            unset($entity_response_array['_calculated_fields']);
99
-        }
100
-        return $entity_response_array;
101
-    }
80
+	/**
81
+	 * Removes the "_calculate_fields" part of entity responses before 4.8.36
82
+	 *
83
+	 * @param array           $entity_response_array
84
+	 * @param EEM_Base        $model
85
+	 * @param string          $request_context
86
+	 * @param WP_REST_Request $request
87
+	 * @param Read            $controller
88
+	 * @return array
89
+	 */
90
+	public function removeCalculatedFieldsFromResponse(
91
+		$entity_response_array,
92
+		EEM_Base $model,
93
+		$request_context,
94
+		WP_REST_Request $request,
95
+		Read $controller
96
+	) {
97
+		if ($this->appliesToVersion($controller->getModelVersionInfo()->requestedVersion())) {
98
+			unset($entity_response_array['_calculated_fields']);
99
+		}
100
+		return $entity_response_array;
101
+	}
102 102
 
103 103
 
104
-    /**
105
-     * Removes the new headers for requests before 4.8.36
106
-     *
107
-     * @param array           $headers
108
-     * @param Controller_Base $controller
109
-     * @param string          $version
110
-     * @return array
111
-     */
112
-    public function removeHeadersNewInThisVersion(
113
-        $headers,
114
-        Controller_Base $controller,
115
-        $version
116
-    ) {
117
-        if ($this->appliesToVersion($version)) {
118
-            $headers = array_diff_key(
119
-                $headers,
120
-                array_flip(
121
-                    array(
122
-                        Base::HEADER_PREFIX_FOR_WP . 'Total',
123
-                        Base::HEADER_PREFIX_FOR_WP . 'TotalPages',
124
-                        Base::HEADER_PREFIX_FOR_WP . 'PageSize',
125
-                    )
126
-                )
127
-            );
128
-        }
129
-        return $headers;
130
-    }
104
+	/**
105
+	 * Removes the new headers for requests before 4.8.36
106
+	 *
107
+	 * @param array           $headers
108
+	 * @param Controller_Base $controller
109
+	 * @param string          $version
110
+	 * @return array
111
+	 */
112
+	public function removeHeadersNewInThisVersion(
113
+		$headers,
114
+		Controller_Base $controller,
115
+		$version
116
+	) {
117
+		if ($this->appliesToVersion($version)) {
118
+			$headers = array_diff_key(
119
+				$headers,
120
+				array_flip(
121
+					array(
122
+						Base::HEADER_PREFIX_FOR_WP . 'Total',
123
+						Base::HEADER_PREFIX_FOR_WP . 'TotalPages',
124
+						Base::HEADER_PREFIX_FOR_WP . 'PageSize',
125
+					)
126
+				)
127
+			);
128
+		}
129
+		return $headers;
130
+	}
131 131
 
132 132
 
133
-    /**
134
-     * Puts the 'featured_image_url' back in for responses before 4.8.36.
135
-     *
136
-     * @param array           $entity_response_array
137
-     * @param EEM_Base        $model
138
-     * @param string          $request_context
139
-     * @param WP_REST_Request $request
140
-     * @param Read            $controller
141
-     * @return array
142
-     */
143
-    public function addOldFeaturedImagePartOfCptEntities(
144
-        $entity_response_array,
145
-        EEM_Base $model,
146
-        $request_context,
147
-        WP_REST_Request $request,
148
-        Read $controller
149
-    ) {
150
-        if ($this->appliesToVersion($controller->getModelVersionInfo()->requestedVersion())
151
-            && $model instanceof \EEM_CPT_Base
152
-        ) {
153
-            $attachment = wp_get_attachment_image_src(
154
-                get_post_thumbnail_id($entity_response_array[$model->primary_key_name()]),
155
-                'full'
156
-            );
157
-            $entity_response_array['featured_image_url'] = ! empty($attachment) ? $attachment[0] : null;
158
-        }
159
-        return $entity_response_array;
160
-    }
133
+	/**
134
+	 * Puts the 'featured_image_url' back in for responses before 4.8.36.
135
+	 *
136
+	 * @param array           $entity_response_array
137
+	 * @param EEM_Base        $model
138
+	 * @param string          $request_context
139
+	 * @param WP_REST_Request $request
140
+	 * @param Read            $controller
141
+	 * @return array
142
+	 */
143
+	public function addOldFeaturedImagePartOfCptEntities(
144
+		$entity_response_array,
145
+		EEM_Base $model,
146
+		$request_context,
147
+		WP_REST_Request $request,
148
+		Read $controller
149
+	) {
150
+		if ($this->appliesToVersion($controller->getModelVersionInfo()->requestedVersion())
151
+			&& $model instanceof \EEM_CPT_Base
152
+		) {
153
+			$attachment = wp_get_attachment_image_src(
154
+				get_post_thumbnail_id($entity_response_array[$model->primary_key_name()]),
155
+				'full'
156
+			);
157
+			$entity_response_array['featured_image_url'] = ! empty($attachment) ? $attachment[0] : null;
158
+		}
159
+		return $entity_response_array;
160
+	}
161 161
 
162 162
 
163
-    /**
164
-     * If the value was infinity, we now use null in our JSON responses,
165
-     * but before this version we used -1.
166
-     *
167
-     * @param mixed                $new_value
168
-     * @param \EE_Model_Field_Base $field_obj
169
-     * @param mixed                $original_value
170
-     * @param string               $requested_value
171
-     * @return mixed
172
-     */
173
-    public function useNegativeOneForInfinityBeforeThisVersion(
174
-        $new_value,
175
-        $field_obj,
176
-        $original_value,
177
-        $requested_value
178
-    ) {
179
-        if ($this->appliesToVersion($requested_value)
180
-            && $original_value === EE_INF
181
-        ) {
182
-            // return the old representation of infinity in the JSON
183
-            return -1;
184
-        }
185
-        return $new_value;
186
-    }
163
+	/**
164
+	 * If the value was infinity, we now use null in our JSON responses,
165
+	 * but before this version we used -1.
166
+	 *
167
+	 * @param mixed                $new_value
168
+	 * @param \EE_Model_Field_Base $field_obj
169
+	 * @param mixed                $original_value
170
+	 * @param string               $requested_value
171
+	 * @return mixed
172
+	 */
173
+	public function useNegativeOneForInfinityBeforeThisVersion(
174
+		$new_value,
175
+		$field_obj,
176
+		$original_value,
177
+		$requested_value
178
+	) {
179
+		if ($this->appliesToVersion($requested_value)
180
+			&& $original_value === EE_INF
181
+		) {
182
+			// return the old representation of infinity in the JSON
183
+			return -1;
184
+		}
185
+		return $new_value;
186
+	}
187 187
 }
Please login to merge, or discard this patch.
core/libraries/rest_api/ModelDataTranslator.php 2 patches
Indentation   +821 added lines, -821 removed lines patch added patch discarded remove patch
@@ -32,825 +32,825 @@
 block discarded – undo
32 32
 class ModelDataTranslator
33 33
 {
34 34
 
35
-    /**
36
-     * We used to use -1 for infinity in the rest api, but that's ambiguous for
37
-     * fields that COULD contain -1; so we use null
38
-     */
39
-    const EE_INF_IN_REST = null;
40
-
41
-
42
-    /**
43
-     * Prepares a possible array of input values from JSON for use by the models
44
-     *
45
-     * @param EE_Model_Field_Base $field_obj
46
-     * @param mixed               $original_value_maybe_array
47
-     * @param string              $requested_version
48
-     * @param string              $timezone_string treat values as being in this timezone
49
-     * @return mixed
50
-     * @throws RestException
51
-     */
52
-    public static function prepareFieldValuesFromJson(
53
-        $field_obj,
54
-        $original_value_maybe_array,
55
-        $requested_version,
56
-        $timezone_string = 'UTC'
57
-    ) {
58
-        if (is_array($original_value_maybe_array)
59
-            && ! $field_obj instanceof EE_Serialized_Text_Field
60
-        ) {
61
-            $new_value_maybe_array = array();
62
-            foreach ($original_value_maybe_array as $array_key => $array_item) {
63
-                $new_value_maybe_array[$array_key] = ModelDataTranslator::prepareFieldValueFromJson(
64
-                    $field_obj,
65
-                    $array_item,
66
-                    $requested_version,
67
-                    $timezone_string
68
-                );
69
-            }
70
-        } else {
71
-            $new_value_maybe_array = ModelDataTranslator::prepareFieldValueFromJson(
72
-                $field_obj,
73
-                $original_value_maybe_array,
74
-                $requested_version,
75
-                $timezone_string
76
-            );
77
-        }
78
-        return $new_value_maybe_array;
79
-    }
80
-
81
-
82
-    /**
83
-     * Prepares an array of field values FOR use in JSON/REST API
84
-     *
85
-     * @param EE_Model_Field_Base $field_obj
86
-     * @param mixed               $original_value_maybe_array
87
-     * @param string              $request_version (eg 4.8.36)
88
-     * @return array
89
-     */
90
-    public static function prepareFieldValuesForJson($field_obj, $original_value_maybe_array, $request_version)
91
-    {
92
-        if (is_array($original_value_maybe_array)) {
93
-            $new_value = array();
94
-            foreach ($original_value_maybe_array as $key => $value) {
95
-                $new_value[$key] = ModelDataTranslator::prepareFieldValuesForJson($field_obj, $value, $request_version);
96
-            }
97
-        } else {
98
-            $new_value = ModelDataTranslator::prepareFieldValueForJson(
99
-                $field_obj,
100
-                $original_value_maybe_array,
101
-                $request_version
102
-            );
103
-        }
104
-        return $new_value;
105
-    }
106
-
107
-
108
-    /**
109
-     * Prepares incoming data from the json or $_REQUEST parameters for the models'
110
-     * "$query_params".
111
-     *
112
-     * @param EE_Model_Field_Base $field_obj
113
-     * @param mixed               $original_value
114
-     * @param string              $requested_version
115
-     * @param string              $timezone_string treat values as being in this timezone
116
-     * @return mixed
117
-     * @throws RestException
118
-     * @throws DomainException
119
-     * @throws EE_Error
120
-     */
121
-    public static function prepareFieldValueFromJson(
122
-        $field_obj,
123
-        $original_value,
124
-        $requested_version,
125
-        $timezone_string = 'UTC' // UTC
126
-    ) {
127
-        // check if they accidentally submitted an error value. If so throw an exception
128
-        if (is_array($original_value)
129
-            && isset($original_value['error_code'], $original_value['error_message'])) {
130
-            throw new RestException(
131
-                'rest_submitted_error_value',
132
-                sprintf(
133
-                    esc_html__(
134
-                        'You tried to submit a JSON error object as a value for %1$s. That\'s not allowed.',
135
-                        'event_espresso'
136
-                    ),
137
-                    $field_obj->get_name()
138
-                ),
139
-                array(
140
-                    'status' => 400,
141
-                )
142
-            );
143
-        }
144
-        // double-check for serialized PHP. We never accept serialized PHP. No way Jose.
145
-        ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
146
-        $timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
147
-        $new_value = null;
148
-        // walk through the submitted data and double-check for serialized PHP. We never accept serialized PHP. No
149
-        // way Jose.
150
-        ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
151
-        if ($field_obj instanceof EE_Infinite_Integer_Field
152
-            && in_array($original_value, array(null, ''), true)
153
-        ) {
154
-            $new_value = EE_INF;
155
-        } elseif ($field_obj instanceof EE_Datetime_Field) {
156
-            $new_value = rest_parse_date(
157
-                self::getTimestampWithTimezoneOffset($original_value, $field_obj, $timezone_string)
158
-            );
159
-            if ($new_value === false) {
160
-                throw new RestException(
161
-                    'invalid_format_for_timestamp',
162
-                    sprintf(
163
-                        esc_html__(
164
-                            'Timestamps received on a request as the value for Date and Time fields must be in %1$s/%2$s format.  The timestamp provided (%3$s) is not that format.',
165
-                            'event_espresso'
166
-                        ),
167
-                        'RFC3339',
168
-                        'ISO8601',
169
-                        $original_value
170
-                    ),
171
-                    array(
172
-                        'status' => 400,
173
-                    )
174
-                );
175
-            }
176
-        } else {
177
-            $new_value = $original_value;
178
-        }
179
-        return $new_value;
180
-    }
181
-
182
-
183
-    /**
184
-     * This checks if the incoming timestamp has timezone information already on it and if it doesn't then adds timezone
185
-     * information via details obtained from the host site.
186
-     *
187
-     * @param string            $original_timestamp
188
-     * @param EE_Datetime_Field $datetime_field
189
-     * @param                   $timezone_string
190
-     * @return string
191
-     * @throws DomainException
192
-     */
193
-    private static function getTimestampWithTimezoneOffset(
194
-        $original_timestamp,
195
-        EE_Datetime_Field $datetime_field,
196
-        $timezone_string
197
-    ) {
198
-        // already have timezone information?
199
-        if (preg_match('/Z|(\+|\-)(\d{2}:\d{2})/', $original_timestamp)) {
200
-            // yes, we're ignoring the timezone.
201
-            return $original_timestamp;
202
-        }
203
-        // need to append timezone
204
-        list($offset_sign, $offset_secs) = self::parseTimezoneOffset(
205
-            $datetime_field->get_timezone_offset(
206
-                new \DateTimeZone($timezone_string),
207
-                $original_timestamp
208
-            )
209
-        );
210
-        $offset_string =
211
-            str_pad(
212
-                floor($offset_secs / HOUR_IN_SECONDS),
213
-                2,
214
-                '0',
215
-                STR_PAD_LEFT
216
-            )
217
-            . ':'
218
-            . str_pad(
219
-                ($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
220
-                2,
221
-                '0',
222
-                STR_PAD_LEFT
223
-            );
224
-        return $original_timestamp . $offset_sign . $offset_string;
225
-    }
226
-
227
-
228
-    /**
229
-     * Throws an exception if $data is a serialized PHP string (or somehow an actually PHP object, although I don't
230
-     * think that can happen). If $data is an array, recurses into its keys and values
231
-     *
232
-     * @param mixed $data
233
-     * @throws RestException
234
-     * @return void
235
-     */
236
-    public static function throwExceptionIfContainsSerializedData($data)
237
-    {
238
-        if (is_array($data)) {
239
-            foreach ($data as $key => $value) {
240
-                ModelDataTranslator::throwExceptionIfContainsSerializedData($key);
241
-                ModelDataTranslator::throwExceptionIfContainsSerializedData($value);
242
-            }
243
-        } else {
244
-            if (is_serialized($data) || is_object($data)) {
245
-                throw new RestException(
246
-                    'serialized_data_submission_prohibited',
247
-                    esc_html__(
248
-                    // @codingStandardsIgnoreStart
249
-                        'You tried to submit a string of serialized text. Serialized PHP is prohibited over the EE4 REST API.',
250
-                        // @codingStandardsIgnoreEnd
251
-                        'event_espresso'
252
-                    )
253
-                );
254
-            }
255
-        }
256
-    }
257
-
258
-
259
-    /**
260
-     * determines what's going on with them timezone strings
261
-     *
262
-     * @param int $timezone_offset
263
-     * @return array
264
-     */
265
-    private static function parseTimezoneOffset($timezone_offset)
266
-    {
267
-        $first_char = substr((string)$timezone_offset, 0, 1);
268
-        if ($first_char === '+' || $first_char === '-') {
269
-            $offset_sign = $first_char;
270
-            $offset_secs = substr((string)$timezone_offset, 1);
271
-        } else {
272
-            $offset_sign = '+';
273
-            $offset_secs = $timezone_offset;
274
-        }
275
-        return array($offset_sign, $offset_secs);
276
-    }
277
-
278
-
279
-    /**
280
-     * Prepares a field's value for display in the API
281
-     *
282
-     * @param EE_Model_Field_Base $field_obj
283
-     * @param mixed               $original_value
284
-     * @param string              $requested_version
285
-     * @return mixed
286
-     */
287
-    public static function prepareFieldValueForJson($field_obj, $original_value, $requested_version)
288
-    {
289
-        if ($original_value === EE_INF) {
290
-            $new_value = ModelDataTranslator::EE_INF_IN_REST;
291
-        } elseif ($field_obj instanceof EE_Datetime_Field) {
292
-            if (is_string($original_value)) {
293
-                // did they submit a string of a unix timestamp?
294
-                if (is_numeric($original_value)) {
295
-                    $datetime_obj = new \DateTime();
296
-                    $datetime_obj->setTimestamp((int)$original_value);
297
-                } else {
298
-                    // first, check if its a MySQL timestamp in GMT
299
-                    $datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
300
-                }
301
-                if (! $datetime_obj instanceof \DateTime) {
302
-                    // so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
303
-                    $datetime_obj = $field_obj->prepare_for_set($original_value);
304
-                }
305
-                $original_value = $datetime_obj;
306
-            }
307
-            if ($original_value instanceof \DateTime) {
308
-                $new_value = $original_value->format('Y-m-d H:i:s');
309
-            } elseif (is_int($original_value) || is_float($original_value)) {
310
-                $new_value = date('Y-m-d H:i:s', $original_value);
311
-            } elseif ($original_value === null || $original_value === '') {
312
-                $new_value = null;
313
-            } else {
314
-                // so it's not a datetime object, unix timestamp (as string or int),
315
-                // MySQL timestamp, or even a string in the field object's format. So no idea what it is
316
-                throw new \EE_Error(
317
-                    sprintf(
318
-                        esc_html__(
319
-                            // @codingStandardsIgnoreStart
320
-                            'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
321
-                            // @codingStandardsIgnoreEnd
322
-                            'event_espresso'
323
-                        ),
324
-                        $original_value,
325
-                        $field_obj->get_name(),
326
-                        $field_obj->get_model_name(),
327
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
328
-                    )
329
-                );
330
-            }
331
-            $new_value = mysql_to_rfc3339($new_value);
332
-        } else {
333
-            $new_value = $original_value;
334
-        }
335
-        // are we about to send an object? just don't. We have no good way to represent it in JSON.
336
-        // can't just check using is_object() because that missed PHP incomplete objects
337
-        if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
338
-            $new_value = array(
339
-                'error_code'    => 'php_object_not_return',
340
-                'error_message' => esc_html__(
341
-                    'The value of this field in the database is a PHP object, which can\'t be represented in JSON.',
342
-                    'event_espresso'
343
-                ),
344
-            );
345
-        }
346
-        return apply_filters(
347
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
348
-            $new_value,
349
-            $field_obj,
350
-            $original_value,
351
-            $requested_version
352
-        );
353
-    }
354
-
355
-
356
-    /**
357
-     * Prepares condition-query-parameters (like what's in where and having) from
358
-     * the format expected in the API to use in the models
359
-     *
360
-     * @param array    $inputted_query_params_of_this_type
361
-     * @param EEM_Base $model
362
-     * @param string   $requested_version
363
-     * @param boolean  $writing whether this data will be written to the DB, or if we're just building a query.
364
-     *                          If we're writing to the DB, we don't expect any operators, or any logic query
365
-     *                          parameters, and we also won't accept serialized data unless the current user has
366
-     *                          unfiltered_html.
367
-     * @return array
368
-     * @throws DomainException
369
-     * @throws RestException
370
-     * @throws EE_Error
371
-     */
372
-    public static function prepareConditionsQueryParamsForModels(
373
-        $inputted_query_params_of_this_type,
374
-        EEM_Base $model,
375
-        $requested_version,
376
-        $writing = false
377
-    ) {
378
-        $query_param_for_models = array();
379
-        $valid_operators = $model->valid_operators();
380
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
381
-            $is_gmt_datetime_field = false;
382
-            $query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
383
-                $query_param_key
384
-            );
385
-            $field = ModelDataTranslator::deduceFieldFromQueryParam(
386
-                $query_param_sans_stars,
387
-                $model
388
-            );
389
-            // double-check is it a *_gmt field?
390
-            if (! $field instanceof EE_Model_Field_Base
391
-                && ModelDataTranslator::isGmtDateFieldName($query_param_sans_stars)
392
-            ) {
393
-                // yep, take off '_gmt', and find the field
394
-                $query_param_key = ModelDataTranslator::removeGmtFromFieldName($query_param_sans_stars);
395
-                $field = ModelDataTranslator::deduceFieldFromQueryParam(
396
-                    $query_param_key,
397
-                    $model
398
-                );
399
-                $timezone = 'UTC';
400
-                $is_gmt_datetime_field = true;
401
-            } elseif ($field instanceof EE_Datetime_Field) {
402
-                // so it's not a GMT field. Set the timezone on the model to the default
403
-                $timezone = \EEH_DTT_Helper::get_valid_timezone_string();
404
-            } else {
405
-                // just keep using what's already set for the timezone
406
-                $timezone = $model->get_timezone();
407
-            }
408
-            if ($field instanceof EE_Model_Field_Base) {
409
-                if (! $writing && is_array($query_param_value)) {
410
-                    if (! \EEH_Array::is_array_numerically_and_sequentially_indexed($query_param_value)) {
411
-                        if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
412
-                            throw new RestException(
413
-                                'numerically_indexed_array_of_values_only',
414
-                                sprintf(
415
-                                    esc_html__(
416
-                                        'The array provided for the parameter "%1$s" should be numerically indexed.',
417
-                                        'event_espresso'
418
-                                    ),
419
-                                    $query_param_key
420
-                                ),
421
-                                array(
422
-                                    'status' => 400,
423
-                                )
424
-                            );
425
-                        }
426
-                    }
427
-                    // did they specify an operator?
428
-                    if (isset($query_param_value[0])
429
-                        && isset($valid_operators[$query_param_value[0]])
430
-                    ) {
431
-                        $op = $query_param_value[0];
432
-                        $translated_value = array($op);
433
-                        if (array_key_exists($op, $model->valid_in_style_operators())
434
-                            && isset($query_param_value[1])
435
-                            && ! isset($query_param_value[2])
436
-                        ) {
437
-                            $translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
438
-                                $field,
439
-                                $query_param_value[1],
440
-                                $requested_version,
441
-                                $timezone
442
-                            );
443
-                        } elseif (array_key_exists($op, $model->valid_between_style_operators())
444
-                                  && isset($query_param_value[1], $query_param_value[2])
445
-                                  && ! isset($query_param_value[3])
446
-                        ) {
447
-                            $translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
448
-                                $field,
449
-                                $query_param_value[1],
450
-                                $requested_version,
451
-                                $timezone
452
-                            );
453
-                            $translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
454
-                                $field,
455
-                                $query_param_value[2],
456
-                                $requested_version,
457
-                                $timezone
458
-                            );
459
-                        } elseif (array_key_exists($op, $model->valid_like_style_operators())
460
-                                  && isset($query_param_value[1])
461
-                                  && ! isset($query_param_value[2])
462
-                        ) {
463
-                            // we want to leave this value mostly-as-is (eg don't force it to be a float
464
-                            // or a boolean or an enum value. Leave it as-is with wildcards etc)
465
-                            // but do verify it at least doesn't have any serialized data
466
-                            ModelDataTranslator::throwExceptionIfContainsSerializedData($query_param_value[1]);
467
-                            $translated_value[] = $query_param_value[1];
468
-                        } elseif (array_key_exists($op, $model->valid_null_style_operators())
469
-                                  && ! isset($query_param_value[1])) {
470
-                            // no arguments should have been provided, so don't look for any
471
-                        } elseif (isset($query_param_value[1])
472
-                                  && ! isset($query_param_value[2])
473
-                                  && ! array_key_exists(
474
-                                      $op,
475
-                                      array_merge(
476
-                                          $model->valid_in_style_operators(),
477
-                                          $model->valid_null_style_operators(),
478
-                                          $model->valid_like_style_operators(),
479
-                                          $model->valid_between_style_operators()
480
-                                      )
481
-                                  )
482
-                        ) {
483
-                            // it's a valid operator, but none of the exceptions. Treat it normally.
484
-                            $translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
485
-                                $field,
486
-                                $query_param_value[1],
487
-                                $requested_version,
488
-                                $timezone
489
-                            );
490
-                        } else {
491
-                            // so they provided a valid operator, but wrong number of arguments
492
-                            if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
493
-                                throw new RestException(
494
-                                    'wrong_number_of_arguments',
495
-                                    sprintf(
496
-                                        esc_html__(
497
-                                            'The operator you provided, "%1$s" had the wrong number of arguments',
498
-                                            'event_espresso'
499
-                                        ),
500
-                                        $op
501
-                                    ),
502
-                                    array(
503
-                                        'status' => 400,
504
-                                    )
505
-                                );
506
-                            }
507
-                            $translated_value = null;
508
-                        }
509
-                    } else {
510
-                        // so they didn't provide a valid operator
511
-                        if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
512
-                            throw new RestException(
513
-                                'invalid_operator',
514
-                                sprintf(
515
-                                    esc_html__(
516
-                                        'You provided an invalid parameter, with key "%1$s" and value "%2$s"',
517
-                                        'event_espresso'
518
-                                    ),
519
-                                    $query_param_key,
520
-                                    $query_param_value
521
-                                ),
522
-                                array(
523
-                                    'status' => 400,
524
-                                )
525
-                            );
526
-                        }
527
-                        // if we aren't in debug mode, then just try our best to fulfill the user's request
528
-                        $translated_value = null;
529
-                    }
530
-                } else {
531
-                    $translated_value = ModelDataTranslator::prepareFieldValueFromJson(
532
-                        $field,
533
-                        $query_param_value,
534
-                        $requested_version,
535
-                        $timezone
536
-                    );
537
-                }
538
-                if ((isset($query_param_for_models[$query_param_key]) && $is_gmt_datetime_field)
539
-                    || $translated_value === null
540
-                ) {
541
-                    // they have already provided a non-gmt field, ignore the gmt one. That's what WP core
542
-                    // currently does (they might change it though). See https://core.trac.wordpress.org/ticket/39954
543
-                    // OR we couldn't create a translated value from their input
544
-                    continue;
545
-                }
546
-                $query_param_for_models[$query_param_key] = $translated_value;
547
-            } else {
548
-                // so this param doesn't correspond to a field eh?
549
-                if ($writing) {
550
-                    // always tell API clients about invalid parameters when they're creating data. Otherwise,
551
-                    // they are probably going to create invalid data
552
-                    throw new RestException(
553
-                        'invalid_field',
554
-                        sprintf(
555
-                            esc_html__('You have provided an invalid parameter: "%1$s"', 'event_espresso'),
556
-                            $query_param_key
557
-                        )
558
-                    );
559
-                } else {
560
-                    // so it's not for a field, is it a logic query param key?
561
-                    if (in_array(
562
-                        $query_param_sans_stars,
563
-                        $model->logic_query_param_keys()
564
-                    )) {
565
-                        $query_param_for_models[$query_param_key] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
566
-                            $query_param_value,
567
-                            $model,
568
-                            $requested_version
569
-                        );
570
-                    } elseif (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
571
-                        // only tell API clients they got it wrong if we're in debug mode
572
-                        // otherwise try our best ot fulfill their request by ignoring this invalid data
573
-                        throw new RestException(
574
-                            'invalid_parameter',
575
-                            sprintf(
576
-                                esc_html__(
577
-                                    'You provided an invalid parameter, with key "%1$s"',
578
-                                    'event_espresso'
579
-                                ),
580
-                                $query_param_sans_stars
581
-                            ),
582
-                            array(
583
-                                'status' => 400,
584
-                            )
585
-                        );
586
-                    }
587
-                }
588
-            }
589
-        }
590
-        return $query_param_for_models;
591
-    }
592
-
593
-
594
-    /**
595
-     * Mostly checks if the last 4 characters are "_gmt", indicating its a
596
-     * gmt date field name
597
-     *
598
-     * @param string $field_name
599
-     * @return boolean
600
-     */
601
-    public static function isGmtDateFieldName($field_name)
602
-    {
603
-        return substr(
604
-            ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($field_name),
605
-            -4,
606
-            4
607
-        ) === '_gmt';
608
-    }
609
-
610
-
611
-    /**
612
-     * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
613
-     *
614
-     * @param string $field_name
615
-     * @return string
616
-     */
617
-    public static function removeGmtFromFieldName($field_name)
618
-    {
619
-        if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
620
-            return $field_name;
621
-        }
622
-        $query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
623
-            $field_name
624
-        );
625
-        $query_param_sans_gmt_and_sans_stars = substr(
626
-            $query_param_sans_stars,
627
-            0,
628
-            strrpos(
629
-                $field_name,
630
-                '_gmt'
631
-            )
632
-        );
633
-        return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
634
-    }
635
-
636
-
637
-    /**
638
-     * Takes a field name from the REST API and prepares it for the model querying
639
-     *
640
-     * @param string $field_name
641
-     * @return string
642
-     */
643
-    public static function prepareFieldNameFromJson($field_name)
644
-    {
645
-        if (ModelDataTranslator::isGmtDateFieldName($field_name)) {
646
-            return ModelDataTranslator::removeGmtFromFieldName($field_name);
647
-        }
648
-        return $field_name;
649
-    }
650
-
651
-
652
-    /**
653
-     * Takes array of field names from REST API and prepares for models
654
-     *
655
-     * @param array $field_names
656
-     * @return array of field names (possibly include model prefixes)
657
-     */
658
-    public static function prepareFieldNamesFromJson(array $field_names)
659
-    {
660
-        $new_array = array();
661
-        foreach ($field_names as $key => $field_name) {
662
-            $new_array[$key] = ModelDataTranslator::prepareFieldNameFromJson($field_name);
663
-        }
664
-        return $new_array;
665
-    }
666
-
667
-
668
-    /**
669
-     * Takes array where array keys are field names (possibly with model path prefixes)
670
-     * from the REST API and prepares them for model querying
671
-     *
672
-     * @param array $field_names_as_keys
673
-     * @return array
674
-     */
675
-    public static function prepareFieldNamesInArrayKeysFromJson(array $field_names_as_keys)
676
-    {
677
-        $new_array = array();
678
-        foreach ($field_names_as_keys as $field_name => $value) {
679
-            $new_array[ModelDataTranslator::prepareFieldNameFromJson($field_name)] = $value;
680
-        }
681
-        return $new_array;
682
-    }
683
-
684
-
685
-    /**
686
-     * Prepares an array of model query params for use in the REST API
687
-     *
688
-     * @param array    $model_query_params
689
-     * @param EEM_Base $model
690
-     * @param string   $requested_version  eg "4.8.36". If null is provided, defaults to the latest release of the EE4
691
-     *                                     REST API
692
-     * @return array which can be passed into the EE4 REST API when querying a model resource
693
-     * @throws EE_Error
694
-     */
695
-    public static function prepareQueryParamsForRestApi(
696
-        array $model_query_params,
697
-        EEM_Base $model,
698
-        $requested_version = null
699
-    ) {
700
-        if ($requested_version === null) {
701
-            $requested_version = \EED_Core_Rest_Api::latest_rest_api_version();
702
-        }
703
-        $rest_query_params = $model_query_params;
704
-        if (isset($model_query_params[0])) {
705
-            $rest_query_params['where'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
706
-                $model_query_params[0],
707
-                $model,
708
-                $requested_version
709
-            );
710
-            unset($rest_query_params[0]);
711
-        }
712
-        if (isset($model_query_params['having'])) {
713
-            $rest_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
714
-                $model_query_params['having'],
715
-                $model,
716
-                $requested_version
717
-            );
718
-        }
719
-        return apply_filters(
720
-            'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
721
-            $rest_query_params,
722
-            $model_query_params,
723
-            $model,
724
-            $requested_version
725
-        );
726
-    }
727
-
728
-
729
-    /**
730
-     * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
731
-     *
732
-     * @param array    $inputted_query_params_of_this_type  eg like the "where" or "having" conditions query params
733
-     *                                                      passed into EEM_Base::get_all()
734
-     * @param EEM_Base $model
735
-     * @param string   $requested_version                   eg "4.8.36"
736
-     * @return array ready for use in the rest api query params
737
-     * @throws EE_Error
738
-     * @throws ObjectDetectedException if somehow a PHP object were in the query params' values,
739
-     *                                                      (which would be really unusual)
740
-     */
741
-    public static function prepareConditionsQueryParamsForRestApi(
742
-        $inputted_query_params_of_this_type,
743
-        EEM_Base $model,
744
-        $requested_version
745
-    ) {
746
-        $query_param_for_models = array();
747
-        foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
748
-            $field = ModelDataTranslator::deduceFieldFromQueryParam(
749
-                ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($query_param_key),
750
-                $model
751
-            );
752
-            if ($field instanceof EE_Model_Field_Base) {
753
-                // did they specify an operator?
754
-                if (is_array($query_param_value)) {
755
-                    $op = $query_param_value[0];
756
-                    $translated_value = array($op);
757
-                    if (isset($query_param_value[1])) {
758
-                        $value = $query_param_value[1];
759
-                        $translated_value[1] = ModelDataTranslator::prepareFieldValuesForJson(
760
-                            $field,
761
-                            $value,
762
-                            $requested_version
763
-                        );
764
-                    }
765
-                } else {
766
-                    $translated_value = ModelDataTranslator::prepareFieldValueForJson(
767
-                        $field,
768
-                        $query_param_value,
769
-                        $requested_version
770
-                    );
771
-                }
772
-                $query_param_for_models[$query_param_key] = $translated_value;
773
-            } else {
774
-                // so it's not for a field, assume it's a logic query param key
775
-                $query_param_for_models[$query_param_key] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
776
-                    $query_param_value,
777
-                    $model,
778
-                    $requested_version
779
-                );
780
-            }
781
-        }
782
-        return $query_param_for_models;
783
-    }
784
-
785
-
786
-    /**
787
-     * @param $condition_query_param_key
788
-     * @return string
789
-     */
790
-    public static function removeStarsAndAnythingAfterFromConditionQueryParamKey($condition_query_param_key)
791
-    {
792
-        $pos_of_star = strpos($condition_query_param_key, '*');
793
-        if ($pos_of_star === false) {
794
-            return $condition_query_param_key;
795
-        } else {
796
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
797
-            return $condition_query_param_sans_star;
798
-        }
799
-    }
800
-
801
-
802
-    /**
803
-     * Takes the input parameter and finds the model field that it indicates.
804
-     *
805
-     * @param string   $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
806
-     * @param EEM_Base $model
807
-     * @return EE_Model_Field_Base
808
-     * @throws EE_Error
809
-     */
810
-    public static function deduceFieldFromQueryParam($query_param_name, EEM_Base $model)
811
-    {
812
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
813
-        // which will help us find the database table and column
814
-        $query_param_parts = explode('.', $query_param_name);
815
-        if (empty($query_param_parts)) {
816
-            throw new EE_Error(
817
-                sprintf(
818
-                    __(
819
-                        '_extract_column_name is empty when trying to extract column and table name from %s',
820
-                        'event_espresso'
821
-                    ),
822
-                    $query_param_name
823
-                )
824
-            );
825
-        }
826
-        $number_of_parts = count($query_param_parts);
827
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
828
-        if ($number_of_parts === 1) {
829
-            $field_name = $last_query_param_part;
830
-        } else {// $number_of_parts >= 2
831
-            // the last part is the column name, and there are only 2parts. therefore...
832
-            $field_name = $last_query_param_part;
833
-            $model = \EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
834
-        }
835
-        try {
836
-            return $model->field_settings_for($field_name, false);
837
-        } catch (EE_Error $e) {
838
-            return null;
839
-        }
840
-    }
841
-
842
-
843
-    /**
844
-     * Returns true if $data can be easily represented in JSON.
845
-     * Basically, objects and resources can't be represented in JSON easily.
846
-     *
847
-     * @param mixed $data
848
-     * @return bool
849
-     */
850
-    protected static function isRepresentableInJson($data)
851
-    {
852
-        return is_scalar($data)
853
-               || is_array($data)
854
-               || is_null($data);
855
-    }
35
+	/**
36
+	 * We used to use -1 for infinity in the rest api, but that's ambiguous for
37
+	 * fields that COULD contain -1; so we use null
38
+	 */
39
+	const EE_INF_IN_REST = null;
40
+
41
+
42
+	/**
43
+	 * Prepares a possible array of input values from JSON for use by the models
44
+	 *
45
+	 * @param EE_Model_Field_Base $field_obj
46
+	 * @param mixed               $original_value_maybe_array
47
+	 * @param string              $requested_version
48
+	 * @param string              $timezone_string treat values as being in this timezone
49
+	 * @return mixed
50
+	 * @throws RestException
51
+	 */
52
+	public static function prepareFieldValuesFromJson(
53
+		$field_obj,
54
+		$original_value_maybe_array,
55
+		$requested_version,
56
+		$timezone_string = 'UTC'
57
+	) {
58
+		if (is_array($original_value_maybe_array)
59
+			&& ! $field_obj instanceof EE_Serialized_Text_Field
60
+		) {
61
+			$new_value_maybe_array = array();
62
+			foreach ($original_value_maybe_array as $array_key => $array_item) {
63
+				$new_value_maybe_array[$array_key] = ModelDataTranslator::prepareFieldValueFromJson(
64
+					$field_obj,
65
+					$array_item,
66
+					$requested_version,
67
+					$timezone_string
68
+				);
69
+			}
70
+		} else {
71
+			$new_value_maybe_array = ModelDataTranslator::prepareFieldValueFromJson(
72
+				$field_obj,
73
+				$original_value_maybe_array,
74
+				$requested_version,
75
+				$timezone_string
76
+			);
77
+		}
78
+		return $new_value_maybe_array;
79
+	}
80
+
81
+
82
+	/**
83
+	 * Prepares an array of field values FOR use in JSON/REST API
84
+	 *
85
+	 * @param EE_Model_Field_Base $field_obj
86
+	 * @param mixed               $original_value_maybe_array
87
+	 * @param string              $request_version (eg 4.8.36)
88
+	 * @return array
89
+	 */
90
+	public static function prepareFieldValuesForJson($field_obj, $original_value_maybe_array, $request_version)
91
+	{
92
+		if (is_array($original_value_maybe_array)) {
93
+			$new_value = array();
94
+			foreach ($original_value_maybe_array as $key => $value) {
95
+				$new_value[$key] = ModelDataTranslator::prepareFieldValuesForJson($field_obj, $value, $request_version);
96
+			}
97
+		} else {
98
+			$new_value = ModelDataTranslator::prepareFieldValueForJson(
99
+				$field_obj,
100
+				$original_value_maybe_array,
101
+				$request_version
102
+			);
103
+		}
104
+		return $new_value;
105
+	}
106
+
107
+
108
+	/**
109
+	 * Prepares incoming data from the json or $_REQUEST parameters for the models'
110
+	 * "$query_params".
111
+	 *
112
+	 * @param EE_Model_Field_Base $field_obj
113
+	 * @param mixed               $original_value
114
+	 * @param string              $requested_version
115
+	 * @param string              $timezone_string treat values as being in this timezone
116
+	 * @return mixed
117
+	 * @throws RestException
118
+	 * @throws DomainException
119
+	 * @throws EE_Error
120
+	 */
121
+	public static function prepareFieldValueFromJson(
122
+		$field_obj,
123
+		$original_value,
124
+		$requested_version,
125
+		$timezone_string = 'UTC' // UTC
126
+	) {
127
+		// check if they accidentally submitted an error value. If so throw an exception
128
+		if (is_array($original_value)
129
+			&& isset($original_value['error_code'], $original_value['error_message'])) {
130
+			throw new RestException(
131
+				'rest_submitted_error_value',
132
+				sprintf(
133
+					esc_html__(
134
+						'You tried to submit a JSON error object as a value for %1$s. That\'s not allowed.',
135
+						'event_espresso'
136
+					),
137
+					$field_obj->get_name()
138
+				),
139
+				array(
140
+					'status' => 400,
141
+				)
142
+			);
143
+		}
144
+		// double-check for serialized PHP. We never accept serialized PHP. No way Jose.
145
+		ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
146
+		$timezone_string = $timezone_string !== '' ? $timezone_string : get_option('timezone_string', '');
147
+		$new_value = null;
148
+		// walk through the submitted data and double-check for serialized PHP. We never accept serialized PHP. No
149
+		// way Jose.
150
+		ModelDataTranslator::throwExceptionIfContainsSerializedData($original_value);
151
+		if ($field_obj instanceof EE_Infinite_Integer_Field
152
+			&& in_array($original_value, array(null, ''), true)
153
+		) {
154
+			$new_value = EE_INF;
155
+		} elseif ($field_obj instanceof EE_Datetime_Field) {
156
+			$new_value = rest_parse_date(
157
+				self::getTimestampWithTimezoneOffset($original_value, $field_obj, $timezone_string)
158
+			);
159
+			if ($new_value === false) {
160
+				throw new RestException(
161
+					'invalid_format_for_timestamp',
162
+					sprintf(
163
+						esc_html__(
164
+							'Timestamps received on a request as the value for Date and Time fields must be in %1$s/%2$s format.  The timestamp provided (%3$s) is not that format.',
165
+							'event_espresso'
166
+						),
167
+						'RFC3339',
168
+						'ISO8601',
169
+						$original_value
170
+					),
171
+					array(
172
+						'status' => 400,
173
+					)
174
+				);
175
+			}
176
+		} else {
177
+			$new_value = $original_value;
178
+		}
179
+		return $new_value;
180
+	}
181
+
182
+
183
+	/**
184
+	 * This checks if the incoming timestamp has timezone information already on it and if it doesn't then adds timezone
185
+	 * information via details obtained from the host site.
186
+	 *
187
+	 * @param string            $original_timestamp
188
+	 * @param EE_Datetime_Field $datetime_field
189
+	 * @param                   $timezone_string
190
+	 * @return string
191
+	 * @throws DomainException
192
+	 */
193
+	private static function getTimestampWithTimezoneOffset(
194
+		$original_timestamp,
195
+		EE_Datetime_Field $datetime_field,
196
+		$timezone_string
197
+	) {
198
+		// already have timezone information?
199
+		if (preg_match('/Z|(\+|\-)(\d{2}:\d{2})/', $original_timestamp)) {
200
+			// yes, we're ignoring the timezone.
201
+			return $original_timestamp;
202
+		}
203
+		// need to append timezone
204
+		list($offset_sign, $offset_secs) = self::parseTimezoneOffset(
205
+			$datetime_field->get_timezone_offset(
206
+				new \DateTimeZone($timezone_string),
207
+				$original_timestamp
208
+			)
209
+		);
210
+		$offset_string =
211
+			str_pad(
212
+				floor($offset_secs / HOUR_IN_SECONDS),
213
+				2,
214
+				'0',
215
+				STR_PAD_LEFT
216
+			)
217
+			. ':'
218
+			. str_pad(
219
+				($offset_secs % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS,
220
+				2,
221
+				'0',
222
+				STR_PAD_LEFT
223
+			);
224
+		return $original_timestamp . $offset_sign . $offset_string;
225
+	}
226
+
227
+
228
+	/**
229
+	 * Throws an exception if $data is a serialized PHP string (or somehow an actually PHP object, although I don't
230
+	 * think that can happen). If $data is an array, recurses into its keys and values
231
+	 *
232
+	 * @param mixed $data
233
+	 * @throws RestException
234
+	 * @return void
235
+	 */
236
+	public static function throwExceptionIfContainsSerializedData($data)
237
+	{
238
+		if (is_array($data)) {
239
+			foreach ($data as $key => $value) {
240
+				ModelDataTranslator::throwExceptionIfContainsSerializedData($key);
241
+				ModelDataTranslator::throwExceptionIfContainsSerializedData($value);
242
+			}
243
+		} else {
244
+			if (is_serialized($data) || is_object($data)) {
245
+				throw new RestException(
246
+					'serialized_data_submission_prohibited',
247
+					esc_html__(
248
+					// @codingStandardsIgnoreStart
249
+						'You tried to submit a string of serialized text. Serialized PHP is prohibited over the EE4 REST API.',
250
+						// @codingStandardsIgnoreEnd
251
+						'event_espresso'
252
+					)
253
+				);
254
+			}
255
+		}
256
+	}
257
+
258
+
259
+	/**
260
+	 * determines what's going on with them timezone strings
261
+	 *
262
+	 * @param int $timezone_offset
263
+	 * @return array
264
+	 */
265
+	private static function parseTimezoneOffset($timezone_offset)
266
+	{
267
+		$first_char = substr((string)$timezone_offset, 0, 1);
268
+		if ($first_char === '+' || $first_char === '-') {
269
+			$offset_sign = $first_char;
270
+			$offset_secs = substr((string)$timezone_offset, 1);
271
+		} else {
272
+			$offset_sign = '+';
273
+			$offset_secs = $timezone_offset;
274
+		}
275
+		return array($offset_sign, $offset_secs);
276
+	}
277
+
278
+
279
+	/**
280
+	 * Prepares a field's value for display in the API
281
+	 *
282
+	 * @param EE_Model_Field_Base $field_obj
283
+	 * @param mixed               $original_value
284
+	 * @param string              $requested_version
285
+	 * @return mixed
286
+	 */
287
+	public static function prepareFieldValueForJson($field_obj, $original_value, $requested_version)
288
+	{
289
+		if ($original_value === EE_INF) {
290
+			$new_value = ModelDataTranslator::EE_INF_IN_REST;
291
+		} elseif ($field_obj instanceof EE_Datetime_Field) {
292
+			if (is_string($original_value)) {
293
+				// did they submit a string of a unix timestamp?
294
+				if (is_numeric($original_value)) {
295
+					$datetime_obj = new \DateTime();
296
+					$datetime_obj->setTimestamp((int)$original_value);
297
+				} else {
298
+					// first, check if its a MySQL timestamp in GMT
299
+					$datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
300
+				}
301
+				if (! $datetime_obj instanceof \DateTime) {
302
+					// so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
303
+					$datetime_obj = $field_obj->prepare_for_set($original_value);
304
+				}
305
+				$original_value = $datetime_obj;
306
+			}
307
+			if ($original_value instanceof \DateTime) {
308
+				$new_value = $original_value->format('Y-m-d H:i:s');
309
+			} elseif (is_int($original_value) || is_float($original_value)) {
310
+				$new_value = date('Y-m-d H:i:s', $original_value);
311
+			} elseif ($original_value === null || $original_value === '') {
312
+				$new_value = null;
313
+			} else {
314
+				// so it's not a datetime object, unix timestamp (as string or int),
315
+				// MySQL timestamp, or even a string in the field object's format. So no idea what it is
316
+				throw new \EE_Error(
317
+					sprintf(
318
+						esc_html__(
319
+							// @codingStandardsIgnoreStart
320
+							'The value "%1$s" for the field "%2$s" on model "%3$s" could not be understood. It should be a PHP DateTime, unix timestamp, MySQL date, or string in the format "%4$s".',
321
+							// @codingStandardsIgnoreEnd
322
+							'event_espresso'
323
+						),
324
+						$original_value,
325
+						$field_obj->get_name(),
326
+						$field_obj->get_model_name(),
327
+						$field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
328
+					)
329
+				);
330
+			}
331
+			$new_value = mysql_to_rfc3339($new_value);
332
+		} else {
333
+			$new_value = $original_value;
334
+		}
335
+		// are we about to send an object? just don't. We have no good way to represent it in JSON.
336
+		// can't just check using is_object() because that missed PHP incomplete objects
337
+		if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
338
+			$new_value = array(
339
+				'error_code'    => 'php_object_not_return',
340
+				'error_message' => esc_html__(
341
+					'The value of this field in the database is a PHP object, which can\'t be represented in JSON.',
342
+					'event_espresso'
343
+				),
344
+			);
345
+		}
346
+		return apply_filters(
347
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_field_for_rest_api',
348
+			$new_value,
349
+			$field_obj,
350
+			$original_value,
351
+			$requested_version
352
+		);
353
+	}
354
+
355
+
356
+	/**
357
+	 * Prepares condition-query-parameters (like what's in where and having) from
358
+	 * the format expected in the API to use in the models
359
+	 *
360
+	 * @param array    $inputted_query_params_of_this_type
361
+	 * @param EEM_Base $model
362
+	 * @param string   $requested_version
363
+	 * @param boolean  $writing whether this data will be written to the DB, or if we're just building a query.
364
+	 *                          If we're writing to the DB, we don't expect any operators, or any logic query
365
+	 *                          parameters, and we also won't accept serialized data unless the current user has
366
+	 *                          unfiltered_html.
367
+	 * @return array
368
+	 * @throws DomainException
369
+	 * @throws RestException
370
+	 * @throws EE_Error
371
+	 */
372
+	public static function prepareConditionsQueryParamsForModels(
373
+		$inputted_query_params_of_this_type,
374
+		EEM_Base $model,
375
+		$requested_version,
376
+		$writing = false
377
+	) {
378
+		$query_param_for_models = array();
379
+		$valid_operators = $model->valid_operators();
380
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
381
+			$is_gmt_datetime_field = false;
382
+			$query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
383
+				$query_param_key
384
+			);
385
+			$field = ModelDataTranslator::deduceFieldFromQueryParam(
386
+				$query_param_sans_stars,
387
+				$model
388
+			);
389
+			// double-check is it a *_gmt field?
390
+			if (! $field instanceof EE_Model_Field_Base
391
+				&& ModelDataTranslator::isGmtDateFieldName($query_param_sans_stars)
392
+			) {
393
+				// yep, take off '_gmt', and find the field
394
+				$query_param_key = ModelDataTranslator::removeGmtFromFieldName($query_param_sans_stars);
395
+				$field = ModelDataTranslator::deduceFieldFromQueryParam(
396
+					$query_param_key,
397
+					$model
398
+				);
399
+				$timezone = 'UTC';
400
+				$is_gmt_datetime_field = true;
401
+			} elseif ($field instanceof EE_Datetime_Field) {
402
+				// so it's not a GMT field. Set the timezone on the model to the default
403
+				$timezone = \EEH_DTT_Helper::get_valid_timezone_string();
404
+			} else {
405
+				// just keep using what's already set for the timezone
406
+				$timezone = $model->get_timezone();
407
+			}
408
+			if ($field instanceof EE_Model_Field_Base) {
409
+				if (! $writing && is_array($query_param_value)) {
410
+					if (! \EEH_Array::is_array_numerically_and_sequentially_indexed($query_param_value)) {
411
+						if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
412
+							throw new RestException(
413
+								'numerically_indexed_array_of_values_only',
414
+								sprintf(
415
+									esc_html__(
416
+										'The array provided for the parameter "%1$s" should be numerically indexed.',
417
+										'event_espresso'
418
+									),
419
+									$query_param_key
420
+								),
421
+								array(
422
+									'status' => 400,
423
+								)
424
+							);
425
+						}
426
+					}
427
+					// did they specify an operator?
428
+					if (isset($query_param_value[0])
429
+						&& isset($valid_operators[$query_param_value[0]])
430
+					) {
431
+						$op = $query_param_value[0];
432
+						$translated_value = array($op);
433
+						if (array_key_exists($op, $model->valid_in_style_operators())
434
+							&& isset($query_param_value[1])
435
+							&& ! isset($query_param_value[2])
436
+						) {
437
+							$translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
438
+								$field,
439
+								$query_param_value[1],
440
+								$requested_version,
441
+								$timezone
442
+							);
443
+						} elseif (array_key_exists($op, $model->valid_between_style_operators())
444
+								  && isset($query_param_value[1], $query_param_value[2])
445
+								  && ! isset($query_param_value[3])
446
+						) {
447
+							$translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
448
+								$field,
449
+								$query_param_value[1],
450
+								$requested_version,
451
+								$timezone
452
+							);
453
+							$translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
454
+								$field,
455
+								$query_param_value[2],
456
+								$requested_version,
457
+								$timezone
458
+							);
459
+						} elseif (array_key_exists($op, $model->valid_like_style_operators())
460
+								  && isset($query_param_value[1])
461
+								  && ! isset($query_param_value[2])
462
+						) {
463
+							// we want to leave this value mostly-as-is (eg don't force it to be a float
464
+							// or a boolean or an enum value. Leave it as-is with wildcards etc)
465
+							// but do verify it at least doesn't have any serialized data
466
+							ModelDataTranslator::throwExceptionIfContainsSerializedData($query_param_value[1]);
467
+							$translated_value[] = $query_param_value[1];
468
+						} elseif (array_key_exists($op, $model->valid_null_style_operators())
469
+								  && ! isset($query_param_value[1])) {
470
+							// no arguments should have been provided, so don't look for any
471
+						} elseif (isset($query_param_value[1])
472
+								  && ! isset($query_param_value[2])
473
+								  && ! array_key_exists(
474
+									  $op,
475
+									  array_merge(
476
+										  $model->valid_in_style_operators(),
477
+										  $model->valid_null_style_operators(),
478
+										  $model->valid_like_style_operators(),
479
+										  $model->valid_between_style_operators()
480
+									  )
481
+								  )
482
+						) {
483
+							// it's a valid operator, but none of the exceptions. Treat it normally.
484
+							$translated_value[] = ModelDataTranslator::prepareFieldValuesFromJson(
485
+								$field,
486
+								$query_param_value[1],
487
+								$requested_version,
488
+								$timezone
489
+							);
490
+						} else {
491
+							// so they provided a valid operator, but wrong number of arguments
492
+							if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
493
+								throw new RestException(
494
+									'wrong_number_of_arguments',
495
+									sprintf(
496
+										esc_html__(
497
+											'The operator you provided, "%1$s" had the wrong number of arguments',
498
+											'event_espresso'
499
+										),
500
+										$op
501
+									),
502
+									array(
503
+										'status' => 400,
504
+									)
505
+								);
506
+							}
507
+							$translated_value = null;
508
+						}
509
+					} else {
510
+						// so they didn't provide a valid operator
511
+						if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
512
+							throw new RestException(
513
+								'invalid_operator',
514
+								sprintf(
515
+									esc_html__(
516
+										'You provided an invalid parameter, with key "%1$s" and value "%2$s"',
517
+										'event_espresso'
518
+									),
519
+									$query_param_key,
520
+									$query_param_value
521
+								),
522
+								array(
523
+									'status' => 400,
524
+								)
525
+							);
526
+						}
527
+						// if we aren't in debug mode, then just try our best to fulfill the user's request
528
+						$translated_value = null;
529
+					}
530
+				} else {
531
+					$translated_value = ModelDataTranslator::prepareFieldValueFromJson(
532
+						$field,
533
+						$query_param_value,
534
+						$requested_version,
535
+						$timezone
536
+					);
537
+				}
538
+				if ((isset($query_param_for_models[$query_param_key]) && $is_gmt_datetime_field)
539
+					|| $translated_value === null
540
+				) {
541
+					// they have already provided a non-gmt field, ignore the gmt one. That's what WP core
542
+					// currently does (they might change it though). See https://core.trac.wordpress.org/ticket/39954
543
+					// OR we couldn't create a translated value from their input
544
+					continue;
545
+				}
546
+				$query_param_for_models[$query_param_key] = $translated_value;
547
+			} else {
548
+				// so this param doesn't correspond to a field eh?
549
+				if ($writing) {
550
+					// always tell API clients about invalid parameters when they're creating data. Otherwise,
551
+					// they are probably going to create invalid data
552
+					throw new RestException(
553
+						'invalid_field',
554
+						sprintf(
555
+							esc_html__('You have provided an invalid parameter: "%1$s"', 'event_espresso'),
556
+							$query_param_key
557
+						)
558
+					);
559
+				} else {
560
+					// so it's not for a field, is it a logic query param key?
561
+					if (in_array(
562
+						$query_param_sans_stars,
563
+						$model->logic_query_param_keys()
564
+					)) {
565
+						$query_param_for_models[$query_param_key] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
566
+							$query_param_value,
567
+							$model,
568
+							$requested_version
569
+						);
570
+					} elseif (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
571
+						// only tell API clients they got it wrong if we're in debug mode
572
+						// otherwise try our best ot fulfill their request by ignoring this invalid data
573
+						throw new RestException(
574
+							'invalid_parameter',
575
+							sprintf(
576
+								esc_html__(
577
+									'You provided an invalid parameter, with key "%1$s"',
578
+									'event_espresso'
579
+								),
580
+								$query_param_sans_stars
581
+							),
582
+							array(
583
+								'status' => 400,
584
+							)
585
+						);
586
+					}
587
+				}
588
+			}
589
+		}
590
+		return $query_param_for_models;
591
+	}
592
+
593
+
594
+	/**
595
+	 * Mostly checks if the last 4 characters are "_gmt", indicating its a
596
+	 * gmt date field name
597
+	 *
598
+	 * @param string $field_name
599
+	 * @return boolean
600
+	 */
601
+	public static function isGmtDateFieldName($field_name)
602
+	{
603
+		return substr(
604
+			ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($field_name),
605
+			-4,
606
+			4
607
+		) === '_gmt';
608
+	}
609
+
610
+
611
+	/**
612
+	 * Removes the last "_gmt" part of a field name (and if there is no "_gmt" at the end, leave it alone)
613
+	 *
614
+	 * @param string $field_name
615
+	 * @return string
616
+	 */
617
+	public static function removeGmtFromFieldName($field_name)
618
+	{
619
+		if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
620
+			return $field_name;
621
+		}
622
+		$query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
623
+			$field_name
624
+		);
625
+		$query_param_sans_gmt_and_sans_stars = substr(
626
+			$query_param_sans_stars,
627
+			0,
628
+			strrpos(
629
+				$field_name,
630
+				'_gmt'
631
+			)
632
+		);
633
+		return str_replace($query_param_sans_stars, $query_param_sans_gmt_and_sans_stars, $field_name);
634
+	}
635
+
636
+
637
+	/**
638
+	 * Takes a field name from the REST API and prepares it for the model querying
639
+	 *
640
+	 * @param string $field_name
641
+	 * @return string
642
+	 */
643
+	public static function prepareFieldNameFromJson($field_name)
644
+	{
645
+		if (ModelDataTranslator::isGmtDateFieldName($field_name)) {
646
+			return ModelDataTranslator::removeGmtFromFieldName($field_name);
647
+		}
648
+		return $field_name;
649
+	}
650
+
651
+
652
+	/**
653
+	 * Takes array of field names from REST API and prepares for models
654
+	 *
655
+	 * @param array $field_names
656
+	 * @return array of field names (possibly include model prefixes)
657
+	 */
658
+	public static function prepareFieldNamesFromJson(array $field_names)
659
+	{
660
+		$new_array = array();
661
+		foreach ($field_names as $key => $field_name) {
662
+			$new_array[$key] = ModelDataTranslator::prepareFieldNameFromJson($field_name);
663
+		}
664
+		return $new_array;
665
+	}
666
+
667
+
668
+	/**
669
+	 * Takes array where array keys are field names (possibly with model path prefixes)
670
+	 * from the REST API and prepares them for model querying
671
+	 *
672
+	 * @param array $field_names_as_keys
673
+	 * @return array
674
+	 */
675
+	public static function prepareFieldNamesInArrayKeysFromJson(array $field_names_as_keys)
676
+	{
677
+		$new_array = array();
678
+		foreach ($field_names_as_keys as $field_name => $value) {
679
+			$new_array[ModelDataTranslator::prepareFieldNameFromJson($field_name)] = $value;
680
+		}
681
+		return $new_array;
682
+	}
683
+
684
+
685
+	/**
686
+	 * Prepares an array of model query params for use in the REST API
687
+	 *
688
+	 * @param array    $model_query_params
689
+	 * @param EEM_Base $model
690
+	 * @param string   $requested_version  eg "4.8.36". If null is provided, defaults to the latest release of the EE4
691
+	 *                                     REST API
692
+	 * @return array which can be passed into the EE4 REST API when querying a model resource
693
+	 * @throws EE_Error
694
+	 */
695
+	public static function prepareQueryParamsForRestApi(
696
+		array $model_query_params,
697
+		EEM_Base $model,
698
+		$requested_version = null
699
+	) {
700
+		if ($requested_version === null) {
701
+			$requested_version = \EED_Core_Rest_Api::latest_rest_api_version();
702
+		}
703
+		$rest_query_params = $model_query_params;
704
+		if (isset($model_query_params[0])) {
705
+			$rest_query_params['where'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
706
+				$model_query_params[0],
707
+				$model,
708
+				$requested_version
709
+			);
710
+			unset($rest_query_params[0]);
711
+		}
712
+		if (isset($model_query_params['having'])) {
713
+			$rest_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
714
+				$model_query_params['having'],
715
+				$model,
716
+				$requested_version
717
+			);
718
+		}
719
+		return apply_filters(
720
+			'FHEE__EventEspresso\core\libraries\rest_api\Model_Data_Translator__prepare_query_params_for_rest_api',
721
+			$rest_query_params,
722
+			$model_query_params,
723
+			$model,
724
+			$requested_version
725
+		);
726
+	}
727
+
728
+
729
+	/**
730
+	 * Prepares all the sub-conditions query parameters (eg having or where conditions) for use in the rest api
731
+	 *
732
+	 * @param array    $inputted_query_params_of_this_type  eg like the "where" or "having" conditions query params
733
+	 *                                                      passed into EEM_Base::get_all()
734
+	 * @param EEM_Base $model
735
+	 * @param string   $requested_version                   eg "4.8.36"
736
+	 * @return array ready for use in the rest api query params
737
+	 * @throws EE_Error
738
+	 * @throws ObjectDetectedException if somehow a PHP object were in the query params' values,
739
+	 *                                                      (which would be really unusual)
740
+	 */
741
+	public static function prepareConditionsQueryParamsForRestApi(
742
+		$inputted_query_params_of_this_type,
743
+		EEM_Base $model,
744
+		$requested_version
745
+	) {
746
+		$query_param_for_models = array();
747
+		foreach ($inputted_query_params_of_this_type as $query_param_key => $query_param_value) {
748
+			$field = ModelDataTranslator::deduceFieldFromQueryParam(
749
+				ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey($query_param_key),
750
+				$model
751
+			);
752
+			if ($field instanceof EE_Model_Field_Base) {
753
+				// did they specify an operator?
754
+				if (is_array($query_param_value)) {
755
+					$op = $query_param_value[0];
756
+					$translated_value = array($op);
757
+					if (isset($query_param_value[1])) {
758
+						$value = $query_param_value[1];
759
+						$translated_value[1] = ModelDataTranslator::prepareFieldValuesForJson(
760
+							$field,
761
+							$value,
762
+							$requested_version
763
+						);
764
+					}
765
+				} else {
766
+					$translated_value = ModelDataTranslator::prepareFieldValueForJson(
767
+						$field,
768
+						$query_param_value,
769
+						$requested_version
770
+					);
771
+				}
772
+				$query_param_for_models[$query_param_key] = $translated_value;
773
+			} else {
774
+				// so it's not for a field, assume it's a logic query param key
775
+				$query_param_for_models[$query_param_key] = ModelDataTranslator::prepareConditionsQueryParamsForRestApi(
776
+					$query_param_value,
777
+					$model,
778
+					$requested_version
779
+				);
780
+			}
781
+		}
782
+		return $query_param_for_models;
783
+	}
784
+
785
+
786
+	/**
787
+	 * @param $condition_query_param_key
788
+	 * @return string
789
+	 */
790
+	public static function removeStarsAndAnythingAfterFromConditionQueryParamKey($condition_query_param_key)
791
+	{
792
+		$pos_of_star = strpos($condition_query_param_key, '*');
793
+		if ($pos_of_star === false) {
794
+			return $condition_query_param_key;
795
+		} else {
796
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
797
+			return $condition_query_param_sans_star;
798
+		}
799
+	}
800
+
801
+
802
+	/**
803
+	 * Takes the input parameter and finds the model field that it indicates.
804
+	 *
805
+	 * @param string   $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
806
+	 * @param EEM_Base $model
807
+	 * @return EE_Model_Field_Base
808
+	 * @throws EE_Error
809
+	 */
810
+	public static function deduceFieldFromQueryParam($query_param_name, EEM_Base $model)
811
+	{
812
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
813
+		// which will help us find the database table and column
814
+		$query_param_parts = explode('.', $query_param_name);
815
+		if (empty($query_param_parts)) {
816
+			throw new EE_Error(
817
+				sprintf(
818
+					__(
819
+						'_extract_column_name is empty when trying to extract column and table name from %s',
820
+						'event_espresso'
821
+					),
822
+					$query_param_name
823
+				)
824
+			);
825
+		}
826
+		$number_of_parts = count($query_param_parts);
827
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
828
+		if ($number_of_parts === 1) {
829
+			$field_name = $last_query_param_part;
830
+		} else {// $number_of_parts >= 2
831
+			// the last part is the column name, and there are only 2parts. therefore...
832
+			$field_name = $last_query_param_part;
833
+			$model = \EE_Registry::instance()->load_model($query_param_parts[$number_of_parts - 2]);
834
+		}
835
+		try {
836
+			return $model->field_settings_for($field_name, false);
837
+		} catch (EE_Error $e) {
838
+			return null;
839
+		}
840
+	}
841
+
842
+
843
+	/**
844
+	 * Returns true if $data can be easily represented in JSON.
845
+	 * Basically, objects and resources can't be represented in JSON easily.
846
+	 *
847
+	 * @param mixed $data
848
+	 * @return bool
849
+	 */
850
+	protected static function isRepresentableInJson($data)
851
+	{
852
+		return is_scalar($data)
853
+			   || is_array($data)
854
+			   || is_null($data);
855
+	}
856 856
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
                 '0',
222 222
                 STR_PAD_LEFT
223 223
             );
224
-        return $original_timestamp . $offset_sign . $offset_string;
224
+        return $original_timestamp.$offset_sign.$offset_string;
225 225
     }
226 226
 
227 227
 
@@ -264,10 +264,10 @@  discard block
 block discarded – undo
264 264
      */
265 265
     private static function parseTimezoneOffset($timezone_offset)
266 266
     {
267
-        $first_char = substr((string)$timezone_offset, 0, 1);
267
+        $first_char = substr((string) $timezone_offset, 0, 1);
268 268
         if ($first_char === '+' || $first_char === '-') {
269 269
             $offset_sign = $first_char;
270
-            $offset_secs = substr((string)$timezone_offset, 1);
270
+            $offset_secs = substr((string) $timezone_offset, 1);
271 271
         } else {
272 272
             $offset_sign = '+';
273 273
             $offset_secs = $timezone_offset;
@@ -293,12 +293,12 @@  discard block
 block discarded – undo
293 293
                 // did they submit a string of a unix timestamp?
294 294
                 if (is_numeric($original_value)) {
295 295
                     $datetime_obj = new \DateTime();
296
-                    $datetime_obj->setTimestamp((int)$original_value);
296
+                    $datetime_obj->setTimestamp((int) $original_value);
297 297
                 } else {
298 298
                     // first, check if its a MySQL timestamp in GMT
299 299
                     $datetime_obj = \DateTime::createFromFormat('Y-m-d H:i:s', $original_value);
300 300
                 }
301
-                if (! $datetime_obj instanceof \DateTime) {
301
+                if ( ! $datetime_obj instanceof \DateTime) {
302 302
                     // so it's not a unix timestamp or a MySQL timestamp. Maybe its in the field's date/time format?
303 303
                     $datetime_obj = $field_obj->prepare_for_set($original_value);
304 304
                 }
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
                         $original_value,
325 325
                         $field_obj->get_name(),
326 326
                         $field_obj->get_model_name(),
327
-                        $field_obj->get_time_format() . ' ' . $field_obj->get_time_format()
327
+                        $field_obj->get_time_format().' '.$field_obj->get_time_format()
328 328
                     )
329 329
                 );
330 330
             }
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
         }
335 335
         // are we about to send an object? just don't. We have no good way to represent it in JSON.
336 336
         // can't just check using is_object() because that missed PHP incomplete objects
337
-        if (! ModelDataTranslator::isRepresentableInJson($new_value)) {
337
+        if ( ! ModelDataTranslator::isRepresentableInJson($new_value)) {
338 338
             $new_value = array(
339 339
                 'error_code'    => 'php_object_not_return',
340 340
                 'error_message' => esc_html__(
@@ -387,7 +387,7 @@  discard block
 block discarded – undo
387 387
                 $model
388 388
             );
389 389
             // double-check is it a *_gmt field?
390
-            if (! $field instanceof EE_Model_Field_Base
390
+            if ( ! $field instanceof EE_Model_Field_Base
391 391
                 && ModelDataTranslator::isGmtDateFieldName($query_param_sans_stars)
392 392
             ) {
393 393
                 // yep, take off '_gmt', and find the field
@@ -406,8 +406,8 @@  discard block
 block discarded – undo
406 406
                 $timezone = $model->get_timezone();
407 407
             }
408 408
             if ($field instanceof EE_Model_Field_Base) {
409
-                if (! $writing && is_array($query_param_value)) {
410
-                    if (! \EEH_Array::is_array_numerically_and_sequentially_indexed($query_param_value)) {
409
+                if ( ! $writing && is_array($query_param_value)) {
410
+                    if ( ! \EEH_Array::is_array_numerically_and_sequentially_indexed($query_param_value)) {
411 411
                         if (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE) {
412 412
                             throw new RestException(
413 413
                                 'numerically_indexed_array_of_values_only',
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
      */
617 617
     public static function removeGmtFromFieldName($field_name)
618 618
     {
619
-        if (! ModelDataTranslator::isGmtDateFieldName($field_name)) {
619
+        if ( ! ModelDataTranslator::isGmtDateFieldName($field_name)) {
620 620
             return $field_name;
621 621
         }
622 622
         $query_param_sans_stars = ModelDataTranslator::removeStarsAndAnythingAfterFromConditionQueryParamKey(
Please login to merge, or discard this patch.
core/libraries/rest_api/calculations/Registration.php 2 patches
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -19,62 +19,62 @@
 block discarded – undo
19 19
 class Registration extends Calculations_Base
20 20
 {
21 21
 
22
-    /**
23
-     * Calculates the checkin status for each datetime this registration has access to
24
-     *
25
-     * @param array            $wpdb_row
26
-     * @param \WP_REST_Request $request
27
-     * @param Base             $controller
28
-     * @return array
29
-     * @throws \EE_Error
30
-     */
31
-    public static function datetimeCheckinStati($wpdb_row, $request, $controller)
32
-    {
33
-        if (is_array($wpdb_row) && isset($wpdb_row['Registration.REG_ID'])) {
34
-            $reg = EEM_Registration::instance()->get_one_by_ID($wpdb_row['Registration.REG_ID']);
35
-        } else {
36
-            $reg = null;
37
-        }
38
-        if (! $reg instanceof EE_Registration
39
-        ) {
40
-            throw new \EE_Error(
41
-                sprintf(
42
-                    __(
43
-                    // @codingStandardsIgnoreStart
44
-                        'Cannot calculate datetime_checkin_stati because the registration with ID %1$s (from database row %2$s) was not found',
45
-                        // @codingStandardsIgnoreEnd
46
-                        'event_espresso'
47
-                    ),
48
-                    $wpdb_row['Registration.REG_ID'],
49
-                    print_r($wpdb_row, true)
50
-                )
51
-            );
52
-        }
53
-        $datetime_ids = EEM_Datetime::instance()->get_col(
54
-            array(
55
-                array(
56
-                    'Ticket.TKT_ID' => $reg->ticket_ID(),
57
-                ),
58
-                'default_where_conditions' => \EEM_Base::default_where_conditions_minimum_all,
59
-            )
60
-        );
61
-        $checkin_stati = array();
62
-        foreach ($datetime_ids as $datetime_id) {
63
-            $status = $reg->check_in_status_for_datetime($datetime_id);
64
-            switch ($status) {
65
-                case EE_Checkin::status_checked_out:
66
-                    $status_pretty = 'OUT';
67
-                    break;
68
-                case EE_Checkin::status_checked_in:
69
-                    $status_pretty = 'IN';
70
-                    break;
71
-                case EE_Checkin::status_checked_never:
72
-                default:
73
-                    $status_pretty = 'NEVER';
74
-                    break;
75
-            }
76
-            $checkin_stati[$datetime_id] = $status_pretty;
77
-        }
78
-        return $checkin_stati;
79
-    }
22
+	/**
23
+	 * Calculates the checkin status for each datetime this registration has access to
24
+	 *
25
+	 * @param array            $wpdb_row
26
+	 * @param \WP_REST_Request $request
27
+	 * @param Base             $controller
28
+	 * @return array
29
+	 * @throws \EE_Error
30
+	 */
31
+	public static function datetimeCheckinStati($wpdb_row, $request, $controller)
32
+	{
33
+		if (is_array($wpdb_row) && isset($wpdb_row['Registration.REG_ID'])) {
34
+			$reg = EEM_Registration::instance()->get_one_by_ID($wpdb_row['Registration.REG_ID']);
35
+		} else {
36
+			$reg = null;
37
+		}
38
+		if (! $reg instanceof EE_Registration
39
+		) {
40
+			throw new \EE_Error(
41
+				sprintf(
42
+					__(
43
+					// @codingStandardsIgnoreStart
44
+						'Cannot calculate datetime_checkin_stati because the registration with ID %1$s (from database row %2$s) was not found',
45
+						// @codingStandardsIgnoreEnd
46
+						'event_espresso'
47
+					),
48
+					$wpdb_row['Registration.REG_ID'],
49
+					print_r($wpdb_row, true)
50
+				)
51
+			);
52
+		}
53
+		$datetime_ids = EEM_Datetime::instance()->get_col(
54
+			array(
55
+				array(
56
+					'Ticket.TKT_ID' => $reg->ticket_ID(),
57
+				),
58
+				'default_where_conditions' => \EEM_Base::default_where_conditions_minimum_all,
59
+			)
60
+		);
61
+		$checkin_stati = array();
62
+		foreach ($datetime_ids as $datetime_id) {
63
+			$status = $reg->check_in_status_for_datetime($datetime_id);
64
+			switch ($status) {
65
+				case EE_Checkin::status_checked_out:
66
+					$status_pretty = 'OUT';
67
+					break;
68
+				case EE_Checkin::status_checked_in:
69
+					$status_pretty = 'IN';
70
+					break;
71
+				case EE_Checkin::status_checked_never:
72
+				default:
73
+					$status_pretty = 'NEVER';
74
+					break;
75
+			}
76
+			$checkin_stati[$datetime_id] = $status_pretty;
77
+		}
78
+		return $checkin_stati;
79
+	}
80 80
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@
 block discarded – undo
35 35
         } else {
36 36
             $reg = null;
37 37
         }
38
-        if (! $reg instanceof EE_Registration
38
+        if ( ! $reg instanceof EE_Registration
39 39
         ) {
40 40
             throw new \EE_Error(
41 41
                 sprintf(
Please login to merge, or discard this patch.
core/libraries/rest_api/calculations/Base.php 2 patches
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -16,40 +16,40 @@
 block discarded – undo
16 16
 class Base
17 17
 {
18 18
 
19
-    /**
20
-     * @param $required_permission
21
-     * @param $attempted_calculation
22
-     * @throws \EventEspresso\core\libraries\rest_api\RestException
23
-     */
24
-    protected static function verifyCurrentUserCan($required_permission, $attempted_calculation)
25
-    {
26
-        if (! current_user_can($required_permission)) {
27
-            throw new RestException(
28
-                'permission_denied',
29
-                sprintf(
30
-                    __(
31
-                    // @codingStandardsIgnoreStart
32
-                        'Permission denied, you cannot calculate %1$s on %2$s because you do not have the capability "%3$s"',
33
-                        // @codingStandardsIgnoreEnd
34
-                        'event_espresso'
35
-                    ),
36
-                    $attempted_calculation,
37
-                    EEH_Inflector::pluralize_and_lower(self::getResourceName()),
38
-                    $required_permission
39
-                )
40
-            );
41
-        }
42
-    }
19
+	/**
20
+	 * @param $required_permission
21
+	 * @param $attempted_calculation
22
+	 * @throws \EventEspresso\core\libraries\rest_api\RestException
23
+	 */
24
+	protected static function verifyCurrentUserCan($required_permission, $attempted_calculation)
25
+	{
26
+		if (! current_user_can($required_permission)) {
27
+			throw new RestException(
28
+				'permission_denied',
29
+				sprintf(
30
+					__(
31
+					// @codingStandardsIgnoreStart
32
+						'Permission denied, you cannot calculate %1$s on %2$s because you do not have the capability "%3$s"',
33
+						// @codingStandardsIgnoreEnd
34
+						'event_espresso'
35
+					),
36
+					$attempted_calculation,
37
+					EEH_Inflector::pluralize_and_lower(self::getResourceName()),
38
+					$required_permission
39
+				)
40
+			);
41
+		}
42
+	}
43 43
 
44 44
 
45
-    /**
46
-     * Gets the name of the resource of the called class
47
-     *
48
-     * @return string
49
-     */
50
-    public static function getResourceName()
51
-    {
52
-        $classname = get_called_class();
53
-        return substr($classname, strrpos($classname, '\\') + 1);
54
-    }
45
+	/**
46
+	 * Gets the name of the resource of the called class
47
+	 *
48
+	 * @return string
49
+	 */
50
+	public static function getResourceName()
51
+	{
52
+		$classname = get_called_class();
53
+		return substr($classname, strrpos($classname, '\\') + 1);
54
+	}
55 55
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@
 block discarded – undo
23 23
      */
24 24
     protected static function verifyCurrentUserCan($required_permission, $attempted_calculation)
25 25
     {
26
-        if (! current_user_can($required_permission)) {
26
+        if ( ! current_user_can($required_permission)) {
27 27
             throw new RestException(
28 28
                 'permission_denied',
29 29
                 sprintf(
Please login to merge, or discard this patch.
core/libraries/rest_api/calculations/Datetime.php 2 patches
Indentation   +131 added lines, -131 removed lines patch added patch discarded remove patch
@@ -11,141 +11,141 @@
 block discarded – undo
11 11
 class Datetime extends Calculations_Base
12 12
 {
13 13
 
14
-    /**
15
-     * Calculates the total spaces available on the datetime, taking into account
16
-     * ticket limits too.
17
-     *
18
-     * @see EE_Datetime::spaces_remaining( true )
19
-     * @param array            $wpdb_row
20
-     * @param \WP_REST_Request $request
21
-     * @param Controller_Base  $controller
22
-     * @return int
23
-     * @throws \EE_Error
24
-     */
25
-    public static function spacesRemainingConsideringTickets($wpdb_row, $request, $controller)
26
-    {
27
-        if (is_array($wpdb_row) && isset($wpdb_row['Datetime.DTT_ID'])) {
28
-            $dtt_obj = EEM_Datetime::instance()->get_one_by_ID($wpdb_row['Datetime.DTT_ID']);
29
-        } else {
30
-            $dtt_obj = null;
31
-        }
32
-        if ($dtt_obj instanceof EE_Datetime) {
33
-            return $dtt_obj->spaces_remaining(true);
34
-        } else {
35
-            throw new \EE_Error(
36
-                sprintf(
37
-                    __(
38
-                    // @codingStandardsIgnoreStart
39
-                        'Cannot calculate spaces_remaining_considering_tickets because the datetime with ID %1$s (from database row %2$s) was not found',
40
-                        // @codingStandardsIgnoreEnd
41
-                        'event_espresso'
42
-                    ),
43
-                    $wpdb_row['Datetime.DTT_ID'],
44
-                    print_r($wpdb_row, true)
45
-                )
46
-            );
47
-        }
48
-    }
14
+	/**
15
+	 * Calculates the total spaces available on the datetime, taking into account
16
+	 * ticket limits too.
17
+	 *
18
+	 * @see EE_Datetime::spaces_remaining( true )
19
+	 * @param array            $wpdb_row
20
+	 * @param \WP_REST_Request $request
21
+	 * @param Controller_Base  $controller
22
+	 * @return int
23
+	 * @throws \EE_Error
24
+	 */
25
+	public static function spacesRemainingConsideringTickets($wpdb_row, $request, $controller)
26
+	{
27
+		if (is_array($wpdb_row) && isset($wpdb_row['Datetime.DTT_ID'])) {
28
+			$dtt_obj = EEM_Datetime::instance()->get_one_by_ID($wpdb_row['Datetime.DTT_ID']);
29
+		} else {
30
+			$dtt_obj = null;
31
+		}
32
+		if ($dtt_obj instanceof EE_Datetime) {
33
+			return $dtt_obj->spaces_remaining(true);
34
+		} else {
35
+			throw new \EE_Error(
36
+				sprintf(
37
+					__(
38
+					// @codingStandardsIgnoreStart
39
+						'Cannot calculate spaces_remaining_considering_tickets because the datetime with ID %1$s (from database row %2$s) was not found',
40
+						// @codingStandardsIgnoreEnd
41
+						'event_espresso'
42
+					),
43
+					$wpdb_row['Datetime.DTT_ID'],
44
+					print_r($wpdb_row, true)
45
+				)
46
+			);
47
+		}
48
+	}
49 49
 
50 50
 
51
-    /**
52
-     * Counts registrations who have checked into this datetime
53
-     *
54
-     * @param array            $wpdb_row
55
-     * @param \WP_REST_Request $request
56
-     * @param Controller_Base  $controller
57
-     * @return int
58
-     * @throws \EE_Error
59
-     * @throws \EventEspresso\core\libraries\rest_api\RestException
60
-     */
61
-    public static function registrationsCheckedInCount($wpdb_row, $request, $controller)
62
-    {
63
-        if (! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
64
-            throw new \EE_Error(
65
-                sprintf(
66
-                    __(
67
-                    // @codingStandardsIgnoreStart
68
-                        'Cannot calculate registrations_checked_in_count because the database row %1$s does not have an entry for "Datetime.DTT_ID"',
69
-                        // @codingStandardsIgnoreEnd
70
-                        'event_espresso'
71
-                    ),
72
-                    print_r($wpdb_row, true)
73
-                )
74
-            );
75
-        }
76
-        self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_in_count');
77
-        return EEM_Registration::instance()
78
-                               ->count_registrations_checked_into_datetime($wpdb_row['Datetime.DTT_ID'], true);
79
-    }
51
+	/**
52
+	 * Counts registrations who have checked into this datetime
53
+	 *
54
+	 * @param array            $wpdb_row
55
+	 * @param \WP_REST_Request $request
56
+	 * @param Controller_Base  $controller
57
+	 * @return int
58
+	 * @throws \EE_Error
59
+	 * @throws \EventEspresso\core\libraries\rest_api\RestException
60
+	 */
61
+	public static function registrationsCheckedInCount($wpdb_row, $request, $controller)
62
+	{
63
+		if (! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
64
+			throw new \EE_Error(
65
+				sprintf(
66
+					__(
67
+					// @codingStandardsIgnoreStart
68
+						'Cannot calculate registrations_checked_in_count because the database row %1$s does not have an entry for "Datetime.DTT_ID"',
69
+						// @codingStandardsIgnoreEnd
70
+						'event_espresso'
71
+					),
72
+					print_r($wpdb_row, true)
73
+				)
74
+			);
75
+		}
76
+		self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_in_count');
77
+		return EEM_Registration::instance()
78
+							   ->count_registrations_checked_into_datetime($wpdb_row['Datetime.DTT_ID'], true);
79
+	}
80 80
 
81 81
 
82
-    /**
83
-     * Counts registrations who have checked out of this datetime
84
-     *
85
-     * @param array            $wpdb_row
86
-     * @param \WP_REST_Request $request
87
-     * @param Controller_Base  $controller
88
-     * @return int
89
-     * @throws \EE_Error
90
-     * @throws \EventEspresso\core\libraries\rest_api\RestException
91
-     */
92
-    public static function registrationsCheckedOutCount($wpdb_row, $request, $controller)
93
-    {
94
-        if (! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
95
-            throw new \EE_Error(
96
-                sprintf(
97
-                    __(
98
-                    // @codingStandardsIgnoreStart
99
-                        'Cannot calculate registrations_checked_out_count because the database row %1$s does not have an entry for "Datetime.DTT_ID"',
100
-                        // @codingStandardsIgnoreEnd
101
-                        'event_espresso'
102
-                    ),
103
-                    print_r($wpdb_row, true)
104
-                )
105
-            );
106
-        }
107
-        self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_out_count');
108
-        return EEM_Registration::instance()
109
-                               ->count_registrations_checked_into_datetime($wpdb_row['Datetime.DTT_ID'], false);
110
-    }
82
+	/**
83
+	 * Counts registrations who have checked out of this datetime
84
+	 *
85
+	 * @param array            $wpdb_row
86
+	 * @param \WP_REST_Request $request
87
+	 * @param Controller_Base  $controller
88
+	 * @return int
89
+	 * @throws \EE_Error
90
+	 * @throws \EventEspresso\core\libraries\rest_api\RestException
91
+	 */
92
+	public static function registrationsCheckedOutCount($wpdb_row, $request, $controller)
93
+	{
94
+		if (! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
95
+			throw new \EE_Error(
96
+				sprintf(
97
+					__(
98
+					// @codingStandardsIgnoreStart
99
+						'Cannot calculate registrations_checked_out_count because the database row %1$s does not have an entry for "Datetime.DTT_ID"',
100
+						// @codingStandardsIgnoreEnd
101
+						'event_espresso'
102
+					),
103
+					print_r($wpdb_row, true)
104
+				)
105
+			);
106
+		}
107
+		self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_out_count');
108
+		return EEM_Registration::instance()
109
+							   ->count_registrations_checked_into_datetime($wpdb_row['Datetime.DTT_ID'], false);
110
+	}
111 111
 
112 112
 
113
-    /**
114
-     * Counts the number of pending-payment registrations for this event (regardless
115
-     * of how many datetimes each registrations' ticket purchase is for)
116
-     *
117
-     * @param array            $wpdb_row
118
-     * @param \WP_REST_Request $request
119
-     * @param Controller_Base  $controller
120
-     * @return int
121
-     * @throws \EE_Error
122
-     * @throws \EventEspresso\core\libraries\rest_api\RestException
123
-     */
124
-    public static function spotsTakenPendingPayment($wpdb_row, $request, $controller)
125
-    {
126
-        if (! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
127
-            throw new \EE_Error(
128
-                sprintf(
129
-                    __(
130
-                    // @codingStandardsIgnoreStart
131
-                        'Cannot calculate spots_taken_pending_payment because the database row %1$s does not have an entry for "Datetime.DTT_ID"',
132
-                        // @codingStandardsIgnoreEnd
133
-                        'event_espresso'
134
-                    ),
135
-                    print_r($wpdb_row, true)
136
-                )
137
-            );
138
-        }
139
-        self::verifyCurrentUserCan('ee_read_registrations', 'spots_taken_pending_payment');
140
-        return EEM_Registration::instance()->count(
141
-            array(
142
-                array(
143
-                    'Ticket.Datetime.DTT_ID' => $wpdb_row['Datetime.DTT_ID'],
144
-                    'STS_ID'                 => EEM_Registration::status_id_pending_payment,
145
-                ),
146
-            ),
147
-            'REG_ID',
148
-            true
149
-        );
150
-    }
113
+	/**
114
+	 * Counts the number of pending-payment registrations for this event (regardless
115
+	 * of how many datetimes each registrations' ticket purchase is for)
116
+	 *
117
+	 * @param array            $wpdb_row
118
+	 * @param \WP_REST_Request $request
119
+	 * @param Controller_Base  $controller
120
+	 * @return int
121
+	 * @throws \EE_Error
122
+	 * @throws \EventEspresso\core\libraries\rest_api\RestException
123
+	 */
124
+	public static function spotsTakenPendingPayment($wpdb_row, $request, $controller)
125
+	{
126
+		if (! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
127
+			throw new \EE_Error(
128
+				sprintf(
129
+					__(
130
+					// @codingStandardsIgnoreStart
131
+						'Cannot calculate spots_taken_pending_payment because the database row %1$s does not have an entry for "Datetime.DTT_ID"',
132
+						// @codingStandardsIgnoreEnd
133
+						'event_espresso'
134
+					),
135
+					print_r($wpdb_row, true)
136
+				)
137
+			);
138
+		}
139
+		self::verifyCurrentUserCan('ee_read_registrations', 'spots_taken_pending_payment');
140
+		return EEM_Registration::instance()->count(
141
+			array(
142
+				array(
143
+					'Ticket.Datetime.DTT_ID' => $wpdb_row['Datetime.DTT_ID'],
144
+					'STS_ID'                 => EEM_Registration::status_id_pending_payment,
145
+				),
146
+			),
147
+			'REG_ID',
148
+			true
149
+		);
150
+	}
151 151
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
      */
61 61
     public static function registrationsCheckedInCount($wpdb_row, $request, $controller)
62 62
     {
63
-        if (! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
63
+        if ( ! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
64 64
             throw new \EE_Error(
65 65
                 sprintf(
66 66
                     __(
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
      */
92 92
     public static function registrationsCheckedOutCount($wpdb_row, $request, $controller)
93 93
     {
94
-        if (! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
94
+        if ( ! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
95 95
             throw new \EE_Error(
96 96
                 sprintf(
97 97
                     __(
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
      */
124 124
     public static function spotsTakenPendingPayment($wpdb_row, $request, $controller)
125 125
     {
126
-        if (! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
126
+        if ( ! is_array($wpdb_row) || ! isset($wpdb_row['Datetime.DTT_ID'])) {
127 127
             throw new \EE_Error(
128 128
                 sprintf(
129 129
                     __(
Please login to merge, or discard this patch.
core/libraries/rest_api/calculations/Event.php 2 patches
Indentation   +387 added lines, -387 removed lines patch added patch discarded remove patch
@@ -21,391 +21,391 @@
 block discarded – undo
21 21
 class Event extends Calculations_Base
22 22
 {
23 23
 
24
-    /**
25
-     * Calculates the total spaces on the event (not subtracting sales, but taking
26
-     * sales into account; so this is the optimum sales that CAN still be achieved)
27
-     * See EE_Event::total_available_spaces( true );
28
-     *
29
-     * @param array            $wpdb_row
30
-     * @param \WP_REST_Request $request
31
-     * @param Base             $controller
32
-     * @return int
33
-     * @throws EE_Error
34
-     */
35
-    public static function optimumSalesAtStart($wpdb_row, $request, $controller)
36
-    {
37
-        $event_obj = null;
38
-        if (Event::wpdbRowHasEventId($wpdb_row)) {
39
-            $event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
40
-        }
41
-        if ($event_obj instanceof EE_Event) {
42
-            return $event_obj->total_available_spaces();
43
-        }
44
-        throw new EE_Error(
45
-            sprintf(
46
-                __(
47
-                // @codingStandardsIgnoreStart
48
-                    'Cannot calculate optimum_sales_at_start because the event with ID %1$s (from database row %2$s) was not found',
49
-                    // @codingStandardsIgnoreEnd
50
-                    'event_espresso'
51
-                ),
52
-                $wpdb_row['Event_CPT.ID'],
53
-                print_r($wpdb_row, true)
54
-            )
55
-        );
56
-    }
57
-
58
-
59
-    /**
60
-     * Calculates the total spaces on the event (ignoring all sales; so this is the optimum
61
-     * sales that COULD have been achieved)
62
-     * See EE_Event::total_available_spaces( true );
63
-     *
64
-     * @param array            $wpdb_row
65
-     * @param \WP_REST_Request $request
66
-     * @param Base             $controller
67
-     * @return int
68
-     * @throws EE_Error
69
-     */
70
-    public static function optimumSalesNow($wpdb_row, $request, $controller)
71
-    {
72
-        $event_obj = null;
73
-        if (Event::wpdbRowHasEventId($wpdb_row)) {
74
-            $event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
75
-        }
76
-        if ($event_obj instanceof EE_Event) {
77
-            return $event_obj->total_available_spaces(true);
78
-        }
79
-        throw new EE_Error(
80
-            sprintf(
81
-                __(
82
-                // @codingStandardsIgnoreStart
83
-                    'Cannot calculate optimum_sales_now because the event with ID %1$s (from database row %2$s) was not found',
84
-                    // @codingStandardsIgnoreEnd
85
-                    'event_espresso'
86
-                ),
87
-                $wpdb_row['Event_CPT.ID'],
88
-                print_r($wpdb_row, true)
89
-            )
90
-        );
91
-    }
92
-
93
-
94
-    /**
95
-     * Like optimum_sales_now, but minus total sales so far.
96
-     * See EE_Event::spaces_remaining_for_sale( true );
97
-     *
98
-     * @param array            $wpdb_row
99
-     * @param \WP_REST_Request $request
100
-     * @param Base             $controller
101
-     * @return int
102
-     * @throws EE_Error
103
-     */
104
-    public static function spacesRemaining($wpdb_row, $request, $controller)
105
-    {
106
-        $event_obj = null;
107
-        if (Event::wpdbRowHasEventId($wpdb_row)) {
108
-            $event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
109
-        }
110
-        if ($event_obj instanceof EE_Event) {
111
-            return $event_obj->spaces_remaining_for_sale();
112
-        }
113
-        throw new EE_Error(
114
-            sprintf(
115
-                __(
116
-                // @codingStandardsIgnoreStart
117
-                    'Cannot calculate spaces_remaining because the event with ID %1$s (from database row %2$s) was not found',
118
-                    // @codingStandardsIgnoreEnd
119
-                    'event_espresso'
120
-                ),
121
-                $wpdb_row['Event_CPT.ID'],
122
-                print_r($wpdb_row, true)
123
-            )
124
-        );
125
-    }
126
-
127
-
128
-    /**
129
-     * Counts the number of approved registrations for this event (regardless
130
-     * of how many datetimes each registrations' ticket purchase is for)
131
-     *
132
-     * @param array            $wpdb_row
133
-     * @param \WP_REST_Request $request
134
-     * @param Base             $controller
135
-     * @return int
136
-     * @throws EE_Error
137
-     */
138
-    public static function spotsTaken($wpdb_row, $request, $controller)
139
-    {
140
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
141
-            throw new EE_Error(
142
-                sprintf(
143
-                    __(
144
-                    // @codingStandardsIgnoreStart
145
-                        'Cannot calculate spots_taken because the database row %1$s does not have a valid entry for "Event_CPT.ID"',
146
-                        // @codingStandardsIgnoreEnd
147
-                        'event_espresso'
148
-                    ),
149
-                    print_r($wpdb_row, true)
150
-                )
151
-            );
152
-        }
153
-        return EEM_Registration::instance()->count(
154
-            array(
155
-                array(
156
-                    'EVT_ID' => $wpdb_row['Event_CPT.ID'],
157
-                    'STS_ID' => EEM_Registration::status_id_approved,
158
-                ),
159
-            ),
160
-            'REG_ID',
161
-            true
162
-        );
163
-    }
164
-
165
-
166
-    /**
167
-     * Counts the number of pending-payment registrations for this event (regardless
168
-     * of how many datetimes each registrations' ticket purchase is for)
169
-     *
170
-     * @param array            $wpdb_row
171
-     * @param \WP_REST_Request $request
172
-     * @param Base             $controller
173
-     * @return int
174
-     * @throws EE_Error
175
-     * @throws RestException
176
-     */
177
-    public static function spotsTakenPendingPayment($wpdb_row, $request, $controller)
178
-    {
179
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
180
-            throw new EE_Error(
181
-                sprintf(
182
-                    __(
183
-                    // @codingStandardsIgnoreStart
184
-                        'Cannot calculate spots_taken_pending_payment because the database row %1$s does not have an entry for "Event_CPT.ID"',
185
-                        // @codingStandardsIgnoreEnd
186
-                        'event_espresso'
187
-                    ),
188
-                    print_r($wpdb_row, true)
189
-                )
190
-            );
191
-        }
192
-        self::verifyCurrentUserCan('ee_read_registrations', 'spots_taken_pending_payment');
193
-        return EEM_Registration::instance()->count(
194
-            array(
195
-                array(
196
-                    'EVT_ID' => $wpdb_row['Event_CPT.ID'],
197
-                    'STS_ID' => EEM_Registration::status_id_pending_payment,
198
-                ),
199
-            ),
200
-            'REG_ID',
201
-            true
202
-        );
203
-    }
204
-
205
-
206
-    /**
207
-     * Counts all the registrations who have checked into one of this events' datetimes
208
-     * See EE_Event::total_available_spaces( false );
209
-     *
210
-     * @param array            $wpdb_row
211
-     * @param \WP_REST_Request $request
212
-     * @param Base             $controller
213
-     * @return int|null if permission denied
214
-     * @throws EE_Error
215
-     * @throws RestException
216
-     */
217
-    public static function registrationsCheckedInCount($wpdb_row, $request, $controller)
218
-    {
219
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
220
-            throw new EE_Error(
221
-                sprintf(
222
-                    __(
223
-                    // @codingStandardsIgnoreStart
224
-                        'Cannot calculate registrations_checked_in_count because the database row %1$s does not have an entry for "Event_CPT.ID"',
225
-                        // @codingStandardsIgnoreEnd
226
-                        'event_espresso'
227
-                    ),
228
-                    print_r($wpdb_row, true)
229
-                )
230
-            );
231
-        }
232
-        self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_in_count');
233
-        return EEM_Registration::instance()->count_registrations_checked_into_event($wpdb_row['Event_CPT.ID'], true);
234
-    }
235
-
236
-
237
-    /**
238
-     * Counts all the registrations who have checked out of one of this events' datetimes
239
-     * See EE_Event::total_available_spaces( false );
240
-     *
241
-     * @param array            $wpdb_row
242
-     * @param \WP_REST_Request $request
243
-     * @param Base             $controller
244
-     * @return int
245
-     * @throws EE_Error
246
-     * @throws RestException
247
-     */
248
-    public static function registrationsCheckedOutCount($wpdb_row, $request, $controller)
249
-    {
250
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
251
-            throw new EE_Error(
252
-                sprintf(
253
-                    __(
254
-                    // @codingStandardsIgnoreStart
255
-                        'Cannot calculate registrations_checked_out_count because the database row %1$s does not have an entry for "Event_CPT.ID"',
256
-                        // @codingStandardsIgnoreEnd
257
-                        'event_espresso'
258
-                    ),
259
-                    print_r($wpdb_row, true)
260
-                )
261
-            );
262
-        }
263
-        self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_out_count');
264
-        return EEM_Registration::instance()->count_registrations_checked_into_event($wpdb_row['Event_CPT.ID'], false);
265
-    }
266
-
267
-
268
-    /**
269
-     * Gets the thumbnail image
270
-     *
271
-     * @param array            $wpdb_row
272
-     * @param \WP_REST_Request $request
273
-     * @param Base             $controller
274
-     * @return array
275
-     * @throws EE_Error
276
-     */
277
-    public static function imageThumbnail($wpdb_row, $request, $controller)
278
-    {
279
-        return self::calculateImageData($wpdb_row, 'thumbnail');
280
-    }
281
-
282
-
283
-    /**
284
-     * Gets the medium image
285
-     *
286
-     * @param array            $wpdb_row
287
-     * @param \WP_REST_Request $request
288
-     * @param Base             $controller
289
-     * @return array
290
-     * @throws EE_Error
291
-     */
292
-    public static function imageMedium($wpdb_row, $request, $controller)
293
-    {
294
-        return self::calculateImageData($wpdb_row, 'medium');
295
-    }
296
-
297
-
298
-    /**
299
-     * Gets the medium-large image
300
-     *
301
-     * @param array            $wpdb_row
302
-     * @param \WP_REST_Request $request
303
-     * @param Base             $controller
304
-     * @return array
305
-     * @throws EE_Error
306
-     */
307
-    public static function imageMediumLarge($wpdb_row, $request, $controller)
308
-    {
309
-        return self::calculateImageData($wpdb_row, 'medium_large');
310
-    }
311
-
312
-
313
-    /**
314
-     * Gets the large image
315
-     *
316
-     * @param array            $wpdb_row
317
-     * @param \WP_REST_Request $request
318
-     * @param Base             $controller
319
-     * @return array
320
-     * @throws EE_Error
321
-     */
322
-    public static function imageLarge($wpdb_row, $request, $controller)
323
-    {
324
-        return self::calculateImageData($wpdb_row, 'large');
325
-    }
326
-
327
-
328
-    /**
329
-     * Gets the post-thumbnail image
330
-     *
331
-     * @param array            $wpdb_row
332
-     * @param \WP_REST_Request $request
333
-     * @param Base             $controller
334
-     * @return array
335
-     * @throws EE_Error
336
-     */
337
-    public static function imagePostThumbnail($wpdb_row, $request, $controller)
338
-    {
339
-        return self::calculateImageData($wpdb_row, 'post-thumbnail');
340
-    }
341
-
342
-
343
-    /**
344
-     * Gets the full size image
345
-     *
346
-     * @param array            $wpdb_row
347
-     * @param \WP_REST_Request $request
348
-     * @param Base             $controller
349
-     * @return array
350
-     * @throws EE_Error
351
-     */
352
-    public static function imageFull($wpdb_row, $request, $controller)
353
-    {
354
-        return self::calculateImageData($wpdb_row, 'full');
355
-    }
356
-
357
-
358
-    /**
359
-     * Gets image specs and formats them for the display in the API,
360
-     * according to the image size requested
361
-     *
362
-     * @param array  $wpdb_row
363
-     * @param string $image_size one of these: thumbnail, medium, medium_large, large, post-thumbnail, full
364
-     * @return array|false if no such image exists. If array it will have keys 'url', 'width', 'height' and 'original'
365
-     * @throws EE_Error
366
-     */
367
-    protected static function calculateImageData($wpdb_row, $image_size)
368
-    {
369
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
370
-            throw new EE_Error(
371
-                sprintf(
372
-                    __(
373
-                    // @codingStandardsIgnoreStart
374
-                        'Cannot calculate image because the database row %1$s does not have an entry for "Event_CPT.ID"',
375
-                        // @codingStandardsIgnoreEnd
376
-                        'event_espresso'
377
-                    ),
378
-                    print_r($wpdb_row, true)
379
-                )
380
-            );
381
-        }
382
-        $EVT_ID = $wpdb_row['Event_CPT.ID'];
383
-        $attachment_id = get_post_thumbnail_id($EVT_ID);
384
-        $data = wp_get_attachment_image_src($attachment_id, $image_size);
385
-        if (! $data) {
386
-            return null;
387
-        }
388
-        $generated = true;
389
-        if (isset($data[3])) {
390
-            $generated = $data[3];
391
-        }
392
-        return array(
393
-            'url'       => $data[0],
394
-            'width'     => $data[1],
395
-            'height'    => $data[2],
396
-            'generated' => $generated,
397
-        );
398
-    }
399
-
400
-
401
-    /**
402
-     * Returns true if the array of data contains 'Event_CPT.ID'. False otherwise
403
-     *
404
-     * @param array $wpdb_row
405
-     * @return bool
406
-     */
407
-    protected static function wpdbRowHasEventId($wpdb_row)
408
-    {
409
-        return (is_array($wpdb_row) && isset($wpdb_row['Event_CPT.ID']) && absint($wpdb_row['Event_CPT.ID']));
410
-    }
24
+	/**
25
+	 * Calculates the total spaces on the event (not subtracting sales, but taking
26
+	 * sales into account; so this is the optimum sales that CAN still be achieved)
27
+	 * See EE_Event::total_available_spaces( true );
28
+	 *
29
+	 * @param array            $wpdb_row
30
+	 * @param \WP_REST_Request $request
31
+	 * @param Base             $controller
32
+	 * @return int
33
+	 * @throws EE_Error
34
+	 */
35
+	public static function optimumSalesAtStart($wpdb_row, $request, $controller)
36
+	{
37
+		$event_obj = null;
38
+		if (Event::wpdbRowHasEventId($wpdb_row)) {
39
+			$event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
40
+		}
41
+		if ($event_obj instanceof EE_Event) {
42
+			return $event_obj->total_available_spaces();
43
+		}
44
+		throw new EE_Error(
45
+			sprintf(
46
+				__(
47
+				// @codingStandardsIgnoreStart
48
+					'Cannot calculate optimum_sales_at_start because the event with ID %1$s (from database row %2$s) was not found',
49
+					// @codingStandardsIgnoreEnd
50
+					'event_espresso'
51
+				),
52
+				$wpdb_row['Event_CPT.ID'],
53
+				print_r($wpdb_row, true)
54
+			)
55
+		);
56
+	}
57
+
58
+
59
+	/**
60
+	 * Calculates the total spaces on the event (ignoring all sales; so this is the optimum
61
+	 * sales that COULD have been achieved)
62
+	 * See EE_Event::total_available_spaces( true );
63
+	 *
64
+	 * @param array            $wpdb_row
65
+	 * @param \WP_REST_Request $request
66
+	 * @param Base             $controller
67
+	 * @return int
68
+	 * @throws EE_Error
69
+	 */
70
+	public static function optimumSalesNow($wpdb_row, $request, $controller)
71
+	{
72
+		$event_obj = null;
73
+		if (Event::wpdbRowHasEventId($wpdb_row)) {
74
+			$event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
75
+		}
76
+		if ($event_obj instanceof EE_Event) {
77
+			return $event_obj->total_available_spaces(true);
78
+		}
79
+		throw new EE_Error(
80
+			sprintf(
81
+				__(
82
+				// @codingStandardsIgnoreStart
83
+					'Cannot calculate optimum_sales_now because the event with ID %1$s (from database row %2$s) was not found',
84
+					// @codingStandardsIgnoreEnd
85
+					'event_espresso'
86
+				),
87
+				$wpdb_row['Event_CPT.ID'],
88
+				print_r($wpdb_row, true)
89
+			)
90
+		);
91
+	}
92
+
93
+
94
+	/**
95
+	 * Like optimum_sales_now, but minus total sales so far.
96
+	 * See EE_Event::spaces_remaining_for_sale( true );
97
+	 *
98
+	 * @param array            $wpdb_row
99
+	 * @param \WP_REST_Request $request
100
+	 * @param Base             $controller
101
+	 * @return int
102
+	 * @throws EE_Error
103
+	 */
104
+	public static function spacesRemaining($wpdb_row, $request, $controller)
105
+	{
106
+		$event_obj = null;
107
+		if (Event::wpdbRowHasEventId($wpdb_row)) {
108
+			$event_obj = EEM_Event::instance()->get_one_by_ID($wpdb_row['Event_CPT.ID']);
109
+		}
110
+		if ($event_obj instanceof EE_Event) {
111
+			return $event_obj->spaces_remaining_for_sale();
112
+		}
113
+		throw new EE_Error(
114
+			sprintf(
115
+				__(
116
+				// @codingStandardsIgnoreStart
117
+					'Cannot calculate spaces_remaining because the event with ID %1$s (from database row %2$s) was not found',
118
+					// @codingStandardsIgnoreEnd
119
+					'event_espresso'
120
+				),
121
+				$wpdb_row['Event_CPT.ID'],
122
+				print_r($wpdb_row, true)
123
+			)
124
+		);
125
+	}
126
+
127
+
128
+	/**
129
+	 * Counts the number of approved registrations for this event (regardless
130
+	 * of how many datetimes each registrations' ticket purchase is for)
131
+	 *
132
+	 * @param array            $wpdb_row
133
+	 * @param \WP_REST_Request $request
134
+	 * @param Base             $controller
135
+	 * @return int
136
+	 * @throws EE_Error
137
+	 */
138
+	public static function spotsTaken($wpdb_row, $request, $controller)
139
+	{
140
+		if (! Event::wpdbRowHasEventId($wpdb_row)) {
141
+			throw new EE_Error(
142
+				sprintf(
143
+					__(
144
+					// @codingStandardsIgnoreStart
145
+						'Cannot calculate spots_taken because the database row %1$s does not have a valid entry for "Event_CPT.ID"',
146
+						// @codingStandardsIgnoreEnd
147
+						'event_espresso'
148
+					),
149
+					print_r($wpdb_row, true)
150
+				)
151
+			);
152
+		}
153
+		return EEM_Registration::instance()->count(
154
+			array(
155
+				array(
156
+					'EVT_ID' => $wpdb_row['Event_CPT.ID'],
157
+					'STS_ID' => EEM_Registration::status_id_approved,
158
+				),
159
+			),
160
+			'REG_ID',
161
+			true
162
+		);
163
+	}
164
+
165
+
166
+	/**
167
+	 * Counts the number of pending-payment registrations for this event (regardless
168
+	 * of how many datetimes each registrations' ticket purchase is for)
169
+	 *
170
+	 * @param array            $wpdb_row
171
+	 * @param \WP_REST_Request $request
172
+	 * @param Base             $controller
173
+	 * @return int
174
+	 * @throws EE_Error
175
+	 * @throws RestException
176
+	 */
177
+	public static function spotsTakenPendingPayment($wpdb_row, $request, $controller)
178
+	{
179
+		if (! Event::wpdbRowHasEventId($wpdb_row)) {
180
+			throw new EE_Error(
181
+				sprintf(
182
+					__(
183
+					// @codingStandardsIgnoreStart
184
+						'Cannot calculate spots_taken_pending_payment because the database row %1$s does not have an entry for "Event_CPT.ID"',
185
+						// @codingStandardsIgnoreEnd
186
+						'event_espresso'
187
+					),
188
+					print_r($wpdb_row, true)
189
+				)
190
+			);
191
+		}
192
+		self::verifyCurrentUserCan('ee_read_registrations', 'spots_taken_pending_payment');
193
+		return EEM_Registration::instance()->count(
194
+			array(
195
+				array(
196
+					'EVT_ID' => $wpdb_row['Event_CPT.ID'],
197
+					'STS_ID' => EEM_Registration::status_id_pending_payment,
198
+				),
199
+			),
200
+			'REG_ID',
201
+			true
202
+		);
203
+	}
204
+
205
+
206
+	/**
207
+	 * Counts all the registrations who have checked into one of this events' datetimes
208
+	 * See EE_Event::total_available_spaces( false );
209
+	 *
210
+	 * @param array            $wpdb_row
211
+	 * @param \WP_REST_Request $request
212
+	 * @param Base             $controller
213
+	 * @return int|null if permission denied
214
+	 * @throws EE_Error
215
+	 * @throws RestException
216
+	 */
217
+	public static function registrationsCheckedInCount($wpdb_row, $request, $controller)
218
+	{
219
+		if (! Event::wpdbRowHasEventId($wpdb_row)) {
220
+			throw new EE_Error(
221
+				sprintf(
222
+					__(
223
+					// @codingStandardsIgnoreStart
224
+						'Cannot calculate registrations_checked_in_count because the database row %1$s does not have an entry for "Event_CPT.ID"',
225
+						// @codingStandardsIgnoreEnd
226
+						'event_espresso'
227
+					),
228
+					print_r($wpdb_row, true)
229
+				)
230
+			);
231
+		}
232
+		self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_in_count');
233
+		return EEM_Registration::instance()->count_registrations_checked_into_event($wpdb_row['Event_CPT.ID'], true);
234
+	}
235
+
236
+
237
+	/**
238
+	 * Counts all the registrations who have checked out of one of this events' datetimes
239
+	 * See EE_Event::total_available_spaces( false );
240
+	 *
241
+	 * @param array            $wpdb_row
242
+	 * @param \WP_REST_Request $request
243
+	 * @param Base             $controller
244
+	 * @return int
245
+	 * @throws EE_Error
246
+	 * @throws RestException
247
+	 */
248
+	public static function registrationsCheckedOutCount($wpdb_row, $request, $controller)
249
+	{
250
+		if (! Event::wpdbRowHasEventId($wpdb_row)) {
251
+			throw new EE_Error(
252
+				sprintf(
253
+					__(
254
+					// @codingStandardsIgnoreStart
255
+						'Cannot calculate registrations_checked_out_count because the database row %1$s does not have an entry for "Event_CPT.ID"',
256
+						// @codingStandardsIgnoreEnd
257
+						'event_espresso'
258
+					),
259
+					print_r($wpdb_row, true)
260
+				)
261
+			);
262
+		}
263
+		self::verifyCurrentUserCan('ee_read_checkins', 'registrations_checked_out_count');
264
+		return EEM_Registration::instance()->count_registrations_checked_into_event($wpdb_row['Event_CPT.ID'], false);
265
+	}
266
+
267
+
268
+	/**
269
+	 * Gets the thumbnail image
270
+	 *
271
+	 * @param array            $wpdb_row
272
+	 * @param \WP_REST_Request $request
273
+	 * @param Base             $controller
274
+	 * @return array
275
+	 * @throws EE_Error
276
+	 */
277
+	public static function imageThumbnail($wpdb_row, $request, $controller)
278
+	{
279
+		return self::calculateImageData($wpdb_row, 'thumbnail');
280
+	}
281
+
282
+
283
+	/**
284
+	 * Gets the medium image
285
+	 *
286
+	 * @param array            $wpdb_row
287
+	 * @param \WP_REST_Request $request
288
+	 * @param Base             $controller
289
+	 * @return array
290
+	 * @throws EE_Error
291
+	 */
292
+	public static function imageMedium($wpdb_row, $request, $controller)
293
+	{
294
+		return self::calculateImageData($wpdb_row, 'medium');
295
+	}
296
+
297
+
298
+	/**
299
+	 * Gets the medium-large image
300
+	 *
301
+	 * @param array            $wpdb_row
302
+	 * @param \WP_REST_Request $request
303
+	 * @param Base             $controller
304
+	 * @return array
305
+	 * @throws EE_Error
306
+	 */
307
+	public static function imageMediumLarge($wpdb_row, $request, $controller)
308
+	{
309
+		return self::calculateImageData($wpdb_row, 'medium_large');
310
+	}
311
+
312
+
313
+	/**
314
+	 * Gets the large image
315
+	 *
316
+	 * @param array            $wpdb_row
317
+	 * @param \WP_REST_Request $request
318
+	 * @param Base             $controller
319
+	 * @return array
320
+	 * @throws EE_Error
321
+	 */
322
+	public static function imageLarge($wpdb_row, $request, $controller)
323
+	{
324
+		return self::calculateImageData($wpdb_row, 'large');
325
+	}
326
+
327
+
328
+	/**
329
+	 * Gets the post-thumbnail image
330
+	 *
331
+	 * @param array            $wpdb_row
332
+	 * @param \WP_REST_Request $request
333
+	 * @param Base             $controller
334
+	 * @return array
335
+	 * @throws EE_Error
336
+	 */
337
+	public static function imagePostThumbnail($wpdb_row, $request, $controller)
338
+	{
339
+		return self::calculateImageData($wpdb_row, 'post-thumbnail');
340
+	}
341
+
342
+
343
+	/**
344
+	 * Gets the full size image
345
+	 *
346
+	 * @param array            $wpdb_row
347
+	 * @param \WP_REST_Request $request
348
+	 * @param Base             $controller
349
+	 * @return array
350
+	 * @throws EE_Error
351
+	 */
352
+	public static function imageFull($wpdb_row, $request, $controller)
353
+	{
354
+		return self::calculateImageData($wpdb_row, 'full');
355
+	}
356
+
357
+
358
+	/**
359
+	 * Gets image specs and formats them for the display in the API,
360
+	 * according to the image size requested
361
+	 *
362
+	 * @param array  $wpdb_row
363
+	 * @param string $image_size one of these: thumbnail, medium, medium_large, large, post-thumbnail, full
364
+	 * @return array|false if no such image exists. If array it will have keys 'url', 'width', 'height' and 'original'
365
+	 * @throws EE_Error
366
+	 */
367
+	protected static function calculateImageData($wpdb_row, $image_size)
368
+	{
369
+		if (! Event::wpdbRowHasEventId($wpdb_row)) {
370
+			throw new EE_Error(
371
+				sprintf(
372
+					__(
373
+					// @codingStandardsIgnoreStart
374
+						'Cannot calculate image because the database row %1$s does not have an entry for "Event_CPT.ID"',
375
+						// @codingStandardsIgnoreEnd
376
+						'event_espresso'
377
+					),
378
+					print_r($wpdb_row, true)
379
+				)
380
+			);
381
+		}
382
+		$EVT_ID = $wpdb_row['Event_CPT.ID'];
383
+		$attachment_id = get_post_thumbnail_id($EVT_ID);
384
+		$data = wp_get_attachment_image_src($attachment_id, $image_size);
385
+		if (! $data) {
386
+			return null;
387
+		}
388
+		$generated = true;
389
+		if (isset($data[3])) {
390
+			$generated = $data[3];
391
+		}
392
+		return array(
393
+			'url'       => $data[0],
394
+			'width'     => $data[1],
395
+			'height'    => $data[2],
396
+			'generated' => $generated,
397
+		);
398
+	}
399
+
400
+
401
+	/**
402
+	 * Returns true if the array of data contains 'Event_CPT.ID'. False otherwise
403
+	 *
404
+	 * @param array $wpdb_row
405
+	 * @return bool
406
+	 */
407
+	protected static function wpdbRowHasEventId($wpdb_row)
408
+	{
409
+		return (is_array($wpdb_row) && isset($wpdb_row['Event_CPT.ID']) && absint($wpdb_row['Event_CPT.ID']));
410
+	}
411 411
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
      */
138 138
     public static function spotsTaken($wpdb_row, $request, $controller)
139 139
     {
140
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
140
+        if ( ! Event::wpdbRowHasEventId($wpdb_row)) {
141 141
             throw new EE_Error(
142 142
                 sprintf(
143 143
                     __(
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
      */
177 177
     public static function spotsTakenPendingPayment($wpdb_row, $request, $controller)
178 178
     {
179
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
179
+        if ( ! Event::wpdbRowHasEventId($wpdb_row)) {
180 180
             throw new EE_Error(
181 181
                 sprintf(
182 182
                     __(
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
      */
217 217
     public static function registrationsCheckedInCount($wpdb_row, $request, $controller)
218 218
     {
219
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
219
+        if ( ! Event::wpdbRowHasEventId($wpdb_row)) {
220 220
             throw new EE_Error(
221 221
                 sprintf(
222 222
                     __(
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
      */
248 248
     public static function registrationsCheckedOutCount($wpdb_row, $request, $controller)
249 249
     {
250
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
250
+        if ( ! Event::wpdbRowHasEventId($wpdb_row)) {
251 251
             throw new EE_Error(
252 252
                 sprintf(
253 253
                     __(
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
      */
367 367
     protected static function calculateImageData($wpdb_row, $image_size)
368 368
     {
369
-        if (! Event::wpdbRowHasEventId($wpdb_row)) {
369
+        if ( ! Event::wpdbRowHasEventId($wpdb_row)) {
370 370
             throw new EE_Error(
371 371
                 sprintf(
372 372
                     __(
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
         $EVT_ID = $wpdb_row['Event_CPT.ID'];
383 383
         $attachment_id = get_post_thumbnail_id($EVT_ID);
384 384
         $data = wp_get_attachment_image_src($attachment_id, $image_size);
385
-        if (! $data) {
385
+        if ( ! $data) {
386 386
             return null;
387 387
         }
388 388
         $generated = true;
Please login to merge, or discard this patch.
core/libraries/rest_api/controllers/model/Write.php 2 patches
Indentation   +305 added lines, -305 removed lines patch added patch discarded remove patch
@@ -30,325 +30,325 @@
 block discarded – undo
30 30
 {
31 31
 
32 32
 
33
-    public function __construct()
34
-    {
35
-        parent::__construct();
36
-        EE_Registry::instance()->load_helper('Inflector');
37
-    }
33
+	public function __construct()
34
+	{
35
+		parent::__construct();
36
+		EE_Registry::instance()->load_helper('Inflector');
37
+	}
38 38
 
39 39
 
40
-    /**
41
-     * Handles requests to get all (or a filtered subset) of entities for a particular model
42
-     *
43
-     * @param WP_REST_Request $request
44
-     * @param string          $version
45
-     * @param string          $model_name
46
-     * @return WP_REST_Response|\WP_Error
47
-     */
48
-    public static function handleRequestInsert(WP_REST_Request $request, $version, $model_name)
49
-    {
50
-        $controller = new Write();
51
-        try {
52
-            $controller->setRequestedVersion($version);
53
-            return $controller->sendResponse(
54
-                $controller->insert(
55
-                    $controller->getModelVersionInfo()->loadModel($model_name),
56
-                    $request
57
-                )
58
-            );
59
-        } catch (\Exception $e) {
60
-            return $controller->sendResponse($e);
61
-        }
62
-    }
40
+	/**
41
+	 * Handles requests to get all (or a filtered subset) of entities for a particular model
42
+	 *
43
+	 * @param WP_REST_Request $request
44
+	 * @param string          $version
45
+	 * @param string          $model_name
46
+	 * @return WP_REST_Response|\WP_Error
47
+	 */
48
+	public static function handleRequestInsert(WP_REST_Request $request, $version, $model_name)
49
+	{
50
+		$controller = new Write();
51
+		try {
52
+			$controller->setRequestedVersion($version);
53
+			return $controller->sendResponse(
54
+				$controller->insert(
55
+					$controller->getModelVersionInfo()->loadModel($model_name),
56
+					$request
57
+				)
58
+			);
59
+		} catch (\Exception $e) {
60
+			return $controller->sendResponse($e);
61
+		}
62
+	}
63 63
 
64 64
 
65
-    /**
66
-     * Handles a request from \WP_REST_Server to update an EE model
67
-     *
68
-     * @param WP_REST_Request $request
69
-     * @param string          $version
70
-     * @param string          $model_name
71
-     * @return WP_REST_Response|\WP_Error
72
-     */
73
-    public static function handleRequestUpdate(WP_REST_Request $request, $version, $model_name)
74
-    {
75
-        $controller = new Write();
76
-        try {
77
-            $controller->setRequestedVersion($version);
78
-            return $controller->sendResponse(
79
-                $controller->update(
80
-                    $controller->getModelVersionInfo()->loadModel($model_name),
81
-                    $request
82
-                )
83
-            );
84
-        } catch (\Exception $e) {
85
-            return $controller->sendResponse($e);
86
-        }
87
-    }
65
+	/**
66
+	 * Handles a request from \WP_REST_Server to update an EE model
67
+	 *
68
+	 * @param WP_REST_Request $request
69
+	 * @param string          $version
70
+	 * @param string          $model_name
71
+	 * @return WP_REST_Response|\WP_Error
72
+	 */
73
+	public static function handleRequestUpdate(WP_REST_Request $request, $version, $model_name)
74
+	{
75
+		$controller = new Write();
76
+		try {
77
+			$controller->setRequestedVersion($version);
78
+			return $controller->sendResponse(
79
+				$controller->update(
80
+					$controller->getModelVersionInfo()->loadModel($model_name),
81
+					$request
82
+				)
83
+			);
84
+		} catch (\Exception $e) {
85
+			return $controller->sendResponse($e);
86
+		}
87
+	}
88 88
 
89 89
 
90
-    /**
91
-     * Deletes a single model object and returns it. Unless
92
-     *
93
-     * @param WP_REST_Request $request
94
-     * @param string          $version
95
-     * @param string          $model_name
96
-     * @return WP_REST_Response|\WP_Error
97
-     */
98
-    public static function handleRequestDelete(WP_REST_Request $request, $version, $model_name)
99
-    {
100
-        $controller = new Write();
101
-        try {
102
-            $controller->setRequestedVersion($version);
103
-            return $controller->sendResponse(
104
-                $controller->delete(
105
-                    $controller->getModelVersionInfo()->loadModel($model_name),
106
-                    $request
107
-                )
108
-            );
109
-        } catch (\Exception $e) {
110
-            return $controller->sendResponse($e);
111
-        }
112
-    }
90
+	/**
91
+	 * Deletes a single model object and returns it. Unless
92
+	 *
93
+	 * @param WP_REST_Request $request
94
+	 * @param string          $version
95
+	 * @param string          $model_name
96
+	 * @return WP_REST_Response|\WP_Error
97
+	 */
98
+	public static function handleRequestDelete(WP_REST_Request $request, $version, $model_name)
99
+	{
100
+		$controller = new Write();
101
+		try {
102
+			$controller->setRequestedVersion($version);
103
+			return $controller->sendResponse(
104
+				$controller->delete(
105
+					$controller->getModelVersionInfo()->loadModel($model_name),
106
+					$request
107
+				)
108
+			);
109
+		} catch (\Exception $e) {
110
+			return $controller->sendResponse($e);
111
+		}
112
+	}
113 113
 
114 114
 
115
-    /**
116
-     * Inserts a new model object according to the $request
117
-     *
118
-     * @param EEM_Base        $model
119
-     * @param WP_REST_Request $request
120
-     * @return array
121
-     * @throws EE_Error
122
-     * @throws RestException
123
-     */
124
-    public function insert(EEM_Base $model, WP_REST_Request $request)
125
-    {
126
-        Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create');
127
-        $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
128
-        if (! current_user_can($default_cap_to_check_for)) {
129
-            throw new RestException(
130
-                'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
131
-                sprintf(
132
-                    esc_html__(
133
-                    // @codingStandardsIgnoreStart
134
-                        'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to insert data into Event Espresso.',
135
-                        // @codingStandardsIgnoreEnd
136
-                        'event_espresso'
137
-                    ),
138
-                    $default_cap_to_check_for
139
-                ),
140
-                array('status' => 403)
141
-            );
142
-        }
143
-        $submitted_json_data = array_merge((array)$request->get_body_params(), (array)$request->get_json_params());
144
-        $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
145
-            $submitted_json_data,
146
-            $model,
147
-            $this->getModelVersionInfo()->requestedVersion(),
148
-            true
149
-        );
150
-        $model_obj = EE_Registry::instance()->load_class(
151
-            $model->get_this_model_name(),
152
-            array($model_data, $model->get_timezone()),
153
-            false,
154
-            false
155
-        );
156
-        $model_obj->save();
157
-        $new_id = $model_obj->ID();
158
-        if (! $new_id) {
159
-            throw new RestException(
160
-                'rest_insertion_failed',
161
-                sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name())
162
-            );
163
-        }
164
-        return $this->returnModelObjAsJsonResponse($model_obj, $request);
165
-    }
115
+	/**
116
+	 * Inserts a new model object according to the $request
117
+	 *
118
+	 * @param EEM_Base        $model
119
+	 * @param WP_REST_Request $request
120
+	 * @return array
121
+	 * @throws EE_Error
122
+	 * @throws RestException
123
+	 */
124
+	public function insert(EEM_Base $model, WP_REST_Request $request)
125
+	{
126
+		Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create');
127
+		$default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
128
+		if (! current_user_can($default_cap_to_check_for)) {
129
+			throw new RestException(
130
+				'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
131
+				sprintf(
132
+					esc_html__(
133
+					// @codingStandardsIgnoreStart
134
+						'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to insert data into Event Espresso.',
135
+						// @codingStandardsIgnoreEnd
136
+						'event_espresso'
137
+					),
138
+					$default_cap_to_check_for
139
+				),
140
+				array('status' => 403)
141
+			);
142
+		}
143
+		$submitted_json_data = array_merge((array)$request->get_body_params(), (array)$request->get_json_params());
144
+		$model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
145
+			$submitted_json_data,
146
+			$model,
147
+			$this->getModelVersionInfo()->requestedVersion(),
148
+			true
149
+		);
150
+		$model_obj = EE_Registry::instance()->load_class(
151
+			$model->get_this_model_name(),
152
+			array($model_data, $model->get_timezone()),
153
+			false,
154
+			false
155
+		);
156
+		$model_obj->save();
157
+		$new_id = $model_obj->ID();
158
+		if (! $new_id) {
159
+			throw new RestException(
160
+				'rest_insertion_failed',
161
+				sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name())
162
+			);
163
+		}
164
+		return $this->returnModelObjAsJsonResponse($model_obj, $request);
165
+	}
166 166
 
167 167
 
168
-    /**
169
-     * Updates an existing model object according to the $request
170
-     *
171
-     * @param EEM_Base        $model
172
-     * @param WP_REST_Request $request
173
-     * @return array
174
-     * @throws EE_Error
175
-     */
176
-    public function update(EEM_Base $model, WP_REST_Request $request)
177
-    {
178
-        Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit');
179
-        $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
180
-        if (! current_user_can($default_cap_to_check_for)) {
181
-            throw new RestException(
182
-                'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
183
-                sprintf(
184
-                    esc_html__(
185
-                    // @codingStandardsIgnoreStart
186
-                        'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to update data into Event Espresso.',
187
-                        // @codingStandardsIgnoreEnd
188
-                        'event_espresso'
189
-                    ),
190
-                    $default_cap_to_check_for
191
-                ),
192
-                array('status' => 403)
193
-            );
194
-        }
195
-        $obj_id = $request->get_param('id');
196
-        if (! $obj_id) {
197
-            throw new RestException(
198
-                'rest_edit_failed',
199
-                sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name())
200
-            );
201
-        }
202
-        $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
203
-            $this->getBodyParams($request),
204
-            $model,
205
-            $this->getModelVersionInfo()->requestedVersion(),
206
-            true
207
-        );
208
-        $model_obj = $model->get_one_by_ID($obj_id);
209
-        if (! $model_obj instanceof EE_Base_Class) {
210
-            $lowercase_model_name = strtolower($model->get_this_model_name());
211
-            throw new RestException(
212
-                sprintf('rest_%s_invalid_id', $lowercase_model_name),
213
-                sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
214
-                array('status' => 404)
215
-            );
216
-        }
217
-        $model_obj->save($model_data);
218
-        return $this->returnModelObjAsJsonResponse($model_obj, $request);
219
-    }
168
+	/**
169
+	 * Updates an existing model object according to the $request
170
+	 *
171
+	 * @param EEM_Base        $model
172
+	 * @param WP_REST_Request $request
173
+	 * @return array
174
+	 * @throws EE_Error
175
+	 */
176
+	public function update(EEM_Base $model, WP_REST_Request $request)
177
+	{
178
+		Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit');
179
+		$default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
180
+		if (! current_user_can($default_cap_to_check_for)) {
181
+			throw new RestException(
182
+				'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
183
+				sprintf(
184
+					esc_html__(
185
+					// @codingStandardsIgnoreStart
186
+						'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to update data into Event Espresso.',
187
+						// @codingStandardsIgnoreEnd
188
+						'event_espresso'
189
+					),
190
+					$default_cap_to_check_for
191
+				),
192
+				array('status' => 403)
193
+			);
194
+		}
195
+		$obj_id = $request->get_param('id');
196
+		if (! $obj_id) {
197
+			throw new RestException(
198
+				'rest_edit_failed',
199
+				sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name())
200
+			);
201
+		}
202
+		$model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
203
+			$this->getBodyParams($request),
204
+			$model,
205
+			$this->getModelVersionInfo()->requestedVersion(),
206
+			true
207
+		);
208
+		$model_obj = $model->get_one_by_ID($obj_id);
209
+		if (! $model_obj instanceof EE_Base_Class) {
210
+			$lowercase_model_name = strtolower($model->get_this_model_name());
211
+			throw new RestException(
212
+				sprintf('rest_%s_invalid_id', $lowercase_model_name),
213
+				sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
214
+				array('status' => 404)
215
+			);
216
+		}
217
+		$model_obj->save($model_data);
218
+		return $this->returnModelObjAsJsonResponse($model_obj, $request);
219
+	}
220 220
 
221 221
 
222
-    /**
223
-     * Updates an existing model object according to the $request
224
-     *
225
-     * @param EEM_Base        $model
226
-     * @param WP_REST_Request $request
227
-     * @return array of either the soft-deleted item, or
228
-     * @throws EE_Error
229
-     */
230
-    public function delete(EEM_Base $model, WP_REST_Request $request)
231
-    {
232
-        Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete');
233
-        $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
234
-        if (! current_user_can($default_cap_to_check_for)) {
235
-            throw new RestException(
236
-                'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
237
-                sprintf(
238
-                    esc_html__(
239
-                    // @codingStandardsIgnoreStart
240
-                        'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to delete data into Event Espresso.',
241
-                        // @codingStandardsIgnoreEnd
242
-                        'event_espresso'
243
-                    ),
244
-                    $default_cap_to_check_for
245
-                ),
246
-                array('status' => 403)
247
-            );
248
-        }
249
-        $obj_id = $request->get_param('id');
250
-        // this is where we would apply more fine-grained caps
251
-        $model_obj = $model->get_one_by_ID($obj_id);
252
-        if (! $model_obj instanceof EE_Base_Class) {
253
-            $lowercase_model_name = strtolower($model->get_this_model_name());
254
-            throw new RestException(
255
-                sprintf('rest_%s_invalid_id', $lowercase_model_name),
256
-                sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
257
-                array('status' => 404)
258
-            );
259
-        }
260
-        $requested_permanent_delete = filter_var($request->get_param('force'), FILTER_VALIDATE_BOOLEAN);
261
-        $requested_allow_blocking = filter_var($request->get_param('allow_blocking'), FILTER_VALIDATE_BOOLEAN);
262
-        if ($requested_permanent_delete) {
263
-            $previous = $this->returnModelObjAsJsonResponse($model_obj, $request);
264
-            $deleted = (bool)$model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
265
-            return array(
266
-                'deleted'  => $deleted,
267
-                'previous' => $previous,
268
-            );
269
-        } else {
270
-            if ($model instanceof EEM_Soft_Delete_Base) {
271
-                $model->delete_by_ID($obj_id, $requested_allow_blocking);
272
-                return $this->returnModelObjAsJsonResponse($model_obj, $request);
273
-            } else {
274
-                throw new RestException(
275
-                    'rest_trash_not_supported',
276
-                    501,
277
-                    sprintf(
278
-                        esc_html__('%1$s do not support trashing. Set force=1 to delete.', 'event_espresso'),
279
-                        EEH_Inflector::pluralize($model->get_this_model_name())
280
-                    )
281
-                );
282
-            }
283
-        }
284
-    }
222
+	/**
223
+	 * Updates an existing model object according to the $request
224
+	 *
225
+	 * @param EEM_Base        $model
226
+	 * @param WP_REST_Request $request
227
+	 * @return array of either the soft-deleted item, or
228
+	 * @throws EE_Error
229
+	 */
230
+	public function delete(EEM_Base $model, WP_REST_Request $request)
231
+	{
232
+		Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete');
233
+		$default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
234
+		if (! current_user_can($default_cap_to_check_for)) {
235
+			throw new RestException(
236
+				'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
237
+				sprintf(
238
+					esc_html__(
239
+					// @codingStandardsIgnoreStart
240
+						'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to delete data into Event Espresso.',
241
+						// @codingStandardsIgnoreEnd
242
+						'event_espresso'
243
+					),
244
+					$default_cap_to_check_for
245
+				),
246
+				array('status' => 403)
247
+			);
248
+		}
249
+		$obj_id = $request->get_param('id');
250
+		// this is where we would apply more fine-grained caps
251
+		$model_obj = $model->get_one_by_ID($obj_id);
252
+		if (! $model_obj instanceof EE_Base_Class) {
253
+			$lowercase_model_name = strtolower($model->get_this_model_name());
254
+			throw new RestException(
255
+				sprintf('rest_%s_invalid_id', $lowercase_model_name),
256
+				sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
257
+				array('status' => 404)
258
+			);
259
+		}
260
+		$requested_permanent_delete = filter_var($request->get_param('force'), FILTER_VALIDATE_BOOLEAN);
261
+		$requested_allow_blocking = filter_var($request->get_param('allow_blocking'), FILTER_VALIDATE_BOOLEAN);
262
+		if ($requested_permanent_delete) {
263
+			$previous = $this->returnModelObjAsJsonResponse($model_obj, $request);
264
+			$deleted = (bool)$model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
265
+			return array(
266
+				'deleted'  => $deleted,
267
+				'previous' => $previous,
268
+			);
269
+		} else {
270
+			if ($model instanceof EEM_Soft_Delete_Base) {
271
+				$model->delete_by_ID($obj_id, $requested_allow_blocking);
272
+				return $this->returnModelObjAsJsonResponse($model_obj, $request);
273
+			} else {
274
+				throw new RestException(
275
+					'rest_trash_not_supported',
276
+					501,
277
+					sprintf(
278
+						esc_html__('%1$s do not support trashing. Set force=1 to delete.', 'event_espresso'),
279
+						EEH_Inflector::pluralize($model->get_this_model_name())
280
+					)
281
+				);
282
+			}
283
+		}
284
+	}
285 285
 
286 286
 
287
-    /**
288
-     * Returns an array ready to be converted into a JSON response, based solely on the model object
289
-     *
290
-     * @param EE_Base_Class   $model_obj
291
-     * @param WP_REST_Request $request
292
-     * @return array ready for a response
293
-     */
294
-    protected function returnModelObjAsJsonResponse(EE_Base_Class $model_obj, WP_REST_Request $request)
295
-    {
296
-        $model = $model_obj->get_model();
297
-        // create an array exactly like the wpdb results row,
298
-        // so we can pass it to controllers/model/Read::create_entity_from_wpdb_result()
299
-        $simulated_db_row = array();
300
-        foreach ($model->field_settings(true) as $field_name => $field_obj) {
301
-            // we need to reconstruct the normal wpdb results, including the db-only fields
302
-            // like a secondary table's primary key. The models expect those (but don't care what value they have)
303
-            if ($field_obj instanceof EE_DB_Only_Field_Base) {
304
-                $raw_value = true;
305
-            } elseif ($field_obj instanceof EE_Datetime_Field) {
306
-                $raw_value = $model_obj->get_DateTime_object($field_name);
307
-            } else {
308
-                $raw_value = $model_obj->get_raw($field_name);
309
-            }
310
-            $simulated_db_row[$field_obj->get_qualified_column()] = $field_obj->prepare_for_use_in_db($raw_value);
311
-        }
312
-        $read_controller = new Read();
313
-        $read_controller->setRequestedVersion($this->getRequestedVersion());
314
-        // the simulates request really doesn't need any info downstream
315
-        $simulated_request = new WP_REST_Request('GET');
316
-        return $read_controller->createEntityFromWpdbResult(
317
-            $model_obj->get_model(),
318
-            $simulated_db_row,
319
-            $simulated_request
320
-        );
321
-    }
287
+	/**
288
+	 * Returns an array ready to be converted into a JSON response, based solely on the model object
289
+	 *
290
+	 * @param EE_Base_Class   $model_obj
291
+	 * @param WP_REST_Request $request
292
+	 * @return array ready for a response
293
+	 */
294
+	protected function returnModelObjAsJsonResponse(EE_Base_Class $model_obj, WP_REST_Request $request)
295
+	{
296
+		$model = $model_obj->get_model();
297
+		// create an array exactly like the wpdb results row,
298
+		// so we can pass it to controllers/model/Read::create_entity_from_wpdb_result()
299
+		$simulated_db_row = array();
300
+		foreach ($model->field_settings(true) as $field_name => $field_obj) {
301
+			// we need to reconstruct the normal wpdb results, including the db-only fields
302
+			// like a secondary table's primary key. The models expect those (but don't care what value they have)
303
+			if ($field_obj instanceof EE_DB_Only_Field_Base) {
304
+				$raw_value = true;
305
+			} elseif ($field_obj instanceof EE_Datetime_Field) {
306
+				$raw_value = $model_obj->get_DateTime_object($field_name);
307
+			} else {
308
+				$raw_value = $model_obj->get_raw($field_name);
309
+			}
310
+			$simulated_db_row[$field_obj->get_qualified_column()] = $field_obj->prepare_for_use_in_db($raw_value);
311
+		}
312
+		$read_controller = new Read();
313
+		$read_controller->setRequestedVersion($this->getRequestedVersion());
314
+		// the simulates request really doesn't need any info downstream
315
+		$simulated_request = new WP_REST_Request('GET');
316
+		return $read_controller->createEntityFromWpdbResult(
317
+			$model_obj->get_model(),
318
+			$simulated_db_row,
319
+			$simulated_request
320
+		);
321
+	}
322 322
 
323 323
 
324
-    /**
325
-     * Gets the item affected by this request
326
-     *
327
-     * @param EEM_Base        $model
328
-     * @param WP_REST_Request $request
329
-     * @param  int|string     $obj_id
330
-     * @return \WP_Error|array
331
-     */
332
-    protected function getOneBasedOnRequest(EEM_Base $model, WP_REST_Request $request, $obj_id)
333
-    {
334
-        $requested_version = $this->getRequestedVersion($request->get_route());
335
-        $get_request = new WP_REST_Request(
336
-            'GET',
337
-            EED_Core_Rest_Api::ee_api_namespace
338
-            . $requested_version
339
-            . '/'
340
-            . EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
341
-            . '/'
342
-            . $obj_id
343
-        );
344
-        $get_request->set_url_params(
345
-            array(
346
-                'id'      => $obj_id,
347
-                'include' => $request->get_param('include'),
348
-            )
349
-        );
350
-        $read_controller = new Read();
351
-        $read_controller->setRequestedVersion($this->getRequestedVersion());
352
-        return $read_controller->getEntityFromModel($model, $get_request);
353
-    }
324
+	/**
325
+	 * Gets the item affected by this request
326
+	 *
327
+	 * @param EEM_Base        $model
328
+	 * @param WP_REST_Request $request
329
+	 * @param  int|string     $obj_id
330
+	 * @return \WP_Error|array
331
+	 */
332
+	protected function getOneBasedOnRequest(EEM_Base $model, WP_REST_Request $request, $obj_id)
333
+	{
334
+		$requested_version = $this->getRequestedVersion($request->get_route());
335
+		$get_request = new WP_REST_Request(
336
+			'GET',
337
+			EED_Core_Rest_Api::ee_api_namespace
338
+			. $requested_version
339
+			. '/'
340
+			. EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
341
+			. '/'
342
+			. $obj_id
343
+		);
344
+		$get_request->set_url_params(
345
+			array(
346
+				'id'      => $obj_id,
347
+				'include' => $request->get_param('include'),
348
+			)
349
+		);
350
+		$read_controller = new Read();
351
+		$read_controller->setRequestedVersion($this->getRequestedVersion());
352
+		return $read_controller->getEntityFromModel($model, $get_request);
353
+	}
354 354
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -125,9 +125,9 @@  discard block
 block discarded – undo
125 125
     {
126 126
         Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create');
127 127
         $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
128
-        if (! current_user_can($default_cap_to_check_for)) {
128
+        if ( ! current_user_can($default_cap_to_check_for)) {
129 129
             throw new RestException(
130
-                'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
130
+                'rest_cannot_create_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
131 131
                 sprintf(
132 132
                     esc_html__(
133 133
                     // @codingStandardsIgnoreStart
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
                 array('status' => 403)
141 141
             );
142 142
         }
143
-        $submitted_json_data = array_merge((array)$request->get_body_params(), (array)$request->get_json_params());
143
+        $submitted_json_data = array_merge((array) $request->get_body_params(), (array) $request->get_json_params());
144 144
         $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
145 145
             $submitted_json_data,
146 146
             $model,
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
         );
156 156
         $model_obj->save();
157 157
         $new_id = $model_obj->ID();
158
-        if (! $new_id) {
158
+        if ( ! $new_id) {
159 159
             throw new RestException(
160 160
                 'rest_insertion_failed',
161 161
                 sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name())
@@ -177,9 +177,9 @@  discard block
 block discarded – undo
177 177
     {
178 178
         Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit');
179 179
         $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
180
-        if (! current_user_can($default_cap_to_check_for)) {
180
+        if ( ! current_user_can($default_cap_to_check_for)) {
181 181
             throw new RestException(
182
-                'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
182
+                'rest_cannot_edit_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
183 183
                 sprintf(
184 184
                     esc_html__(
185 185
                     // @codingStandardsIgnoreStart
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
             );
194 194
         }
195 195
         $obj_id = $request->get_param('id');
196
-        if (! $obj_id) {
196
+        if ( ! $obj_id) {
197 197
             throw new RestException(
198 198
                 'rest_edit_failed',
199 199
                 sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name())
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
             true
207 207
         );
208 208
         $model_obj = $model->get_one_by_ID($obj_id);
209
-        if (! $model_obj instanceof EE_Base_Class) {
209
+        if ( ! $model_obj instanceof EE_Base_Class) {
210 210
             $lowercase_model_name = strtolower($model->get_this_model_name());
211 211
             throw new RestException(
212 212
                 sprintf('rest_%s_invalid_id', $lowercase_model_name),
@@ -231,9 +231,9 @@  discard block
 block discarded – undo
231 231
     {
232 232
         Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete');
233 233
         $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
234
-        if (! current_user_can($default_cap_to_check_for)) {
234
+        if ( ! current_user_can($default_cap_to_check_for)) {
235 235
             throw new RestException(
236
-                'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
236
+                'rest_cannot_delete_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
237 237
                 sprintf(
238 238
                     esc_html__(
239 239
                     // @codingStandardsIgnoreStart
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
         $obj_id = $request->get_param('id');
250 250
         // this is where we would apply more fine-grained caps
251 251
         $model_obj = $model->get_one_by_ID($obj_id);
252
-        if (! $model_obj instanceof EE_Base_Class) {
252
+        if ( ! $model_obj instanceof EE_Base_Class) {
253 253
             $lowercase_model_name = strtolower($model->get_this_model_name());
254 254
             throw new RestException(
255 255
                 sprintf('rest_%s_invalid_id', $lowercase_model_name),
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
         $requested_allow_blocking = filter_var($request->get_param('allow_blocking'), FILTER_VALIDATE_BOOLEAN);
262 262
         if ($requested_permanent_delete) {
263 263
             $previous = $this->returnModelObjAsJsonResponse($model_obj, $request);
264
-            $deleted = (bool)$model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
264
+            $deleted = (bool) $model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
265 265
             return array(
266 266
                 'deleted'  => $deleted,
267 267
                 'previous' => $previous,
Please login to merge, or discard this patch.