Completed
Branch Gutenberg/BUG/fix-editor-asset... (099b99)
by
unknown
29:37 queued 19:20
created
core/libraries/rest_api/controllers/model/Read.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1306,7 +1306,7 @@
 block discarded – undo
1306 1306
      *
1307 1307
      * @param EEM_Base        $model
1308 1308
      * @param WP_REST_Request $request
1309
-     * @param null            $context
1309
+     * @param string            $context
1310 1310
      * @return array|WP_Error
1311 1311
      */
1312 1312
     public function getOneOrReportPermissionError(EEM_Base $model, WP_REST_Request $request, $context = null)
Please login to merge, or discard this patch.
Indentation   +1346 added lines, -1346 removed lines patch added patch discarded remove patch
@@ -40,1350 +40,1350 @@
 block discarded – undo
40 40
 {
41 41
 
42 42
 
43
-    /**
44
-     * @var CalculatedModelFields
45
-     */
46
-    protected $fields_calculator;
47
-
48
-
49
-    /**
50
-     * Read constructor.
51
-     * @param CalculatedModelFields $fields_calculator
52
-     */
53
-    public function __construct(CalculatedModelFields $fields_calculator)
54
-    {
55
-        parent::__construct();
56
-        $this->fields_calculator = $fields_calculator;
57
-    }
58
-
59
-
60
-    /**
61
-     * Handles requests to get all (or a filtered subset) of entities for a particular model
62
-     *
63
-     * @param WP_REST_Request $request
64
-     * @param string $version
65
-     * @param string $model_name
66
-     * @return WP_REST_Response|WP_Error
67
-     * @throws InvalidArgumentException
68
-     * @throws InvalidDataTypeException
69
-     * @throws InvalidInterfaceException
70
-     */
71
-    public static function handleRequestGetAll(WP_REST_Request $request, $version, $model_name)
72
-    {
73
-        $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
74
-        try {
75
-            $controller->setRequestedVersion($version);
76
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
77
-                return $controller->sendResponse(
78
-                    new WP_Error(
79
-                        'endpoint_parsing_error',
80
-                        sprintf(
81
-                            __(
82
-                                'There is no model for endpoint %s. Please contact event espresso support',
83
-                                'event_espresso'
84
-                            ),
85
-                            $model_name
86
-                        )
87
-                    )
88
-                );
89
-            }
90
-            return $controller->sendResponse(
91
-                $controller->getEntitiesFromModel(
92
-                    $controller->getModelVersionInfo()->loadModel($model_name),
93
-                    $request
94
-                )
95
-            );
96
-        } catch (Exception $e) {
97
-            return $controller->sendResponse($e);
98
-        }
99
-    }
100
-
101
-
102
-    /**
103
-     * Prepares and returns schema for any OPTIONS request.
104
-     *
105
-     * @param string $version The API endpoint version being used.
106
-     * @param string $model_name Something like `Event` or `Registration`
107
-     * @return array
108
-     * @throws InvalidArgumentException
109
-     * @throws InvalidDataTypeException
110
-     * @throws InvalidInterfaceException
111
-     */
112
-    public static function handleSchemaRequest($version, $model_name)
113
-    {
114
-        $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
115
-        try {
116
-            $controller->setRequestedVersion($version);
117
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
118
-                return array();
119
-            }
120
-            // get the model for this version
121
-            $model = $controller->getModelVersionInfo()->loadModel($model_name);
122
-            $model_schema = new JsonModelSchema($model, LoaderFactory::getLoader()->getShared('EventEspresso\core\libraries\rest_api\CalculatedModelFields'));
123
-            return $model_schema->getModelSchemaForRelations(
124
-                $controller->getModelVersionInfo()->relationSettings($model),
125
-                $controller->customizeSchemaForRestResponse(
126
-                    $model,
127
-                    $model_schema->getModelSchemaForFields(
128
-                        $controller->getModelVersionInfo()->fieldsOnModelInThisVersion($model),
129
-                        $model_schema->getInitialSchemaStructure()
130
-                    )
131
-                )
132
-            );
133
-        } catch (Exception $e) {
134
-            return array();
135
-        }
136
-    }
137
-
138
-
139
-    /**
140
-     * This loops through each field in the given schema for the model and does the following:
141
-     * - add any extra fields that are REST API specific and related to existing fields.
142
-     * - transform default values into the correct format for a REST API response.
143
-     *
144
-     * @param EEM_Base $model
145
-     * @param array    $schema
146
-     * @return array  The final schema.
147
-     */
148
-    protected function customizeSchemaForRestResponse(EEM_Base $model, array $schema)
149
-    {
150
-        foreach ($this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) as $field_name => $field) {
151
-            $schema = $this->translateDefaultsForRestResponse(
152
-                $field_name,
153
-                $field,
154
-                $this->maybeAddExtraFieldsToSchema($field_name, $field, $schema)
155
-            );
156
-        }
157
-        return $schema;
158
-    }
159
-
160
-
161
-    /**
162
-     * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST
163
-     * response.
164
-     *
165
-     * @param                      $field_name
166
-     * @param EE_Model_Field_Base  $field
167
-     * @param array                $schema
168
-     * @return array
169
-     * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
170
-     * did, let's know about it ASAP, so let the exception bubble up)
171
-     */
172
-    protected function translateDefaultsForRestResponse($field_name, EE_Model_Field_Base $field, array $schema)
173
-    {
174
-        if (isset($schema['properties'][ $field_name ]['default'])) {
175
-            if (is_array($schema['properties'][ $field_name ]['default'])) {
176
-                foreach ($schema['properties'][ $field_name ]['default'] as $default_key => $default_value) {
177
-                    if ($default_key === 'raw') {
178
-                        $schema['properties'][ $field_name ]['default'][ $default_key ] =
179
-                            ModelDataTranslator::prepareFieldValueForJson(
180
-                                $field,
181
-                                $default_value,
182
-                                $this->getModelVersionInfo()->requestedVersion()
183
-                            );
184
-                    }
185
-                }
186
-            } else {
187
-                $schema['properties'][ $field_name ]['default'] = ModelDataTranslator::prepareFieldValueForJson(
188
-                    $field,
189
-                    $schema['properties'][ $field_name ]['default'],
190
-                    $this->getModelVersionInfo()->requestedVersion()
191
-                );
192
-            }
193
-        }
194
-        return $schema;
195
-    }
196
-
197
-
198
-    /**
199
-     * Adds additional fields to the schema
200
-     * The REST API returns a GMT value field for each datetime field in the resource.  Thus the description about this
201
-     * needs to be added to the schema.
202
-     *
203
-     * @param                      $field_name
204
-     * @param EE_Model_Field_Base  $field
205
-     * @param array                $schema
206
-     * @return array
207
-     */
208
-    protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema)
209
-    {
210
-        if ($field instanceof EE_Datetime_Field) {
211
-            $schema['properties'][ $field_name . '_gmt' ] = $field->getSchema();
212
-            // modify the description
213
-            $schema['properties'][ $field_name . '_gmt' ]['description'] = sprintf(
214
-                esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
215
-                wp_specialchars_decode($field->get_nicename(), ENT_QUOTES)
216
-            );
217
-        }
218
-        return $schema;
219
-    }
220
-
221
-
222
-    /**
223
-     * Used to figure out the route from the request when a `WP_REST_Request` object is not available
224
-     *
225
-     * @return string
226
-     */
227
-    protected function getRouteFromRequest()
228
-    {
229
-        if (isset($GLOBALS['wp'])
230
-            && $GLOBALS['wp'] instanceof \WP
231
-            && isset($GLOBALS['wp']->query_vars['rest_route'])
232
-        ) {
233
-            return $GLOBALS['wp']->query_vars['rest_route'];
234
-        } else {
235
-            return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
236
-        }
237
-    }
238
-
239
-
240
-    /**
241
-     * Gets a single entity related to the model indicated in the path and its id
242
-     *
243
-     * @param WP_REST_Request $request
244
-     * @param string $version
245
-     * @param string $model_name
246
-     * @return WP_REST_Response|WP_Error
247
-     * @throws InvalidDataTypeException
248
-     * @throws InvalidInterfaceException
249
-     * @throws InvalidArgumentException
250
-     */
251
-    public static function handleRequestGetOne(WP_REST_Request $request, $version, $model_name)
252
-    {
253
-        $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
254
-        try {
255
-            $controller->setRequestedVersion($version);
256
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
257
-                return $controller->sendResponse(
258
-                    new WP_Error(
259
-                        'endpoint_parsing_error',
260
-                        sprintf(
261
-                            __(
262
-                                'There is no model for endpoint %s. Please contact event espresso support',
263
-                                'event_espresso'
264
-                            ),
265
-                            $model_name
266
-                        )
267
-                    )
268
-                );
269
-            }
270
-            return $controller->sendResponse(
271
-                $controller->getEntityFromModel(
272
-                    $controller->getModelVersionInfo()->loadModel($model_name),
273
-                    $request
274
-                )
275
-            );
276
-        } catch (Exception $e) {
277
-            return $controller->sendResponse($e);
278
-        }
279
-    }
280
-
281
-
282
-    /**
283
-     * Gets all the related entities (or if its a belongs-to relation just the one)
284
-     * to the item with the given id
285
-     *
286
-     * @param WP_REST_Request $request
287
-     * @param string $version
288
-     * @param string $model_name
289
-     * @param string $related_model_name
290
-     * @return WP_REST_Response|WP_Error
291
-     * @throws InvalidDataTypeException
292
-     * @throws InvalidInterfaceException
293
-     * @throws InvalidArgumentException
294
-     */
295
-    public static function handleRequestGetRelated(
296
-        WP_REST_Request $request,
297
-        $version,
298
-        $model_name,
299
-        $related_model_name
300
-    ) {
301
-        $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
302
-        try {
303
-            $controller->setRequestedVersion($version);
304
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
305
-                return $controller->sendResponse(
306
-                    new WP_Error(
307
-                        'endpoint_parsing_error',
308
-                        sprintf(
309
-                            __(
310
-                                'There is no model for endpoint %s. Please contact event espresso support',
311
-                                'event_espresso'
312
-                            ),
313
-                            $model_name
314
-                        )
315
-                    )
316
-                );
317
-            }
318
-            $main_model = $controller->getModelVersionInfo()->loadModel($model_name);
319
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
320
-                return $controller->sendResponse(
321
-                    new WP_Error(
322
-                        'endpoint_parsing_error',
323
-                        sprintf(
324
-                            __(
325
-                                'There is no model for endpoint %s. Please contact event espresso support',
326
-                                'event_espresso'
327
-                            ),
328
-                            $related_model_name
329
-                        )
330
-                    )
331
-                );
332
-            }
333
-            return $controller->sendResponse(
334
-                $controller->getEntitiesFromRelation(
335
-                    $request->get_param('id'),
336
-                    $main_model->related_settings_for($related_model_name),
337
-                    $request
338
-                )
339
-            );
340
-        } catch (Exception $e) {
341
-            return $controller->sendResponse($e);
342
-        }
343
-    }
344
-
345
-
346
-    /**
347
-     * Gets a collection for the given model and filters
348
-     *
349
-     * @param EEM_Base        $model
350
-     * @param WP_REST_Request $request
351
-     * @return array|WP_Error
352
-     */
353
-    public function getEntitiesFromModel($model, $request)
354
-    {
355
-        $query_params = $this->createModelQueryParams($model, $request->get_params());
356
-        if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
357
-            $model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
358
-            return new WP_Error(
359
-                sprintf('rest_%s_cannot_list', $model_name_plural),
360
-                sprintf(
361
-                    __('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
362
-                    $model_name_plural,
363
-                    Capabilities::getMissingPermissionsString($model, $query_params['caps'])
364
-                ),
365
-                array('status' => 403)
366
-            );
367
-        }
368
-        if (! $request->get_header('no_rest_headers')) {
369
-            $this->setHeadersFromQueryParams($model, $query_params);
370
-        }
371
-        /** @type array $results */
372
-        $results = $model->get_all_wpdb_results($query_params);
373
-        $nice_results = array();
374
-        foreach ($results as $result) {
375
-            $nice_results[] = $this->createEntityFromWpdbResult(
376
-                $model,
377
-                $result,
378
-                $request
379
-            );
380
-        }
381
-        return $nice_results;
382
-    }
383
-
384
-
385
-    /**
386
-     * Gets the collection for given relation object
387
-     * The same as Read::get_entities_from_model(), except if the relation
388
-     * is a HABTM relation, in which case it merges any non-foreign-key fields from
389
-     * the join-model-object into the results
390
-     *
391
-     * @param array                   $primary_model_query_params query params for finding the item from which
392
-     *                                                            relations will be based
393
-     * @param \EE_Model_Relation_Base $relation
394
-     * @param WP_REST_Request         $request
395
-     * @return WP_Error|array
396
-     * @throws RestException
397
-     */
398
-    protected function getEntitiesFromRelationUsingModelQueryParams($primary_model_query_params, $relation, $request)
399
-    {
400
-        $context = $this->validateContext($request->get_param('caps'));
401
-        $model = $relation->get_this_model();
402
-        $related_model = $relation->get_other_model();
403
-        if (! isset($primary_model_query_params[0])) {
404
-            $primary_model_query_params[0] = array();
405
-        }
406
-        // check if they can access the 1st model object
407
-        $primary_model_query_params = array(
408
-            0       => $primary_model_query_params[0],
409
-            'limit' => 1,
410
-        );
411
-        if ($model instanceof \EEM_Soft_Delete_Base) {
412
-            $primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included(
413
-                $primary_model_query_params
414
-            );
415
-        }
416
-        $restricted_query_params = $primary_model_query_params;
417
-        $restricted_query_params['caps'] = $context;
418
-        $this->setDebugInfo('main model query params', $restricted_query_params);
419
-        $this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context));
420
-        if (! (
421
-            Capabilities::currentUserHasPartialAccessTo($related_model, $context)
422
-            && $model->exists($restricted_query_params)
423
-        )
424
-        ) {
425
-            if ($relation instanceof EE_Belongs_To_Relation) {
426
-                $related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
427
-            } else {
428
-                $related_model_name_maybe_plural = EEH_Inflector::pluralize_and_lower(
429
-                    $related_model->get_this_model_name()
430
-                );
431
-            }
432
-            return new WP_Error(
433
-                sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
434
-                sprintf(
435
-                    __(
436
-                        'Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
437
-                        'event_espresso'
438
-                    ),
439
-                    $related_model_name_maybe_plural,
440
-                    $relation->get_this_model()->get_this_model_name(),
441
-                    implode(
442
-                        ',',
443
-                        array_keys(
444
-                            Capabilities::getMissingPermissions($related_model, $context)
445
-                        )
446
-                    )
447
-                ),
448
-                array('status' => 403)
449
-            );
450
-        }
451
-        $query_params = $this->createModelQueryParams($relation->get_other_model(), $request->get_params());
452
-        foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
453
-            $query_params[0][ $relation->get_this_model()->get_this_model_name()
454
-                              . '.'
455
-                              . $where_condition_key ] = $where_condition_value;
456
-        }
457
-        $query_params['default_where_conditions'] = 'none';
458
-        $query_params['caps'] = $context;
459
-        if (! $request->get_header('no_rest_headers')) {
460
-            $this->setHeadersFromQueryParams($relation->get_other_model(), $query_params);
461
-        }
462
-        /** @type array $results */
463
-        $results = $relation->get_other_model()->get_all_wpdb_results($query_params);
464
-        $nice_results = array();
465
-        foreach ($results as $result) {
466
-            $nice_result = $this->createEntityFromWpdbResult(
467
-                $relation->get_other_model(),
468
-                $result,
469
-                $request
470
-            );
471
-            if ($relation instanceof \EE_HABTM_Relation) {
472
-                // put the unusual stuff (properties from the HABTM relation) first, and make sure
473
-                // if there are conflicts we prefer the properties from the main model
474
-                $join_model_result = $this->createEntityFromWpdbResult(
475
-                    $relation->get_join_model(),
476
-                    $result,
477
-                    $request
478
-                );
479
-                $joined_result = array_merge($nice_result, $join_model_result);
480
-                // but keep the meta stuff from the main model
481
-                if (isset($nice_result['meta'])) {
482
-                    $joined_result['meta'] = $nice_result['meta'];
483
-                }
484
-                $nice_result = $joined_result;
485
-            }
486
-            $nice_results[] = $nice_result;
487
-        }
488
-        if ($relation instanceof EE_Belongs_To_Relation) {
489
-            return array_shift($nice_results);
490
-        } else {
491
-            return $nice_results;
492
-        }
493
-    }
494
-
495
-
496
-    /**
497
-     * Gets the collection for given relation object
498
-     * The same as Read::get_entities_from_model(), except if the relation
499
-     * is a HABTM relation, in which case it merges any non-foreign-key fields from
500
-     * the join-model-object into the results
501
-     *
502
-     * @param string                  $id the ID of the thing we are fetching related stuff from
503
-     * @param \EE_Model_Relation_Base $relation
504
-     * @param WP_REST_Request         $request
505
-     * @return array|WP_Error
506
-     * @throws EE_Error
507
-     */
508
-    public function getEntitiesFromRelation($id, $relation, $request)
509
-    {
510
-        if (! $relation->get_this_model()->has_primary_key_field()) {
511
-            throw new EE_Error(
512
-                sprintf(
513
-                    __(
514
-                    // @codingStandardsIgnoreStart
515
-                        'Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
516
-                        // @codingStandardsIgnoreEnd
517
-                        'event_espresso'
518
-                    ),
519
-                    $relation->get_this_model()->get_this_model_name()
520
-                )
521
-            );
522
-        }
523
-        return $this->getEntitiesFromRelationUsingModelQueryParams(
524
-            array(
525
-                array(
526
-                    $relation->get_this_model()->primary_key_name() => $id,
527
-                ),
528
-            ),
529
-            $relation,
530
-            $request
531
-        );
532
-    }
533
-
534
-
535
-    /**
536
-     * Sets the headers that are based on the model and query params,
537
-     * like the total records. This should only be called on the original request
538
-     * from the client, not on subsequent internal
539
-     *
540
-     * @param EEM_Base $model
541
-     * @param array    $query_params
542
-     * @return void
543
-     */
544
-    protected function setHeadersFromQueryParams($model, $query_params)
545
-    {
546
-        $this->setDebugInfo('model query params', $query_params);
547
-        $this->setDebugInfo(
548
-            'missing caps',
549
-            Capabilities::getMissingPermissionsString($model, $query_params['caps'])
550
-        );
551
-        // normally the limit to a 2-part array, where the 2nd item is the limit
552
-        if (! isset($query_params['limit'])) {
553
-            $query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
554
-        }
555
-        if (is_array($query_params['limit'])) {
556
-            $limit_parts = $query_params['limit'];
557
-        } else {
558
-            $limit_parts = explode(',', $query_params['limit']);
559
-            if (count($limit_parts) == 1) {
560
-                $limit_parts = array(0, $limit_parts[0]);
561
-            }
562
-        }
563
-        // remove the group by and having parts of the query, as those will
564
-        // make the sql query return an array of values, instead of just a single value
565
-        unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
566
-        $count = $model->count($query_params, null, true);
567
-        $pages = $count / $limit_parts[1];
568
-        $this->setResponseHeader('Total', $count, false);
569
-        $this->setResponseHeader('PageSize', $limit_parts[1], false);
570
-        $this->setResponseHeader('TotalPages', ceil($pages), false);
571
-    }
572
-
573
-
574
-    /**
575
-     * Changes database results into REST API entities
576
-     *
577
-     * @param EEM_Base        $model
578
-     * @param array           $db_row     like results from $wpdb->get_results()
579
-     * @param WP_REST_Request $rest_request
580
-     * @param string          $deprecated no longer used
581
-     * @return array ready for being converted into json for sending to client
582
-     */
583
-    public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null)
584
-    {
585
-        if (! $rest_request instanceof WP_REST_Request) {
586
-            // ok so this was called in the old style, where the 3rd arg was
587
-            // $include, and the 4th arg was $context
588
-            // now setup the request just to avoid fatal errors, although we won't be able
589
-            // to truly make use of it because it's kinda devoid of info
590
-            $rest_request = new WP_REST_Request();
591
-            $rest_request->set_param('include', $rest_request);
592
-            $rest_request->set_param('caps', $deprecated);
593
-        }
594
-        if ($rest_request->get_param('caps') == null) {
595
-            $rest_request->set_param('caps', EEM_Base::caps_read);
596
-        }
597
-        $entity_array = $this->createBareEntityFromWpdbResults($model, $db_row);
598
-        $entity_array = $this->addExtraFields($model, $db_row, $entity_array);
599
-        $entity_array['_links'] = $this->getEntityLinks($model, $db_row, $entity_array);
600
-        $entity_array['_calculated_fields'] = $this->getEntityCalculations($model, $db_row, $rest_request);
601
-        $entity_array = apply_filters(
602
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
603
-            $entity_array,
604
-            $model,
605
-            $rest_request->get_param('caps'),
606
-            $rest_request,
607
-            $this
608
-        );
609
-        $entity_array = $this->includeRequestedModels($model, $rest_request, $entity_array, $db_row);
610
-        $entity_array = apply_filters(
611
-            'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
612
-            $entity_array,
613
-            $model,
614
-            $rest_request->get_param('caps'),
615
-            $rest_request,
616
-            $this
617
-        );
618
-        $result_without_inaccessible_fields = Capabilities::filterOutInaccessibleEntityFields(
619
-            $entity_array,
620
-            $model,
621
-            $rest_request->get_param('caps'),
622
-            $this->getModelVersionInfo(),
623
-            $model->get_index_primary_key_string(
624
-                $model->deduce_fields_n_values_from_cols_n_values($db_row)
625
-            )
626
-        );
627
-        $this->setDebugInfo(
628
-            'inaccessible fields',
629
-            array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
630
-        );
631
-        return apply_filters(
632
-            'FHEE__Read__create_entity_from_wpdb_results__entity_return',
633
-            $result_without_inaccessible_fields,
634
-            $model,
635
-            $rest_request->get_param('caps')
636
-        );
637
-    }
638
-
639
-
640
-    /**
641
-     * Creates a REST entity array (JSON object we're going to return in the response, but
642
-     * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
643
-     * from $wpdb->get_row( $sql, ARRAY_A)
644
-     *
645
-     * @param EEM_Base $model
646
-     * @param array    $db_row
647
-     * @return array entity mostly ready for converting to JSON and sending in the response
648
-     */
649
-    protected function createBareEntityFromWpdbResults(EEM_Base $model, $db_row)
650
-    {
651
-        $result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
652
-        $result = array_intersect_key(
653
-            $result,
654
-            $this->getModelVersionInfo()->fieldsOnModelInThisVersion($model)
655
-        );
656
-        // if this is a CPT, we need to set the global $post to it,
657
-        // otherwise shortcodes etc won't work properly while rendering it
658
-        if ($model instanceof \EEM_CPT_Base) {
659
-            $do_chevy_shuffle = true;
660
-        } else {
661
-            $do_chevy_shuffle = false;
662
-        }
663
-        if ($do_chevy_shuffle) {
664
-            global $post;
665
-            $old_post = $post;
666
-            $post = get_post($result[ $model->primary_key_name() ]);
667
-            if (! $post instanceof \WP_Post) {
668
-                // well that's weird, because $result is what we JUST fetched from the database
669
-                throw new RestException(
670
-                    'error_fetching_post_from_database_results',
671
-                    esc_html__(
672
-                        'An item was retrieved from the database but it\'s not a WP_Post like it should be.',
673
-                        'event_espresso'
674
-                    )
675
-                );
676
-            }
677
-            $model_object_classname = 'EE_' . $model->get_this_model_name();
678
-            $post->{$model_object_classname} = \EE_Registry::instance()->load_class(
679
-                $model_object_classname,
680
-                $result,
681
-                false,
682
-                false
683
-            );
684
-        }
685
-        foreach ($result as $field_name => $field_value) {
686
-            $field_obj = $model->field_settings_for($field_name);
687
-            if ($this->isSubclassOfOne($field_obj, $this->getModelVersionInfo()->fieldsIgnored())) {
688
-                unset($result[ $field_name ]);
689
-            } elseif ($this->isSubclassOfOne(
690
-                $field_obj,
691
-                $this->getModelVersionInfo()->fieldsThatHaveRenderedFormat()
692
-            )
693
-            ) {
694
-                $result[ $field_name ] = array(
695
-                    'raw'      => $this->prepareFieldObjValueForJson($field_obj, $field_value),
696
-                    'rendered' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
697
-                );
698
-            } elseif ($this->isSubclassOfOne(
699
-                $field_obj,
700
-                $this->getModelVersionInfo()->fieldsThatHavePrettyFormat()
701
-            )
702
-            ) {
703
-                $result[ $field_name ] = array(
704
-                    'raw'    => $this->prepareFieldObjValueForJson($field_obj, $field_value),
705
-                    'pretty' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
706
-                );
707
-            } elseif ($field_obj instanceof \EE_Datetime_Field) {
708
-                $field_value = $field_obj->prepare_for_set_from_db($field_value);
709
-                // if the value is null, but we're not supposed to permit null, then set to the field's default
710
-                if (is_null($field_value)) {
711
-                    $field_value = $field_obj->getDefaultDateTimeObj();
712
-                }
713
-                if (is_null($field_value)) {
714
-                    $gmt_date = $local_date = ModelDataTranslator::prepareFieldValuesForJson(
715
-                        $field_obj,
716
-                        $field_value,
717
-                        $this->getModelVersionInfo()->requestedVersion()
718
-                    );
719
-                } else {
720
-                    $timezone = $field_value->getTimezone();
721
-                    EEH_DTT_Helper::setTimezone($field_value, new DateTimeZone('UTC'));
722
-                    $gmt_date = ModelDataTranslator::prepareFieldValuesForJson(
723
-                        $field_obj,
724
-                        $field_value,
725
-                        $this->getModelVersionInfo()->requestedVersion()
726
-                    );
727
-                    EEH_DTT_Helper::setTimezone($field_value, $timezone);
728
-                    $local_date = ModelDataTranslator::prepareFieldValuesForJson(
729
-                        $field_obj,
730
-                        $field_value,
731
-                        $this->getModelVersionInfo()->requestedVersion()
732
-                    );
733
-                }
734
-                $result[ $field_name . '_gmt' ] = $gmt_date;
735
-                $result[ $field_name ] = $local_date;
736
-            } else {
737
-                $result[ $field_name ] = $this->prepareFieldObjValueForJson($field_obj, $field_value);
738
-            }
739
-        }
740
-        if ($do_chevy_shuffle) {
741
-            $post = $old_post;
742
-        }
743
-        return $result;
744
-    }
745
-
746
-
747
-    /**
748
-     * Takes a value all the way from the DB representation, to the model object's representation, to the
749
-     * user-facing PHP representation, to the REST API representation. (Assumes you've already taken from the DB
750
-     * representation using $field_obj->prepare_for_set_from_db())
751
-     *
752
-     * @param EE_Model_Field_Base $field_obj
753
-     * @param mixed               $value  as it's stored on a model object
754
-     * @param string              $format valid values are 'normal' (default), 'pretty', 'datetime_obj'
755
-     * @return mixed
756
-     * @throws ObjectDetectedException if $value contains a PHP object
757
-     */
758
-    protected function prepareFieldObjValueForJson(EE_Model_Field_Base $field_obj, $value, $format = 'normal')
759
-    {
760
-        $value = $field_obj->prepare_for_set_from_db($value);
761
-        switch ($format) {
762
-            case 'pretty':
763
-                $value = $field_obj->prepare_for_pretty_echoing($value);
764
-                break;
765
-            case 'normal':
766
-            default:
767
-                $value = $field_obj->prepare_for_get($value);
768
-                break;
769
-        }
770
-        return ModelDataTranslator::prepareFieldValuesForJson(
771
-            $field_obj,
772
-            $value,
773
-            $this->getModelVersionInfo()->requestedVersion()
774
-        );
775
-    }
776
-
777
-
778
-    /**
779
-     * Adds a few extra fields to the entity response
780
-     *
781
-     * @param EEM_Base $model
782
-     * @param array    $db_row
783
-     * @param array    $entity_array
784
-     * @return array modified entity
785
-     */
786
-    protected function addExtraFields(EEM_Base $model, $db_row, $entity_array)
787
-    {
788
-        if ($model instanceof EEM_CPT_Base) {
789
-            $entity_array['link'] = get_permalink($db_row[ $model->get_primary_key_field()->get_qualified_column() ]);
790
-        }
791
-        return $entity_array;
792
-    }
793
-
794
-
795
-    /**
796
-     * Gets links we want to add to the response
797
-     *
798
-     * @global \WP_REST_Server $wp_rest_server
799
-     * @param EEM_Base         $model
800
-     * @param array            $db_row
801
-     * @param array            $entity_array
802
-     * @return array the _links item in the entity
803
-     */
804
-    protected function getEntityLinks($model, $db_row, $entity_array)
805
-    {
806
-        // add basic links
807
-        $links = array();
808
-        if ($model->has_primary_key_field()) {
809
-            $links['self'] = array(
810
-                array(
811
-                    'href' => $this->getVersionedLinkTo(
812
-                        EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
813
-                        . '/'
814
-                        . $entity_array[ $model->primary_key_name() ]
815
-                    ),
816
-                ),
817
-            );
818
-        }
819
-        $links['collection'] = array(
820
-            array(
821
-                'href' => $this->getVersionedLinkTo(
822
-                    EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
823
-                ),
824
-            ),
825
-        );
826
-        // add links to related models
827
-        if ($model->has_primary_key_field()) {
828
-            foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) {
829
-                $related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj);
830
-                $links[ EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part ] = array(
831
-                    array(
832
-                        'href'   => $this->getVersionedLinkTo(
833
-                            EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
834
-                            . '/'
835
-                            . $entity_array[ $model->primary_key_name() ]
836
-                            . '/'
837
-                            . $related_model_part
838
-                        ),
839
-                        'single' => $relation_obj instanceof EE_Belongs_To_Relation ? true : false,
840
-                    ),
841
-                );
842
-            }
843
-        }
844
-        return $links;
845
-    }
846
-
847
-
848
-    /**
849
-     * Adds the included models indicated in the request to the entity provided
850
-     *
851
-     * @param EEM_Base        $model
852
-     * @param WP_REST_Request $rest_request
853
-     * @param array           $entity_array
854
-     * @param array           $db_row
855
-     * @return array the modified entity
856
-     */
857
-    protected function includeRequestedModels(
858
-        EEM_Base $model,
859
-        WP_REST_Request $rest_request,
860
-        $entity_array,
861
-        $db_row = array()
862
-    ) {
863
-        // if $db_row not included, hope the entity array has what we need
864
-        if (! $db_row) {
865
-            $db_row = $entity_array;
866
-        }
867
-        $includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), '');
868
-        $includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model);
869
-        // if they passed in * or didn't specify any includes, return everything
870
-        if (! in_array('*', $includes_for_this_model)
871
-            && ! empty($includes_for_this_model)
872
-        ) {
873
-            if ($model->has_primary_key_field()) {
874
-                // always include the primary key. ya just gotta know that at least
875
-                $includes_for_this_model[] = $model->primary_key_name();
876
-            }
877
-            if ($this->explodeAndGetItemsPrefixedWith($rest_request->get_param('calculate'), '')) {
878
-                $includes_for_this_model[] = '_calculated_fields';
879
-            }
880
-            $entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
881
-        }
882
-        $relation_settings = $this->getModelVersionInfo()->relationSettings($model);
883
-        foreach ($relation_settings as $relation_name => $relation_obj) {
884
-            $related_fields_to_include = $this->explodeAndGetItemsPrefixedWith(
885
-                $rest_request->get_param('include'),
886
-                $relation_name
887
-            );
888
-            $related_fields_to_calculate = $this->explodeAndGetItemsPrefixedWith(
889
-                $rest_request->get_param('calculate'),
890
-                $relation_name
891
-            );
892
-            // did they specify they wanted to include a related model, or
893
-            // specific fields from a related model?
894
-            // or did they specify to calculate a field from a related model?
895
-            if ($related_fields_to_include || $related_fields_to_calculate) {
896
-                // if so, we should include at least some part of the related model
897
-                $pretend_related_request = new WP_REST_Request();
898
-                $pretend_related_request->set_query_params(
899
-                    array(
900
-                        'caps'      => $rest_request->get_param('caps'),
901
-                        'include'   => $related_fields_to_include,
902
-                        'calculate' => $related_fields_to_calculate,
903
-                    )
904
-                );
905
-                $pretend_related_request->add_header('no_rest_headers', true);
906
-                $primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
907
-                    $model->get_index_primary_key_string(
908
-                        $model->deduce_fields_n_values_from_cols_n_values($db_row)
909
-                    )
910
-                );
911
-                $related_results = $this->getEntitiesFromRelationUsingModelQueryParams(
912
-                    $primary_model_query_params,
913
-                    $relation_obj,
914
-                    $pretend_related_request
915
-                );
916
-                $entity_array[ Read::getRelatedEntityName($relation_name, $relation_obj) ] = $related_results
917
-                                                                                             instanceof
918
-                                                                                             WP_Error
919
-                    ? null
920
-                    : $related_results;
921
-            }
922
-        }
923
-        return $entity_array;
924
-    }
925
-
926
-
927
-    /**
928
-     * Returns a new array with all the names of models removed. Eg
929
-     * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
930
-     *
931
-     * @param array $arr
932
-     * @return array
933
-     */
934
-    private function removeModelNamesFromArray($arr)
935
-    {
936
-        return array_diff($arr, array_keys(EE_Registry::instance()->non_abstract_db_models));
937
-    }
938
-
939
-
940
-    /**
941
-     * Gets the calculated fields for the response
942
-     *
943
-     * @param EEM_Base        $model
944
-     * @param array           $wpdb_row
945
-     * @param WP_REST_Request $rest_request
946
-     * @return \stdClass the _calculations item in the entity
947
-     * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
948
-     * did, let's know about it ASAP, so let the exception bubble up)
949
-     */
950
-    protected function getEntityCalculations($model, $wpdb_row, $rest_request)
951
-    {
952
-        $calculated_fields = $this->explodeAndGetItemsPrefixedWith(
953
-            $rest_request->get_param('calculate'),
954
-            ''
955
-        );
956
-        // note: setting calculate=* doesn't do anything
957
-        $calculated_fields_to_return = new \stdClass();
958
-        foreach ($calculated_fields as $field_to_calculate) {
959
-            try {
960
-                $calculated_fields_to_return->$field_to_calculate = ModelDataTranslator::prepareFieldValueForJson(
961
-                    null,
962
-                    $this->fields_calculator->retrieveCalculatedFieldValue(
963
-                        $model,
964
-                        $field_to_calculate,
965
-                        $wpdb_row,
966
-                        $rest_request,
967
-                        $this
968
-                    ),
969
-                    $this->getModelVersionInfo()->requestedVersion()
970
-                );
971
-            } catch (RestException $e) {
972
-                // if we don't have permission to read it, just leave it out. but let devs know about the problem
973
-                $this->setResponseHeader(
974
-                    'Notices-Field-Calculation-Errors['
975
-                    . $e->getStringCode()
976
-                    . ']['
977
-                    . $model->get_this_model_name()
978
-                    . ']['
979
-                    . $field_to_calculate
980
-                    . ']',
981
-                    $e->getMessage(),
982
-                    true
983
-                );
984
-            }
985
-        }
986
-        return $calculated_fields_to_return;
987
-    }
988
-
989
-
990
-    /**
991
-     * Gets the full URL to the resource, taking the requested version into account
992
-     *
993
-     * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
994
-     * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
995
-     */
996
-    public function getVersionedLinkTo($link_part_after_version_and_slash)
997
-    {
998
-        return rest_url(
999
-            EED_Core_Rest_Api::get_versioned_route_to(
1000
-                $link_part_after_version_and_slash,
1001
-                $this->getModelVersionInfo()->requestedVersion()
1002
-            )
1003
-        );
1004
-    }
1005
-
1006
-
1007
-    /**
1008
-     * Gets the correct lowercase name for the relation in the API according
1009
-     * to the relation's type
1010
-     *
1011
-     * @param string                  $relation_name
1012
-     * @param \EE_Model_Relation_Base $relation_obj
1013
-     * @return string
1014
-     */
1015
-    public static function getRelatedEntityName($relation_name, $relation_obj)
1016
-    {
1017
-        if ($relation_obj instanceof EE_Belongs_To_Relation) {
1018
-            return strtolower($relation_name);
1019
-        } else {
1020
-            return EEH_Inflector::pluralize_and_lower($relation_name);
1021
-        }
1022
-    }
1023
-
1024
-
1025
-    /**
1026
-     * Gets the one model object with the specified id for the specified model
1027
-     *
1028
-     * @param EEM_Base        $model
1029
-     * @param WP_REST_Request $request
1030
-     * @return array|WP_Error
1031
-     */
1032
-    public function getEntityFromModel($model, $request)
1033
-    {
1034
-        $context = $this->validateContext($request->get_param('caps'));
1035
-        return $this->getOneOrReportPermissionError($model, $request, $context);
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * If a context is provided which isn't valid, maybe it was added in a future
1041
-     * version so just treat it as a default read
1042
-     *
1043
-     * @param string $context
1044
-     * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
1045
-     */
1046
-    public function validateContext($context)
1047
-    {
1048
-        if (! $context) {
1049
-            $context = EEM_Base::caps_read;
1050
-        }
1051
-        $valid_contexts = EEM_Base::valid_cap_contexts();
1052
-        if (in_array($context, $valid_contexts)) {
1053
-            return $context;
1054
-        } else {
1055
-            return EEM_Base::caps_read;
1056
-        }
1057
-    }
1058
-
1059
-
1060
-    /**
1061
-     * Verifies the passed in value is an allowable default where conditions value.
1062
-     *
1063
-     * @param $default_query_params
1064
-     * @return string
1065
-     */
1066
-    public function validateDefaultQueryParams($default_query_params)
1067
-    {
1068
-        $valid_default_where_conditions_for_api_calls = array(
1069
-            EEM_Base::default_where_conditions_all,
1070
-            EEM_Base::default_where_conditions_minimum_all,
1071
-            EEM_Base::default_where_conditions_minimum_others,
1072
-        );
1073
-        if (! $default_query_params) {
1074
-            $default_query_params = EEM_Base::default_where_conditions_all;
1075
-        }
1076
-        if (in_array(
1077
-            $default_query_params,
1078
-            $valid_default_where_conditions_for_api_calls,
1079
-            true
1080
-        )) {
1081
-            return $default_query_params;
1082
-        } else {
1083
-            return EEM_Base::default_where_conditions_all;
1084
-        }
1085
-    }
1086
-
1087
-
1088
-    /**
1089
-     * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
1090
-     * Note: right now the query parameter keys for fields (and related fields)
1091
-     * can be left as-is, but it's quite possible this will change someday.
1092
-     * Also, this method's contents might be candidate for moving to Model_Data_Translator
1093
-     *
1094
-     * @param EEM_Base $model
1095
-     * @param array    $query_parameters  from $_GET parameter @see Read:handle_request_get_all
1096
-     * @return array like what EEM_Base::get_all() expects or FALSE to indicate
1097
-     *                                    that absolutely no results should be returned
1098
-     * @throws EE_Error
1099
-     * @throws RestException
1100
-     */
1101
-    public function createModelQueryParams($model, $query_parameters)
1102
-    {
1103
-        $model_query_params = array();
1104
-        if (isset($query_parameters['where'])) {
1105
-            $model_query_params[0] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1106
-                $query_parameters['where'],
1107
-                $model,
1108
-                $this->getModelVersionInfo()->requestedVersion()
1109
-            );
1110
-        }
1111
-        if (isset($query_parameters['order_by'])) {
1112
-            $order_by = $query_parameters['order_by'];
1113
-        } elseif (isset($query_parameters['orderby'])) {
1114
-            $order_by = $query_parameters['orderby'];
1115
-        } else {
1116
-            $order_by = null;
1117
-        }
1118
-        if ($order_by !== null) {
1119
-            if (is_array($order_by)) {
1120
-                $order_by = ModelDataTranslator::prepareFieldNamesInArrayKeysFromJson($order_by);
1121
-            } else {
1122
-                // it's a single item
1123
-                $order_by = ModelDataTranslator::prepareFieldNameFromJson($order_by);
1124
-            }
1125
-            $model_query_params['order_by'] = $order_by;
1126
-        }
1127
-        if (isset($query_parameters['group_by'])) {
1128
-            $group_by = $query_parameters['group_by'];
1129
-        } elseif (isset($query_parameters['groupby'])) {
1130
-            $group_by = $query_parameters['groupby'];
1131
-        } else {
1132
-            $group_by = array_keys($model->get_combined_primary_key_fields());
1133
-        }
1134
-        // make sure they're all real names
1135
-        if (is_array($group_by)) {
1136
-            $group_by = ModelDataTranslator::prepareFieldNamesFromJson($group_by);
1137
-        }
1138
-        if ($group_by !== null) {
1139
-            $model_query_params['group_by'] = $group_by;
1140
-        }
1141
-        if (isset($query_parameters['having'])) {
1142
-            $model_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1143
-                $query_parameters['having'],
1144
-                $model,
1145
-                $this->getModelVersionInfo()->requestedVersion()
1146
-            );
1147
-        }
1148
-        if (isset($query_parameters['order'])) {
1149
-            $model_query_params['order'] = $query_parameters['order'];
1150
-        }
1151
-        if (isset($query_parameters['mine'])) {
1152
-            $model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
1153
-        }
1154
-        if (isset($query_parameters['limit'])) {
1155
-            // limit should be either a string like '23' or '23,43', or an array with two items in it
1156
-            if (! is_array($query_parameters['limit'])) {
1157
-                $limit_array = explode(',', (string) $query_parameters['limit']);
1158
-            } else {
1159
-                $limit_array = $query_parameters['limit'];
1160
-            }
1161
-            $sanitized_limit = array();
1162
-            foreach ($limit_array as $key => $limit_part) {
1163
-                if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1164
-                    throw new EE_Error(
1165
-                        sprintf(
1166
-                            __(
1167
-                            // @codingStandardsIgnoreStart
1168
-                                'An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
1169
-                                // @codingStandardsIgnoreEnd
1170
-                                'event_espresso'
1171
-                            ),
1172
-                            wp_json_encode($query_parameters['limit'])
1173
-                        )
1174
-                    );
1175
-                }
1176
-                $sanitized_limit[] = (int) $limit_part;
1177
-            }
1178
-            $model_query_params['limit'] = implode(',', $sanitized_limit);
1179
-        } else {
1180
-            $model_query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
1181
-        }
1182
-        if (isset($query_parameters['caps'])) {
1183
-            $model_query_params['caps'] = $this->validateContext($query_parameters['caps']);
1184
-        } else {
1185
-            $model_query_params['caps'] = EEM_Base::caps_read;
1186
-        }
1187
-        if (isset($query_parameters['default_where_conditions'])) {
1188
-            $model_query_params['default_where_conditions'] = $this->validateDefaultQueryParams(
1189
-                $query_parameters['default_where_conditions']
1190
-            );
1191
-        }
1192
-        return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
1193
-    }
1194
-
1195
-
1196
-    /**
1197
-     * Changes the REST-style query params for use in the models
1198
-     *
1199
-     * @deprecated
1200
-     * @param EEM_Base $model
1201
-     * @param array    $query_params sub-array from @see EEM_Base::get_all()
1202
-     * @return array
1203
-     */
1204
-    public function prepareRestQueryParamsKeyForModels($model, $query_params)
1205
-    {
1206
-        $model_ready_query_params = array();
1207
-        foreach ($query_params as $key => $value) {
1208
-            if (is_array($value)) {
1209
-                $model_ready_query_params[ $key ] = $this->prepareRestQueryParamsKeyForModels($model, $value);
1210
-            } else {
1211
-                $model_ready_query_params[ $key ] = $value;
1212
-            }
1213
-        }
1214
-        return $model_ready_query_params;
1215
-    }
1216
-
1217
-
1218
-    /**
1219
-     * @deprecated instead use ModelDataTranslator::prepareFieldValuesFromJson()
1220
-     * @param $model
1221
-     * @param $query_params
1222
-     * @return array
1223
-     */
1224
-    public function prepareRestQueryParamsValuesForModels($model, $query_params)
1225
-    {
1226
-        $model_ready_query_params = array();
1227
-        foreach ($query_params as $key => $value) {
1228
-            if (is_array($value)) {
1229
-                $model_ready_query_params[ $key ] = $this->prepareRestQueryParamsValuesForModels($model, $value);
1230
-            } else {
1231
-                $model_ready_query_params[ $key ] = $value;
1232
-            }
1233
-        }
1234
-        return $model_ready_query_params;
1235
-    }
1236
-
1237
-
1238
-    /**
1239
-     * Explodes the string on commas, and only returns items with $prefix followed by a period.
1240
-     * If no prefix is specified, returns items with no period.
1241
-     *
1242
-     * @param string|array $string_to_explode eg "jibba,jabba, blah, blah, blah" or array('jibba', 'jabba' )
1243
-     * @param string       $prefix            "Event" or "foobar"
1244
-     * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1245
-     *                                        we only return strings starting with that and a period; if no prefix was
1246
-     *                                        specified we return all items containing NO periods
1247
-     */
1248
-    public function explodeAndGetItemsPrefixedWith($string_to_explode, $prefix)
1249
-    {
1250
-        if (is_string($string_to_explode)) {
1251
-            $exploded_contents = explode(',', $string_to_explode);
1252
-        } elseif (is_array($string_to_explode)) {
1253
-            $exploded_contents = $string_to_explode;
1254
-        } else {
1255
-            $exploded_contents = array();
1256
-        }
1257
-        // if the string was empty, we want an empty array
1258
-        $exploded_contents = array_filter($exploded_contents);
1259
-        $contents_with_prefix = array();
1260
-        foreach ($exploded_contents as $item) {
1261
-            $item = trim($item);
1262
-            // if no prefix was provided, so we look for items with no "." in them
1263
-            if (! $prefix) {
1264
-                // does this item have a period?
1265
-                if (strpos($item, '.') === false) {
1266
-                    // if not, then its what we're looking for
1267
-                    $contents_with_prefix[] = $item;
1268
-                }
1269
-            } elseif (strpos($item, $prefix . '.') === 0) {
1270
-                // this item has the prefix and a period, grab it
1271
-                $contents_with_prefix[] = substr(
1272
-                    $item,
1273
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1274
-                );
1275
-            } elseif ($item === $prefix) {
1276
-                // this item is JUST the prefix
1277
-                // so let's grab everything after, which is a blank string
1278
-                $contents_with_prefix[] = '';
1279
-            }
1280
-        }
1281
-        return $contents_with_prefix;
1282
-    }
1283
-
1284
-
1285
-    /**
1286
-     * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1287
-     * Deprecated because its return values were really quite confusing- sometimes it returned
1288
-     * an empty array (when the include string was blank or '*') or sometimes it returned
1289
-     * array('*') (when you provided a model and a model of that kind was found).
1290
-     * Parses the $include_string so we fetch all the field names relating to THIS model
1291
-     * (ie have NO period in them), or for the provided model (ie start with the model
1292
-     * name and then a period).
1293
-     * @param string $include_string @see Read:handle_request_get_all
1294
-     * @param string $model_name
1295
-     * @return array of fields for this model. If $model_name is provided, then
1296
-     *                               the fields for that model, with the model's name removed from each.
1297
-     *                               If $include_string was blank or '*' returns an empty array
1298
-     */
1299
-    public function extractIncludesForThisModel($include_string, $model_name = null)
1300
-    {
1301
-        if (is_array($include_string)) {
1302
-            $include_string = implode(',', $include_string);
1303
-        }
1304
-        if ($include_string === '*' || $include_string === '') {
1305
-            return array();
1306
-        }
1307
-        $includes = explode(',', $include_string);
1308
-        $extracted_fields_to_include = array();
1309
-        if ($model_name) {
1310
-            foreach ($includes as $field_to_include) {
1311
-                $field_to_include = trim($field_to_include);
1312
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1313
-                    // found the model name at the exact start
1314
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1315
-                    $extracted_fields_to_include[] = $field_sans_model_name;
1316
-                } elseif ($field_to_include == $model_name) {
1317
-                    $extracted_fields_to_include[] = '*';
1318
-                }
1319
-            }
1320
-        } else {
1321
-            // look for ones with no period
1322
-            foreach ($includes as $field_to_include) {
1323
-                $field_to_include = trim($field_to_include);
1324
-                if (strpos($field_to_include, '.') === false
1325
-                    && ! $this->getModelVersionInfo()->isModelNameInThisVersion($field_to_include)
1326
-                ) {
1327
-                    $extracted_fields_to_include[] = $field_to_include;
1328
-                }
1329
-            }
1330
-        }
1331
-        return $extracted_fields_to_include;
1332
-    }
1333
-
1334
-
1335
-    /**
1336
-     * Gets the single item using the model according to the request in the context given, otherwise
1337
-     * returns that it's inaccessible to the current user
1338
-     *
1339
-     * @param EEM_Base        $model
1340
-     * @param WP_REST_Request $request
1341
-     * @param null            $context
1342
-     * @return array|WP_Error
1343
-     */
1344
-    public function getOneOrReportPermissionError(EEM_Base $model, WP_REST_Request $request, $context = null)
1345
-    {
1346
-        $query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
1347
-        if ($model instanceof \EEM_Soft_Delete_Base) {
1348
-            $query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
1349
-        }
1350
-        $restricted_query_params = $query_params;
1351
-        $restricted_query_params['caps'] = $context;
1352
-        $this->setDebugInfo('model query params', $restricted_query_params);
1353
-        $model_rows = $model->get_all_wpdb_results($restricted_query_params);
1354
-        if (! empty($model_rows)) {
1355
-            return $this->createEntityFromWpdbResult(
1356
-                $model,
1357
-                array_shift($model_rows),
1358
-                $request
1359
-            );
1360
-        } else {
1361
-            // ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
1362
-            $lowercase_model_name = strtolower($model->get_this_model_name());
1363
-            $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
1364
-            if (! empty($model_rows_found_sans_restrictions)) {
1365
-                // you got shafted- it existed but we didn't want to tell you!
1366
-                return new WP_Error(
1367
-                    'rest_user_cannot_' . $context,
1368
-                    sprintf(
1369
-                        __('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'),
1370
-                        $context,
1371
-                        strtolower($model->get_this_model_name()),
1372
-                        Capabilities::getMissingPermissionsString(
1373
-                            $model,
1374
-                            $context
1375
-                        )
1376
-                    ),
1377
-                    array('status' => 403)
1378
-                );
1379
-            } else {
1380
-                // it's not you. It just doesn't exist
1381
-                return new WP_Error(
1382
-                    sprintf('rest_%s_invalid_id', $lowercase_model_name),
1383
-                    sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
1384
-                    array('status' => 404)
1385
-                );
1386
-            }
1387
-        }
1388
-    }
43
+	/**
44
+	 * @var CalculatedModelFields
45
+	 */
46
+	protected $fields_calculator;
47
+
48
+
49
+	/**
50
+	 * Read constructor.
51
+	 * @param CalculatedModelFields $fields_calculator
52
+	 */
53
+	public function __construct(CalculatedModelFields $fields_calculator)
54
+	{
55
+		parent::__construct();
56
+		$this->fields_calculator = $fields_calculator;
57
+	}
58
+
59
+
60
+	/**
61
+	 * Handles requests to get all (or a filtered subset) of entities for a particular model
62
+	 *
63
+	 * @param WP_REST_Request $request
64
+	 * @param string $version
65
+	 * @param string $model_name
66
+	 * @return WP_REST_Response|WP_Error
67
+	 * @throws InvalidArgumentException
68
+	 * @throws InvalidDataTypeException
69
+	 * @throws InvalidInterfaceException
70
+	 */
71
+	public static function handleRequestGetAll(WP_REST_Request $request, $version, $model_name)
72
+	{
73
+		$controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
74
+		try {
75
+			$controller->setRequestedVersion($version);
76
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
77
+				return $controller->sendResponse(
78
+					new WP_Error(
79
+						'endpoint_parsing_error',
80
+						sprintf(
81
+							__(
82
+								'There is no model for endpoint %s. Please contact event espresso support',
83
+								'event_espresso'
84
+							),
85
+							$model_name
86
+						)
87
+					)
88
+				);
89
+			}
90
+			return $controller->sendResponse(
91
+				$controller->getEntitiesFromModel(
92
+					$controller->getModelVersionInfo()->loadModel($model_name),
93
+					$request
94
+				)
95
+			);
96
+		} catch (Exception $e) {
97
+			return $controller->sendResponse($e);
98
+		}
99
+	}
100
+
101
+
102
+	/**
103
+	 * Prepares and returns schema for any OPTIONS request.
104
+	 *
105
+	 * @param string $version The API endpoint version being used.
106
+	 * @param string $model_name Something like `Event` or `Registration`
107
+	 * @return array
108
+	 * @throws InvalidArgumentException
109
+	 * @throws InvalidDataTypeException
110
+	 * @throws InvalidInterfaceException
111
+	 */
112
+	public static function handleSchemaRequest($version, $model_name)
113
+	{
114
+		$controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
115
+		try {
116
+			$controller->setRequestedVersion($version);
117
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
118
+				return array();
119
+			}
120
+			// get the model for this version
121
+			$model = $controller->getModelVersionInfo()->loadModel($model_name);
122
+			$model_schema = new JsonModelSchema($model, LoaderFactory::getLoader()->getShared('EventEspresso\core\libraries\rest_api\CalculatedModelFields'));
123
+			return $model_schema->getModelSchemaForRelations(
124
+				$controller->getModelVersionInfo()->relationSettings($model),
125
+				$controller->customizeSchemaForRestResponse(
126
+					$model,
127
+					$model_schema->getModelSchemaForFields(
128
+						$controller->getModelVersionInfo()->fieldsOnModelInThisVersion($model),
129
+						$model_schema->getInitialSchemaStructure()
130
+					)
131
+				)
132
+			);
133
+		} catch (Exception $e) {
134
+			return array();
135
+		}
136
+	}
137
+
138
+
139
+	/**
140
+	 * This loops through each field in the given schema for the model and does the following:
141
+	 * - add any extra fields that are REST API specific and related to existing fields.
142
+	 * - transform default values into the correct format for a REST API response.
143
+	 *
144
+	 * @param EEM_Base $model
145
+	 * @param array    $schema
146
+	 * @return array  The final schema.
147
+	 */
148
+	protected function customizeSchemaForRestResponse(EEM_Base $model, array $schema)
149
+	{
150
+		foreach ($this->getModelVersionInfo()->fieldsOnModelInThisVersion($model) as $field_name => $field) {
151
+			$schema = $this->translateDefaultsForRestResponse(
152
+				$field_name,
153
+				$field,
154
+				$this->maybeAddExtraFieldsToSchema($field_name, $field, $schema)
155
+			);
156
+		}
157
+		return $schema;
158
+	}
159
+
160
+
161
+	/**
162
+	 * This is used to ensure that the 'default' value set in the schema response is formatted correctly for the REST
163
+	 * response.
164
+	 *
165
+	 * @param                      $field_name
166
+	 * @param EE_Model_Field_Base  $field
167
+	 * @param array                $schema
168
+	 * @return array
169
+	 * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
170
+	 * did, let's know about it ASAP, so let the exception bubble up)
171
+	 */
172
+	protected function translateDefaultsForRestResponse($field_name, EE_Model_Field_Base $field, array $schema)
173
+	{
174
+		if (isset($schema['properties'][ $field_name ]['default'])) {
175
+			if (is_array($schema['properties'][ $field_name ]['default'])) {
176
+				foreach ($schema['properties'][ $field_name ]['default'] as $default_key => $default_value) {
177
+					if ($default_key === 'raw') {
178
+						$schema['properties'][ $field_name ]['default'][ $default_key ] =
179
+							ModelDataTranslator::prepareFieldValueForJson(
180
+								$field,
181
+								$default_value,
182
+								$this->getModelVersionInfo()->requestedVersion()
183
+							);
184
+					}
185
+				}
186
+			} else {
187
+				$schema['properties'][ $field_name ]['default'] = ModelDataTranslator::prepareFieldValueForJson(
188
+					$field,
189
+					$schema['properties'][ $field_name ]['default'],
190
+					$this->getModelVersionInfo()->requestedVersion()
191
+				);
192
+			}
193
+		}
194
+		return $schema;
195
+	}
196
+
197
+
198
+	/**
199
+	 * Adds additional fields to the schema
200
+	 * The REST API returns a GMT value field for each datetime field in the resource.  Thus the description about this
201
+	 * needs to be added to the schema.
202
+	 *
203
+	 * @param                      $field_name
204
+	 * @param EE_Model_Field_Base  $field
205
+	 * @param array                $schema
206
+	 * @return array
207
+	 */
208
+	protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema)
209
+	{
210
+		if ($field instanceof EE_Datetime_Field) {
211
+			$schema['properties'][ $field_name . '_gmt' ] = $field->getSchema();
212
+			// modify the description
213
+			$schema['properties'][ $field_name . '_gmt' ]['description'] = sprintf(
214
+				esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
215
+				wp_specialchars_decode($field->get_nicename(), ENT_QUOTES)
216
+			);
217
+		}
218
+		return $schema;
219
+	}
220
+
221
+
222
+	/**
223
+	 * Used to figure out the route from the request when a `WP_REST_Request` object is not available
224
+	 *
225
+	 * @return string
226
+	 */
227
+	protected function getRouteFromRequest()
228
+	{
229
+		if (isset($GLOBALS['wp'])
230
+			&& $GLOBALS['wp'] instanceof \WP
231
+			&& isset($GLOBALS['wp']->query_vars['rest_route'])
232
+		) {
233
+			return $GLOBALS['wp']->query_vars['rest_route'];
234
+		} else {
235
+			return isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '/';
236
+		}
237
+	}
238
+
239
+
240
+	/**
241
+	 * Gets a single entity related to the model indicated in the path and its id
242
+	 *
243
+	 * @param WP_REST_Request $request
244
+	 * @param string $version
245
+	 * @param string $model_name
246
+	 * @return WP_REST_Response|WP_Error
247
+	 * @throws InvalidDataTypeException
248
+	 * @throws InvalidInterfaceException
249
+	 * @throws InvalidArgumentException
250
+	 */
251
+	public static function handleRequestGetOne(WP_REST_Request $request, $version, $model_name)
252
+	{
253
+		$controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
254
+		try {
255
+			$controller->setRequestedVersion($version);
256
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
257
+				return $controller->sendResponse(
258
+					new WP_Error(
259
+						'endpoint_parsing_error',
260
+						sprintf(
261
+							__(
262
+								'There is no model for endpoint %s. Please contact event espresso support',
263
+								'event_espresso'
264
+							),
265
+							$model_name
266
+						)
267
+					)
268
+				);
269
+			}
270
+			return $controller->sendResponse(
271
+				$controller->getEntityFromModel(
272
+					$controller->getModelVersionInfo()->loadModel($model_name),
273
+					$request
274
+				)
275
+			);
276
+		} catch (Exception $e) {
277
+			return $controller->sendResponse($e);
278
+		}
279
+	}
280
+
281
+
282
+	/**
283
+	 * Gets all the related entities (or if its a belongs-to relation just the one)
284
+	 * to the item with the given id
285
+	 *
286
+	 * @param WP_REST_Request $request
287
+	 * @param string $version
288
+	 * @param string $model_name
289
+	 * @param string $related_model_name
290
+	 * @return WP_REST_Response|WP_Error
291
+	 * @throws InvalidDataTypeException
292
+	 * @throws InvalidInterfaceException
293
+	 * @throws InvalidArgumentException
294
+	 */
295
+	public static function handleRequestGetRelated(
296
+		WP_REST_Request $request,
297
+		$version,
298
+		$model_name,
299
+		$related_model_name
300
+	) {
301
+		$controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
302
+		try {
303
+			$controller->setRequestedVersion($version);
304
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
305
+				return $controller->sendResponse(
306
+					new WP_Error(
307
+						'endpoint_parsing_error',
308
+						sprintf(
309
+							__(
310
+								'There is no model for endpoint %s. Please contact event espresso support',
311
+								'event_espresso'
312
+							),
313
+							$model_name
314
+						)
315
+					)
316
+				);
317
+			}
318
+			$main_model = $controller->getModelVersionInfo()->loadModel($model_name);
319
+			if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
320
+				return $controller->sendResponse(
321
+					new WP_Error(
322
+						'endpoint_parsing_error',
323
+						sprintf(
324
+							__(
325
+								'There is no model for endpoint %s. Please contact event espresso support',
326
+								'event_espresso'
327
+							),
328
+							$related_model_name
329
+						)
330
+					)
331
+				);
332
+			}
333
+			return $controller->sendResponse(
334
+				$controller->getEntitiesFromRelation(
335
+					$request->get_param('id'),
336
+					$main_model->related_settings_for($related_model_name),
337
+					$request
338
+				)
339
+			);
340
+		} catch (Exception $e) {
341
+			return $controller->sendResponse($e);
342
+		}
343
+	}
344
+
345
+
346
+	/**
347
+	 * Gets a collection for the given model and filters
348
+	 *
349
+	 * @param EEM_Base        $model
350
+	 * @param WP_REST_Request $request
351
+	 * @return array|WP_Error
352
+	 */
353
+	public function getEntitiesFromModel($model, $request)
354
+	{
355
+		$query_params = $this->createModelQueryParams($model, $request->get_params());
356
+		if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
357
+			$model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
358
+			return new WP_Error(
359
+				sprintf('rest_%s_cannot_list', $model_name_plural),
360
+				sprintf(
361
+					__('Sorry, you are not allowed to list %1$s. Missing permissions: %2$s', 'event_espresso'),
362
+					$model_name_plural,
363
+					Capabilities::getMissingPermissionsString($model, $query_params['caps'])
364
+				),
365
+				array('status' => 403)
366
+			);
367
+		}
368
+		if (! $request->get_header('no_rest_headers')) {
369
+			$this->setHeadersFromQueryParams($model, $query_params);
370
+		}
371
+		/** @type array $results */
372
+		$results = $model->get_all_wpdb_results($query_params);
373
+		$nice_results = array();
374
+		foreach ($results as $result) {
375
+			$nice_results[] = $this->createEntityFromWpdbResult(
376
+				$model,
377
+				$result,
378
+				$request
379
+			);
380
+		}
381
+		return $nice_results;
382
+	}
383
+
384
+
385
+	/**
386
+	 * Gets the collection for given relation object
387
+	 * The same as Read::get_entities_from_model(), except if the relation
388
+	 * is a HABTM relation, in which case it merges any non-foreign-key fields from
389
+	 * the join-model-object into the results
390
+	 *
391
+	 * @param array                   $primary_model_query_params query params for finding the item from which
392
+	 *                                                            relations will be based
393
+	 * @param \EE_Model_Relation_Base $relation
394
+	 * @param WP_REST_Request         $request
395
+	 * @return WP_Error|array
396
+	 * @throws RestException
397
+	 */
398
+	protected function getEntitiesFromRelationUsingModelQueryParams($primary_model_query_params, $relation, $request)
399
+	{
400
+		$context = $this->validateContext($request->get_param('caps'));
401
+		$model = $relation->get_this_model();
402
+		$related_model = $relation->get_other_model();
403
+		if (! isset($primary_model_query_params[0])) {
404
+			$primary_model_query_params[0] = array();
405
+		}
406
+		// check if they can access the 1st model object
407
+		$primary_model_query_params = array(
408
+			0       => $primary_model_query_params[0],
409
+			'limit' => 1,
410
+		);
411
+		if ($model instanceof \EEM_Soft_Delete_Base) {
412
+			$primary_model_query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included(
413
+				$primary_model_query_params
414
+			);
415
+		}
416
+		$restricted_query_params = $primary_model_query_params;
417
+		$restricted_query_params['caps'] = $context;
418
+		$this->setDebugInfo('main model query params', $restricted_query_params);
419
+		$this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context));
420
+		if (! (
421
+			Capabilities::currentUserHasPartialAccessTo($related_model, $context)
422
+			&& $model->exists($restricted_query_params)
423
+		)
424
+		) {
425
+			if ($relation instanceof EE_Belongs_To_Relation) {
426
+				$related_model_name_maybe_plural = strtolower($related_model->get_this_model_name());
427
+			} else {
428
+				$related_model_name_maybe_plural = EEH_Inflector::pluralize_and_lower(
429
+					$related_model->get_this_model_name()
430
+				);
431
+			}
432
+			return new WP_Error(
433
+				sprintf('rest_%s_cannot_list', $related_model_name_maybe_plural),
434
+				sprintf(
435
+					__(
436
+						'Sorry, you are not allowed to list %1$s related to %2$s. Missing permissions: %3$s',
437
+						'event_espresso'
438
+					),
439
+					$related_model_name_maybe_plural,
440
+					$relation->get_this_model()->get_this_model_name(),
441
+					implode(
442
+						',',
443
+						array_keys(
444
+							Capabilities::getMissingPermissions($related_model, $context)
445
+						)
446
+					)
447
+				),
448
+				array('status' => 403)
449
+			);
450
+		}
451
+		$query_params = $this->createModelQueryParams($relation->get_other_model(), $request->get_params());
452
+		foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
453
+			$query_params[0][ $relation->get_this_model()->get_this_model_name()
454
+							  . '.'
455
+							  . $where_condition_key ] = $where_condition_value;
456
+		}
457
+		$query_params['default_where_conditions'] = 'none';
458
+		$query_params['caps'] = $context;
459
+		if (! $request->get_header('no_rest_headers')) {
460
+			$this->setHeadersFromQueryParams($relation->get_other_model(), $query_params);
461
+		}
462
+		/** @type array $results */
463
+		$results = $relation->get_other_model()->get_all_wpdb_results($query_params);
464
+		$nice_results = array();
465
+		foreach ($results as $result) {
466
+			$nice_result = $this->createEntityFromWpdbResult(
467
+				$relation->get_other_model(),
468
+				$result,
469
+				$request
470
+			);
471
+			if ($relation instanceof \EE_HABTM_Relation) {
472
+				// put the unusual stuff (properties from the HABTM relation) first, and make sure
473
+				// if there are conflicts we prefer the properties from the main model
474
+				$join_model_result = $this->createEntityFromWpdbResult(
475
+					$relation->get_join_model(),
476
+					$result,
477
+					$request
478
+				);
479
+				$joined_result = array_merge($nice_result, $join_model_result);
480
+				// but keep the meta stuff from the main model
481
+				if (isset($nice_result['meta'])) {
482
+					$joined_result['meta'] = $nice_result['meta'];
483
+				}
484
+				$nice_result = $joined_result;
485
+			}
486
+			$nice_results[] = $nice_result;
487
+		}
488
+		if ($relation instanceof EE_Belongs_To_Relation) {
489
+			return array_shift($nice_results);
490
+		} else {
491
+			return $nice_results;
492
+		}
493
+	}
494
+
495
+
496
+	/**
497
+	 * Gets the collection for given relation object
498
+	 * The same as Read::get_entities_from_model(), except if the relation
499
+	 * is a HABTM relation, in which case it merges any non-foreign-key fields from
500
+	 * the join-model-object into the results
501
+	 *
502
+	 * @param string                  $id the ID of the thing we are fetching related stuff from
503
+	 * @param \EE_Model_Relation_Base $relation
504
+	 * @param WP_REST_Request         $request
505
+	 * @return array|WP_Error
506
+	 * @throws EE_Error
507
+	 */
508
+	public function getEntitiesFromRelation($id, $relation, $request)
509
+	{
510
+		if (! $relation->get_this_model()->has_primary_key_field()) {
511
+			throw new EE_Error(
512
+				sprintf(
513
+					__(
514
+					// @codingStandardsIgnoreStart
515
+						'Read::get_entities_from_relation should only be called from a model with a primary key, it was called from %1$s',
516
+						// @codingStandardsIgnoreEnd
517
+						'event_espresso'
518
+					),
519
+					$relation->get_this_model()->get_this_model_name()
520
+				)
521
+			);
522
+		}
523
+		return $this->getEntitiesFromRelationUsingModelQueryParams(
524
+			array(
525
+				array(
526
+					$relation->get_this_model()->primary_key_name() => $id,
527
+				),
528
+			),
529
+			$relation,
530
+			$request
531
+		);
532
+	}
533
+
534
+
535
+	/**
536
+	 * Sets the headers that are based on the model and query params,
537
+	 * like the total records. This should only be called on the original request
538
+	 * from the client, not on subsequent internal
539
+	 *
540
+	 * @param EEM_Base $model
541
+	 * @param array    $query_params
542
+	 * @return void
543
+	 */
544
+	protected function setHeadersFromQueryParams($model, $query_params)
545
+	{
546
+		$this->setDebugInfo('model query params', $query_params);
547
+		$this->setDebugInfo(
548
+			'missing caps',
549
+			Capabilities::getMissingPermissionsString($model, $query_params['caps'])
550
+		);
551
+		// normally the limit to a 2-part array, where the 2nd item is the limit
552
+		if (! isset($query_params['limit'])) {
553
+			$query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
554
+		}
555
+		if (is_array($query_params['limit'])) {
556
+			$limit_parts = $query_params['limit'];
557
+		} else {
558
+			$limit_parts = explode(',', $query_params['limit']);
559
+			if (count($limit_parts) == 1) {
560
+				$limit_parts = array(0, $limit_parts[0]);
561
+			}
562
+		}
563
+		// remove the group by and having parts of the query, as those will
564
+		// make the sql query return an array of values, instead of just a single value
565
+		unset($query_params['group_by'], $query_params['having'], $query_params['limit']);
566
+		$count = $model->count($query_params, null, true);
567
+		$pages = $count / $limit_parts[1];
568
+		$this->setResponseHeader('Total', $count, false);
569
+		$this->setResponseHeader('PageSize', $limit_parts[1], false);
570
+		$this->setResponseHeader('TotalPages', ceil($pages), false);
571
+	}
572
+
573
+
574
+	/**
575
+	 * Changes database results into REST API entities
576
+	 *
577
+	 * @param EEM_Base        $model
578
+	 * @param array           $db_row     like results from $wpdb->get_results()
579
+	 * @param WP_REST_Request $rest_request
580
+	 * @param string          $deprecated no longer used
581
+	 * @return array ready for being converted into json for sending to client
582
+	 */
583
+	public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null)
584
+	{
585
+		if (! $rest_request instanceof WP_REST_Request) {
586
+			// ok so this was called in the old style, where the 3rd arg was
587
+			// $include, and the 4th arg was $context
588
+			// now setup the request just to avoid fatal errors, although we won't be able
589
+			// to truly make use of it because it's kinda devoid of info
590
+			$rest_request = new WP_REST_Request();
591
+			$rest_request->set_param('include', $rest_request);
592
+			$rest_request->set_param('caps', $deprecated);
593
+		}
594
+		if ($rest_request->get_param('caps') == null) {
595
+			$rest_request->set_param('caps', EEM_Base::caps_read);
596
+		}
597
+		$entity_array = $this->createBareEntityFromWpdbResults($model, $db_row);
598
+		$entity_array = $this->addExtraFields($model, $db_row, $entity_array);
599
+		$entity_array['_links'] = $this->getEntityLinks($model, $db_row, $entity_array);
600
+		$entity_array['_calculated_fields'] = $this->getEntityCalculations($model, $db_row, $rest_request);
601
+		$entity_array = apply_filters(
602
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_including_requested_models',
603
+			$entity_array,
604
+			$model,
605
+			$rest_request->get_param('caps'),
606
+			$rest_request,
607
+			$this
608
+		);
609
+		$entity_array = $this->includeRequestedModels($model, $rest_request, $entity_array, $db_row);
610
+		$entity_array = apply_filters(
611
+			'FHEE__Read__create_entity_from_wpdb_results__entity_before_inaccessible_field_removal',
612
+			$entity_array,
613
+			$model,
614
+			$rest_request->get_param('caps'),
615
+			$rest_request,
616
+			$this
617
+		);
618
+		$result_without_inaccessible_fields = Capabilities::filterOutInaccessibleEntityFields(
619
+			$entity_array,
620
+			$model,
621
+			$rest_request->get_param('caps'),
622
+			$this->getModelVersionInfo(),
623
+			$model->get_index_primary_key_string(
624
+				$model->deduce_fields_n_values_from_cols_n_values($db_row)
625
+			)
626
+		);
627
+		$this->setDebugInfo(
628
+			'inaccessible fields',
629
+			array_keys(array_diff_key($entity_array, $result_without_inaccessible_fields))
630
+		);
631
+		return apply_filters(
632
+			'FHEE__Read__create_entity_from_wpdb_results__entity_return',
633
+			$result_without_inaccessible_fields,
634
+			$model,
635
+			$rest_request->get_param('caps')
636
+		);
637
+	}
638
+
639
+
640
+	/**
641
+	 * Creates a REST entity array (JSON object we're going to return in the response, but
642
+	 * for now still a PHP array, but soon enough we'll call json_encode on it, don't worry),
643
+	 * from $wpdb->get_row( $sql, ARRAY_A)
644
+	 *
645
+	 * @param EEM_Base $model
646
+	 * @param array    $db_row
647
+	 * @return array entity mostly ready for converting to JSON and sending in the response
648
+	 */
649
+	protected function createBareEntityFromWpdbResults(EEM_Base $model, $db_row)
650
+	{
651
+		$result = $model->deduce_fields_n_values_from_cols_n_values($db_row);
652
+		$result = array_intersect_key(
653
+			$result,
654
+			$this->getModelVersionInfo()->fieldsOnModelInThisVersion($model)
655
+		);
656
+		// if this is a CPT, we need to set the global $post to it,
657
+		// otherwise shortcodes etc won't work properly while rendering it
658
+		if ($model instanceof \EEM_CPT_Base) {
659
+			$do_chevy_shuffle = true;
660
+		} else {
661
+			$do_chevy_shuffle = false;
662
+		}
663
+		if ($do_chevy_shuffle) {
664
+			global $post;
665
+			$old_post = $post;
666
+			$post = get_post($result[ $model->primary_key_name() ]);
667
+			if (! $post instanceof \WP_Post) {
668
+				// well that's weird, because $result is what we JUST fetched from the database
669
+				throw new RestException(
670
+					'error_fetching_post_from_database_results',
671
+					esc_html__(
672
+						'An item was retrieved from the database but it\'s not a WP_Post like it should be.',
673
+						'event_espresso'
674
+					)
675
+				);
676
+			}
677
+			$model_object_classname = 'EE_' . $model->get_this_model_name();
678
+			$post->{$model_object_classname} = \EE_Registry::instance()->load_class(
679
+				$model_object_classname,
680
+				$result,
681
+				false,
682
+				false
683
+			);
684
+		}
685
+		foreach ($result as $field_name => $field_value) {
686
+			$field_obj = $model->field_settings_for($field_name);
687
+			if ($this->isSubclassOfOne($field_obj, $this->getModelVersionInfo()->fieldsIgnored())) {
688
+				unset($result[ $field_name ]);
689
+			} elseif ($this->isSubclassOfOne(
690
+				$field_obj,
691
+				$this->getModelVersionInfo()->fieldsThatHaveRenderedFormat()
692
+			)
693
+			) {
694
+				$result[ $field_name ] = array(
695
+					'raw'      => $this->prepareFieldObjValueForJson($field_obj, $field_value),
696
+					'rendered' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
697
+				);
698
+			} elseif ($this->isSubclassOfOne(
699
+				$field_obj,
700
+				$this->getModelVersionInfo()->fieldsThatHavePrettyFormat()
701
+			)
702
+			) {
703
+				$result[ $field_name ] = array(
704
+					'raw'    => $this->prepareFieldObjValueForJson($field_obj, $field_value),
705
+					'pretty' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
706
+				);
707
+			} elseif ($field_obj instanceof \EE_Datetime_Field) {
708
+				$field_value = $field_obj->prepare_for_set_from_db($field_value);
709
+				// if the value is null, but we're not supposed to permit null, then set to the field's default
710
+				if (is_null($field_value)) {
711
+					$field_value = $field_obj->getDefaultDateTimeObj();
712
+				}
713
+				if (is_null($field_value)) {
714
+					$gmt_date = $local_date = ModelDataTranslator::prepareFieldValuesForJson(
715
+						$field_obj,
716
+						$field_value,
717
+						$this->getModelVersionInfo()->requestedVersion()
718
+					);
719
+				} else {
720
+					$timezone = $field_value->getTimezone();
721
+					EEH_DTT_Helper::setTimezone($field_value, new DateTimeZone('UTC'));
722
+					$gmt_date = ModelDataTranslator::prepareFieldValuesForJson(
723
+						$field_obj,
724
+						$field_value,
725
+						$this->getModelVersionInfo()->requestedVersion()
726
+					);
727
+					EEH_DTT_Helper::setTimezone($field_value, $timezone);
728
+					$local_date = ModelDataTranslator::prepareFieldValuesForJson(
729
+						$field_obj,
730
+						$field_value,
731
+						$this->getModelVersionInfo()->requestedVersion()
732
+					);
733
+				}
734
+				$result[ $field_name . '_gmt' ] = $gmt_date;
735
+				$result[ $field_name ] = $local_date;
736
+			} else {
737
+				$result[ $field_name ] = $this->prepareFieldObjValueForJson($field_obj, $field_value);
738
+			}
739
+		}
740
+		if ($do_chevy_shuffle) {
741
+			$post = $old_post;
742
+		}
743
+		return $result;
744
+	}
745
+
746
+
747
+	/**
748
+	 * Takes a value all the way from the DB representation, to the model object's representation, to the
749
+	 * user-facing PHP representation, to the REST API representation. (Assumes you've already taken from the DB
750
+	 * representation using $field_obj->prepare_for_set_from_db())
751
+	 *
752
+	 * @param EE_Model_Field_Base $field_obj
753
+	 * @param mixed               $value  as it's stored on a model object
754
+	 * @param string              $format valid values are 'normal' (default), 'pretty', 'datetime_obj'
755
+	 * @return mixed
756
+	 * @throws ObjectDetectedException if $value contains a PHP object
757
+	 */
758
+	protected function prepareFieldObjValueForJson(EE_Model_Field_Base $field_obj, $value, $format = 'normal')
759
+	{
760
+		$value = $field_obj->prepare_for_set_from_db($value);
761
+		switch ($format) {
762
+			case 'pretty':
763
+				$value = $field_obj->prepare_for_pretty_echoing($value);
764
+				break;
765
+			case 'normal':
766
+			default:
767
+				$value = $field_obj->prepare_for_get($value);
768
+				break;
769
+		}
770
+		return ModelDataTranslator::prepareFieldValuesForJson(
771
+			$field_obj,
772
+			$value,
773
+			$this->getModelVersionInfo()->requestedVersion()
774
+		);
775
+	}
776
+
777
+
778
+	/**
779
+	 * Adds a few extra fields to the entity response
780
+	 *
781
+	 * @param EEM_Base $model
782
+	 * @param array    $db_row
783
+	 * @param array    $entity_array
784
+	 * @return array modified entity
785
+	 */
786
+	protected function addExtraFields(EEM_Base $model, $db_row, $entity_array)
787
+	{
788
+		if ($model instanceof EEM_CPT_Base) {
789
+			$entity_array['link'] = get_permalink($db_row[ $model->get_primary_key_field()->get_qualified_column() ]);
790
+		}
791
+		return $entity_array;
792
+	}
793
+
794
+
795
+	/**
796
+	 * Gets links we want to add to the response
797
+	 *
798
+	 * @global \WP_REST_Server $wp_rest_server
799
+	 * @param EEM_Base         $model
800
+	 * @param array            $db_row
801
+	 * @param array            $entity_array
802
+	 * @return array the _links item in the entity
803
+	 */
804
+	protected function getEntityLinks($model, $db_row, $entity_array)
805
+	{
806
+		// add basic links
807
+		$links = array();
808
+		if ($model->has_primary_key_field()) {
809
+			$links['self'] = array(
810
+				array(
811
+					'href' => $this->getVersionedLinkTo(
812
+						EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
813
+						. '/'
814
+						. $entity_array[ $model->primary_key_name() ]
815
+					),
816
+				),
817
+			);
818
+		}
819
+		$links['collection'] = array(
820
+			array(
821
+				'href' => $this->getVersionedLinkTo(
822
+					EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
823
+				),
824
+			),
825
+		);
826
+		// add links to related models
827
+		if ($model->has_primary_key_field()) {
828
+			foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) {
829
+				$related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj);
830
+				$links[ EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part ] = array(
831
+					array(
832
+						'href'   => $this->getVersionedLinkTo(
833
+							EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
834
+							. '/'
835
+							. $entity_array[ $model->primary_key_name() ]
836
+							. '/'
837
+							. $related_model_part
838
+						),
839
+						'single' => $relation_obj instanceof EE_Belongs_To_Relation ? true : false,
840
+					),
841
+				);
842
+			}
843
+		}
844
+		return $links;
845
+	}
846
+
847
+
848
+	/**
849
+	 * Adds the included models indicated in the request to the entity provided
850
+	 *
851
+	 * @param EEM_Base        $model
852
+	 * @param WP_REST_Request $rest_request
853
+	 * @param array           $entity_array
854
+	 * @param array           $db_row
855
+	 * @return array the modified entity
856
+	 */
857
+	protected function includeRequestedModels(
858
+		EEM_Base $model,
859
+		WP_REST_Request $rest_request,
860
+		$entity_array,
861
+		$db_row = array()
862
+	) {
863
+		// if $db_row not included, hope the entity array has what we need
864
+		if (! $db_row) {
865
+			$db_row = $entity_array;
866
+		}
867
+		$includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), '');
868
+		$includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model);
869
+		// if they passed in * or didn't specify any includes, return everything
870
+		if (! in_array('*', $includes_for_this_model)
871
+			&& ! empty($includes_for_this_model)
872
+		) {
873
+			if ($model->has_primary_key_field()) {
874
+				// always include the primary key. ya just gotta know that at least
875
+				$includes_for_this_model[] = $model->primary_key_name();
876
+			}
877
+			if ($this->explodeAndGetItemsPrefixedWith($rest_request->get_param('calculate'), '')) {
878
+				$includes_for_this_model[] = '_calculated_fields';
879
+			}
880
+			$entity_array = array_intersect_key($entity_array, array_flip($includes_for_this_model));
881
+		}
882
+		$relation_settings = $this->getModelVersionInfo()->relationSettings($model);
883
+		foreach ($relation_settings as $relation_name => $relation_obj) {
884
+			$related_fields_to_include = $this->explodeAndGetItemsPrefixedWith(
885
+				$rest_request->get_param('include'),
886
+				$relation_name
887
+			);
888
+			$related_fields_to_calculate = $this->explodeAndGetItemsPrefixedWith(
889
+				$rest_request->get_param('calculate'),
890
+				$relation_name
891
+			);
892
+			// did they specify they wanted to include a related model, or
893
+			// specific fields from a related model?
894
+			// or did they specify to calculate a field from a related model?
895
+			if ($related_fields_to_include || $related_fields_to_calculate) {
896
+				// if so, we should include at least some part of the related model
897
+				$pretend_related_request = new WP_REST_Request();
898
+				$pretend_related_request->set_query_params(
899
+					array(
900
+						'caps'      => $rest_request->get_param('caps'),
901
+						'include'   => $related_fields_to_include,
902
+						'calculate' => $related_fields_to_calculate,
903
+					)
904
+				);
905
+				$pretend_related_request->add_header('no_rest_headers', true);
906
+				$primary_model_query_params = $model->alter_query_params_to_restrict_by_ID(
907
+					$model->get_index_primary_key_string(
908
+						$model->deduce_fields_n_values_from_cols_n_values($db_row)
909
+					)
910
+				);
911
+				$related_results = $this->getEntitiesFromRelationUsingModelQueryParams(
912
+					$primary_model_query_params,
913
+					$relation_obj,
914
+					$pretend_related_request
915
+				);
916
+				$entity_array[ Read::getRelatedEntityName($relation_name, $relation_obj) ] = $related_results
917
+																							 instanceof
918
+																							 WP_Error
919
+					? null
920
+					: $related_results;
921
+			}
922
+		}
923
+		return $entity_array;
924
+	}
925
+
926
+
927
+	/**
928
+	 * Returns a new array with all the names of models removed. Eg
929
+	 * array( 'Event', 'Datetime.*', 'foobar' ) would become array( 'Datetime.*', 'foobar' )
930
+	 *
931
+	 * @param array $arr
932
+	 * @return array
933
+	 */
934
+	private function removeModelNamesFromArray($arr)
935
+	{
936
+		return array_diff($arr, array_keys(EE_Registry::instance()->non_abstract_db_models));
937
+	}
938
+
939
+
940
+	/**
941
+	 * Gets the calculated fields for the response
942
+	 *
943
+	 * @param EEM_Base        $model
944
+	 * @param array           $wpdb_row
945
+	 * @param WP_REST_Request $rest_request
946
+	 * @return \stdClass the _calculations item in the entity
947
+	 * @throws ObjectDetectedException if a default value has a PHP object, which should never do (and if we
948
+	 * did, let's know about it ASAP, so let the exception bubble up)
949
+	 */
950
+	protected function getEntityCalculations($model, $wpdb_row, $rest_request)
951
+	{
952
+		$calculated_fields = $this->explodeAndGetItemsPrefixedWith(
953
+			$rest_request->get_param('calculate'),
954
+			''
955
+		);
956
+		// note: setting calculate=* doesn't do anything
957
+		$calculated_fields_to_return = new \stdClass();
958
+		foreach ($calculated_fields as $field_to_calculate) {
959
+			try {
960
+				$calculated_fields_to_return->$field_to_calculate = ModelDataTranslator::prepareFieldValueForJson(
961
+					null,
962
+					$this->fields_calculator->retrieveCalculatedFieldValue(
963
+						$model,
964
+						$field_to_calculate,
965
+						$wpdb_row,
966
+						$rest_request,
967
+						$this
968
+					),
969
+					$this->getModelVersionInfo()->requestedVersion()
970
+				);
971
+			} catch (RestException $e) {
972
+				// if we don't have permission to read it, just leave it out. but let devs know about the problem
973
+				$this->setResponseHeader(
974
+					'Notices-Field-Calculation-Errors['
975
+					. $e->getStringCode()
976
+					. ']['
977
+					. $model->get_this_model_name()
978
+					. ']['
979
+					. $field_to_calculate
980
+					. ']',
981
+					$e->getMessage(),
982
+					true
983
+				);
984
+			}
985
+		}
986
+		return $calculated_fields_to_return;
987
+	}
988
+
989
+
990
+	/**
991
+	 * Gets the full URL to the resource, taking the requested version into account
992
+	 *
993
+	 * @param string $link_part_after_version_and_slash eg "events/10/datetimes"
994
+	 * @return string url eg "http://mysite.com/wp-json/ee/v4.6/events/10/datetimes"
995
+	 */
996
+	public function getVersionedLinkTo($link_part_after_version_and_slash)
997
+	{
998
+		return rest_url(
999
+			EED_Core_Rest_Api::get_versioned_route_to(
1000
+				$link_part_after_version_and_slash,
1001
+				$this->getModelVersionInfo()->requestedVersion()
1002
+			)
1003
+		);
1004
+	}
1005
+
1006
+
1007
+	/**
1008
+	 * Gets the correct lowercase name for the relation in the API according
1009
+	 * to the relation's type
1010
+	 *
1011
+	 * @param string                  $relation_name
1012
+	 * @param \EE_Model_Relation_Base $relation_obj
1013
+	 * @return string
1014
+	 */
1015
+	public static function getRelatedEntityName($relation_name, $relation_obj)
1016
+	{
1017
+		if ($relation_obj instanceof EE_Belongs_To_Relation) {
1018
+			return strtolower($relation_name);
1019
+		} else {
1020
+			return EEH_Inflector::pluralize_and_lower($relation_name);
1021
+		}
1022
+	}
1023
+
1024
+
1025
+	/**
1026
+	 * Gets the one model object with the specified id for the specified model
1027
+	 *
1028
+	 * @param EEM_Base        $model
1029
+	 * @param WP_REST_Request $request
1030
+	 * @return array|WP_Error
1031
+	 */
1032
+	public function getEntityFromModel($model, $request)
1033
+	{
1034
+		$context = $this->validateContext($request->get_param('caps'));
1035
+		return $this->getOneOrReportPermissionError($model, $request, $context);
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * If a context is provided which isn't valid, maybe it was added in a future
1041
+	 * version so just treat it as a default read
1042
+	 *
1043
+	 * @param string $context
1044
+	 * @return string array key of EEM_Base::cap_contexts_to_cap_action_map()
1045
+	 */
1046
+	public function validateContext($context)
1047
+	{
1048
+		if (! $context) {
1049
+			$context = EEM_Base::caps_read;
1050
+		}
1051
+		$valid_contexts = EEM_Base::valid_cap_contexts();
1052
+		if (in_array($context, $valid_contexts)) {
1053
+			return $context;
1054
+		} else {
1055
+			return EEM_Base::caps_read;
1056
+		}
1057
+	}
1058
+
1059
+
1060
+	/**
1061
+	 * Verifies the passed in value is an allowable default where conditions value.
1062
+	 *
1063
+	 * @param $default_query_params
1064
+	 * @return string
1065
+	 */
1066
+	public function validateDefaultQueryParams($default_query_params)
1067
+	{
1068
+		$valid_default_where_conditions_for_api_calls = array(
1069
+			EEM_Base::default_where_conditions_all,
1070
+			EEM_Base::default_where_conditions_minimum_all,
1071
+			EEM_Base::default_where_conditions_minimum_others,
1072
+		);
1073
+		if (! $default_query_params) {
1074
+			$default_query_params = EEM_Base::default_where_conditions_all;
1075
+		}
1076
+		if (in_array(
1077
+			$default_query_params,
1078
+			$valid_default_where_conditions_for_api_calls,
1079
+			true
1080
+		)) {
1081
+			return $default_query_params;
1082
+		} else {
1083
+			return EEM_Base::default_where_conditions_all;
1084
+		}
1085
+	}
1086
+
1087
+
1088
+	/**
1089
+	 * Translates API filter get parameter into $query_params array used by EEM_Base::get_all().
1090
+	 * Note: right now the query parameter keys for fields (and related fields)
1091
+	 * can be left as-is, but it's quite possible this will change someday.
1092
+	 * Also, this method's contents might be candidate for moving to Model_Data_Translator
1093
+	 *
1094
+	 * @param EEM_Base $model
1095
+	 * @param array    $query_parameters  from $_GET parameter @see Read:handle_request_get_all
1096
+	 * @return array like what EEM_Base::get_all() expects or FALSE to indicate
1097
+	 *                                    that absolutely no results should be returned
1098
+	 * @throws EE_Error
1099
+	 * @throws RestException
1100
+	 */
1101
+	public function createModelQueryParams($model, $query_parameters)
1102
+	{
1103
+		$model_query_params = array();
1104
+		if (isset($query_parameters['where'])) {
1105
+			$model_query_params[0] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1106
+				$query_parameters['where'],
1107
+				$model,
1108
+				$this->getModelVersionInfo()->requestedVersion()
1109
+			);
1110
+		}
1111
+		if (isset($query_parameters['order_by'])) {
1112
+			$order_by = $query_parameters['order_by'];
1113
+		} elseif (isset($query_parameters['orderby'])) {
1114
+			$order_by = $query_parameters['orderby'];
1115
+		} else {
1116
+			$order_by = null;
1117
+		}
1118
+		if ($order_by !== null) {
1119
+			if (is_array($order_by)) {
1120
+				$order_by = ModelDataTranslator::prepareFieldNamesInArrayKeysFromJson($order_by);
1121
+			} else {
1122
+				// it's a single item
1123
+				$order_by = ModelDataTranslator::prepareFieldNameFromJson($order_by);
1124
+			}
1125
+			$model_query_params['order_by'] = $order_by;
1126
+		}
1127
+		if (isset($query_parameters['group_by'])) {
1128
+			$group_by = $query_parameters['group_by'];
1129
+		} elseif (isset($query_parameters['groupby'])) {
1130
+			$group_by = $query_parameters['groupby'];
1131
+		} else {
1132
+			$group_by = array_keys($model->get_combined_primary_key_fields());
1133
+		}
1134
+		// make sure they're all real names
1135
+		if (is_array($group_by)) {
1136
+			$group_by = ModelDataTranslator::prepareFieldNamesFromJson($group_by);
1137
+		}
1138
+		if ($group_by !== null) {
1139
+			$model_query_params['group_by'] = $group_by;
1140
+		}
1141
+		if (isset($query_parameters['having'])) {
1142
+			$model_query_params['having'] = ModelDataTranslator::prepareConditionsQueryParamsForModels(
1143
+				$query_parameters['having'],
1144
+				$model,
1145
+				$this->getModelVersionInfo()->requestedVersion()
1146
+			);
1147
+		}
1148
+		if (isset($query_parameters['order'])) {
1149
+			$model_query_params['order'] = $query_parameters['order'];
1150
+		}
1151
+		if (isset($query_parameters['mine'])) {
1152
+			$model_query_params = $model->alter_query_params_to_only_include_mine($model_query_params);
1153
+		}
1154
+		if (isset($query_parameters['limit'])) {
1155
+			// limit should be either a string like '23' or '23,43', or an array with two items in it
1156
+			if (! is_array($query_parameters['limit'])) {
1157
+				$limit_array = explode(',', (string) $query_parameters['limit']);
1158
+			} else {
1159
+				$limit_array = $query_parameters['limit'];
1160
+			}
1161
+			$sanitized_limit = array();
1162
+			foreach ($limit_array as $key => $limit_part) {
1163
+				if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1164
+					throw new EE_Error(
1165
+						sprintf(
1166
+							__(
1167
+							// @codingStandardsIgnoreStart
1168
+								'An invalid limit filter was provided. It was: %s. If the EE4 JSON REST API weren\'t in debug mode, this message would not appear.',
1169
+								// @codingStandardsIgnoreEnd
1170
+								'event_espresso'
1171
+							),
1172
+							wp_json_encode($query_parameters['limit'])
1173
+						)
1174
+					);
1175
+				}
1176
+				$sanitized_limit[] = (int) $limit_part;
1177
+			}
1178
+			$model_query_params['limit'] = implode(',', $sanitized_limit);
1179
+		} else {
1180
+			$model_query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
1181
+		}
1182
+		if (isset($query_parameters['caps'])) {
1183
+			$model_query_params['caps'] = $this->validateContext($query_parameters['caps']);
1184
+		} else {
1185
+			$model_query_params['caps'] = EEM_Base::caps_read;
1186
+		}
1187
+		if (isset($query_parameters['default_where_conditions'])) {
1188
+			$model_query_params['default_where_conditions'] = $this->validateDefaultQueryParams(
1189
+				$query_parameters['default_where_conditions']
1190
+			);
1191
+		}
1192
+		return apply_filters('FHEE__Read__create_model_query_params', $model_query_params, $query_parameters, $model);
1193
+	}
1194
+
1195
+
1196
+	/**
1197
+	 * Changes the REST-style query params for use in the models
1198
+	 *
1199
+	 * @deprecated
1200
+	 * @param EEM_Base $model
1201
+	 * @param array    $query_params sub-array from @see EEM_Base::get_all()
1202
+	 * @return array
1203
+	 */
1204
+	public function prepareRestQueryParamsKeyForModels($model, $query_params)
1205
+	{
1206
+		$model_ready_query_params = array();
1207
+		foreach ($query_params as $key => $value) {
1208
+			if (is_array($value)) {
1209
+				$model_ready_query_params[ $key ] = $this->prepareRestQueryParamsKeyForModels($model, $value);
1210
+			} else {
1211
+				$model_ready_query_params[ $key ] = $value;
1212
+			}
1213
+		}
1214
+		return $model_ready_query_params;
1215
+	}
1216
+
1217
+
1218
+	/**
1219
+	 * @deprecated instead use ModelDataTranslator::prepareFieldValuesFromJson()
1220
+	 * @param $model
1221
+	 * @param $query_params
1222
+	 * @return array
1223
+	 */
1224
+	public function prepareRestQueryParamsValuesForModels($model, $query_params)
1225
+	{
1226
+		$model_ready_query_params = array();
1227
+		foreach ($query_params as $key => $value) {
1228
+			if (is_array($value)) {
1229
+				$model_ready_query_params[ $key ] = $this->prepareRestQueryParamsValuesForModels($model, $value);
1230
+			} else {
1231
+				$model_ready_query_params[ $key ] = $value;
1232
+			}
1233
+		}
1234
+		return $model_ready_query_params;
1235
+	}
1236
+
1237
+
1238
+	/**
1239
+	 * Explodes the string on commas, and only returns items with $prefix followed by a period.
1240
+	 * If no prefix is specified, returns items with no period.
1241
+	 *
1242
+	 * @param string|array $string_to_explode eg "jibba,jabba, blah, blah, blah" or array('jibba', 'jabba' )
1243
+	 * @param string       $prefix            "Event" or "foobar"
1244
+	 * @return array $string_to_exploded exploded on COMMAS, and if a prefix was specified
1245
+	 *                                        we only return strings starting with that and a period; if no prefix was
1246
+	 *                                        specified we return all items containing NO periods
1247
+	 */
1248
+	public function explodeAndGetItemsPrefixedWith($string_to_explode, $prefix)
1249
+	{
1250
+		if (is_string($string_to_explode)) {
1251
+			$exploded_contents = explode(',', $string_to_explode);
1252
+		} elseif (is_array($string_to_explode)) {
1253
+			$exploded_contents = $string_to_explode;
1254
+		} else {
1255
+			$exploded_contents = array();
1256
+		}
1257
+		// if the string was empty, we want an empty array
1258
+		$exploded_contents = array_filter($exploded_contents);
1259
+		$contents_with_prefix = array();
1260
+		foreach ($exploded_contents as $item) {
1261
+			$item = trim($item);
1262
+			// if no prefix was provided, so we look for items with no "." in them
1263
+			if (! $prefix) {
1264
+				// does this item have a period?
1265
+				if (strpos($item, '.') === false) {
1266
+					// if not, then its what we're looking for
1267
+					$contents_with_prefix[] = $item;
1268
+				}
1269
+			} elseif (strpos($item, $prefix . '.') === 0) {
1270
+				// this item has the prefix and a period, grab it
1271
+				$contents_with_prefix[] = substr(
1272
+					$item,
1273
+					strpos($item, $prefix . '.') + strlen($prefix . '.')
1274
+				);
1275
+			} elseif ($item === $prefix) {
1276
+				// this item is JUST the prefix
1277
+				// so let's grab everything after, which is a blank string
1278
+				$contents_with_prefix[] = '';
1279
+			}
1280
+		}
1281
+		return $contents_with_prefix;
1282
+	}
1283
+
1284
+
1285
+	/**
1286
+	 * @deprecated since 4.8.36.rc.001 You should instead use Read::explode_and_get_items_prefixed_with.
1287
+	 * Deprecated because its return values were really quite confusing- sometimes it returned
1288
+	 * an empty array (when the include string was blank or '*') or sometimes it returned
1289
+	 * array('*') (when you provided a model and a model of that kind was found).
1290
+	 * Parses the $include_string so we fetch all the field names relating to THIS model
1291
+	 * (ie have NO period in them), or for the provided model (ie start with the model
1292
+	 * name and then a period).
1293
+	 * @param string $include_string @see Read:handle_request_get_all
1294
+	 * @param string $model_name
1295
+	 * @return array of fields for this model. If $model_name is provided, then
1296
+	 *                               the fields for that model, with the model's name removed from each.
1297
+	 *                               If $include_string was blank or '*' returns an empty array
1298
+	 */
1299
+	public function extractIncludesForThisModel($include_string, $model_name = null)
1300
+	{
1301
+		if (is_array($include_string)) {
1302
+			$include_string = implode(',', $include_string);
1303
+		}
1304
+		if ($include_string === '*' || $include_string === '') {
1305
+			return array();
1306
+		}
1307
+		$includes = explode(',', $include_string);
1308
+		$extracted_fields_to_include = array();
1309
+		if ($model_name) {
1310
+			foreach ($includes as $field_to_include) {
1311
+				$field_to_include = trim($field_to_include);
1312
+				if (strpos($field_to_include, $model_name . '.') === 0) {
1313
+					// found the model name at the exact start
1314
+					$field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1315
+					$extracted_fields_to_include[] = $field_sans_model_name;
1316
+				} elseif ($field_to_include == $model_name) {
1317
+					$extracted_fields_to_include[] = '*';
1318
+				}
1319
+			}
1320
+		} else {
1321
+			// look for ones with no period
1322
+			foreach ($includes as $field_to_include) {
1323
+				$field_to_include = trim($field_to_include);
1324
+				if (strpos($field_to_include, '.') === false
1325
+					&& ! $this->getModelVersionInfo()->isModelNameInThisVersion($field_to_include)
1326
+				) {
1327
+					$extracted_fields_to_include[] = $field_to_include;
1328
+				}
1329
+			}
1330
+		}
1331
+		return $extracted_fields_to_include;
1332
+	}
1333
+
1334
+
1335
+	/**
1336
+	 * Gets the single item using the model according to the request in the context given, otherwise
1337
+	 * returns that it's inaccessible to the current user
1338
+	 *
1339
+	 * @param EEM_Base        $model
1340
+	 * @param WP_REST_Request $request
1341
+	 * @param null            $context
1342
+	 * @return array|WP_Error
1343
+	 */
1344
+	public function getOneOrReportPermissionError(EEM_Base $model, WP_REST_Request $request, $context = null)
1345
+	{
1346
+		$query_params = array(array($model->primary_key_name() => $request->get_param('id')), 'limit' => 1);
1347
+		if ($model instanceof \EEM_Soft_Delete_Base) {
1348
+			$query_params = $model->alter_query_params_so_deleted_and_undeleted_items_included($query_params);
1349
+		}
1350
+		$restricted_query_params = $query_params;
1351
+		$restricted_query_params['caps'] = $context;
1352
+		$this->setDebugInfo('model query params', $restricted_query_params);
1353
+		$model_rows = $model->get_all_wpdb_results($restricted_query_params);
1354
+		if (! empty($model_rows)) {
1355
+			return $this->createEntityFromWpdbResult(
1356
+				$model,
1357
+				array_shift($model_rows),
1358
+				$request
1359
+			);
1360
+		} else {
1361
+			// ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
1362
+			$lowercase_model_name = strtolower($model->get_this_model_name());
1363
+			$model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
1364
+			if (! empty($model_rows_found_sans_restrictions)) {
1365
+				// you got shafted- it existed but we didn't want to tell you!
1366
+				return new WP_Error(
1367
+					'rest_user_cannot_' . $context,
1368
+					sprintf(
1369
+						__('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'),
1370
+						$context,
1371
+						strtolower($model->get_this_model_name()),
1372
+						Capabilities::getMissingPermissionsString(
1373
+							$model,
1374
+							$context
1375
+						)
1376
+					),
1377
+					array('status' => 403)
1378
+				);
1379
+			} else {
1380
+				// it's not you. It just doesn't exist
1381
+				return new WP_Error(
1382
+					sprintf('rest_%s_invalid_id', $lowercase_model_name),
1383
+					sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
1384
+					array('status' => 404)
1385
+				);
1386
+			}
1387
+		}
1388
+	}
1389 1389
 }
Please login to merge, or discard this patch.
Spacing   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
         $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
74 74
         try {
75 75
             $controller->setRequestedVersion($version);
76
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
76
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
77 77
                 return $controller->sendResponse(
78 78
                     new WP_Error(
79 79
                         'endpoint_parsing_error',
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
         $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
115 115
         try {
116 116
             $controller->setRequestedVersion($version);
117
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
117
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
118 118
                 return array();
119 119
             }
120 120
             // get the model for this version
@@ -171,11 +171,11 @@  discard block
 block discarded – undo
171 171
      */
172 172
     protected function translateDefaultsForRestResponse($field_name, EE_Model_Field_Base $field, array $schema)
173 173
     {
174
-        if (isset($schema['properties'][ $field_name ]['default'])) {
175
-            if (is_array($schema['properties'][ $field_name ]['default'])) {
176
-                foreach ($schema['properties'][ $field_name ]['default'] as $default_key => $default_value) {
174
+        if (isset($schema['properties'][$field_name]['default'])) {
175
+            if (is_array($schema['properties'][$field_name]['default'])) {
176
+                foreach ($schema['properties'][$field_name]['default'] as $default_key => $default_value) {
177 177
                     if ($default_key === 'raw') {
178
-                        $schema['properties'][ $field_name ]['default'][ $default_key ] =
178
+                        $schema['properties'][$field_name]['default'][$default_key] =
179 179
                             ModelDataTranslator::prepareFieldValueForJson(
180 180
                                 $field,
181 181
                                 $default_value,
@@ -184,9 +184,9 @@  discard block
 block discarded – undo
184 184
                     }
185 185
                 }
186 186
             } else {
187
-                $schema['properties'][ $field_name ]['default'] = ModelDataTranslator::prepareFieldValueForJson(
187
+                $schema['properties'][$field_name]['default'] = ModelDataTranslator::prepareFieldValueForJson(
188 188
                     $field,
189
-                    $schema['properties'][ $field_name ]['default'],
189
+                    $schema['properties'][$field_name]['default'],
190 190
                     $this->getModelVersionInfo()->requestedVersion()
191 191
                 );
192 192
             }
@@ -208,9 +208,9 @@  discard block
 block discarded – undo
208 208
     protected function maybeAddExtraFieldsToSchema($field_name, EE_Model_Field_Base $field, array $schema)
209 209
     {
210 210
         if ($field instanceof EE_Datetime_Field) {
211
-            $schema['properties'][ $field_name . '_gmt' ] = $field->getSchema();
211
+            $schema['properties'][$field_name.'_gmt'] = $field->getSchema();
212 212
             // modify the description
213
-            $schema['properties'][ $field_name . '_gmt' ]['description'] = sprintf(
213
+            $schema['properties'][$field_name.'_gmt']['description'] = sprintf(
214 214
                 esc_html__('%s - the value for this field is in GMT.', 'event_espresso'),
215 215
                 wp_specialchars_decode($field->get_nicename(), ENT_QUOTES)
216 216
             );
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
         $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
254 254
         try {
255 255
             $controller->setRequestedVersion($version);
256
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
256
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
257 257
                 return $controller->sendResponse(
258 258
                     new WP_Error(
259 259
                         'endpoint_parsing_error',
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
         $controller = LoaderFactory::getLoader()->getNew('EventEspresso\core\libraries\rest_api\controllers\model\Read');
302 302
         try {
303 303
             $controller->setRequestedVersion($version);
304
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
304
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($model_name)) {
305 305
                 return $controller->sendResponse(
306 306
                     new WP_Error(
307 307
                         'endpoint_parsing_error',
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
                 );
317 317
             }
318 318
             $main_model = $controller->getModelVersionInfo()->loadModel($model_name);
319
-            if (! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
319
+            if ( ! $controller->getModelVersionInfo()->isModelNameInThisVersion($related_model_name)) {
320 320
                 return $controller->sendResponse(
321 321
                     new WP_Error(
322 322
                         'endpoint_parsing_error',
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
     public function getEntitiesFromModel($model, $request)
354 354
     {
355 355
         $query_params = $this->createModelQueryParams($model, $request->get_params());
356
-        if (! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
356
+        if ( ! Capabilities::currentUserHasPartialAccessTo($model, $query_params['caps'])) {
357 357
             $model_name_plural = EEH_Inflector::pluralize_and_lower($model->get_this_model_name());
358 358
             return new WP_Error(
359 359
                 sprintf('rest_%s_cannot_list', $model_name_plural),
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
                 array('status' => 403)
366 366
             );
367 367
         }
368
-        if (! $request->get_header('no_rest_headers')) {
368
+        if ( ! $request->get_header('no_rest_headers')) {
369 369
             $this->setHeadersFromQueryParams($model, $query_params);
370 370
         }
371 371
         /** @type array $results */
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
         $context = $this->validateContext($request->get_param('caps'));
401 401
         $model = $relation->get_this_model();
402 402
         $related_model = $relation->get_other_model();
403
-        if (! isset($primary_model_query_params[0])) {
403
+        if ( ! isset($primary_model_query_params[0])) {
404 404
             $primary_model_query_params[0] = array();
405 405
         }
406 406
         // check if they can access the 1st model object
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
         $restricted_query_params['caps'] = $context;
418 418
         $this->setDebugInfo('main model query params', $restricted_query_params);
419 419
         $this->setDebugInfo('missing caps', Capabilities::getMissingPermissionsString($related_model, $context));
420
-        if (! (
420
+        if ( ! (
421 421
             Capabilities::currentUserHasPartialAccessTo($related_model, $context)
422 422
             && $model->exists($restricted_query_params)
423 423
         )
@@ -450,13 +450,13 @@  discard block
 block discarded – undo
450 450
         }
451 451
         $query_params = $this->createModelQueryParams($relation->get_other_model(), $request->get_params());
452 452
         foreach ($primary_model_query_params[0] as $where_condition_key => $where_condition_value) {
453
-            $query_params[0][ $relation->get_this_model()->get_this_model_name()
453
+            $query_params[0][$relation->get_this_model()->get_this_model_name()
454 454
                               . '.'
455
-                              . $where_condition_key ] = $where_condition_value;
455
+                              . $where_condition_key] = $where_condition_value;
456 456
         }
457 457
         $query_params['default_where_conditions'] = 'none';
458 458
         $query_params['caps'] = $context;
459
-        if (! $request->get_header('no_rest_headers')) {
459
+        if ( ! $request->get_header('no_rest_headers')) {
460 460
             $this->setHeadersFromQueryParams($relation->get_other_model(), $query_params);
461 461
         }
462 462
         /** @type array $results */
@@ -507,7 +507,7 @@  discard block
 block discarded – undo
507 507
      */
508 508
     public function getEntitiesFromRelation($id, $relation, $request)
509 509
     {
510
-        if (! $relation->get_this_model()->has_primary_key_field()) {
510
+        if ( ! $relation->get_this_model()->has_primary_key_field()) {
511 511
             throw new EE_Error(
512 512
                 sprintf(
513 513
                     __(
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
             Capabilities::getMissingPermissionsString($model, $query_params['caps'])
550 550
         );
551 551
         // normally the limit to a 2-part array, where the 2nd item is the limit
552
-        if (! isset($query_params['limit'])) {
552
+        if ( ! isset($query_params['limit'])) {
553 553
             $query_params['limit'] = EED_Core_Rest_Api::get_default_query_limit();
554 554
         }
555 555
         if (is_array($query_params['limit'])) {
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
      */
583 583
     public function createEntityFromWpdbResult($model, $db_row, $rest_request, $deprecated = null)
584 584
     {
585
-        if (! $rest_request instanceof WP_REST_Request) {
585
+        if ( ! $rest_request instanceof WP_REST_Request) {
586 586
             // ok so this was called in the old style, where the 3rd arg was
587 587
             // $include, and the 4th arg was $context
588 588
             // now setup the request just to avoid fatal errors, although we won't be able
@@ -663,8 +663,8 @@  discard block
 block discarded – undo
663 663
         if ($do_chevy_shuffle) {
664 664
             global $post;
665 665
             $old_post = $post;
666
-            $post = get_post($result[ $model->primary_key_name() ]);
667
-            if (! $post instanceof \WP_Post) {
666
+            $post = get_post($result[$model->primary_key_name()]);
667
+            if ( ! $post instanceof \WP_Post) {
668 668
                 // well that's weird, because $result is what we JUST fetched from the database
669 669
                 throw new RestException(
670 670
                     'error_fetching_post_from_database_results',
@@ -674,7 +674,7 @@  discard block
 block discarded – undo
674 674
                     )
675 675
                 );
676 676
             }
677
-            $model_object_classname = 'EE_' . $model->get_this_model_name();
677
+            $model_object_classname = 'EE_'.$model->get_this_model_name();
678 678
             $post->{$model_object_classname} = \EE_Registry::instance()->load_class(
679 679
                 $model_object_classname,
680 680
                 $result,
@@ -685,13 +685,13 @@  discard block
 block discarded – undo
685 685
         foreach ($result as $field_name => $field_value) {
686 686
             $field_obj = $model->field_settings_for($field_name);
687 687
             if ($this->isSubclassOfOne($field_obj, $this->getModelVersionInfo()->fieldsIgnored())) {
688
-                unset($result[ $field_name ]);
688
+                unset($result[$field_name]);
689 689
             } elseif ($this->isSubclassOfOne(
690 690
                 $field_obj,
691 691
                 $this->getModelVersionInfo()->fieldsThatHaveRenderedFormat()
692 692
             )
693 693
             ) {
694
-                $result[ $field_name ] = array(
694
+                $result[$field_name] = array(
695 695
                     'raw'      => $this->prepareFieldObjValueForJson($field_obj, $field_value),
696 696
                     'rendered' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
697 697
                 );
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
                 $this->getModelVersionInfo()->fieldsThatHavePrettyFormat()
701 701
             )
702 702
             ) {
703
-                $result[ $field_name ] = array(
703
+                $result[$field_name] = array(
704 704
                     'raw'    => $this->prepareFieldObjValueForJson($field_obj, $field_value),
705 705
                     'pretty' => $this->prepareFieldObjValueForJson($field_obj, $field_value, 'pretty'),
706 706
                 );
@@ -731,10 +731,10 @@  discard block
 block discarded – undo
731 731
                         $this->getModelVersionInfo()->requestedVersion()
732 732
                     );
733 733
                 }
734
-                $result[ $field_name . '_gmt' ] = $gmt_date;
735
-                $result[ $field_name ] = $local_date;
734
+                $result[$field_name.'_gmt'] = $gmt_date;
735
+                $result[$field_name] = $local_date;
736 736
             } else {
737
-                $result[ $field_name ] = $this->prepareFieldObjValueForJson($field_obj, $field_value);
737
+                $result[$field_name] = $this->prepareFieldObjValueForJson($field_obj, $field_value);
738 738
             }
739 739
         }
740 740
         if ($do_chevy_shuffle) {
@@ -786,7 +786,7 @@  discard block
 block discarded – undo
786 786
     protected function addExtraFields(EEM_Base $model, $db_row, $entity_array)
787 787
     {
788 788
         if ($model instanceof EEM_CPT_Base) {
789
-            $entity_array['link'] = get_permalink($db_row[ $model->get_primary_key_field()->get_qualified_column() ]);
789
+            $entity_array['link'] = get_permalink($db_row[$model->get_primary_key_field()->get_qualified_column()]);
790 790
         }
791 791
         return $entity_array;
792 792
     }
@@ -811,7 +811,7 @@  discard block
 block discarded – undo
811 811
                     'href' => $this->getVersionedLinkTo(
812 812
                         EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
813 813
                         . '/'
814
-                        . $entity_array[ $model->primary_key_name() ]
814
+                        . $entity_array[$model->primary_key_name()]
815 815
                     ),
816 816
                 ),
817 817
             );
@@ -827,12 +827,12 @@  discard block
 block discarded – undo
827 827
         if ($model->has_primary_key_field()) {
828 828
             foreach ($this->getModelVersionInfo()->relationSettings($model) as $relation_name => $relation_obj) {
829 829
                 $related_model_part = Read::getRelatedEntityName($relation_name, $relation_obj);
830
-                $links[ EED_Core_Rest_Api::ee_api_link_namespace . $related_model_part ] = array(
830
+                $links[EED_Core_Rest_Api::ee_api_link_namespace.$related_model_part] = array(
831 831
                     array(
832 832
                         'href'   => $this->getVersionedLinkTo(
833 833
                             EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
834 834
                             . '/'
835
-                            . $entity_array[ $model->primary_key_name() ]
835
+                            . $entity_array[$model->primary_key_name()]
836 836
                             . '/'
837 837
                             . $related_model_part
838 838
                         ),
@@ -861,13 +861,13 @@  discard block
 block discarded – undo
861 861
         $db_row = array()
862 862
     ) {
863 863
         // if $db_row not included, hope the entity array has what we need
864
-        if (! $db_row) {
864
+        if ( ! $db_row) {
865 865
             $db_row = $entity_array;
866 866
         }
867 867
         $includes_for_this_model = $this->explodeAndGetItemsPrefixedWith($rest_request->get_param('include'), '');
868 868
         $includes_for_this_model = $this->removeModelNamesFromArray($includes_for_this_model);
869 869
         // if they passed in * or didn't specify any includes, return everything
870
-        if (! in_array('*', $includes_for_this_model)
870
+        if ( ! in_array('*', $includes_for_this_model)
871 871
             && ! empty($includes_for_this_model)
872 872
         ) {
873 873
             if ($model->has_primary_key_field()) {
@@ -913,7 +913,7 @@  discard block
 block discarded – undo
913 913
                     $relation_obj,
914 914
                     $pretend_related_request
915 915
                 );
916
-                $entity_array[ Read::getRelatedEntityName($relation_name, $relation_obj) ] = $related_results
916
+                $entity_array[Read::getRelatedEntityName($relation_name, $relation_obj)] = $related_results
917 917
                                                                                              instanceof
918 918
                                                                                              WP_Error
919 919
                     ? null
@@ -1045,7 +1045,7 @@  discard block
 block discarded – undo
1045 1045
      */
1046 1046
     public function validateContext($context)
1047 1047
     {
1048
-        if (! $context) {
1048
+        if ( ! $context) {
1049 1049
             $context = EEM_Base::caps_read;
1050 1050
         }
1051 1051
         $valid_contexts = EEM_Base::valid_cap_contexts();
@@ -1070,7 +1070,7 @@  discard block
 block discarded – undo
1070 1070
             EEM_Base::default_where_conditions_minimum_all,
1071 1071
             EEM_Base::default_where_conditions_minimum_others,
1072 1072
         );
1073
-        if (! $default_query_params) {
1073
+        if ( ! $default_query_params) {
1074 1074
             $default_query_params = EEM_Base::default_where_conditions_all;
1075 1075
         }
1076 1076
         if (in_array(
@@ -1153,14 +1153,14 @@  discard block
 block discarded – undo
1153 1153
         }
1154 1154
         if (isset($query_parameters['limit'])) {
1155 1155
             // limit should be either a string like '23' or '23,43', or an array with two items in it
1156
-            if (! is_array($query_parameters['limit'])) {
1156
+            if ( ! is_array($query_parameters['limit'])) {
1157 1157
                 $limit_array = explode(',', (string) $query_parameters['limit']);
1158 1158
             } else {
1159 1159
                 $limit_array = $query_parameters['limit'];
1160 1160
             }
1161 1161
             $sanitized_limit = array();
1162 1162
             foreach ($limit_array as $key => $limit_part) {
1163
-                if ($this->debug_mode && (! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1163
+                if ($this->debug_mode && ( ! is_numeric($limit_part) || count($sanitized_limit) > 2)) {
1164 1164
                     throw new EE_Error(
1165 1165
                         sprintf(
1166 1166
                             __(
@@ -1206,9 +1206,9 @@  discard block
 block discarded – undo
1206 1206
         $model_ready_query_params = array();
1207 1207
         foreach ($query_params as $key => $value) {
1208 1208
             if (is_array($value)) {
1209
-                $model_ready_query_params[ $key ] = $this->prepareRestQueryParamsKeyForModels($model, $value);
1209
+                $model_ready_query_params[$key] = $this->prepareRestQueryParamsKeyForModels($model, $value);
1210 1210
             } else {
1211
-                $model_ready_query_params[ $key ] = $value;
1211
+                $model_ready_query_params[$key] = $value;
1212 1212
             }
1213 1213
         }
1214 1214
         return $model_ready_query_params;
@@ -1226,9 +1226,9 @@  discard block
 block discarded – undo
1226 1226
         $model_ready_query_params = array();
1227 1227
         foreach ($query_params as $key => $value) {
1228 1228
             if (is_array($value)) {
1229
-                $model_ready_query_params[ $key ] = $this->prepareRestQueryParamsValuesForModels($model, $value);
1229
+                $model_ready_query_params[$key] = $this->prepareRestQueryParamsValuesForModels($model, $value);
1230 1230
             } else {
1231
-                $model_ready_query_params[ $key ] = $value;
1231
+                $model_ready_query_params[$key] = $value;
1232 1232
             }
1233 1233
         }
1234 1234
         return $model_ready_query_params;
@@ -1260,17 +1260,17 @@  discard block
 block discarded – undo
1260 1260
         foreach ($exploded_contents as $item) {
1261 1261
             $item = trim($item);
1262 1262
             // if no prefix was provided, so we look for items with no "." in them
1263
-            if (! $prefix) {
1263
+            if ( ! $prefix) {
1264 1264
                 // does this item have a period?
1265 1265
                 if (strpos($item, '.') === false) {
1266 1266
                     // if not, then its what we're looking for
1267 1267
                     $contents_with_prefix[] = $item;
1268 1268
                 }
1269
-            } elseif (strpos($item, $prefix . '.') === 0) {
1269
+            } elseif (strpos($item, $prefix.'.') === 0) {
1270 1270
                 // this item has the prefix and a period, grab it
1271 1271
                 $contents_with_prefix[] = substr(
1272 1272
                     $item,
1273
-                    strpos($item, $prefix . '.') + strlen($prefix . '.')
1273
+                    strpos($item, $prefix.'.') + strlen($prefix.'.')
1274 1274
                 );
1275 1275
             } elseif ($item === $prefix) {
1276 1276
                 // this item is JUST the prefix
@@ -1309,9 +1309,9 @@  discard block
 block discarded – undo
1309 1309
         if ($model_name) {
1310 1310
             foreach ($includes as $field_to_include) {
1311 1311
                 $field_to_include = trim($field_to_include);
1312
-                if (strpos($field_to_include, $model_name . '.') === 0) {
1312
+                if (strpos($field_to_include, $model_name.'.') === 0) {
1313 1313
                     // found the model name at the exact start
1314
-                    $field_sans_model_name = str_replace($model_name . '.', '', $field_to_include);
1314
+                    $field_sans_model_name = str_replace($model_name.'.', '', $field_to_include);
1315 1315
                     $extracted_fields_to_include[] = $field_sans_model_name;
1316 1316
                 } elseif ($field_to_include == $model_name) {
1317 1317
                     $extracted_fields_to_include[] = '*';
@@ -1351,7 +1351,7 @@  discard block
 block discarded – undo
1351 1351
         $restricted_query_params['caps'] = $context;
1352 1352
         $this->setDebugInfo('model query params', $restricted_query_params);
1353 1353
         $model_rows = $model->get_all_wpdb_results($restricted_query_params);
1354
-        if (! empty($model_rows)) {
1354
+        if ( ! empty($model_rows)) {
1355 1355
             return $this->createEntityFromWpdbResult(
1356 1356
                 $model,
1357 1357
                 array_shift($model_rows),
@@ -1361,10 +1361,10 @@  discard block
 block discarded – undo
1361 1361
             // ok let's test to see if we WOULD have found it, had we not had restrictions from missing capabilities
1362 1362
             $lowercase_model_name = strtolower($model->get_this_model_name());
1363 1363
             $model_rows_found_sans_restrictions = $model->get_all_wpdb_results($query_params);
1364
-            if (! empty($model_rows_found_sans_restrictions)) {
1364
+            if ( ! empty($model_rows_found_sans_restrictions)) {
1365 1365
                 // you got shafted- it existed but we didn't want to tell you!
1366 1366
                 return new WP_Error(
1367
-                    'rest_user_cannot_' . $context,
1367
+                    'rest_user_cannot_'.$context,
1368 1368
                     sprintf(
1369 1369
                         __('Sorry, you cannot %1$s this %2$s. Missing permissions are: %3$s', 'event_espresso'),
1370 1370
                         $context,
Please login to merge, or discard this patch.
core/Psr4Autoloader.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
      * Loads the class file for a given class name.
121 121
      *
122 122
      * @param string $class The fully-qualified class name.
123
-     * @return mixed The mapped file name on success, or boolean false on
123
+     * @return string|false The mapped file name on success, or boolean false on
124 124
      *                      failure.
125 125
      */
126 126
     public function loadClass($class)
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
      *
154 154
      * @param string $prefix         The namespace prefix.
155 155
      * @param string $relative_class The relative class name.
156
-     * @return mixed Boolean false if no mapped file can be loaded, or the
156
+     * @return string|false Boolean false if no mapped file can be loaded, or the
157 157
      *                               name of the mapped file that was loaded.
158 158
      */
159 159
     protected function loadMappedFile($prefix, $relative_class)
Please login to merge, or discard this patch.
Indentation   +146 added lines, -146 removed lines patch added patch discarded remove patch
@@ -45,150 +45,150 @@
 block discarded – undo
45 45
 class Psr4Autoloader
46 46
 {
47 47
 
48
-    /**
49
-     * namespace separator
50
-     */
51
-    const NS = '\\';
52
-
53
-    /**
54
-     * An associative array where the key is a namespace prefix and the value
55
-     * is an array of base directories for classes in that namespace.
56
-     *
57
-     * @var array
58
-     */
59
-    protected $prefixes = array();
60
-
61
-
62
-    /**
63
-     * returns an array of registered namespace prefixes
64
-     *
65
-     * @param string $prefix
66
-     * @return array
67
-     */
68
-    public function prefixes($prefix = '')
69
-    {
70
-        if (! empty($prefix)) {
71
-            // are there any base directories for this namespace prefix?
72
-            return isset($this->prefixes[ $prefix ]) ? $this->prefixes[ $prefix ] : array();
73
-        }
74
-        return $this->prefixes;
75
-    }
76
-
77
-
78
-    /**
79
-     * Register loader with SPL autoloader stack.
80
-     *
81
-     * @return void
82
-     */
83
-    public function register()
84
-    {
85
-        spl_autoload_register(array($this, 'loadClass'));
86
-    }
87
-
88
-
89
-    /**
90
-     * Adds a base directory for a namespace prefix.
91
-     *
92
-     * @param string $prefix   The namespace prefix.
93
-     * @param string $base_dir A base directory for class files in the
94
-     *                         namespace.
95
-     * @param bool   $prepend  If true, prepend the base directory to the stack
96
-     *                         instead of appending it; this causes it to be searched first rather
97
-     *                         than last.
98
-     * @return void
99
-     */
100
-    public function addNamespace($prefix, $base_dir, $prepend = false)
101
-    {
102
-        // normalize namespace prefix
103
-        $prefix = trim($prefix, Psr4Autoloader::NS) . Psr4Autoloader::NS;
104
-        // normalize the base directory with a trailing separator
105
-        $base_dir = \EEH_File::standardise_and_end_with_directory_separator($base_dir);
106
-        // initialize the namespace prefix array
107
-        if (isset($this->prefixes[ $prefix ]) === false) {
108
-            $this->prefixes[ $prefix ] = array();
109
-        }
110
-        // retain the base directory for the namespace prefix
111
-        if ($prepend) {
112
-            array_unshift($this->prefixes[ $prefix ], $base_dir);
113
-        } else {
114
-            $this->prefixes[ $prefix ][] = $base_dir;
115
-        }
116
-    }
117
-
118
-
119
-    /**
120
-     * Loads the class file for a given class name.
121
-     *
122
-     * @param string $class The fully-qualified class name.
123
-     * @return mixed The mapped file name on success, or boolean false on
124
-     *                      failure.
125
-     */
126
-    public function loadClass($class)
127
-    {
128
-        // the current namespace prefix
129
-        $prefix = $class;
130
-        // work backwards through the namespace names of the fully-qualified
131
-        // class name to find a mapped file name
132
-        while (false !== $pos = strrpos($prefix, Psr4Autoloader::NS)) {
133
-            // retain the trailing namespace separator in the prefix
134
-            $prefix = substr($class, 0, $pos + 1);
135
-            // the rest is the relative class name
136
-            $relative_class = substr($class, $pos + 1);
137
-            // try to load a mapped file for the prefix and relative class
138
-            $mapped_file = $this->loadMappedFile($prefix, $relative_class);
139
-            if ($mapped_file) {
140
-                return $mapped_file;
141
-            }
142
-            // remove the trailing namespace separator for the next iteration
143
-            // of strrpos()
144
-            $prefix = rtrim($prefix, Psr4Autoloader::NS);
145
-        }
146
-        // never found a mapped file
147
-        return false;
148
-    }
149
-
150
-
151
-    /**
152
-     * Load the mapped file for a namespace prefix and relative class.
153
-     *
154
-     * @param string $prefix         The namespace prefix.
155
-     * @param string $relative_class The relative class name.
156
-     * @return mixed Boolean false if no mapped file can be loaded, or the
157
-     *                               name of the mapped file that was loaded.
158
-     */
159
-    protected function loadMappedFile($prefix, $relative_class)
160
-    {
161
-        // look through base directories for this namespace prefix
162
-        foreach ($this->prefixes($prefix) as $base_dir) {
163
-            // replace the namespace prefix with the base directory,
164
-            // replace namespace separators with directory separators
165
-            // in the relative class name, append with .php
166
-            $file = $base_dir
167
-                    . str_replace(Psr4Autoloader::NS, DS, $relative_class)
168
-                    . '.php';
169
-            // if the mapped file exists, require it
170
-            if ($this->requireFile($file)) {
171
-                // yes, we're done
172
-                return $file;
173
-            }
174
-        }
175
-        // never found it
176
-        return false;
177
-    }
178
-
179
-
180
-    /**
181
-     * If a file exists, require it from the file system.
182
-     *
183
-     * @param string $file The file to require.
184
-     * @return bool True if the file exists, false if not.
185
-     */
186
-    protected function requireFile($file)
187
-    {
188
-        if (file_exists($file)) {
189
-            require $file;
190
-            return true;
191
-        }
192
-        return false;
193
-    }
48
+	/**
49
+	 * namespace separator
50
+	 */
51
+	const NS = '\\';
52
+
53
+	/**
54
+	 * An associative array where the key is a namespace prefix and the value
55
+	 * is an array of base directories for classes in that namespace.
56
+	 *
57
+	 * @var array
58
+	 */
59
+	protected $prefixes = array();
60
+
61
+
62
+	/**
63
+	 * returns an array of registered namespace prefixes
64
+	 *
65
+	 * @param string $prefix
66
+	 * @return array
67
+	 */
68
+	public function prefixes($prefix = '')
69
+	{
70
+		if (! empty($prefix)) {
71
+			// are there any base directories for this namespace prefix?
72
+			return isset($this->prefixes[ $prefix ]) ? $this->prefixes[ $prefix ] : array();
73
+		}
74
+		return $this->prefixes;
75
+	}
76
+
77
+
78
+	/**
79
+	 * Register loader with SPL autoloader stack.
80
+	 *
81
+	 * @return void
82
+	 */
83
+	public function register()
84
+	{
85
+		spl_autoload_register(array($this, 'loadClass'));
86
+	}
87
+
88
+
89
+	/**
90
+	 * Adds a base directory for a namespace prefix.
91
+	 *
92
+	 * @param string $prefix   The namespace prefix.
93
+	 * @param string $base_dir A base directory for class files in the
94
+	 *                         namespace.
95
+	 * @param bool   $prepend  If true, prepend the base directory to the stack
96
+	 *                         instead of appending it; this causes it to be searched first rather
97
+	 *                         than last.
98
+	 * @return void
99
+	 */
100
+	public function addNamespace($prefix, $base_dir, $prepend = false)
101
+	{
102
+		// normalize namespace prefix
103
+		$prefix = trim($prefix, Psr4Autoloader::NS) . Psr4Autoloader::NS;
104
+		// normalize the base directory with a trailing separator
105
+		$base_dir = \EEH_File::standardise_and_end_with_directory_separator($base_dir);
106
+		// initialize the namespace prefix array
107
+		if (isset($this->prefixes[ $prefix ]) === false) {
108
+			$this->prefixes[ $prefix ] = array();
109
+		}
110
+		// retain the base directory for the namespace prefix
111
+		if ($prepend) {
112
+			array_unshift($this->prefixes[ $prefix ], $base_dir);
113
+		} else {
114
+			$this->prefixes[ $prefix ][] = $base_dir;
115
+		}
116
+	}
117
+
118
+
119
+	/**
120
+	 * Loads the class file for a given class name.
121
+	 *
122
+	 * @param string $class The fully-qualified class name.
123
+	 * @return mixed The mapped file name on success, or boolean false on
124
+	 *                      failure.
125
+	 */
126
+	public function loadClass($class)
127
+	{
128
+		// the current namespace prefix
129
+		$prefix = $class;
130
+		// work backwards through the namespace names of the fully-qualified
131
+		// class name to find a mapped file name
132
+		while (false !== $pos = strrpos($prefix, Psr4Autoloader::NS)) {
133
+			// retain the trailing namespace separator in the prefix
134
+			$prefix = substr($class, 0, $pos + 1);
135
+			// the rest is the relative class name
136
+			$relative_class = substr($class, $pos + 1);
137
+			// try to load a mapped file for the prefix and relative class
138
+			$mapped_file = $this->loadMappedFile($prefix, $relative_class);
139
+			if ($mapped_file) {
140
+				return $mapped_file;
141
+			}
142
+			// remove the trailing namespace separator for the next iteration
143
+			// of strrpos()
144
+			$prefix = rtrim($prefix, Psr4Autoloader::NS);
145
+		}
146
+		// never found a mapped file
147
+		return false;
148
+	}
149
+
150
+
151
+	/**
152
+	 * Load the mapped file for a namespace prefix and relative class.
153
+	 *
154
+	 * @param string $prefix         The namespace prefix.
155
+	 * @param string $relative_class The relative class name.
156
+	 * @return mixed Boolean false if no mapped file can be loaded, or the
157
+	 *                               name of the mapped file that was loaded.
158
+	 */
159
+	protected function loadMappedFile($prefix, $relative_class)
160
+	{
161
+		// look through base directories for this namespace prefix
162
+		foreach ($this->prefixes($prefix) as $base_dir) {
163
+			// replace the namespace prefix with the base directory,
164
+			// replace namespace separators with directory separators
165
+			// in the relative class name, append with .php
166
+			$file = $base_dir
167
+					. str_replace(Psr4Autoloader::NS, DS, $relative_class)
168
+					. '.php';
169
+			// if the mapped file exists, require it
170
+			if ($this->requireFile($file)) {
171
+				// yes, we're done
172
+				return $file;
173
+			}
174
+		}
175
+		// never found it
176
+		return false;
177
+	}
178
+
179
+
180
+	/**
181
+	 * If a file exists, require it from the file system.
182
+	 *
183
+	 * @param string $file The file to require.
184
+	 * @return bool True if the file exists, false if not.
185
+	 */
186
+	protected function requireFile($file)
187
+	{
188
+		if (file_exists($file)) {
189
+			require $file;
190
+			return true;
191
+		}
192
+		return false;
193
+	}
194 194
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -67,9 +67,9 @@  discard block
 block discarded – undo
67 67
      */
68 68
     public function prefixes($prefix = '')
69 69
     {
70
-        if (! empty($prefix)) {
70
+        if ( ! empty($prefix)) {
71 71
             // are there any base directories for this namespace prefix?
72
-            return isset($this->prefixes[ $prefix ]) ? $this->prefixes[ $prefix ] : array();
72
+            return isset($this->prefixes[$prefix]) ? $this->prefixes[$prefix] : array();
73 73
         }
74 74
         return $this->prefixes;
75 75
     }
@@ -100,18 +100,18 @@  discard block
 block discarded – undo
100 100
     public function addNamespace($prefix, $base_dir, $prepend = false)
101 101
     {
102 102
         // normalize namespace prefix
103
-        $prefix = trim($prefix, Psr4Autoloader::NS) . Psr4Autoloader::NS;
103
+        $prefix = trim($prefix, Psr4Autoloader::NS).Psr4Autoloader::NS;
104 104
         // normalize the base directory with a trailing separator
105 105
         $base_dir = \EEH_File::standardise_and_end_with_directory_separator($base_dir);
106 106
         // initialize the namespace prefix array
107
-        if (isset($this->prefixes[ $prefix ]) === false) {
108
-            $this->prefixes[ $prefix ] = array();
107
+        if (isset($this->prefixes[$prefix]) === false) {
108
+            $this->prefixes[$prefix] = array();
109 109
         }
110 110
         // retain the base directory for the namespace prefix
111 111
         if ($prepend) {
112
-            array_unshift($this->prefixes[ $prefix ], $base_dir);
112
+            array_unshift($this->prefixes[$prefix], $base_dir);
113 113
         } else {
114
-            $this->prefixes[ $prefix ][] = $base_dir;
114
+            $this->prefixes[$prefix][] = $base_dir;
115 115
         }
116 116
     }
117 117
 
Please login to merge, or discard this patch.
core/services/container/SharedCoffeeMaker.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@
 block discarded – undo
30 30
     /**
31 31
      * @param RecipeInterface $recipe
32 32
      * @param array           $arguments
33
-     * @return mixed
33
+     * @return boolean
34 34
      */
35 35
     public function brew(RecipeInterface $recipe, $arguments = array())
36 36
     {
Please login to merge, or discard this patch.
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -18,43 +18,43 @@
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * @return string
23
-     */
24
-    public function type()
25
-    {
26
-        return CoffeeMaker::BREW_SHARED;
27
-    }
21
+	/**
22
+	 * @return string
23
+	 */
24
+	public function type()
25
+	{
26
+		return CoffeeMaker::BREW_SHARED;
27
+	}
28 28
 
29 29
 
30
-    /**
31
-     * @param RecipeInterface $recipe
32
-     * @param array           $arguments
33
-     * @return mixed
34
-     */
35
-    public function brew(RecipeInterface $recipe, $arguments = array())
36
-    {
37
-        $this->resolveClassAndFilepath($recipe);
38
-        $reflector = $this->injector()->getReflectionClass($recipe->fqcn());
39
-        $method = $this->resolveInstantiationMethod($reflector);
40
-        switch ($method) {
41
-            case 'instance':
42
-            case 'new_instance':
43
-            case 'new_instance_from_db':
44
-                $service = call_user_func_array(
45
-                    array($reflector->getName(), $method),
46
-                    $this->injector()->resolveDependencies($recipe, $reflector, $arguments)
47
-                );
48
-                break;
49
-            case 'newInstance':
50
-                $service = $reflector->newInstance();
51
-                break;
52
-            case 'newInstanceArgs':
53
-            default:
54
-                $service = $reflector->newInstanceArgs(
55
-                    $this->injector()->resolveDependencies($recipe, $reflector, $arguments)
56
-                );
57
-        }
58
-        return $this->coffeePot()->addService($recipe->identifier(), $service);
59
-    }
30
+	/**
31
+	 * @param RecipeInterface $recipe
32
+	 * @param array           $arguments
33
+	 * @return mixed
34
+	 */
35
+	public function brew(RecipeInterface $recipe, $arguments = array())
36
+	{
37
+		$this->resolveClassAndFilepath($recipe);
38
+		$reflector = $this->injector()->getReflectionClass($recipe->fqcn());
39
+		$method = $this->resolveInstantiationMethod($reflector);
40
+		switch ($method) {
41
+			case 'instance':
42
+			case 'new_instance':
43
+			case 'new_instance_from_db':
44
+				$service = call_user_func_array(
45
+					array($reflector->getName(), $method),
46
+					$this->injector()->resolveDependencies($recipe, $reflector, $arguments)
47
+				);
48
+				break;
49
+			case 'newInstance':
50
+				$service = $reflector->newInstance();
51
+				break;
52
+			case 'newInstanceArgs':
53
+			default:
54
+				$service = $reflector->newInstanceArgs(
55
+					$this->injector()->resolveDependencies($recipe, $reflector, $arguments)
56
+				);
57
+		}
58
+		return $this->coffeePot()->addService($recipe->identifier(), $service);
59
+	}
60 60
 }
Please login to merge, or discard this patch.
core/services/formatters/AsciiOnly.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@
 block discarded – undo
33 33
     /**
34 34
      * Taken from https://gist.github.com/jaywilliams/119517
35 35
      *
36
-     * @param $string
36
+     * @param string $string
37 37
      * @return string
38 38
      */
39 39
     protected function convertAscii($string)
Please login to merge, or discard this patch.
Unused Use Statements   -2 removed lines patch added patch discarded remove patch
@@ -2,8 +2,6 @@
 block discarded – undo
2 2
 
3 3
 namespace EventEspresso\core\services\formatters;
4 4
 
5
-use EventEspresso\core\exceptions\InvalidDataTypeException;
6
-
7 5
 /**
8 6
  * Class AsciiOnly
9 7
  * Removes all non-ascii characters from the string
Please login to merge, or discard this patch.
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -15,58 +15,58 @@
 block discarded – undo
15 15
 class AsciiOnly extends FormatterBase
16 16
 {
17 17
 
18
-    /**
19
-     * Removes all non Ascii characters from string
20
-     *
21
-     * @param string|int|float $input anything easily cast into a string
22
-     * @return string
23
-     */
24
-    public function format($input)
25
-    {
26
-        // in case an int or float etc was passed in
27
-        $input = (string) $input;
28
-        $input = $this->convertAscii($input);
29
-        return $input;
30
-    }
18
+	/**
19
+	 * Removes all non Ascii characters from string
20
+	 *
21
+	 * @param string|int|float $input anything easily cast into a string
22
+	 * @return string
23
+	 */
24
+	public function format($input)
25
+	{
26
+		// in case an int or float etc was passed in
27
+		$input = (string) $input;
28
+		$input = $this->convertAscii($input);
29
+		return $input;
30
+	}
31 31
 
32 32
 
33
-    /**
34
-     * Taken from https://gist.github.com/jaywilliams/119517
35
-     *
36
-     * @param $string
37
-     * @return string
38
-     */
39
-    protected function convertAscii($string)
40
-    {
41
-        // Replace Single Curly Quotes
42
-        $search[] = chr(226) . chr(128) . chr(152);
43
-        $replace[] = "'";
44
-        $search[] = chr(226) . chr(128) . chr(153);
45
-        $replace[] = "'";
46
-        // Replace Smart Double Curly Quotes
47
-        $search[] = chr(226) . chr(128) . chr(156);
48
-        $replace[] = '"';
49
-        $search[] = chr(226) . chr(128) . chr(157);
50
-        $replace[] = '"';
51
-        // Replace En Dash
52
-        $search[] = chr(226) . chr(128) . chr(147);
53
-        $replace[] = '--';
54
-        // Replace Em Dash
55
-        $search[] = chr(226) . chr(128) . chr(148);
56
-        $replace[] = '---';
57
-        // Replace Bullet
58
-        $search[] = chr(226) . chr(128) . chr(162);
59
-        $replace[] = '*';
60
-        // Replace Middle Dot
61
-        $search[] = chr(194) . chr(183);
62
-        $replace[] = '*';
63
-        // Replace Ellipsis with three consecutive dots
64
-        $search[] = chr(226) . chr(128) . chr(166);
65
-        $replace[] = '...';
66
-        // Apply Replacements
67
-        $string = str_replace($search, $replace, $string);
68
-        // Remove any non-ASCII Characters
69
-        $string = preg_replace("/[^\x01-\x7F]/", "", $string);
70
-        return $string;
71
-    }
33
+	/**
34
+	 * Taken from https://gist.github.com/jaywilliams/119517
35
+	 *
36
+	 * @param $string
37
+	 * @return string
38
+	 */
39
+	protected function convertAscii($string)
40
+	{
41
+		// Replace Single Curly Quotes
42
+		$search[] = chr(226) . chr(128) . chr(152);
43
+		$replace[] = "'";
44
+		$search[] = chr(226) . chr(128) . chr(153);
45
+		$replace[] = "'";
46
+		// Replace Smart Double Curly Quotes
47
+		$search[] = chr(226) . chr(128) . chr(156);
48
+		$replace[] = '"';
49
+		$search[] = chr(226) . chr(128) . chr(157);
50
+		$replace[] = '"';
51
+		// Replace En Dash
52
+		$search[] = chr(226) . chr(128) . chr(147);
53
+		$replace[] = '--';
54
+		// Replace Em Dash
55
+		$search[] = chr(226) . chr(128) . chr(148);
56
+		$replace[] = '---';
57
+		// Replace Bullet
58
+		$search[] = chr(226) . chr(128) . chr(162);
59
+		$replace[] = '*';
60
+		// Replace Middle Dot
61
+		$search[] = chr(194) . chr(183);
62
+		$replace[] = '*';
63
+		// Replace Ellipsis with three consecutive dots
64
+		$search[] = chr(226) . chr(128) . chr(166);
65
+		$replace[] = '...';
66
+		// Apply Replacements
67
+		$string = str_replace($search, $replace, $string);
68
+		// Remove any non-ASCII Characters
69
+		$string = preg_replace("/[^\x01-\x7F]/", "", $string);
70
+		return $string;
71
+	}
72 72
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -39,29 +39,29 @@
 block discarded – undo
39 39
     protected function convertAscii($string)
40 40
     {
41 41
         // Replace Single Curly Quotes
42
-        $search[] = chr(226) . chr(128) . chr(152);
42
+        $search[] = chr(226).chr(128).chr(152);
43 43
         $replace[] = "'";
44
-        $search[] = chr(226) . chr(128) . chr(153);
44
+        $search[] = chr(226).chr(128).chr(153);
45 45
         $replace[] = "'";
46 46
         // Replace Smart Double Curly Quotes
47
-        $search[] = chr(226) . chr(128) . chr(156);
47
+        $search[] = chr(226).chr(128).chr(156);
48 48
         $replace[] = '"';
49
-        $search[] = chr(226) . chr(128) . chr(157);
49
+        $search[] = chr(226).chr(128).chr(157);
50 50
         $replace[] = '"';
51 51
         // Replace En Dash
52
-        $search[] = chr(226) . chr(128) . chr(147);
52
+        $search[] = chr(226).chr(128).chr(147);
53 53
         $replace[] = '--';
54 54
         // Replace Em Dash
55
-        $search[] = chr(226) . chr(128) . chr(148);
55
+        $search[] = chr(226).chr(128).chr(148);
56 56
         $replace[] = '---';
57 57
         // Replace Bullet
58
-        $search[] = chr(226) . chr(128) . chr(162);
58
+        $search[] = chr(226).chr(128).chr(162);
59 59
         $replace[] = '*';
60 60
         // Replace Middle Dot
61
-        $search[] = chr(194) . chr(183);
61
+        $search[] = chr(194).chr(183);
62 62
         $replace[] = '*';
63 63
         // Replace Ellipsis with three consecutive dots
64
-        $search[] = chr(226) . chr(128) . chr(166);
64
+        $search[] = chr(226).chr(128).chr(166);
65 65
         $replace[] = '...';
66 66
         // Apply Replacements
67 67
         $string = str_replace($search, $replace, $string);
Please login to merge, or discard this patch.
core/services/locators/FqcnLocator.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@
 block discarded – undo
70 70
      * given a valid namespace, will find all files that match the provided mask
71 71
      *
72 72
      * @access public
73
-     * @param string|array $namespaces
73
+     * @param string $namespaces
74 74
      * @return FilesystemIterator
75 75
      * @throws \EventEspresso\core\exceptions\InvalidClassException
76 76
      * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
Please login to merge, or discard this patch.
Indentation   +143 added lines, -143 removed lines patch added patch discarded remove patch
@@ -17,147 +17,147 @@
 block discarded – undo
17 17
 class FqcnLocator extends Locator
18 18
 {
19 19
 
20
-    /**
21
-     * @var array $FQCNs
22
-     */
23
-    protected $FQCNs = array();
24
-
25
-    /**
26
-     * @var array $namespaces
27
-     */
28
-    protected $namespaces = array();
29
-
30
-
31
-    /**
32
-     * @access protected
33
-     * @param string $namespace
34
-     * @param string $namespace_base_dir
35
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
36
-     */
37
-    protected function setNamespace($namespace, $namespace_base_dir)
38
-    {
39
-        if (! is_string($namespace)) {
40
-            throw new InvalidDataTypeException('$namespace', $namespace, 'string');
41
-        }
42
-        if (! is_string($namespace_base_dir)) {
43
-            throw new InvalidDataTypeException('$namespace_base_dir', $namespace_base_dir, 'string');
44
-        }
45
-        $this->namespaces[ $namespace ] = $namespace_base_dir;
46
-    }
47
-
48
-
49
-    /**
50
-     * @access public
51
-     * @return array
52
-     */
53
-    public function getFQCNs()
54
-    {
55
-        return $this->FQCNs;
56
-    }
57
-
58
-
59
-    /**
60
-     * @access public
61
-     * @return int
62
-     */
63
-    public function count()
64
-    {
65
-        return count($this->FQCNs);
66
-    }
67
-
68
-
69
-    /**
70
-     * given a valid namespace, will find all files that match the provided mask
71
-     *
72
-     * @access public
73
-     * @param string|array $namespaces
74
-     * @return FilesystemIterator
75
-     * @throws \EventEspresso\core\exceptions\InvalidClassException
76
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
77
-     */
78
-    public function locate($namespaces)
79
-    {
80
-        if (! (is_string($namespaces) || is_array($namespaces))) {
81
-            throw new InvalidDataTypeException('$namespaces', $namespaces, 'string or array');
82
-        }
83
-        foreach ((array) $namespaces as $namespace) {
84
-            foreach ($this->FindFQCNsByNamespace($namespace) as $key => $file) {
85
-                $this->FQCNs[ $key ] = $file;
86
-            }
87
-        }
88
-        return $this->FQCNs;
89
-    }
90
-
91
-
92
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
93
-
94
-    /**
95
-     * given a partial namespace, will find all files in that folder
96
-     * ** PLZ NOTE **
97
-     * This assumes that all files within the specified folder should be loaded
98
-     *
99
-     * @access protected
100
-     * @param array $partial_namespace
101
-     * @return FilesystemIterator
102
-     * @throws \EventEspresso\core\exceptions\InvalidClassException
103
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
104
-     */
105
-    protected function FindFQCNsByNamespace($partial_namespace)
106
-    {
107
-        $iterator = new FilesystemIterator(
108
-            $this->getDirectoryFromPartialNamespace($partial_namespace)
109
-        );
110
-        foreach ($this->flags as $flag) {
111
-            $iterator->setFlags($flag);
112
-        }
113
-        if (iterator_count($iterator) === 0) {
114
-            return array();
115
-        }
116
-        foreach ($iterator as $file) {
117
-            $file = \EEH_File::standardise_directory_separators($file);
118
-            foreach ($this->namespaces as $namespace => $base_dir) {
119
-                $namespace .= Psr4Autoloader::NS;
120
-                if (strpos($file, $base_dir) === 0) {
121
-                    $this->FQCNs[] = Psr4Autoloader::NS . str_replace(
122
-                        array($base_dir, DS, '.php'),
123
-                        array($namespace, Psr4Autoloader::NS, ''),
124
-                        $file
125
-                    );
126
-                }
127
-            }
128
-        }
129
-        return $this->FQCNs;
130
-    }
131
-
132
-
133
-    /**
134
-     * getDirectoryFromPartialNamespace
135
-     *
136
-     * @access protected
137
-     * @param  string $partial_namespace almost fully qualified class name ?
138
-     * @return string
139
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
140
-     * @throws \EventEspresso\core\exceptions\InvalidClassException
141
-     */
142
-    protected function getDirectoryFromPartialNamespace($partial_namespace)
143
-    {
144
-        if (empty($partial_namespace)) {
145
-            throw new InvalidClassException($partial_namespace);
146
-        }
147
-        // load our PSR-4 Autoloader so we can get the list of registered namespaces from it
148
-        $psr4_loader = \EE_Psr4AutoloaderInit::psr4_loader();
149
-        // breakup the incoming namespace into segments then loop thru them
150
-        $namespace_segments = explode(Psr4Autoloader::NS, trim($partial_namespace, Psr4Autoloader::NS));
151
-        // we're only interested in the first element, so pull that from the array
152
-        $namespace = array_shift($namespace_segments);
153
-        // check if there's a base directory registered for that namespace
154
-        $prefix = $psr4_loader->prefixes($namespace . Psr4Autoloader::NS);
155
-        // nope? then the incoming namespace is invalid
156
-        if (empty($prefix) || empty($prefix[0])) {
157
-            throw new InvalidClassException($partial_namespace);
158
-        }
159
-        $this->setNamespace($namespace, $prefix[0]);
160
-        // but if it's good, add that base directory to the rest of the path, and return it
161
-        return $prefix[0] . implode(DS, $namespace_segments) . DS;
162
-    }
20
+	/**
21
+	 * @var array $FQCNs
22
+	 */
23
+	protected $FQCNs = array();
24
+
25
+	/**
26
+	 * @var array $namespaces
27
+	 */
28
+	protected $namespaces = array();
29
+
30
+
31
+	/**
32
+	 * @access protected
33
+	 * @param string $namespace
34
+	 * @param string $namespace_base_dir
35
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
36
+	 */
37
+	protected function setNamespace($namespace, $namespace_base_dir)
38
+	{
39
+		if (! is_string($namespace)) {
40
+			throw new InvalidDataTypeException('$namespace', $namespace, 'string');
41
+		}
42
+		if (! is_string($namespace_base_dir)) {
43
+			throw new InvalidDataTypeException('$namespace_base_dir', $namespace_base_dir, 'string');
44
+		}
45
+		$this->namespaces[ $namespace ] = $namespace_base_dir;
46
+	}
47
+
48
+
49
+	/**
50
+	 * @access public
51
+	 * @return array
52
+	 */
53
+	public function getFQCNs()
54
+	{
55
+		return $this->FQCNs;
56
+	}
57
+
58
+
59
+	/**
60
+	 * @access public
61
+	 * @return int
62
+	 */
63
+	public function count()
64
+	{
65
+		return count($this->FQCNs);
66
+	}
67
+
68
+
69
+	/**
70
+	 * given a valid namespace, will find all files that match the provided mask
71
+	 *
72
+	 * @access public
73
+	 * @param string|array $namespaces
74
+	 * @return FilesystemIterator
75
+	 * @throws \EventEspresso\core\exceptions\InvalidClassException
76
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
77
+	 */
78
+	public function locate($namespaces)
79
+	{
80
+		if (! (is_string($namespaces) || is_array($namespaces))) {
81
+			throw new InvalidDataTypeException('$namespaces', $namespaces, 'string or array');
82
+		}
83
+		foreach ((array) $namespaces as $namespace) {
84
+			foreach ($this->FindFQCNsByNamespace($namespace) as $key => $file) {
85
+				$this->FQCNs[ $key ] = $file;
86
+			}
87
+		}
88
+		return $this->FQCNs;
89
+	}
90
+
91
+
92
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
93
+
94
+	/**
95
+	 * given a partial namespace, will find all files in that folder
96
+	 * ** PLZ NOTE **
97
+	 * This assumes that all files within the specified folder should be loaded
98
+	 *
99
+	 * @access protected
100
+	 * @param array $partial_namespace
101
+	 * @return FilesystemIterator
102
+	 * @throws \EventEspresso\core\exceptions\InvalidClassException
103
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
104
+	 */
105
+	protected function FindFQCNsByNamespace($partial_namespace)
106
+	{
107
+		$iterator = new FilesystemIterator(
108
+			$this->getDirectoryFromPartialNamespace($partial_namespace)
109
+		);
110
+		foreach ($this->flags as $flag) {
111
+			$iterator->setFlags($flag);
112
+		}
113
+		if (iterator_count($iterator) === 0) {
114
+			return array();
115
+		}
116
+		foreach ($iterator as $file) {
117
+			$file = \EEH_File::standardise_directory_separators($file);
118
+			foreach ($this->namespaces as $namespace => $base_dir) {
119
+				$namespace .= Psr4Autoloader::NS;
120
+				if (strpos($file, $base_dir) === 0) {
121
+					$this->FQCNs[] = Psr4Autoloader::NS . str_replace(
122
+						array($base_dir, DS, '.php'),
123
+						array($namespace, Psr4Autoloader::NS, ''),
124
+						$file
125
+					);
126
+				}
127
+			}
128
+		}
129
+		return $this->FQCNs;
130
+	}
131
+
132
+
133
+	/**
134
+	 * getDirectoryFromPartialNamespace
135
+	 *
136
+	 * @access protected
137
+	 * @param  string $partial_namespace almost fully qualified class name ?
138
+	 * @return string
139
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
140
+	 * @throws \EventEspresso\core\exceptions\InvalidClassException
141
+	 */
142
+	protected function getDirectoryFromPartialNamespace($partial_namespace)
143
+	{
144
+		if (empty($partial_namespace)) {
145
+			throw new InvalidClassException($partial_namespace);
146
+		}
147
+		// load our PSR-4 Autoloader so we can get the list of registered namespaces from it
148
+		$psr4_loader = \EE_Psr4AutoloaderInit::psr4_loader();
149
+		// breakup the incoming namespace into segments then loop thru them
150
+		$namespace_segments = explode(Psr4Autoloader::NS, trim($partial_namespace, Psr4Autoloader::NS));
151
+		// we're only interested in the first element, so pull that from the array
152
+		$namespace = array_shift($namespace_segments);
153
+		// check if there's a base directory registered for that namespace
154
+		$prefix = $psr4_loader->prefixes($namespace . Psr4Autoloader::NS);
155
+		// nope? then the incoming namespace is invalid
156
+		if (empty($prefix) || empty($prefix[0])) {
157
+			throw new InvalidClassException($partial_namespace);
158
+		}
159
+		$this->setNamespace($namespace, $prefix[0]);
160
+		// but if it's good, add that base directory to the rest of the path, and return it
161
+		return $prefix[0] . implode(DS, $namespace_segments) . DS;
162
+	}
163 163
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -36,13 +36,13 @@  discard block
 block discarded – undo
36 36
      */
37 37
     protected function setNamespace($namespace, $namespace_base_dir)
38 38
     {
39
-        if (! is_string($namespace)) {
39
+        if ( ! is_string($namespace)) {
40 40
             throw new InvalidDataTypeException('$namespace', $namespace, 'string');
41 41
         }
42
-        if (! is_string($namespace_base_dir)) {
42
+        if ( ! is_string($namespace_base_dir)) {
43 43
             throw new InvalidDataTypeException('$namespace_base_dir', $namespace_base_dir, 'string');
44 44
         }
45
-        $this->namespaces[ $namespace ] = $namespace_base_dir;
45
+        $this->namespaces[$namespace] = $namespace_base_dir;
46 46
     }
47 47
 
48 48
 
@@ -77,12 +77,12 @@  discard block
 block discarded – undo
77 77
      */
78 78
     public function locate($namespaces)
79 79
     {
80
-        if (! (is_string($namespaces) || is_array($namespaces))) {
80
+        if ( ! (is_string($namespaces) || is_array($namespaces))) {
81 81
             throw new InvalidDataTypeException('$namespaces', $namespaces, 'string or array');
82 82
         }
83 83
         foreach ((array) $namespaces as $namespace) {
84 84
             foreach ($this->FindFQCNsByNamespace($namespace) as $key => $file) {
85
-                $this->FQCNs[ $key ] = $file;
85
+                $this->FQCNs[$key] = $file;
86 86
             }
87 87
         }
88 88
         return $this->FQCNs;
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
             foreach ($this->namespaces as $namespace => $base_dir) {
119 119
                 $namespace .= Psr4Autoloader::NS;
120 120
                 if (strpos($file, $base_dir) === 0) {
121
-                    $this->FQCNs[] = Psr4Autoloader::NS . str_replace(
121
+                    $this->FQCNs[] = Psr4Autoloader::NS.str_replace(
122 122
                         array($base_dir, DS, '.php'),
123 123
                         array($namespace, Psr4Autoloader::NS, ''),
124 124
                         $file
@@ -151,13 +151,13 @@  discard block
 block discarded – undo
151 151
         // we're only interested in the first element, so pull that from the array
152 152
         $namespace = array_shift($namespace_segments);
153 153
         // check if there's a base directory registered for that namespace
154
-        $prefix = $psr4_loader->prefixes($namespace . Psr4Autoloader::NS);
154
+        $prefix = $psr4_loader->prefixes($namespace.Psr4Autoloader::NS);
155 155
         // nope? then the incoming namespace is invalid
156 156
         if (empty($prefix) || empty($prefix[0])) {
157 157
             throw new InvalidClassException($partial_namespace);
158 158
         }
159 159
         $this->setNamespace($namespace, $prefix[0]);
160 160
         // but if it's good, add that base directory to the rest of the path, and return it
161
-        return $prefix[0] . implode(DS, $namespace_segments) . DS;
161
+        return $prefix[0].implode(DS, $namespace_segments).DS;
162 162
     }
163 163
 }
Please login to merge, or discard this patch.
modules/ticket_selector/ProcessTicketSelector.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -473,7 +473,7 @@
 block discarded – undo
473 473
      *
474 474
      * @param EE_Ticket $ticket
475 475
      * @param int       $qty
476
-     * @return TRUE on success, FALSE on fail
476
+     * @return boolean on success, FALSE on fail
477 477
      * @throws InvalidArgumentException
478 478
      * @throws InvalidInterfaceException
479 479
      * @throws InvalidDataTypeException
Please login to merge, or discard this patch.
Indentation   +497 added lines, -497 removed lines patch added patch discarded remove patch
@@ -33,526 +33,526 @@
 block discarded – undo
33 33
 class ProcessTicketSelector
34 34
 {
35 35
 
36
-    /**
37
-     * @var EE_Cart $cart
38
-     */
39
-    private $cart;
36
+	/**
37
+	 * @var EE_Cart $cart
38
+	 */
39
+	private $cart;
40 40
 
41
-    /**
42
-     * @var EE_Core_Config $core_config
43
-     */
44
-    private $core_config;
41
+	/**
42
+	 * @var EE_Core_Config $core_config
43
+	 */
44
+	private $core_config;
45 45
 
46
-    /**
47
-     * @var Request $request
48
-     */
49
-    private $request;
46
+	/**
47
+	 * @var Request $request
48
+	 */
49
+	private $request;
50 50
 
51
-    /**
52
-     * @var EE_Session $session
53
-     */
54
-    private $session;
51
+	/**
52
+	 * @var EE_Session $session
53
+	 */
54
+	private $session;
55 55
 
56
-    /**
57
-     * @var EEM_Ticket $ticket_model
58
-     */
59
-    private $ticket_model;
56
+	/**
57
+	 * @var EEM_Ticket $ticket_model
58
+	 */
59
+	private $ticket_model;
60 60
 
61
-    /**
62
-     * @var TicketDatetimeAvailabilityTracker $tracker
63
-     */
64
-    private $tracker;
61
+	/**
62
+	 * @var TicketDatetimeAvailabilityTracker $tracker
63
+	 */
64
+	private $tracker;
65 65
 
66 66
 
67
-    /**
68
-     * ProcessTicketSelector constructor.
69
-     * NOTE: PLZ use the Loader to instantiate this class if need be
70
-     * so that all dependencies get injected correctly (which will happen automatically)
71
-     * Null values for parameters are only for backwards compatibility but will be removed later on.
72
-     *
73
-     * @param EE_Core_Config                    $core_config
74
-     * @param Request                           $request
75
-     * @param EE_Session                        $session
76
-     * @param EEM_Ticket                        $ticket_model
77
-     * @param TicketDatetimeAvailabilityTracker $tracker
78
-     * @throws InvalidArgumentException
79
-     * @throws InvalidDataTypeException
80
-     * @throws InvalidInterfaceException
81
-     */
82
-    public function __construct(
83
-        EE_Core_Config $core_config = null,
84
-        Request $request = null,
85
-        EE_Session $session = null,
86
-        EEM_Ticket $ticket_model = null,
87
-        TicketDatetimeAvailabilityTracker $tracker = null
88
-    ) {
89
-        /** @var LoaderInterface $loader */
90
-        $loader = LoaderFactory::getLoader();
91
-        $this->core_config = $core_config instanceof EE_Core_Config
92
-            ? $core_config
93
-            : $loader->getShared('EE_Core_Config');
94
-        $this->request = $request instanceof Request
95
-            ? $request
96
-            : $loader->getShared('EventEspresso\core\services\request\Request');
97
-        $this->session = $session instanceof EE_Session
98
-            ? $session
99
-            : $loader->getShared('EE_Session');
100
-        $this->ticket_model = $ticket_model instanceof EEM_Ticket
101
-            ? $ticket_model
102
-            : $loader->getShared('EEM_Ticket');
103
-        $this->tracker = $tracker instanceof TicketDatetimeAvailabilityTracker
104
-            ? $tracker
105
-            : $loader->getShared('EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker');
106
-    }
67
+	/**
68
+	 * ProcessTicketSelector constructor.
69
+	 * NOTE: PLZ use the Loader to instantiate this class if need be
70
+	 * so that all dependencies get injected correctly (which will happen automatically)
71
+	 * Null values for parameters are only for backwards compatibility but will be removed later on.
72
+	 *
73
+	 * @param EE_Core_Config                    $core_config
74
+	 * @param Request                           $request
75
+	 * @param EE_Session                        $session
76
+	 * @param EEM_Ticket                        $ticket_model
77
+	 * @param TicketDatetimeAvailabilityTracker $tracker
78
+	 * @throws InvalidArgumentException
79
+	 * @throws InvalidDataTypeException
80
+	 * @throws InvalidInterfaceException
81
+	 */
82
+	public function __construct(
83
+		EE_Core_Config $core_config = null,
84
+		Request $request = null,
85
+		EE_Session $session = null,
86
+		EEM_Ticket $ticket_model = null,
87
+		TicketDatetimeAvailabilityTracker $tracker = null
88
+	) {
89
+		/** @var LoaderInterface $loader */
90
+		$loader = LoaderFactory::getLoader();
91
+		$this->core_config = $core_config instanceof EE_Core_Config
92
+			? $core_config
93
+			: $loader->getShared('EE_Core_Config');
94
+		$this->request = $request instanceof Request
95
+			? $request
96
+			: $loader->getShared('EventEspresso\core\services\request\Request');
97
+		$this->session = $session instanceof EE_Session
98
+			? $session
99
+			: $loader->getShared('EE_Session');
100
+		$this->ticket_model = $ticket_model instanceof EEM_Ticket
101
+			? $ticket_model
102
+			: $loader->getShared('EEM_Ticket');
103
+		$this->tracker = $tracker instanceof TicketDatetimeAvailabilityTracker
104
+			? $tracker
105
+			: $loader->getShared('EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker');
106
+	}
107 107
 
108 108
 
109
-    /**
110
-     * cancelTicketSelections
111
-     *
112
-     * @return bool
113
-     * @throws EE_Error
114
-     * @throws InvalidArgumentException
115
-     * @throws InvalidInterfaceException
116
-     * @throws InvalidDataTypeException
117
-     */
118
-    public function cancelTicketSelections()
119
-    {
120
-        // check nonce
121
-        if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
122
-            return false;
123
-        }
124
-        $this->session->clear_session(__CLASS__, __FUNCTION__);
125
-        if ($this->request->requestParamIsSet('event_id')) {
126
-            EEH_URL::safeRedirectAndExit(
127
-                EEH_Event_View::event_link_url(
128
-                    $this->request->getRequestParam('event_id')
129
-                )
130
-            );
131
-        }
132
-        EEH_URL::safeRedirectAndExit(
133
-            site_url('/' . $this->core_config->event_cpt_slug . '/')
134
-        );
135
-        return true;
136
-    }
109
+	/**
110
+	 * cancelTicketSelections
111
+	 *
112
+	 * @return bool
113
+	 * @throws EE_Error
114
+	 * @throws InvalidArgumentException
115
+	 * @throws InvalidInterfaceException
116
+	 * @throws InvalidDataTypeException
117
+	 */
118
+	public function cancelTicketSelections()
119
+	{
120
+		// check nonce
121
+		if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
122
+			return false;
123
+		}
124
+		$this->session->clear_session(__CLASS__, __FUNCTION__);
125
+		if ($this->request->requestParamIsSet('event_id')) {
126
+			EEH_URL::safeRedirectAndExit(
127
+				EEH_Event_View::event_link_url(
128
+					$this->request->getRequestParam('event_id')
129
+				)
130
+			);
131
+		}
132
+		EEH_URL::safeRedirectAndExit(
133
+			site_url('/' . $this->core_config->event_cpt_slug . '/')
134
+		);
135
+		return true;
136
+	}
137 137
 
138 138
 
139
-    /**
140
-     * processTicketSelectorNonce
141
-     *
142
-     * @param  string $nonce_name
143
-     * @param string  $id
144
-     * @return bool
145
-     */
146
-    private function processTicketSelectorNonce($nonce_name, $id = '')
147
-    {
148
-        $nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
149
-        if (! $this->request->isAdmin()
150
-            && (
151
-                ! $this->request->is_set($nonce_name_with_id)
152
-                || ! wp_verify_nonce(
153
-                    $this->request->get($nonce_name_with_id),
154
-                    $nonce_name
155
-                )
156
-            )
157
-        ) {
158
-            EE_Error::add_error(
159
-                sprintf(
160
-                    esc_html__(
161
-                        'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
162
-                        'event_espresso'
163
-                    ),
164
-                    '<br/>'
165
-                ),
166
-                __FILE__,
167
-                __FUNCTION__,
168
-                __LINE__
169
-            );
170
-            return false;
171
-        }
172
-        return true;
173
-    }
139
+	/**
140
+	 * processTicketSelectorNonce
141
+	 *
142
+	 * @param  string $nonce_name
143
+	 * @param string  $id
144
+	 * @return bool
145
+	 */
146
+	private function processTicketSelectorNonce($nonce_name, $id = '')
147
+	{
148
+		$nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
149
+		if (! $this->request->isAdmin()
150
+			&& (
151
+				! $this->request->is_set($nonce_name_with_id)
152
+				|| ! wp_verify_nonce(
153
+					$this->request->get($nonce_name_with_id),
154
+					$nonce_name
155
+				)
156
+			)
157
+		) {
158
+			EE_Error::add_error(
159
+				sprintf(
160
+					esc_html__(
161
+						'We\'re sorry but your request failed to pass a security check.%sPlease click the back button on your browser and try again.',
162
+						'event_espresso'
163
+					),
164
+					'<br/>'
165
+				),
166
+				__FILE__,
167
+				__FUNCTION__,
168
+				__LINE__
169
+			);
170
+			return false;
171
+		}
172
+		return true;
173
+	}
174 174
 
175 175
 
176
-    /**
177
-     * process_ticket_selections
178
-     *
179
-     * @return array|bool
180
-     * @throws EE_Error
181
-     * @throws InvalidArgumentException
182
-     * @throws InvalidDataTypeException
183
-     * @throws InvalidInterfaceException
184
-     */
185
-    public function processTicketSelections()
186
-    {
187
-        do_action('EED_Ticket_Selector__process_ticket_selections__before');
188
-        if ($this->request->isBot()) {
189
-            EEH_URL::safeRedirectAndExit(
190
-                apply_filters(
191
-                    'FHEE__EE_Ticket_Selector__process_ticket_selections__bot_redirect_url',
192
-                    site_url()
193
-                )
194
-            );
195
-        }
196
-        // do we have an event id?
197
-        $id = $this->getEventId();
198
-        // we should really only have 1 registration in the works now
199
-        // (ie, no MER) so unless otherwise requested, clear the session
200
-        if (apply_filters('FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true)) {
201
-            $this->session->clear_session(__CLASS__, __FUNCTION__);
202
-        }
203
-        // validate/sanitize/filter data
204
-        $valid = apply_filters(
205
-            'FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data',
206
-            $this->validatePostData($id)
207
-        );
208
-        // check total tickets ordered vs max number of attendees that can register
209
-        if ($valid['total_tickets'] > $valid['max_atndz']) {
210
-            $this->maxAttendeesViolation($valid);
211
-        } else {
212
-            // all data appears to be valid
213
-            if ($this->processSuccessfulCart($this->addTicketsToCart($valid))) {
214
-                return true;
215
-            }
216
-        }
217
-        // die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
218
-        // at this point, just return if registration is being made from admin
219
-        if ($this->request->isAdmin() || $this->request->isFrontAjax()) {
220
-            return false;
221
-        }
222
-        if ($valid['return_url']) {
223
-            EEH_URL::safeRedirectAndExit($valid['return_url']);
224
-        }
225
-        if ($id) {
226
-            EEH_URL::safeRedirectAndExit(get_permalink($id));
227
-        }
228
-        echo EE_Error::get_notices();
229
-        return false;
230
-    }
176
+	/**
177
+	 * process_ticket_selections
178
+	 *
179
+	 * @return array|bool
180
+	 * @throws EE_Error
181
+	 * @throws InvalidArgumentException
182
+	 * @throws InvalidDataTypeException
183
+	 * @throws InvalidInterfaceException
184
+	 */
185
+	public function processTicketSelections()
186
+	{
187
+		do_action('EED_Ticket_Selector__process_ticket_selections__before');
188
+		if ($this->request->isBot()) {
189
+			EEH_URL::safeRedirectAndExit(
190
+				apply_filters(
191
+					'FHEE__EE_Ticket_Selector__process_ticket_selections__bot_redirect_url',
192
+					site_url()
193
+				)
194
+			);
195
+		}
196
+		// do we have an event id?
197
+		$id = $this->getEventId();
198
+		// we should really only have 1 registration in the works now
199
+		// (ie, no MER) so unless otherwise requested, clear the session
200
+		if (apply_filters('FHEE__EE_Ticket_Selector__process_ticket_selections__clear_session', true)) {
201
+			$this->session->clear_session(__CLASS__, __FUNCTION__);
202
+		}
203
+		// validate/sanitize/filter data
204
+		$valid = apply_filters(
205
+			'FHEE__EED_Ticket_Selector__process_ticket_selections__valid_post_data',
206
+			$this->validatePostData($id)
207
+		);
208
+		// check total tickets ordered vs max number of attendees that can register
209
+		if ($valid['total_tickets'] > $valid['max_atndz']) {
210
+			$this->maxAttendeesViolation($valid);
211
+		} else {
212
+			// all data appears to be valid
213
+			if ($this->processSuccessfulCart($this->addTicketsToCart($valid))) {
214
+				return true;
215
+			}
216
+		}
217
+		// die(); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< KILL BEFORE REDIRECT
218
+		// at this point, just return if registration is being made from admin
219
+		if ($this->request->isAdmin() || $this->request->isFrontAjax()) {
220
+			return false;
221
+		}
222
+		if ($valid['return_url']) {
223
+			EEH_URL::safeRedirectAndExit($valid['return_url']);
224
+		}
225
+		if ($id) {
226
+			EEH_URL::safeRedirectAndExit(get_permalink($id));
227
+		}
228
+		echo EE_Error::get_notices();
229
+		return false;
230
+	}
231 231
 
232 232
 
233
-    /**
234
-     * @return int
235
-     */
236
-    private function getEventId()
237
-    {
238
-        // do we have an event id?
239
-        if (! $this->request->requestParamIsSet('tkt-slctr-event-id')) {
240
-            // $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
241
-            EE_Error::add_error(
242
-                sprintf(
243
-                    esc_html__(
244
-                        'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
245
-                        'event_espresso'
246
-                    ),
247
-                    '<br/>'
248
-                ),
249
-                __FILE__,
250
-                __FUNCTION__,
251
-                __LINE__
252
-            );
253
-        }
254
-        // if event id is valid
255
-        return absint($this->request->getRequestParam('tkt-slctr-event-id'));
256
-    }
233
+	/**
234
+	 * @return int
235
+	 */
236
+	private function getEventId()
237
+	{
238
+		// do we have an event id?
239
+		if (! $this->request->requestParamIsSet('tkt-slctr-event-id')) {
240
+			// $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
241
+			EE_Error::add_error(
242
+				sprintf(
243
+					esc_html__(
244
+						'An event id was not provided or was not received.%sPlease click the back button on your browser and try again.',
245
+						'event_espresso'
246
+					),
247
+					'<br/>'
248
+				),
249
+				__FILE__,
250
+				__FUNCTION__,
251
+				__LINE__
252
+			);
253
+		}
254
+		// if event id is valid
255
+		return absint($this->request->getRequestParam('tkt-slctr-event-id'));
256
+	}
257 257
 
258 258
 
259
-    /**
260
-     * validate_post_data
261
-     *
262
-     * @param int $id
263
-     * @return array|FALSE
264
-     */
265
-    private function validatePostData($id = 0)
266
-    {
267
-        if (! $id) {
268
-            EE_Error::add_error(
269
-                esc_html__('The event id provided was not valid.', 'event_espresso'),
270
-                __FILE__,
271
-                __FUNCTION__,
272
-                __LINE__
273
-            );
274
-            return false;
275
-        }
276
-        // start with an empty array()
277
-        $valid_data = array();
278
-        // grab valid id
279
-        $valid_data['id'] = $id;
280
-        // array of other form names
281
-        $inputs_to_clean = array(
282
-            'event_id'   => 'tkt-slctr-event-id',
283
-            'max_atndz'  => 'tkt-slctr-max-atndz-',
284
-            'rows'       => 'tkt-slctr-rows-',
285
-            'qty'        => 'tkt-slctr-qty-',
286
-            'ticket_id'  => 'tkt-slctr-ticket-id-',
287
-            'return_url' => 'tkt-slctr-return-url-',
288
-        );
289
-        // let's track the total number of tickets ordered.'
290
-        $valid_data['total_tickets'] = 0;
291
-        // cycle through $inputs_to_clean array
292
-        foreach ($inputs_to_clean as $what => $input_to_clean) {
293
-            // check for POST data
294
-            if ($this->request->requestParamIsSet($input_to_clean . $id)) {
295
-                // grab value
296
-                $input_value = $this->request->getRequestParam($input_to_clean . $id);
297
-                switch ($what) {
298
-                    // integers
299
-                    case 'event_id':
300
-                        $valid_data[ $what ] = absint($input_value);
301
-                        // get event via the event id we put in the form
302
-                        break;
303
-                    case 'rows':
304
-                    case 'max_atndz':
305
-                        $valid_data[ $what ] = absint($input_value);
306
-                        break;
307
-                    // arrays of integers
308
-                    case 'qty':
309
-                        /** @var array $row_qty */
310
-                        $row_qty = $input_value;
311
-                        // if qty is coming from a radio button input, then we need to assemble an array of rows
312
-                        if (! is_array($row_qty)) {
313
-                            /** @var string $row_qty */
314
-                            // get number of rows
315
-                            $rows = $this->request->requestParamIsSet('tkt-slctr-rows-' . $id)
316
-                                ? absint($this->request->getRequestParam('tkt-slctr-rows-' . $id))
317
-                                : 1;
318
-                            // explode integers by the dash
319
-                            $row_qty = explode('-', $row_qty);
320
-                            $row = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
321
-                            $qty = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
322
-                            $row_qty = array($row => $qty);
323
-                            for ($x = 1; $x <= $rows; $x++) {
324
-                                if (! isset($row_qty[ $x ])) {
325
-                                    $row_qty[ $x ] = 0;
326
-                                }
327
-                            }
328
-                        }
329
-                        ksort($row_qty);
330
-                        // cycle thru values
331
-                        foreach ($row_qty as $qty) {
332
-                            $qty = absint($qty);
333
-                            // sanitize as integers
334
-                            $valid_data[ $what ][] = $qty;
335
-                            $valid_data['total_tickets'] += $qty;
336
-                        }
337
-                        break;
338
-                    // array of integers
339
-                    case 'ticket_id':
340
-                        // cycle thru values
341
-                        foreach ((array) $input_value as $key => $value) {
342
-                            // allow only integers
343
-                            $valid_data[ $what ][ $key ] = absint($value);
344
-                        }
345
-                        break;
346
-                    case 'return_url':
347
-                        // grab and sanitize return-url
348
-                        $input_value = esc_url_raw($input_value);
349
-                        // was the request coming from an iframe ? if so, then:
350
-                        if (strpos($input_value, 'event_list=iframe')) {
351
-                            // get anchor fragment
352
-                            $input_value = explode('#', $input_value);
353
-                            $input_value = end($input_value);
354
-                            // use event list url instead, but append anchor
355
-                            $input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
356
-                        }
357
-                        $valid_data[ $what ] = $input_value;
358
-                        break;
359
-                }    // end switch $what
360
-            }
361
-        }    // end foreach $inputs_to_clean
362
-        return $valid_data;
363
-    }
259
+	/**
260
+	 * validate_post_data
261
+	 *
262
+	 * @param int $id
263
+	 * @return array|FALSE
264
+	 */
265
+	private function validatePostData($id = 0)
266
+	{
267
+		if (! $id) {
268
+			EE_Error::add_error(
269
+				esc_html__('The event id provided was not valid.', 'event_espresso'),
270
+				__FILE__,
271
+				__FUNCTION__,
272
+				__LINE__
273
+			);
274
+			return false;
275
+		}
276
+		// start with an empty array()
277
+		$valid_data = array();
278
+		// grab valid id
279
+		$valid_data['id'] = $id;
280
+		// array of other form names
281
+		$inputs_to_clean = array(
282
+			'event_id'   => 'tkt-slctr-event-id',
283
+			'max_atndz'  => 'tkt-slctr-max-atndz-',
284
+			'rows'       => 'tkt-slctr-rows-',
285
+			'qty'        => 'tkt-slctr-qty-',
286
+			'ticket_id'  => 'tkt-slctr-ticket-id-',
287
+			'return_url' => 'tkt-slctr-return-url-',
288
+		);
289
+		// let's track the total number of tickets ordered.'
290
+		$valid_data['total_tickets'] = 0;
291
+		// cycle through $inputs_to_clean array
292
+		foreach ($inputs_to_clean as $what => $input_to_clean) {
293
+			// check for POST data
294
+			if ($this->request->requestParamIsSet($input_to_clean . $id)) {
295
+				// grab value
296
+				$input_value = $this->request->getRequestParam($input_to_clean . $id);
297
+				switch ($what) {
298
+					// integers
299
+					case 'event_id':
300
+						$valid_data[ $what ] = absint($input_value);
301
+						// get event via the event id we put in the form
302
+						break;
303
+					case 'rows':
304
+					case 'max_atndz':
305
+						$valid_data[ $what ] = absint($input_value);
306
+						break;
307
+					// arrays of integers
308
+					case 'qty':
309
+						/** @var array $row_qty */
310
+						$row_qty = $input_value;
311
+						// if qty is coming from a radio button input, then we need to assemble an array of rows
312
+						if (! is_array($row_qty)) {
313
+							/** @var string $row_qty */
314
+							// get number of rows
315
+							$rows = $this->request->requestParamIsSet('tkt-slctr-rows-' . $id)
316
+								? absint($this->request->getRequestParam('tkt-slctr-rows-' . $id))
317
+								: 1;
318
+							// explode integers by the dash
319
+							$row_qty = explode('-', $row_qty);
320
+							$row = isset($row_qty[0]) ? absint($row_qty[0]) : 1;
321
+							$qty = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
322
+							$row_qty = array($row => $qty);
323
+							for ($x = 1; $x <= $rows; $x++) {
324
+								if (! isset($row_qty[ $x ])) {
325
+									$row_qty[ $x ] = 0;
326
+								}
327
+							}
328
+						}
329
+						ksort($row_qty);
330
+						// cycle thru values
331
+						foreach ($row_qty as $qty) {
332
+							$qty = absint($qty);
333
+							// sanitize as integers
334
+							$valid_data[ $what ][] = $qty;
335
+							$valid_data['total_tickets'] += $qty;
336
+						}
337
+						break;
338
+					// array of integers
339
+					case 'ticket_id':
340
+						// cycle thru values
341
+						foreach ((array) $input_value as $key => $value) {
342
+							// allow only integers
343
+							$valid_data[ $what ][ $key ] = absint($value);
344
+						}
345
+						break;
346
+					case 'return_url':
347
+						// grab and sanitize return-url
348
+						$input_value = esc_url_raw($input_value);
349
+						// was the request coming from an iframe ? if so, then:
350
+						if (strpos($input_value, 'event_list=iframe')) {
351
+							// get anchor fragment
352
+							$input_value = explode('#', $input_value);
353
+							$input_value = end($input_value);
354
+							// use event list url instead, but append anchor
355
+							$input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
356
+						}
357
+						$valid_data[ $what ] = $input_value;
358
+						break;
359
+				}    // end switch $what
360
+			}
361
+		}    // end foreach $inputs_to_clean
362
+		return $valid_data;
363
+	}
364 364
 
365 365
 
366
-    /**
367
-     * @param array $valid
368
-     */
369
-    private function maxAttendeesViolation(array $valid)
370
-    {
371
-        // ordering too many tickets !!!
372
-        $total_tickets_string = esc_html(
373
-            _n(
374
-                'You have attempted to purchase %s ticket.',
375
-                'You have attempted to purchase %s tickets.',
376
-                $valid['total_tickets'],
377
-                'event_espresso'
378
-            )
379
-        );
380
-        $limit_error_1 = sprintf($total_tickets_string, $valid['total_tickets']);
381
-        // dev only message
382
-        $max_attendees_string = esc_html(
383
-            _n(
384
-                'The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
385
-                'The registration limit for this event is %s tickets per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
386
-                $valid['max_atndz'],
387
-                'event_espresso'
388
-            )
389
-        );
390
-        $limit_error_2 = sprintf($max_attendees_string, $valid['max_atndz'], $valid['max_atndz']);
391
-        EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
392
-    }
366
+	/**
367
+	 * @param array $valid
368
+	 */
369
+	private function maxAttendeesViolation(array $valid)
370
+	{
371
+		// ordering too many tickets !!!
372
+		$total_tickets_string = esc_html(
373
+			_n(
374
+				'You have attempted to purchase %s ticket.',
375
+				'You have attempted to purchase %s tickets.',
376
+				$valid['total_tickets'],
377
+				'event_espresso'
378
+			)
379
+		);
380
+		$limit_error_1 = sprintf($total_tickets_string, $valid['total_tickets']);
381
+		// dev only message
382
+		$max_attendees_string = esc_html(
383
+			_n(
384
+				'The registration limit for this event is %s ticket per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
385
+				'The registration limit for this event is %s tickets per registration, therefore the total number of tickets you may purchase at a time can not exceed %s.',
386
+				$valid['max_atndz'],
387
+				'event_espresso'
388
+			)
389
+		);
390
+		$limit_error_2 = sprintf($max_attendees_string, $valid['max_atndz'], $valid['max_atndz']);
391
+		EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
392
+	}
393 393
 
394 394
 
395
-    /**
396
-     * @param array $valid
397
-     * @return int|TRUE
398
-     * @throws EE_Error
399
-     * @throws InvalidArgumentException
400
-     * @throws InvalidDataTypeException
401
-     * @throws InvalidInterfaceException
402
-     */
403
-    private function addTicketsToCart(array $valid)
404
-    {
405
-        $tickets_added = 0;
406
-        $tickets_selected = false;
407
-        if ($valid['total_tickets'] > 0) {
408
-            // load cart using factory because we don't want to do so until actually needed
409
-            $this->cart = CartFactory::getCart();
410
-            // cycle thru the number of data rows sent from the event listing
411
-            for ($x = 0; $x < $valid['rows']; $x++) {
412
-                // does this row actually contain a ticket quantity?
413
-                if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
414
-                    // YES we have a ticket quantity
415
-                    $tickets_selected = true;
416
-                    $valid_ticket = false;
417
-                    // \EEH_Debug_Tools::printr(
418
-                    //     $valid['ticket_id'][ $x ],
419
-                    //     '$valid[\'ticket_id\'][ $x ]',
420
-                    //     __FILE__, __LINE__
421
-                    // );
422
-                    if (isset($valid['ticket_id'][ $x ])) {
423
-                        // get ticket via the ticket id we put in the form
424
-                        $ticket = $this->ticket_model->get_one_by_ID($valid['ticket_id'][ $x ]);
425
-                        if ($ticket instanceof EE_Ticket) {
426
-                            $valid_ticket = true;
427
-                            $tickets_added += $this->addTicketToCart(
428
-                                $ticket,
429
-                                $valid['qty'][ $x ]
430
-                            );
431
-                        }
432
-                    }
433
-                    if ($valid_ticket !== true) {
434
-                        // nothing added to cart retrieved
435
-                        EE_Error::add_error(
436
-                            sprintf(
437
-                                esc_html__(
438
-                                    'A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
439
-                                    'event_espresso'
440
-                                ),
441
-                                '<br/>'
442
-                            ),
443
-                            __FILE__,
444
-                            __FUNCTION__,
445
-                            __LINE__
446
-                        );
447
-                    }
448
-                    if (EE_Error::has_error()) {
449
-                        break;
450
-                    }
451
-                }
452
-            }
453
-        }
454
-        do_action(
455
-            'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
456
-            $this->cart,
457
-            $this
458
-        );
459
-        if (! apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tickets_selected)) {
460
-            // no ticket quantities were selected
461
-            EE_Error::add_error(
462
-                esc_html__('You need to select a ticket quantity before you can proceed.', 'event_espresso'),
463
-                __FILE__,
464
-                __FUNCTION__,
465
-                __LINE__
466
-            );
467
-        }
468
-        return $tickets_added;
469
-    }
395
+	/**
396
+	 * @param array $valid
397
+	 * @return int|TRUE
398
+	 * @throws EE_Error
399
+	 * @throws InvalidArgumentException
400
+	 * @throws InvalidDataTypeException
401
+	 * @throws InvalidInterfaceException
402
+	 */
403
+	private function addTicketsToCart(array $valid)
404
+	{
405
+		$tickets_added = 0;
406
+		$tickets_selected = false;
407
+		if ($valid['total_tickets'] > 0) {
408
+			// load cart using factory because we don't want to do so until actually needed
409
+			$this->cart = CartFactory::getCart();
410
+			// cycle thru the number of data rows sent from the event listing
411
+			for ($x = 0; $x < $valid['rows']; $x++) {
412
+				// does this row actually contain a ticket quantity?
413
+				if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
414
+					// YES we have a ticket quantity
415
+					$tickets_selected = true;
416
+					$valid_ticket = false;
417
+					// \EEH_Debug_Tools::printr(
418
+					//     $valid['ticket_id'][ $x ],
419
+					//     '$valid[\'ticket_id\'][ $x ]',
420
+					//     __FILE__, __LINE__
421
+					// );
422
+					if (isset($valid['ticket_id'][ $x ])) {
423
+						// get ticket via the ticket id we put in the form
424
+						$ticket = $this->ticket_model->get_one_by_ID($valid['ticket_id'][ $x ]);
425
+						if ($ticket instanceof EE_Ticket) {
426
+							$valid_ticket = true;
427
+							$tickets_added += $this->addTicketToCart(
428
+								$ticket,
429
+								$valid['qty'][ $x ]
430
+							);
431
+						}
432
+					}
433
+					if ($valid_ticket !== true) {
434
+						// nothing added to cart retrieved
435
+						EE_Error::add_error(
436
+							sprintf(
437
+								esc_html__(
438
+									'A valid ticket could not be retrieved for the event.%sPlease click the back button on your browser and try again.',
439
+									'event_espresso'
440
+								),
441
+								'<br/>'
442
+							),
443
+							__FILE__,
444
+							__FUNCTION__,
445
+							__LINE__
446
+						);
447
+					}
448
+					if (EE_Error::has_error()) {
449
+						break;
450
+					}
451
+				}
452
+			}
453
+		}
454
+		do_action(
455
+			'AHEE__EE_Ticket_Selector__process_ticket_selections__after_tickets_added_to_cart',
456
+			$this->cart,
457
+			$this
458
+		);
459
+		if (! apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tickets_selected)) {
460
+			// no ticket quantities were selected
461
+			EE_Error::add_error(
462
+				esc_html__('You need to select a ticket quantity before you can proceed.', 'event_espresso'),
463
+				__FILE__,
464
+				__FUNCTION__,
465
+				__LINE__
466
+			);
467
+		}
468
+		return $tickets_added;
469
+	}
470 470
 
471 471
 
472
-    /**
473
-     * adds a ticket to the cart
474
-     *
475
-     * @param EE_Ticket $ticket
476
-     * @param int       $qty
477
-     * @return TRUE on success, FALSE on fail
478
-     * @throws InvalidArgumentException
479
-     * @throws InvalidInterfaceException
480
-     * @throws InvalidDataTypeException
481
-     * @throws EE_Error
482
-     */
483
-    private function addTicketToCart(EE_Ticket $ticket, $qty = 1)
484
-    {
485
-        // get the number of spaces left for this datetime ticket
486
-        $available_spaces = $this->tracker->ticketDatetimeAvailability($ticket);
487
-        // compare available spaces against the number of tickets being purchased
488
-        if ($available_spaces >= $qty) {
489
-            // allow addons to prevent a ticket from being added to cart
490
-            if (! apply_filters(
491
-                'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart',
492
-                true,
493
-                $ticket,
494
-                $qty,
495
-                $available_spaces
496
-            )) {
497
-                return false;
498
-            }
499
-            $qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
500
-            // add event to cart
501
-            if ($this->cart->add_ticket_to_cart($ticket, $qty)) {
502
-                $this->tracker->recalculateTicketDatetimeAvailability($ticket, $qty);
503
-                return true;
504
-            }
505
-            return false;
506
-        }
507
-        $this->tracker->processAvailabilityError($ticket, $qty, $this->cart->all_ticket_quantity_count());
508
-        return false;
509
-    }
472
+	/**
473
+	 * adds a ticket to the cart
474
+	 *
475
+	 * @param EE_Ticket $ticket
476
+	 * @param int       $qty
477
+	 * @return TRUE on success, FALSE on fail
478
+	 * @throws InvalidArgumentException
479
+	 * @throws InvalidInterfaceException
480
+	 * @throws InvalidDataTypeException
481
+	 * @throws EE_Error
482
+	 */
483
+	private function addTicketToCart(EE_Ticket $ticket, $qty = 1)
484
+	{
485
+		// get the number of spaces left for this datetime ticket
486
+		$available_spaces = $this->tracker->ticketDatetimeAvailability($ticket);
487
+		// compare available spaces against the number of tickets being purchased
488
+		if ($available_spaces >= $qty) {
489
+			// allow addons to prevent a ticket from being added to cart
490
+			if (! apply_filters(
491
+				'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart',
492
+				true,
493
+				$ticket,
494
+				$qty,
495
+				$available_spaces
496
+			)) {
497
+				return false;
498
+			}
499
+			$qty = absint(apply_filters('FHEE__EE_Ticket_Selector___add_ticket_to_cart__ticket_qty', $qty, $ticket));
500
+			// add event to cart
501
+			if ($this->cart->add_ticket_to_cart($ticket, $qty)) {
502
+				$this->tracker->recalculateTicketDatetimeAvailability($ticket, $qty);
503
+				return true;
504
+			}
505
+			return false;
506
+		}
507
+		$this->tracker->processAvailabilityError($ticket, $qty, $this->cart->all_ticket_quantity_count());
508
+		return false;
509
+	}
510 510
 
511 511
 
512
-    /**
513
-     * @param $tickets_added
514
-     * @return bool
515
-     * @throws InvalidInterfaceException
516
-     * @throws InvalidDataTypeException
517
-     * @throws EE_Error
518
-     * @throws InvalidArgumentException
519
-     */
520
-    private function processSuccessfulCart($tickets_added)
521
-    {
522
-        // exit('KILL REDIRECT BEFORE CART UPDATE'); // <<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
523
-        if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
524
-            // make sure cart is loaded
525
-            if (! $this->cart instanceof EE_Cart) {
526
-                $this->cart = CartFactory::getCart();
527
-            }
528
-            do_action(
529
-                'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
530
-                $this->cart,
531
-                $this
532
-            );
533
-            $this->cart->recalculate_all_cart_totals();
534
-            $this->cart->save_cart(false);
535
-            // exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<  OR HERE TO KILL REDIRECT AFTER CART UPDATE
536
-            // just return TRUE for registrations being made from admin
537
-            if ($this->request->isAdmin() || $this->request->isFrontAjax()) {
538
-                return true;
539
-            }
540
-            EEH_URL::safeRedirectAndExit(
541
-                apply_filters(
542
-                    'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
543
-                    $this->core_config->reg_page_url()
544
-                )
545
-            );
546
-        }
547
-        if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
548
-            // nothing added to cart
549
-            EE_Error::add_attention(
550
-                esc_html__('No tickets were added for the event', 'event_espresso'),
551
-                __FILE__,
552
-                __FUNCTION__,
553
-                __LINE__
554
-            );
555
-        }
556
-        return false;
557
-    }
512
+	/**
513
+	 * @param $tickets_added
514
+	 * @return bool
515
+	 * @throws InvalidInterfaceException
516
+	 * @throws InvalidDataTypeException
517
+	 * @throws EE_Error
518
+	 * @throws InvalidArgumentException
519
+	 */
520
+	private function processSuccessfulCart($tickets_added)
521
+	{
522
+		// exit('KILL REDIRECT BEFORE CART UPDATE'); // <<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
523
+		if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
524
+			// make sure cart is loaded
525
+			if (! $this->cart instanceof EE_Cart) {
526
+				$this->cart = CartFactory::getCart();
527
+			}
528
+			do_action(
529
+				'FHEE__EE_Ticket_Selector__process_ticket_selections__before_redirecting_to_checkout',
530
+				$this->cart,
531
+				$this
532
+			);
533
+			$this->cart->recalculate_all_cart_totals();
534
+			$this->cart->save_cart(false);
535
+			// exit('KILL REDIRECT AFTER CART UPDATE'); // <<<<<<<<  OR HERE TO KILL REDIRECT AFTER CART UPDATE
536
+			// just return TRUE for registrations being made from admin
537
+			if ($this->request->isAdmin() || $this->request->isFrontAjax()) {
538
+				return true;
539
+			}
540
+			EEH_URL::safeRedirectAndExit(
541
+				apply_filters(
542
+					'FHEE__EE_Ticket_Selector__process_ticket_selections__success_redirect_url',
543
+					$this->core_config->reg_page_url()
544
+				)
545
+			);
546
+		}
547
+		if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
548
+			// nothing added to cart
549
+			EE_Error::add_attention(
550
+				esc_html__('No tickets were added for the event', 'event_espresso'),
551
+				__FILE__,
552
+				__FUNCTION__,
553
+				__LINE__
554
+			);
555
+		}
556
+		return false;
557
+	}
558 558
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
     public function cancelTicketSelections()
119 119
     {
120 120
         // check nonce
121
-        if (! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
121
+        if ( ! $this->processTicketSelectorNonce('cancel_ticket_selections')) {
122 122
             return false;
123 123
         }
124 124
         $this->session->clear_session(__CLASS__, __FUNCTION__);
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
             );
131 131
         }
132 132
         EEH_URL::safeRedirectAndExit(
133
-            site_url('/' . $this->core_config->event_cpt_slug . '/')
133
+            site_url('/'.$this->core_config->event_cpt_slug.'/')
134 134
         );
135 135
         return true;
136 136
     }
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
     private function processTicketSelectorNonce($nonce_name, $id = '')
147 147
     {
148 148
         $nonce_name_with_id = ! empty($id) ? "{$nonce_name}_nonce_{$id}" : "{$nonce_name}_nonce";
149
-        if (! $this->request->isAdmin()
149
+        if ( ! $this->request->isAdmin()
150 150
             && (
151 151
                 ! $this->request->is_set($nonce_name_with_id)
152 152
                 || ! wp_verify_nonce(
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
     private function getEventId()
237 237
     {
238 238
         // do we have an event id?
239
-        if (! $this->request->requestParamIsSet('tkt-slctr-event-id')) {
239
+        if ( ! $this->request->requestParamIsSet('tkt-slctr-event-id')) {
240 240
             // $_POST['tkt-slctr-event-id'] was not set ?!?!?!?
241 241
             EE_Error::add_error(
242 242
                 sprintf(
@@ -264,7 +264,7 @@  discard block
 block discarded – undo
264 264
      */
265 265
     private function validatePostData($id = 0)
266 266
     {
267
-        if (! $id) {
267
+        if ( ! $id) {
268 268
             EE_Error::add_error(
269 269
                 esc_html__('The event id provided was not valid.', 'event_espresso'),
270 270
                 __FILE__,
@@ -291,29 +291,29 @@  discard block
 block discarded – undo
291 291
         // cycle through $inputs_to_clean array
292 292
         foreach ($inputs_to_clean as $what => $input_to_clean) {
293 293
             // check for POST data
294
-            if ($this->request->requestParamIsSet($input_to_clean . $id)) {
294
+            if ($this->request->requestParamIsSet($input_to_clean.$id)) {
295 295
                 // grab value
296
-                $input_value = $this->request->getRequestParam($input_to_clean . $id);
296
+                $input_value = $this->request->getRequestParam($input_to_clean.$id);
297 297
                 switch ($what) {
298 298
                     // integers
299 299
                     case 'event_id':
300
-                        $valid_data[ $what ] = absint($input_value);
300
+                        $valid_data[$what] = absint($input_value);
301 301
                         // get event via the event id we put in the form
302 302
                         break;
303 303
                     case 'rows':
304 304
                     case 'max_atndz':
305
-                        $valid_data[ $what ] = absint($input_value);
305
+                        $valid_data[$what] = absint($input_value);
306 306
                         break;
307 307
                     // arrays of integers
308 308
                     case 'qty':
309 309
                         /** @var array $row_qty */
310 310
                         $row_qty = $input_value;
311 311
                         // if qty is coming from a radio button input, then we need to assemble an array of rows
312
-                        if (! is_array($row_qty)) {
312
+                        if ( ! is_array($row_qty)) {
313 313
                             /** @var string $row_qty */
314 314
                             // get number of rows
315
-                            $rows = $this->request->requestParamIsSet('tkt-slctr-rows-' . $id)
316
-                                ? absint($this->request->getRequestParam('tkt-slctr-rows-' . $id))
315
+                            $rows = $this->request->requestParamIsSet('tkt-slctr-rows-'.$id)
316
+                                ? absint($this->request->getRequestParam('tkt-slctr-rows-'.$id))
317 317
                                 : 1;
318 318
                             // explode integers by the dash
319 319
                             $row_qty = explode('-', $row_qty);
@@ -321,8 +321,8 @@  discard block
 block discarded – undo
321 321
                             $qty = isset($row_qty[1]) ? absint($row_qty[1]) : 0;
322 322
                             $row_qty = array($row => $qty);
323 323
                             for ($x = 1; $x <= $rows; $x++) {
324
-                                if (! isset($row_qty[ $x ])) {
325
-                                    $row_qty[ $x ] = 0;
324
+                                if ( ! isset($row_qty[$x])) {
325
+                                    $row_qty[$x] = 0;
326 326
                                 }
327 327
                             }
328 328
                         }
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
                         foreach ($row_qty as $qty) {
332 332
                             $qty = absint($qty);
333 333
                             // sanitize as integers
334
-                            $valid_data[ $what ][] = $qty;
334
+                            $valid_data[$what][] = $qty;
335 335
                             $valid_data['total_tickets'] += $qty;
336 336
                         }
337 337
                         break;
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
                         // cycle thru values
341 341
                         foreach ((array) $input_value as $key => $value) {
342 342
                             // allow only integers
343
-                            $valid_data[ $what ][ $key ] = absint($value);
343
+                            $valid_data[$what][$key] = absint($value);
344 344
                         }
345 345
                         break;
346 346
                     case 'return_url':
@@ -352,9 +352,9 @@  discard block
 block discarded – undo
352 352
                             $input_value = explode('#', $input_value);
353 353
                             $input_value = end($input_value);
354 354
                             // use event list url instead, but append anchor
355
-                            $input_value = EEH_Event_View::event_archive_url() . '#' . $input_value;
355
+                            $input_value = EEH_Event_View::event_archive_url().'#'.$input_value;
356 356
                         }
357
-                        $valid_data[ $what ] = $input_value;
357
+                        $valid_data[$what] = $input_value;
358 358
                         break;
359 359
                 }    // end switch $what
360 360
             }
@@ -388,7 +388,7 @@  discard block
 block discarded – undo
388 388
             )
389 389
         );
390 390
         $limit_error_2 = sprintf($max_attendees_string, $valid['max_atndz'], $valid['max_atndz']);
391
-        EE_Error::add_error($limit_error_1 . '<br/>' . $limit_error_2, __FILE__, __FUNCTION__, __LINE__);
391
+        EE_Error::add_error($limit_error_1.'<br/>'.$limit_error_2, __FILE__, __FUNCTION__, __LINE__);
392 392
     }
393 393
 
394 394
 
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
             // cycle thru the number of data rows sent from the event listing
411 411
             for ($x = 0; $x < $valid['rows']; $x++) {
412 412
                 // does this row actually contain a ticket quantity?
413
-                if (isset($valid['qty'][ $x ]) && $valid['qty'][ $x ] > 0) {
413
+                if (isset($valid['qty'][$x]) && $valid['qty'][$x] > 0) {
414 414
                     // YES we have a ticket quantity
415 415
                     $tickets_selected = true;
416 416
                     $valid_ticket = false;
@@ -419,14 +419,14 @@  discard block
 block discarded – undo
419 419
                     //     '$valid[\'ticket_id\'][ $x ]',
420 420
                     //     __FILE__, __LINE__
421 421
                     // );
422
-                    if (isset($valid['ticket_id'][ $x ])) {
422
+                    if (isset($valid['ticket_id'][$x])) {
423 423
                         // get ticket via the ticket id we put in the form
424
-                        $ticket = $this->ticket_model->get_one_by_ID($valid['ticket_id'][ $x ]);
424
+                        $ticket = $this->ticket_model->get_one_by_ID($valid['ticket_id'][$x]);
425 425
                         if ($ticket instanceof EE_Ticket) {
426 426
                             $valid_ticket = true;
427 427
                             $tickets_added += $this->addTicketToCart(
428 428
                                 $ticket,
429
-                                $valid['qty'][ $x ]
429
+                                $valid['qty'][$x]
430 430
                             );
431 431
                         }
432 432
                     }
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
             $this->cart,
457 457
             $this
458 458
         );
459
-        if (! apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tickets_selected)) {
459
+        if ( ! apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__tckts_slctd', $tickets_selected)) {
460 460
             // no ticket quantities were selected
461 461
             EE_Error::add_error(
462 462
                 esc_html__('You need to select a ticket quantity before you can proceed.', 'event_espresso'),
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
         // compare available spaces against the number of tickets being purchased
488 488
         if ($available_spaces >= $qty) {
489 489
             // allow addons to prevent a ticket from being added to cart
490
-            if (! apply_filters(
490
+            if ( ! apply_filters(
491 491
                 'FHEE__EE_Ticket_Selector___add_ticket_to_cart__allow_add_to_cart',
492 492
                 true,
493 493
                 $ticket,
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
         // exit('KILL REDIRECT BEFORE CART UPDATE'); // <<<<<<<<<<<<<<<<< KILL REDIRECT HERE BEFORE CART UPDATE
523 523
         if (apply_filters('FHEE__EED_Ticket_Selector__process_ticket_selections__success', $tickets_added)) {
524 524
             // make sure cart is loaded
525
-            if (! $this->cart instanceof EE_Cart) {
525
+            if ( ! $this->cart instanceof EE_Cart) {
526 526
                 $this->cart = CartFactory::getCart();
527 527
             }
528 528
             do_action(
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
                 )
545 545
             );
546 546
         }
547
-        if (! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
547
+        if ( ! EE_Error::has_error() && ! EE_Error::has_error(true, 'attention')) {
548 548
             // nothing added to cart
549 549
             EE_Error::add_attention(
550 550
                 esc_html__('No tickets were added for the event', 'event_espresso'),
Please login to merge, or discard this patch.
widgets/EspressoWidget.php 2 patches
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -13,28 +13,28 @@
 block discarded – undo
13 13
 {
14 14
 
15 15
 
16
-    /**
17
-     * @param string $name
18
-     * @param array  $widget_options
19
-     * @param array  $control_options
20
-     */
21
-    public function __construct($name = '', array $widget_options = array(), array $control_options = array())
22
-    {
23
-        $id_base = EspressoWidget::getIdBase(get_class($this));
24
-        $control_options['id_base'] = $id_base;
25
-        $control_options['height'] = isset($control_options['height']) ? $control_options['height'] : 300;
26
-        $control_options['width'] = isset($control_options['width']) ? $control_options['width'] : 350;
27
-        // Register widget with WordPress
28
-        parent::__construct($id_base, $name, $widget_options, $control_options);
29
-    }
16
+	/**
17
+	 * @param string $name
18
+	 * @param array  $widget_options
19
+	 * @param array  $control_options
20
+	 */
21
+	public function __construct($name = '', array $widget_options = array(), array $control_options = array())
22
+	{
23
+		$id_base = EspressoWidget::getIdBase(get_class($this));
24
+		$control_options['id_base'] = $id_base;
25
+		$control_options['height'] = isset($control_options['height']) ? $control_options['height'] : 300;
26
+		$control_options['width'] = isset($control_options['width']) ? $control_options['width'] : 350;
27
+		// Register widget with WordPress
28
+		parent::__construct($id_base, $name, $widget_options, $control_options);
29
+	}
30 30
 
31 31
 
32
-    /**
33
-     * @param string $widget_class
34
-     * @return string
35
-     */
36
-    public static function getIdBase($widget_class)
37
-    {
38
-        return sanitize_title(str_replace(array('EEW_', '_'), array('EE_', '-'), $widget_class)) . '-widget';
39
-    }
32
+	/**
33
+	 * @param string $widget_class
34
+	 * @return string
35
+	 */
36
+	public static function getIdBase($widget_class)
37
+	{
38
+		return sanitize_title(str_replace(array('EEW_', '_'), array('EE_', '-'), $widget_class)) . '-widget';
39
+	}
40 40
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -35,6 +35,6 @@
 block discarded – undo
35 35
      */
36 36
     public static function getIdBase($widget_class)
37 37
     {
38
-        return sanitize_title(str_replace(array('EEW_', '_'), array('EE_', '-'), $widget_class)) . '-widget';
38
+        return sanitize_title(str_replace(array('EEW_', '_'), array('EE_', '-'), $widget_class)).'-widget';
39 39
     }
40 40
 }
Please login to merge, or discard this patch.
modules/ticket_selector/TicketSelectorRowStandard.php 2 patches
Indentation   +355 added lines, -355 removed lines patch added patch discarded remove patch
@@ -17,359 +17,359 @@
 block discarded – undo
17 17
 class TicketSelectorRowStandard extends TicketSelectorRow
18 18
 {
19 19
 
20
-    /**
21
-     * @var TicketDetails $ticket_details
22
-     */
23
-    protected $ticket_details;
24
-
25
-    /**
26
-     * @var \EE_Ticket_Selector_Config $template_settings
27
-     */
28
-    protected $template_settings;
29
-
30
-    /**
31
-     * @var EE_Tax_Config $tax_settings
32
-     */
33
-    protected $tax_settings;
34
-
35
-    /**
36
-     * @var boolean $prices_displayed_including_taxes
37
-     */
38
-    protected $prices_displayed_including_taxes;
39
-
40
-    /**
41
-     * @var int $row
42
-     */
43
-    protected $row;
44
-
45
-    /**
46
-     * @var int $cols
47
-     */
48
-    protected $cols;
49
-
50
-    /**
51
-     * @var boolean $hidden_input_qty
52
-     */
53
-    protected $hidden_input_qty;
54
-
55
-    /**
56
-     * @var string $ticket_datetime_classes
57
-     */
58
-    protected $ticket_datetime_classes;
59
-
60
-
61
-    /**
62
-     * TicketDetails constructor.
63
-     *
64
-     * @param TicketDetails $ticket_details
65
-     * @param EE_Tax_Config $tax_settings
66
-     * @param int           $total_tickets
67
-     * @param int           $max_attendees
68
-     * @param int           $row
69
-     * @param int           $cols
70
-     * @param boolean       $required_ticket_sold_out
71
-     * @param string        $event_status
72
-     * @param string        $ticket_datetime_classes
73
-     * @throws EE_Error
74
-     * @throws UnexpectedEntityException
75
-     */
76
-    public function __construct(
77
-        TicketDetails $ticket_details,
78
-        EE_Tax_Config $tax_settings,
79
-        $total_tickets,
80
-        $max_attendees,
81
-        $row,
82
-        $cols,
83
-        $required_ticket_sold_out,
84
-        $event_status,
85
-        $ticket_datetime_classes
86
-    ) {
87
-        $this->ticket_details = $ticket_details;
88
-        $this->template_settings = $ticket_details->getTemplateSettings();
89
-        $this->tax_settings = $tax_settings;
90
-        $this->row = $row;
91
-        $this->cols = $cols;
92
-        $this->ticket_datetime_classes = $ticket_datetime_classes;
93
-        parent::__construct(
94
-            $ticket_details->getTicket(),
95
-            $max_attendees,
96
-            $ticket_details->getDateFormat(),
97
-            $event_status,
98
-            $required_ticket_sold_out,
99
-            $total_tickets
100
-        );
101
-    }
102
-
103
-
104
-    /**
105
-     * other ticket rows will need to know if a required ticket is sold out,
106
-     * so that they are not offered for sale
107
-     *
108
-     * @return boolean
109
-     */
110
-    public function getRequiredTicketSoldOut()
111
-    {
112
-        return $this->required_ticket_sold_out;
113
-    }
114
-
115
-
116
-    /**
117
-     * @return int
118
-     */
119
-    public function getCols()
120
-    {
121
-        return $this->cols;
122
-    }
123
-
124
-
125
-    /**
126
-     * getHtml
127
-     *
128
-     * @return string
129
-     * @throws EE_Error
130
-     */
131
-    public function getHtml()
132
-    {
133
-        $this->min = 0;
134
-        $this->max = $this->ticket->max();
135
-        $remaining = $this->ticket->remaining();
136
-        if ($this->ticket->is_on_sale() && $this->ticket->is_remaining()) {
137
-            $this->setTicketMinAndMax($remaining);
138
-        } else {
139
-            // set flag if ticket is required (flag is set to start date so that future tickets are not blocked)
140
-            $this->required_ticket_sold_out = $this->ticket->required() && ! $remaining
141
-                ? $this->ticket->start_date()
142
-                : $this->required_ticket_sold_out;
143
-        }
144
-        $this->setTicketPriceDetails();
145
-        $this->setTicketStatusClasses($remaining);
146
-        $filtered_row_html = $this->getFilteredRowHtml();
147
-        if ($filtered_row_html !== false) {
148
-            return $filtered_row_html;
149
-        }
150
-        $ticket_selector_row_html = EEH_HTML::tr(
151
-            '',
152
-            '',
153
-            "tckt-slctr-tbl-tr {$this->status_class}{$this->ticket_datetime_classes} "
154
-            . espresso_get_object_css_class($this->ticket)
155
-        );
156
-        $filtered_row_content = $this->getFilteredRowContents();
157
-        if ($filtered_row_content !== false && $this->max_attendees === 1) {
158
-            return $ticket_selector_row_html
159
-                   . $filtered_row_content
160
-                   . $this->ticketQtyAndIdHiddenInputs()
161
-                   . EEH_HTML::trx();
162
-        }
163
-        if ($filtered_row_content !== false) {
164
-            return $ticket_selector_row_html
165
-                   . $filtered_row_content
166
-                   . EEH_HTML::trx();
167
-        }
168
-        $this->hidden_input_qty = $this->max_attendees > 1;
169
-
170
-        $ticket_selector_row_html .= $this->ticketNameTableCell();
171
-        $ticket_selector_row_html .= $this->ticketPriceTableCell();
172
-        $ticket_selector_row_html .= EEH_HTML::td(
173
-            '',
174
-            '',
175
-            'tckt-slctr-tbl-td-qty cntr',
176
-            '',
177
-            'headers="quantity-' . $this->EVT_ID . '"'
178
-        );
179
-        $this->setTicketStatusDisplay($remaining);
180
-        if (empty($this->ticket_status_display)) {
181
-            if ($this->max_attendees === 1) {
182
-                // only ONE attendee is allowed to register at a time
183
-                $ticket_selector_row_html .= $this->onlyOneAttendeeCanRegister();
184
-            } elseif ($this->max > 0) {
185
-                $ticket_selector_row_html .= $this->ticketQuantitySelector();
186
-            }
187
-        }
188
-        $ticket_selector_row_html .= $this->ticket_status_display;
189
-        $ticket_selector_row_html .= $this->ticketQtyAndIdHiddenInputs();
190
-        $ticket_selector_row_html .= $this->ticket_details->display(
191
-            $this->ticket_price,
192
-            $remaining,
193
-            $this->cols
194
-        );
195
-        $ticket_selector_row_html .= EEH_HTML::tdx();
196
-        $ticket_selector_row_html .= EEH_HTML::trx();
197
-
198
-
199
-        $this->row++;
200
-        return $ticket_selector_row_html;
201
-    }
202
-
203
-
204
-    /**
205
-     * getTicketPriceDetails
206
-     *
207
-     * @return void
208
-     * @throws EE_Error
209
-     */
210
-    protected function setTicketPriceDetails()
211
-    {
212
-        $this->ticket_price = $this->tax_settings->prices_displayed_including_taxes
213
-            ? $this->ticket->get_ticket_total_with_taxes()
214
-            : $this->ticket->get_ticket_subtotal();
215
-        $this->ticket_bundle = false;
216
-        $ticket_min = $this->ticket->min();
217
-        // for ticket bundles, set min and max qty the same
218
-        if ($ticket_min !== 0 && $ticket_min === $this->ticket->max()) {
219
-            $this->ticket_price *= $ticket_min;
220
-            $this->ticket_bundle = true;
221
-        }
222
-        $this->ticket_price = apply_filters(
223
-            'FHEE__ticket_selector_chart_template__ticket_price',
224
-            $this->ticket_price,
225
-            $this->ticket
226
-        );
227
-    }
228
-
229
-
230
-    /**
231
-     * ticketNameTableCell
232
-     *
233
-     * @return string
234
-     * @throws EE_Error
235
-     */
236
-    protected function ticketNameTableCell()
237
-    {
238
-        $html = EEH_HTML::td(
239
-            '',
240
-            '',
241
-            'tckt-slctr-tbl-td-name',
242
-            '',
243
-            'headers="details-' . $this->EVT_ID . '"'
244
-        );
245
-        $html .= EEH_HTML::strong($this->ticket->get_pretty('TKT_name'));
246
-        $html .= $this->ticket_details->getShowHideLinks();
247
-        if ($this->ticket->required()) {
248
-            $html .= EEH_HTML::p(
249
-                apply_filters(
250
-                    'FHEE__ticket_selector_chart_template__ticket_required_message',
251
-                    esc_html__('This ticket is required and must be purchased.', 'event_espresso')
252
-                ),
253
-                '',
254
-                'ticket-required-pg'
255
-            );
256
-        }
257
-        $html .= EEH_HTML::tdx();
258
-        return $html;
259
-    }
260
-
261
-
262
-    /**
263
-     * ticketPriceTableCell
264
-     *
265
-     * @return string
266
-     * @throws EE_Error
267
-     */
268
-    protected function ticketPriceTableCell()
269
-    {
270
-        $html = '';
271
-        if (apply_filters('FHEE__ticket_selector_chart_template__display_ticket_price_details', true)) {
272
-            $html .= EEH_HTML::td(
273
-                '',
274
-                '',
275
-                'tckt-slctr-tbl-td-price jst-rght',
276
-                '',
277
-                'headers="price-' . $this->EVT_ID . '"'
278
-            );
279
-            $html .= \EEH_Template::format_currency($this->ticket_price);
280
-            $html .= $this->ticket->taxable()
281
-                ? EEH_HTML::span('*', '', 'taxable-tickets-asterisk grey-text')
282
-                : '';
283
-            $html .= '&nbsp;';
284
-            // phpcs:disable WordPress.WP.I18n.NoEmptyStrings
285
-            $html .= EEH_HTML::span(
286
-                $this->ticket_bundle
287
-                    ? apply_filters(
288
-                        'FHEE__ticket_selector_chart_template__per_ticket_bundle_text',
289
-                        __(' / bundle', 'event_espresso')
290
-                    )
291
-                    : apply_filters(
292
-                        'FHEE__ticket_selector_chart_template__per_ticket_text',
293
-                        __('', 'event_espresso')
294
-                    ),
295
-                '',
296
-                'smaller-text no-bold'
297
-            );
298
-            $html .= '&nbsp;';
299
-            $html .= EEH_HTML::tdx();
300
-            $this->cols++;
301
-        }
302
-        return $html;
303
-    }
304
-
305
-
306
-    /**
307
-     * onlyOneAttendeeCanRegister
308
-     *
309
-     * @return string
310
-     */
311
-    protected function onlyOneAttendeeCanRegister()
312
-    {
313
-        // display submit button since we have tickets available
314
-        add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
315
-        $this->hidden_input_qty = false;
316
-        $id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
317
-        $html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
318
-        $html .= esc_html__('Select this ticket', 'event_espresso') . '</label>';
319
-        $html .= '<input type="radio" name="tkt-slctr-qty-' . $this->EVT_ID . '"';
320
-        $html .= ' id="' . $id . '"';
321
-        $html .= ' class="ticket-selector-tbl-qty-slct" value="' . $this->row . '-1"';
322
-        $html .= $this->total_tickets === 1 ? ' checked="checked"' : '';
323
-        $html .= ' title=""/>';
324
-        return $html;
325
-    }
326
-
327
-
328
-    /**
329
-     * ticketQuantitySelector
330
-     *
331
-     * @return string
332
-     * @throws EE_Error
333
-     */
334
-    protected function ticketQuantitySelector()
335
-    {
336
-        // display submit button since we have tickets available
337
-        add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
338
-        $this->hidden_input_qty = false;
339
-        $id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
340
-        $html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
341
-        $html .= esc_html__('Quantity', 'event_espresso') . '</label>';
342
-        $html .= '<select name="tkt-slctr-qty-' . $this->EVT_ID . '[]"';
343
-        $html .= ' id="' . $id . '"';
344
-        $html .= ' class="ticket-selector-tbl-qty-slct">';
345
-        // this ensures that non-required tickets with non-zero MIN QTYs don't HAVE to be purchased
346
-        if ($this->min !== 0 && ! $this->ticket->required()) {
347
-            $html .= '<option value="0">&nbsp;0&nbsp;</option>';
348
-        }
349
-        // offer ticket quantities from the min to the max
350
-        for ($i = $this->min; $i <= $this->max; $i++) {
351
-            $html .= '<option value="' . $i . '">&nbsp;' . $i . '&nbsp;</option>';
352
-        }
353
-        $html .= '</select>';
354
-        return $html;
355
-    }
356
-
357
-
358
-    /**
359
-     * getHiddenInputs
360
-     *
361
-     * @return string
362
-     * @throws EE_Error
363
-     */
364
-    protected function ticketQtyAndIdHiddenInputs()
365
-    {
366
-        $html = '';
367
-        // depending on group reg we need to change the format for qty
368
-        if ($this->hidden_input_qty) {
369
-            $html .= '<input type="hidden" name="tkt-slctr-qty-' . $this->EVT_ID . '[]" value="0"/>';
370
-        }
371
-        $html .= '<input type="hidden" name="tkt-slctr-ticket-id-' . $this->EVT_ID . '[]"';
372
-        $html .= ' value="' . $this->ticket->ID() . '"/>';
373
-        return $html;
374
-    }
20
+	/**
21
+	 * @var TicketDetails $ticket_details
22
+	 */
23
+	protected $ticket_details;
24
+
25
+	/**
26
+	 * @var \EE_Ticket_Selector_Config $template_settings
27
+	 */
28
+	protected $template_settings;
29
+
30
+	/**
31
+	 * @var EE_Tax_Config $tax_settings
32
+	 */
33
+	protected $tax_settings;
34
+
35
+	/**
36
+	 * @var boolean $prices_displayed_including_taxes
37
+	 */
38
+	protected $prices_displayed_including_taxes;
39
+
40
+	/**
41
+	 * @var int $row
42
+	 */
43
+	protected $row;
44
+
45
+	/**
46
+	 * @var int $cols
47
+	 */
48
+	protected $cols;
49
+
50
+	/**
51
+	 * @var boolean $hidden_input_qty
52
+	 */
53
+	protected $hidden_input_qty;
54
+
55
+	/**
56
+	 * @var string $ticket_datetime_classes
57
+	 */
58
+	protected $ticket_datetime_classes;
59
+
60
+
61
+	/**
62
+	 * TicketDetails constructor.
63
+	 *
64
+	 * @param TicketDetails $ticket_details
65
+	 * @param EE_Tax_Config $tax_settings
66
+	 * @param int           $total_tickets
67
+	 * @param int           $max_attendees
68
+	 * @param int           $row
69
+	 * @param int           $cols
70
+	 * @param boolean       $required_ticket_sold_out
71
+	 * @param string        $event_status
72
+	 * @param string        $ticket_datetime_classes
73
+	 * @throws EE_Error
74
+	 * @throws UnexpectedEntityException
75
+	 */
76
+	public function __construct(
77
+		TicketDetails $ticket_details,
78
+		EE_Tax_Config $tax_settings,
79
+		$total_tickets,
80
+		$max_attendees,
81
+		$row,
82
+		$cols,
83
+		$required_ticket_sold_out,
84
+		$event_status,
85
+		$ticket_datetime_classes
86
+	) {
87
+		$this->ticket_details = $ticket_details;
88
+		$this->template_settings = $ticket_details->getTemplateSettings();
89
+		$this->tax_settings = $tax_settings;
90
+		$this->row = $row;
91
+		$this->cols = $cols;
92
+		$this->ticket_datetime_classes = $ticket_datetime_classes;
93
+		parent::__construct(
94
+			$ticket_details->getTicket(),
95
+			$max_attendees,
96
+			$ticket_details->getDateFormat(),
97
+			$event_status,
98
+			$required_ticket_sold_out,
99
+			$total_tickets
100
+		);
101
+	}
102
+
103
+
104
+	/**
105
+	 * other ticket rows will need to know if a required ticket is sold out,
106
+	 * so that they are not offered for sale
107
+	 *
108
+	 * @return boolean
109
+	 */
110
+	public function getRequiredTicketSoldOut()
111
+	{
112
+		return $this->required_ticket_sold_out;
113
+	}
114
+
115
+
116
+	/**
117
+	 * @return int
118
+	 */
119
+	public function getCols()
120
+	{
121
+		return $this->cols;
122
+	}
123
+
124
+
125
+	/**
126
+	 * getHtml
127
+	 *
128
+	 * @return string
129
+	 * @throws EE_Error
130
+	 */
131
+	public function getHtml()
132
+	{
133
+		$this->min = 0;
134
+		$this->max = $this->ticket->max();
135
+		$remaining = $this->ticket->remaining();
136
+		if ($this->ticket->is_on_sale() && $this->ticket->is_remaining()) {
137
+			$this->setTicketMinAndMax($remaining);
138
+		} else {
139
+			// set flag if ticket is required (flag is set to start date so that future tickets are not blocked)
140
+			$this->required_ticket_sold_out = $this->ticket->required() && ! $remaining
141
+				? $this->ticket->start_date()
142
+				: $this->required_ticket_sold_out;
143
+		}
144
+		$this->setTicketPriceDetails();
145
+		$this->setTicketStatusClasses($remaining);
146
+		$filtered_row_html = $this->getFilteredRowHtml();
147
+		if ($filtered_row_html !== false) {
148
+			return $filtered_row_html;
149
+		}
150
+		$ticket_selector_row_html = EEH_HTML::tr(
151
+			'',
152
+			'',
153
+			"tckt-slctr-tbl-tr {$this->status_class}{$this->ticket_datetime_classes} "
154
+			. espresso_get_object_css_class($this->ticket)
155
+		);
156
+		$filtered_row_content = $this->getFilteredRowContents();
157
+		if ($filtered_row_content !== false && $this->max_attendees === 1) {
158
+			return $ticket_selector_row_html
159
+				   . $filtered_row_content
160
+				   . $this->ticketQtyAndIdHiddenInputs()
161
+				   . EEH_HTML::trx();
162
+		}
163
+		if ($filtered_row_content !== false) {
164
+			return $ticket_selector_row_html
165
+				   . $filtered_row_content
166
+				   . EEH_HTML::trx();
167
+		}
168
+		$this->hidden_input_qty = $this->max_attendees > 1;
169
+
170
+		$ticket_selector_row_html .= $this->ticketNameTableCell();
171
+		$ticket_selector_row_html .= $this->ticketPriceTableCell();
172
+		$ticket_selector_row_html .= EEH_HTML::td(
173
+			'',
174
+			'',
175
+			'tckt-slctr-tbl-td-qty cntr',
176
+			'',
177
+			'headers="quantity-' . $this->EVT_ID . '"'
178
+		);
179
+		$this->setTicketStatusDisplay($remaining);
180
+		if (empty($this->ticket_status_display)) {
181
+			if ($this->max_attendees === 1) {
182
+				// only ONE attendee is allowed to register at a time
183
+				$ticket_selector_row_html .= $this->onlyOneAttendeeCanRegister();
184
+			} elseif ($this->max > 0) {
185
+				$ticket_selector_row_html .= $this->ticketQuantitySelector();
186
+			}
187
+		}
188
+		$ticket_selector_row_html .= $this->ticket_status_display;
189
+		$ticket_selector_row_html .= $this->ticketQtyAndIdHiddenInputs();
190
+		$ticket_selector_row_html .= $this->ticket_details->display(
191
+			$this->ticket_price,
192
+			$remaining,
193
+			$this->cols
194
+		);
195
+		$ticket_selector_row_html .= EEH_HTML::tdx();
196
+		$ticket_selector_row_html .= EEH_HTML::trx();
197
+
198
+
199
+		$this->row++;
200
+		return $ticket_selector_row_html;
201
+	}
202
+
203
+
204
+	/**
205
+	 * getTicketPriceDetails
206
+	 *
207
+	 * @return void
208
+	 * @throws EE_Error
209
+	 */
210
+	protected function setTicketPriceDetails()
211
+	{
212
+		$this->ticket_price = $this->tax_settings->prices_displayed_including_taxes
213
+			? $this->ticket->get_ticket_total_with_taxes()
214
+			: $this->ticket->get_ticket_subtotal();
215
+		$this->ticket_bundle = false;
216
+		$ticket_min = $this->ticket->min();
217
+		// for ticket bundles, set min and max qty the same
218
+		if ($ticket_min !== 0 && $ticket_min === $this->ticket->max()) {
219
+			$this->ticket_price *= $ticket_min;
220
+			$this->ticket_bundle = true;
221
+		}
222
+		$this->ticket_price = apply_filters(
223
+			'FHEE__ticket_selector_chart_template__ticket_price',
224
+			$this->ticket_price,
225
+			$this->ticket
226
+		);
227
+	}
228
+
229
+
230
+	/**
231
+	 * ticketNameTableCell
232
+	 *
233
+	 * @return string
234
+	 * @throws EE_Error
235
+	 */
236
+	protected function ticketNameTableCell()
237
+	{
238
+		$html = EEH_HTML::td(
239
+			'',
240
+			'',
241
+			'tckt-slctr-tbl-td-name',
242
+			'',
243
+			'headers="details-' . $this->EVT_ID . '"'
244
+		);
245
+		$html .= EEH_HTML::strong($this->ticket->get_pretty('TKT_name'));
246
+		$html .= $this->ticket_details->getShowHideLinks();
247
+		if ($this->ticket->required()) {
248
+			$html .= EEH_HTML::p(
249
+				apply_filters(
250
+					'FHEE__ticket_selector_chart_template__ticket_required_message',
251
+					esc_html__('This ticket is required and must be purchased.', 'event_espresso')
252
+				),
253
+				'',
254
+				'ticket-required-pg'
255
+			);
256
+		}
257
+		$html .= EEH_HTML::tdx();
258
+		return $html;
259
+	}
260
+
261
+
262
+	/**
263
+	 * ticketPriceTableCell
264
+	 *
265
+	 * @return string
266
+	 * @throws EE_Error
267
+	 */
268
+	protected function ticketPriceTableCell()
269
+	{
270
+		$html = '';
271
+		if (apply_filters('FHEE__ticket_selector_chart_template__display_ticket_price_details', true)) {
272
+			$html .= EEH_HTML::td(
273
+				'',
274
+				'',
275
+				'tckt-slctr-tbl-td-price jst-rght',
276
+				'',
277
+				'headers="price-' . $this->EVT_ID . '"'
278
+			);
279
+			$html .= \EEH_Template::format_currency($this->ticket_price);
280
+			$html .= $this->ticket->taxable()
281
+				? EEH_HTML::span('*', '', 'taxable-tickets-asterisk grey-text')
282
+				: '';
283
+			$html .= '&nbsp;';
284
+			// phpcs:disable WordPress.WP.I18n.NoEmptyStrings
285
+			$html .= EEH_HTML::span(
286
+				$this->ticket_bundle
287
+					? apply_filters(
288
+						'FHEE__ticket_selector_chart_template__per_ticket_bundle_text',
289
+						__(' / bundle', 'event_espresso')
290
+					)
291
+					: apply_filters(
292
+						'FHEE__ticket_selector_chart_template__per_ticket_text',
293
+						__('', 'event_espresso')
294
+					),
295
+				'',
296
+				'smaller-text no-bold'
297
+			);
298
+			$html .= '&nbsp;';
299
+			$html .= EEH_HTML::tdx();
300
+			$this->cols++;
301
+		}
302
+		return $html;
303
+	}
304
+
305
+
306
+	/**
307
+	 * onlyOneAttendeeCanRegister
308
+	 *
309
+	 * @return string
310
+	 */
311
+	protected function onlyOneAttendeeCanRegister()
312
+	{
313
+		// display submit button since we have tickets available
314
+		add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
315
+		$this->hidden_input_qty = false;
316
+		$id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
317
+		$html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
318
+		$html .= esc_html__('Select this ticket', 'event_espresso') . '</label>';
319
+		$html .= '<input type="radio" name="tkt-slctr-qty-' . $this->EVT_ID . '"';
320
+		$html .= ' id="' . $id . '"';
321
+		$html .= ' class="ticket-selector-tbl-qty-slct" value="' . $this->row . '-1"';
322
+		$html .= $this->total_tickets === 1 ? ' checked="checked"' : '';
323
+		$html .= ' title=""/>';
324
+		return $html;
325
+	}
326
+
327
+
328
+	/**
329
+	 * ticketQuantitySelector
330
+	 *
331
+	 * @return string
332
+	 * @throws EE_Error
333
+	 */
334
+	protected function ticketQuantitySelector()
335
+	{
336
+		// display submit button since we have tickets available
337
+		add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
338
+		$this->hidden_input_qty = false;
339
+		$id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
340
+		$html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
341
+		$html .= esc_html__('Quantity', 'event_espresso') . '</label>';
342
+		$html .= '<select name="tkt-slctr-qty-' . $this->EVT_ID . '[]"';
343
+		$html .= ' id="' . $id . '"';
344
+		$html .= ' class="ticket-selector-tbl-qty-slct">';
345
+		// this ensures that non-required tickets with non-zero MIN QTYs don't HAVE to be purchased
346
+		if ($this->min !== 0 && ! $this->ticket->required()) {
347
+			$html .= '<option value="0">&nbsp;0&nbsp;</option>';
348
+		}
349
+		// offer ticket quantities from the min to the max
350
+		for ($i = $this->min; $i <= $this->max; $i++) {
351
+			$html .= '<option value="' . $i . '">&nbsp;' . $i . '&nbsp;</option>';
352
+		}
353
+		$html .= '</select>';
354
+		return $html;
355
+	}
356
+
357
+
358
+	/**
359
+	 * getHiddenInputs
360
+	 *
361
+	 * @return string
362
+	 * @throws EE_Error
363
+	 */
364
+	protected function ticketQtyAndIdHiddenInputs()
365
+	{
366
+		$html = '';
367
+		// depending on group reg we need to change the format for qty
368
+		if ($this->hidden_input_qty) {
369
+			$html .= '<input type="hidden" name="tkt-slctr-qty-' . $this->EVT_ID . '[]" value="0"/>';
370
+		}
371
+		$html .= '<input type="hidden" name="tkt-slctr-ticket-id-' . $this->EVT_ID . '[]"';
372
+		$html .= ' value="' . $this->ticket->ID() . '"/>';
373
+		return $html;
374
+	}
375 375
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
             '',
175 175
             'tckt-slctr-tbl-td-qty cntr',
176 176
             '',
177
-            'headers="quantity-' . $this->EVT_ID . '"'
177
+            'headers="quantity-'.$this->EVT_ID.'"'
178 178
         );
179 179
         $this->setTicketStatusDisplay($remaining);
180 180
         if (empty($this->ticket_status_display)) {
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
             '',
241 241
             'tckt-slctr-tbl-td-name',
242 242
             '',
243
-            'headers="details-' . $this->EVT_ID . '"'
243
+            'headers="details-'.$this->EVT_ID.'"'
244 244
         );
245 245
         $html .= EEH_HTML::strong($this->ticket->get_pretty('TKT_name'));
246 246
         $html .= $this->ticket_details->getShowHideLinks();
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
                 '',
275 275
                 'tckt-slctr-tbl-td-price jst-rght',
276 276
                 '',
277
-                'headers="price-' . $this->EVT_ID . '"'
277
+                'headers="price-'.$this->EVT_ID.'"'
278 278
             );
279 279
             $html .= \EEH_Template::format_currency($this->ticket_price);
280 280
             $html .= $this->ticket->taxable()
@@ -313,12 +313,12 @@  discard block
 block discarded – undo
313 313
         // display submit button since we have tickets available
314 314
         add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
315 315
         $this->hidden_input_qty = false;
316
-        $id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
317
-        $html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
318
-        $html .= esc_html__('Select this ticket', 'event_espresso') . '</label>';
319
-        $html .= '<input type="radio" name="tkt-slctr-qty-' . $this->EVT_ID . '"';
320
-        $html .= ' id="' . $id . '"';
321
-        $html .= ' class="ticket-selector-tbl-qty-slct" value="' . $this->row . '-1"';
316
+        $id = 'ticket-selector-tbl-qty-slct-'.$this->EVT_ID.'-'.$this->row;
317
+        $html = '<label class="ee-a11y-screen-reader-text" for="'.$id.'">';
318
+        $html .= esc_html__('Select this ticket', 'event_espresso').'</label>';
319
+        $html .= '<input type="radio" name="tkt-slctr-qty-'.$this->EVT_ID.'"';
320
+        $html .= ' id="'.$id.'"';
321
+        $html .= ' class="ticket-selector-tbl-qty-slct" value="'.$this->row.'-1"';
322 322
         $html .= $this->total_tickets === 1 ? ' checked="checked"' : '';
323 323
         $html .= ' title=""/>';
324 324
         return $html;
@@ -336,11 +336,11 @@  discard block
 block discarded – undo
336 336
         // display submit button since we have tickets available
337 337
         add_filter('FHEE__EE_Ticket_Selector__display_ticket_selector_submit', '__return_true');
338 338
         $this->hidden_input_qty = false;
339
-        $id = 'ticket-selector-tbl-qty-slct-' . $this->EVT_ID . '-' . $this->row;
340
-        $html = '<label class="ee-a11y-screen-reader-text" for="' . $id . '">';
341
-        $html .= esc_html__('Quantity', 'event_espresso') . '</label>';
342
-        $html .= '<select name="tkt-slctr-qty-' . $this->EVT_ID . '[]"';
343
-        $html .= ' id="' . $id . '"';
339
+        $id = 'ticket-selector-tbl-qty-slct-'.$this->EVT_ID.'-'.$this->row;
340
+        $html = '<label class="ee-a11y-screen-reader-text" for="'.$id.'">';
341
+        $html .= esc_html__('Quantity', 'event_espresso').'</label>';
342
+        $html .= '<select name="tkt-slctr-qty-'.$this->EVT_ID.'[]"';
343
+        $html .= ' id="'.$id.'"';
344 344
         $html .= ' class="ticket-selector-tbl-qty-slct">';
345 345
         // this ensures that non-required tickets with non-zero MIN QTYs don't HAVE to be purchased
346 346
         if ($this->min !== 0 && ! $this->ticket->required()) {
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
         }
349 349
         // offer ticket quantities from the min to the max
350 350
         for ($i = $this->min; $i <= $this->max; $i++) {
351
-            $html .= '<option value="' . $i . '">&nbsp;' . $i . '&nbsp;</option>';
351
+            $html .= '<option value="'.$i.'">&nbsp;'.$i.'&nbsp;</option>';
352 352
         }
353 353
         $html .= '</select>';
354 354
         return $html;
@@ -366,10 +366,10 @@  discard block
 block discarded – undo
366 366
         $html = '';
367 367
         // depending on group reg we need to change the format for qty
368 368
         if ($this->hidden_input_qty) {
369
-            $html .= '<input type="hidden" name="tkt-slctr-qty-' . $this->EVT_ID . '[]" value="0"/>';
369
+            $html .= '<input type="hidden" name="tkt-slctr-qty-'.$this->EVT_ID.'[]" value="0"/>';
370 370
         }
371
-        $html .= '<input type="hidden" name="tkt-slctr-ticket-id-' . $this->EVT_ID . '[]"';
372
-        $html .= ' value="' . $this->ticket->ID() . '"/>';
371
+        $html .= '<input type="hidden" name="tkt-slctr-ticket-id-'.$this->EVT_ID.'[]"';
372
+        $html .= ' value="'.$this->ticket->ID().'"/>';
373 373
         return $html;
374 374
     }
375 375
 }
Please login to merge, or discard this patch.
modules/ticket_selector/TicketSelectorIframeEmbedButton.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -14,24 +14,24 @@
 block discarded – undo
14 14
 class TicketSelectorIframeEmbedButton extends IframeEmbedButton
15 15
 {
16 16
 
17
-    /**
18
-     * TicketSelectorIframeEmbedButton constructor.
19
-     */
20
-    public function __construct()
21
-    {
22
-        parent::__construct(
23
-            esc_html__('Ticket Selector', 'event_espresso'),
24
-            'ticket_selector'
25
-        );
26
-    }
17
+	/**
18
+	 * TicketSelectorIframeEmbedButton constructor.
19
+	 */
20
+	public function __construct()
21
+	{
22
+		parent::__construct(
23
+			esc_html__('Ticket Selector', 'event_espresso'),
24
+			'ticket_selector'
25
+		);
26
+	}
27 27
 
28 28
 
29
-    /**
30
-     * Adds an iframe embed code button to the Event editor.
31
-     */
32
-    public function addEventEditorIframeEmbedButton()
33
-    {
34
-        // add button for iframe code to event editor.
35
-        $this->addEventEditorIframeEmbedButtonFilter();
36
-    }
29
+	/**
30
+	 * Adds an iframe embed code button to the Event editor.
31
+	 */
32
+	public function addEventEditorIframeEmbedButton()
33
+	{
34
+		// add button for iframe code to event editor.
35
+		$this->addEventEditorIframeEmbedButtonFilter();
36
+	}
37 37
 }
Please login to merge, or discard this patch.