Completed
Branch models-cleanup/model-relations (278059)
by
unknown
79:14 queued 69:54
created
core/db_classes/EE_Base_Class.class.php 3 patches
Doc Comments   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -393,7 +393,7 @@  discard block
 block discarded – undo
393 393
      * If a model name is provided (eg Registration), gets the model classname for that model.
394 394
      * Also works if a model class's classname is provided (eg EE_Registration).
395 395
      *
396
-     * @param null $model_name
396
+     * @param string $model_name
397 397
      * @return string like EEM_Attendee
398 398
      */
399 399
     private static function _get_model_classname($model_name = null)
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
      *
581 581
      * @param EE_Datetime_Field $datetime_field
582 582
      * @param bool              $pretty
583
-     * @param null              $date_or_time
583
+     * @param string|null              $date_or_time
584 584
      * @return void
585 585
      * @throws InvalidArgumentException
586 586
      * @throws InvalidInterfaceException
@@ -1582,7 +1582,7 @@  discard block
 block discarded – undo
1582 1582
      *
1583 1583
      * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
1584 1584
      *                             where the first value is the date format and the second value is the time format.
1585
-     * @return mixed string|array
1585
+     * @return string string|array
1586 1586
      */
1587 1587
     public function get_format($full = true)
1588 1588
     {
@@ -1705,7 +1705,7 @@  discard block
 block discarded – undo
1705 1705
      *
1706 1706
      * @param null  $field_to_order_by  What field is being used as the reference point.
1707 1707
      * @param array $query_params       Any additional conditions on the query.
1708
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1708
+     * @param string  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1709 1709
      *                                  you can indicate just the columns you want returned
1710 1710
      * @return array|EE_Base_Class
1711 1711
      * @throws ReflectionException
@@ -1733,7 +1733,7 @@  discard block
 block discarded – undo
1733 1733
      *
1734 1734
      * @param null  $field_to_order_by  What field is being used as the reference point.
1735 1735
      * @param array $query_params       Any additional conditions on the query.
1736
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1736
+     * @param string  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1737 1737
      *                                  you can indicate just the column you want returned
1738 1738
      * @return array|EE_Base_Class
1739 1739
      * @throws ReflectionException
@@ -2183,7 +2183,7 @@  discard block
 block discarded – undo
2183 2183
      * Deletes this model object permanently from db
2184 2184
      * (but keep in mind related models may block the delete and return an error)
2185 2185
      *
2186
-     * @return bool | int
2186
+     * @return integer | int
2187 2187
      * @throws ReflectionException
2188 2188
      * @throws InvalidArgumentException
2189 2189
      * @throws InvalidInterfaceException
@@ -2616,7 +2616,7 @@  discard block
 block discarded – undo
2616 2616
      * @param string $field_to_sum  name of field to count by.
2617 2617
      *                              By default, uses primary key
2618 2618
      *                              (which doesn't make much sense, so you should probably change it)
2619
-     * @return int
2619
+     * @return double
2620 2620
      * @throws ReflectionException
2621 2621
      * @throws InvalidArgumentException
2622 2622
      * @throws InvalidInterfaceException
@@ -3256,7 +3256,7 @@  discard block
 block discarded – undo
3256 3256
      * sets the time on a datetime property
3257 3257
      *
3258 3258
      * @access protected
3259
-     * @param string|Datetime $time       a valid time string for php datetime functions (or DateTime object)
3259
+     * @param string $time       a valid time string for php datetime functions (or DateTime object)
3260 3260
      * @param string          $field_name the name of the field the time is being set on (must match a
3261 3261
      *                                    EE_Datetime_Field)
3262 3262
      * @throws InvalidArgumentException
@@ -3351,7 +3351,7 @@  discard block
 block discarded – undo
3351 3351
      * sets the date on a datetime property
3352 3352
      *
3353 3353
      * @access protected
3354
-     * @param string|DateTime $date       a valid date string for php datetime functions ( or DateTime object)
3354
+     * @param string $date       a valid date string for php datetime functions ( or DateTime object)
3355 3355
      * @param string          $field_name the name of the field the date is being set on (must match a
3356 3356
      *                                    EE_Datetime_Field)
3357 3357
      * @throws InvalidArgumentException
Please login to merge, or discard this patch.
Indentation   +3367 added lines, -3367 removed lines patch added patch discarded remove patch
@@ -13,3382 +13,3382 @@
 block discarded – undo
13 13
 abstract class EE_Base_Class
14 14
 {
15 15
 
16
-    /**
17
-     * @var boolean indicating whether or not this model object is intended to ever be saved
18
-     * For example, we might create model objects intended to only be used for the duration
19
-     * of this request and to be thrown away, and if they were accidentally saved
20
-     * it would be a bug.
21
-     */
22
-    protected $_allow_persist = true;
23
-
24
-    /**
25
-     * This property is for holding a cached array of object properties indexed by property name as the key.
26
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
27
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
28
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
29
-     *
30
-     * @var array
31
-     */
32
-    protected $_cached_properties = [];
33
-
34
-    /**
35
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
36
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
37
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
38
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
39
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
40
-     * array as:
41
-     * array(
42
-     *  'Registration_Count' => 24
43
-     * );
44
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
45
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
46
-     * info)
47
-     *
48
-     * @var array
49
-     */
50
-    protected $custom_selection_results = [];
51
-
52
-    /**
53
-     * date format
54
-     * pattern or format for displaying dates
55
-     *
56
-     * @var string $_dt_frmt
57
-     */
58
-    protected $_dt_frmt;
59
-
60
-    /**
61
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
62
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
63
-     *
64
-     * @var array
65
-     */
66
-    protected $_fields = [];
67
-
68
-    /**
69
-     * @var boolean indicating whether or not this model object's properties have changed since construction
70
-     */
71
-    protected $_has_changes = false;
72
-
73
-    /**
74
-     * @var EEM_Base
75
-     */
76
-    protected $_model;
77
-
78
-
79
-    /**
80
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
81
-     * single
82
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
83
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
84
-     * all others have an array)
85
-     *
86
-     * @var array
87
-     */
88
-    protected $_model_relations = [];
89
-
90
-    /**
91
-     * This is an array of the original properties and values provided during construction
92
-     * of this model object. (keys are model field names, values are their values).
93
-     * This list is important to remember so that when we are merging data from the db, we know
94
-     * which values to override and which to not override.
95
-     *
96
-     * @var array
97
-     */
98
-    protected $_props_n_values_provided_in_constructor;
99
-
100
-    /**
101
-     * Timezone
102
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
103
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
104
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
105
-     * access to it.
106
-     *
107
-     * @var string
108
-     */
109
-    protected $_timezone;
110
-
111
-    /**
112
-     * time format
113
-     * pattern or format for displaying time
114
-     *
115
-     * @var string $_tm_frmt
116
-     */
117
-    protected $_tm_frmt;
118
-
119
-
120
-    /**
121
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
122
-     * play nice
123
-     *
124
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
125
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
126
-     *                                                         TXN_amount, QST_name, etc) and values are their values
127
-     * @param boolean $by_db                                   a flag for setting if the class is instantiated by the
128
-     *                                                         corresponding db model or not.
129
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
130
-     *                                                         be in when instantiating a EE_Base_Class object.
131
-     * @param array   $date_formats                            An array of date formats to set on construct where first
132
-     *                                                         value is the date_format and second value is the time
133
-     *                                                         format.
134
-     * @throws InvalidArgumentException
135
-     * @throws InvalidInterfaceException
136
-     * @throws InvalidDataTypeException
137
-     * @throws EE_Error
138
-     * @throws ReflectionException
139
-     */
140
-    protected function __construct($fieldValues = [], $by_db = false, $timezone = '', $date_formats = [])
141
-    {
142
-        $className = get_class($this);
143
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
144
-        $this->_model = $this->get_model();
145
-        $model_fields = $this->_model->field_settings();
146
-        // ensure $fieldValues is an array
147
-        $fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
148
-        // verify client code has not passed any invalid field names
149
-        foreach ($fieldValues as $field_name => $field_value) {
150
-            if (! isset($model_fields[ $field_name ])) {
151
-                throw new EE_Error(
152
-                    sprintf(
153
-                        esc_html__(
154
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
155
-                            'event_espresso'
156
-                        ),
157
-                        $field_name,
158
-                        get_class($this),
159
-                        implode(', ', array_keys($model_fields))
160
-                    )
161
-                );
162
-            }
163
-        }
164
-        $this->set_timezone($timezone);
165
-        if (! empty($date_formats) && is_array($date_formats)) {
166
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
167
-        } else {
168
-            // set default formats for date and time
169
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
170
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
171
-        }
172
-        // if db model is instantiating
173
-        if ($by_db) {
174
-            // client code has indicated these field values are from the database
175
-            foreach ($model_fields as $fieldName => $field) {
176
-                $this->set_from_db(
177
-                    $fieldName,
178
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
179
-                );
180
-            }
181
-        } else {
182
-            // we're constructing a brand
183
-            // new instance of the model object. Generally, this means we'll need to do more field validation
184
-            foreach ($model_fields as $fieldName => $field) {
185
-                $this->set(
186
-                    $fieldName,
187
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
188
-                    true
189
-                );
190
-            }
191
-        }
192
-        // remember what values were passed to this constructor
193
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
194
-        // remember in entity mapper
195
-        if (! $by_db && $this->_model->has_primary_key_field() && $this->ID()) {
196
-            $this->_model->add_to_entity_map($this);
197
-        }
198
-        // setup all the relations
199
-        foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
200
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
202
-            } else {
203
-                $this->_model_relations[ $relation_name ] = [];
204
-            }
205
-        }
206
-        /**
207
-         * Action done at the end of each model object construction
208
-         *
209
-         * @param EE_Base_Class $this the model object just created
210
-         */
211
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
-    }
213
-
214
-
215
-    /**
216
-     * for getting a model while instantiated.
217
-     *
218
-     * @return EEM_Base | EEM_CPT_Base
219
-     * @throws ReflectionException
220
-     * @throws InvalidArgumentException
221
-     * @throws InvalidInterfaceException
222
-     * @throws InvalidDataTypeException
223
-     * @throws EE_Error
224
-     */
225
-    public function get_model()
226
-    {
227
-        if (! $this->_model) {
228
-            $modelName    = self::_get_model_classname(get_class($this));
229
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
230
-        }
231
-        return $this->_model;
232
-    }
233
-
234
-
235
-    /**
236
-     * Overrides parent because parent expects old models.
237
-     * This also doesn't do any validation, and won't work for serialized arrays
238
-     *
239
-     * @param string $field_name
240
-     * @param mixed  $field_value_from_db
241
-     * @throws InvalidArgumentException
242
-     * @throws InvalidInterfaceException
243
-     * @throws InvalidDataTypeException
244
-     * @throws EE_Error
245
-     */
246
-    public function set_from_db($field_name, $field_value_from_db)
247
-    {
248
-        $field_obj = $this->_model->field_settings_for($field_name);
249
-        if ($field_obj instanceof EE_Model_Field_Base) {
250
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
251
-            // eg, a CPT model object could have an entry in the posts table, but no
252
-            // entry in the meta table. Meaning that all its columns in the meta table
253
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
254
-            if ($field_value_from_db === null) {
255
-                if ($field_obj->is_nullable()) {
256
-                    // if the field allows nulls, then let it be null
257
-                    $field_value = null;
258
-                } else {
259
-                    $field_value = $field_obj->get_default_value();
260
-                }
261
-            } else {
262
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
263
-            }
264
-            $this->_fields[ $field_name ] = $field_value;
265
-            $this->_clear_cached_property($field_name);
266
-        }
267
-    }
268
-
269
-
270
-    /**
271
-     * Overrides parent because parent expects old models.
272
-     * This also doesn't do any validation, and won't work for serialized arrays
273
-     *
274
-     * @param string $field_name
275
-     * @param mixed  $field_value
276
-     * @param bool   $use_default
277
-     * @throws InvalidArgumentException
278
-     * @throws InvalidInterfaceException
279
-     * @throws InvalidDataTypeException
280
-     * @throws EE_Error
281
-     * @throws ReflectionException
282
-     * @throws ReflectionException
283
-     * @throws ReflectionException
284
-     */
285
-    public function set($field_name, $field_value, $use_default = false)
286
-    {
287
-        // if not using default and nothing has changed, and object has already been setup (has ID),
288
-        // then don't do anything
289
-        if (
290
-            ! $use_default
291
-            && $this->_fields[ $field_name ] === $field_value
292
-            && $this->ID()
293
-        ) {
294
-            return;
295
-        }
296
-        $this->_has_changes = true;
297
-        $field_obj          = $this->_model->field_settings_for($field_name);
298
-        if ($field_obj instanceof EE_Model_Field_Base) {
299
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
300
-            if ($field_obj instanceof EE_Datetime_Field) {
301
-                $field_obj->set_timezone($this->_timezone);
302
-                $field_obj->set_date_format($this->_dt_frmt);
303
-                $field_obj->set_time_format($this->_tm_frmt);
304
-            }
305
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
306
-            // should the value be null?
307
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
308
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
309
-                /**
310
-                 * To save having to refactor all the models, if a default value is used for a
311
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
312
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
313
-                 * object.
314
-                 *
315
-                 * @since 4.6.10+
316
-                 */
317
-                if (
318
-                    $field_obj instanceof EE_Datetime_Field
319
-                    && $this->_fields[ $field_name ] !== null
320
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
321
-                ) {
322
-                    empty($this->_fields[ $field_name ])
323
-                        ? $this->set($field_name, time())
324
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
325
-                }
326
-            } else {
327
-                $this->_fields[ $field_name ] = $holder_of_value;
328
-            }
329
-            // if we're not in the constructor...
330
-            // now check if what we set was a primary key
331
-            if (
332
-                // note: props_n_values_provided_in_constructor is only set at the END of the constructor
333
-                $this->_props_n_values_provided_in_constructor
334
-                && $field_value
335
-                && $field_name === $this->_model->primary_key_name()
336
-            ) {
337
-                // if so, we want all this object's fields to be filled either with
338
-                // what we've explicitly set on this model
339
-                // or what we have in the db
340
-                // echo "setting primary key!";
341
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
342
-                $obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
343
-                foreach ($fields_on_model as $field_obj) {
344
-                    if (
345
-                        ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
346
-                        && $field_obj->get_name() !== $field_name
347
-                    ) {
348
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
349
-                    }
350
-                }
351
-                // oh this model object has an ID? well make sure its in the entity mapper
352
-                $this->_model->add_to_entity_map($this);
353
-            }
354
-            // let's unset any cache for this field_name from the $_cached_properties property.
355
-            $this->_clear_cached_property($field_name);
356
-        } else {
357
-            throw new EE_Error(
358
-                sprintf(
359
-                    esc_html__(
360
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
361
-                        'event_espresso'
362
-                    ),
363
-                    $field_name
364
-                )
365
-            );
366
-        }
367
-    }
368
-
369
-
370
-    /**
371
-     * Gets the value of the primary key.
372
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
373
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
374
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
375
-     *
376
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
377
-     * @throws InvalidArgumentException
378
-     * @throws InvalidInterfaceException
379
-     * @throws InvalidDataTypeException
380
-     * @throws EE_Error
381
-     */
382
-    public function ID()
383
-    {
384
-        // now that we know the name of the variable, use a variable variable to get its value and return its
385
-        if ($this->_model->has_primary_key_field()) {
386
-            return $this->_fields[ $this->_model->primary_key_name() ];
387
-        }
388
-        return $this->_model->get_index_primary_key_string($this->_fields);
389
-    }
390
-
391
-
392
-    /**
393
-     * If a model name is provided (eg Registration), gets the model classname for that model.
394
-     * Also works if a model class's classname is provided (eg EE_Registration).
395
-     *
396
-     * @param null $model_name
397
-     * @return string like EEM_Attendee
398
-     */
399
-    private static function _get_model_classname($model_name = null)
400
-    {
401
-        if (strpos($model_name, 'EE_') === 0) {
402
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
403
-        } else {
404
-            $model_classname = 'EEM_' . $model_name;
405
-        }
406
-        return $model_classname;
407
-    }
408
-
409
-
410
-    /**
411
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
412
-     *
413
-     * @param string $model_classname
414
-     * @param string $timezone
415
-     * @return EEM_Base
416
-     * @throws ReflectionException
417
-     * @throws InvalidArgumentException
418
-     * @throws InvalidInterfaceException
419
-     * @throws InvalidDataTypeException
420
-     * @throws EE_Error
421
-     */
422
-    protected static function _get_model_instance_with_name($model_classname, $timezone = '')
423
-    {
424
-        $model_classname = str_replace('EEM_', '', $model_classname);
425
-        $model           = EE_Registry::instance()->load_model($model_classname);
426
-        $model->set_timezone($timezone);
427
-        return $model;
428
-    }
429
-
430
-
431
-    /**
432
-     * This just clears out ONE property if it exists in the cache
433
-     *
434
-     * @param string $property_name the property to remove if it exists (from the _cached_properties array)
435
-     * @return void
436
-     */
437
-    protected function _clear_cached_property($property_name)
438
-    {
439
-        if (isset($this->_cached_properties[ $property_name ])) {
440
-            unset($this->_cached_properties[ $property_name ]);
441
-        }
442
-    }
443
-
444
-
445
-    /**
446
-     * Gets the EEM_*_Model for this class
447
-     *
448
-     * @param string $classname
449
-     * @param string $timezone
450
-     * @return EEM_Base
451
-     * @throws InvalidArgumentException
452
-     * @throws InvalidInterfaceException
453
-     * @throws InvalidDataTypeException
454
-     * @throws EE_Error
455
-     * @throws ReflectionException
456
-     */
457
-    protected static function _get_model($classname, $timezone = '')
458
-    {
459
-        // find model for this class
460
-        if (! $classname) {
461
-            throw new EE_Error(
462
-                sprintf(
463
-                    esc_html__(
464
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
465
-                        'event_espresso'
466
-                    ),
467
-                    $classname
468
-                )
469
-            );
470
-        }
471
-        $modelName = self::_get_model_classname($classname);
472
-        return self::_get_model_instance_with_name($modelName, $timezone);
473
-    }
474
-
475
-
476
-    /**
477
-     * verifies that the specified field is of the correct type
478
-     *
479
-     * @param string $field_name
480
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
481
-     *                                (in cases where the same property may be used for different outputs
482
-     *                                - i.e. datetime, money etc.)
483
-     * @return mixed
484
-     * @throws InvalidArgumentException
485
-     * @throws InvalidInterfaceException
486
-     * @throws InvalidDataTypeException
487
-     * @throws EE_Error
488
-     */
489
-    public function get($field_name, $extra_cache_ref = null)
490
-    {
491
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
492
-    }
493
-
494
-
495
-    /**
496
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
497
-     * This also SETS the cache if we return the actual property!
498
-     *
499
-     * @param string $field_name       the name of the property we're trying to retrieve
500
-     * @param bool   $pretty
501
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
502
-     *                                 (in cases where the same property may be used for different outputs
503
-     *                                 - i.e. datetime, money etc.)
504
-     *                                 It can also accept certain pre-defined "schema" strings
505
-     *                                 to define how to output the property.
506
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
507
-     * @return mixed                   whatever the value for the property is we're retrieving
508
-     * @throws InvalidArgumentException
509
-     * @throws InvalidInterfaceException
510
-     * @throws InvalidDataTypeException
511
-     * @throws EE_Error
512
-     */
513
-    protected function _get_cached_property($field_name, $pretty = false, $extra_cache_ref = null)
514
-    {
515
-        // verify the field exists
516
-        $this->_model->field_settings_for($field_name);
517
-        $cache_type = $pretty ? 'pretty' : 'standard';
518
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
519
-        if (isset($this->_cached_properties[ $field_name ][ $cache_type ])) {
520
-            return $this->_cached_properties[ $field_name ][ $cache_type ];
521
-        }
522
-        $value = $this->_get_fresh_property($field_name, $pretty, $extra_cache_ref);
523
-        $this->_set_cached_property($field_name, $value, $cache_type);
524
-        return $value;
525
-    }
526
-
527
-
528
-    /**
529
-     * If the cache didn't fetch the needed item, this fetches it.
530
-     *
531
-     * @param string $field_name
532
-     * @param bool   $pretty
533
-     * @param string $extra_cache_ref
534
-     * @return mixed
535
-     * @throws InvalidArgumentException
536
-     * @throws InvalidInterfaceException
537
-     * @throws InvalidDataTypeException
538
-     * @throws EE_Error
539
-     */
540
-    protected function _get_fresh_property($field_name, $pretty = false, $extra_cache_ref = null)
541
-    {
542
-        $field_obj = $this->_model->field_settings_for($field_name);
543
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
544
-        if ($field_obj instanceof EE_Datetime_Field) {
545
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
546
-        }
547
-        if (! isset($this->_fields[ $field_name ])) {
548
-            $this->_fields[ $field_name ] = null;
549
-        }
550
-        return $pretty
551
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $field_name ], $extra_cache_ref)
552
-            : $field_obj->prepare_for_get($this->_fields[ $field_name ]);
553
-    }
554
-
555
-
556
-    /**
557
-     * For adding an item to the cached_properties property.
558
-     *
559
-     * @access protected
560
-     * @param string      $field_name the property item the corresponding value is for.
561
-     * @param mixed       $value      The value we are caching.
562
-     * @param string|null $cache_type
563
-     * @return void
564
-     * @throws InvalidArgumentException
565
-     * @throws InvalidInterfaceException
566
-     * @throws InvalidDataTypeException
567
-     * @throws EE_Error
568
-     */
569
-    protected function _set_cached_property($field_name, $value, $cache_type = null)
570
-    {
571
-        // first make sure this property exists
572
-        $this->_model->field_settings_for($field_name);
573
-        $cache_type                                             = empty($cache_type) ? 'standard' : $cache_type;
574
-        $this->_cached_properties[ $field_name ][ $cache_type ] = $value;
575
-    }
576
-
577
-
578
-    /**
579
-     * set timezone, formats, and output for EE_Datetime_Field objects
580
-     *
581
-     * @param EE_Datetime_Field $datetime_field
582
-     * @param bool              $pretty
583
-     * @param null              $date_or_time
584
-     * @return void
585
-     * @throws InvalidArgumentException
586
-     * @throws InvalidInterfaceException
587
-     * @throws InvalidDataTypeException
588
-     */
589
-    protected function _prepare_datetime_field(
590
-        EE_Datetime_Field $datetime_field,
591
-        $pretty = false,
592
-        $date_or_time = null
593
-    ) {
594
-        $datetime_field->set_timezone($this->_timezone);
595
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
596
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
597
-        // set the output returned
598
-        switch ($date_or_time) {
599
-            case 'D':
600
-                $datetime_field->set_date_time_output('date');
601
-                break;
602
-            case 'T':
603
-                $datetime_field->set_date_time_output('time');
604
-                break;
605
-            default:
606
-                $datetime_field->set_date_time_output();
607
-        }
608
-    }
609
-
610
-
611
-    /**
612
-     * @param $props_n_values
613
-     * @param $classname
614
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
615
-     * @throws ReflectionException
616
-     * @throws InvalidArgumentException
617
-     * @throws InvalidInterfaceException
618
-     * @throws InvalidDataTypeException
619
-     * @throws EE_Error
620
-     */
621
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
622
-    {
623
-        // TODO: will not work for Term_Relationships because they have no PK!
624
-        $primary_id_ref = self::_get_primary_key_name($classname);
625
-        if (
626
-            array_key_exists($primary_id_ref, $props_n_values)
627
-            && ! empty($props_n_values[ $primary_id_ref ])
628
-        ) {
629
-            $id = $props_n_values[ $primary_id_ref ];
630
-            return self::_get_model($classname)->get_from_entity_map($id);
631
-        }
632
-        return false;
633
-    }
634
-
635
-
636
-    /**
637
-     * returns the name of the primary key attribute
638
-     *
639
-     * @param null $classname
640
-     * @return string
641
-     * @throws InvalidArgumentException
642
-     * @throws InvalidInterfaceException
643
-     * @throws InvalidDataTypeException
644
-     * @throws EE_Error
645
-     * @throws ReflectionException
646
-     */
647
-    protected static function _get_primary_key_name($classname = null)
648
-    {
649
-        if (! $classname) {
650
-            throw new EE_Error(
651
-                sprintf(
652
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
653
-                    $classname
654
-                )
655
-            );
656
-        }
657
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
658
-    }
659
-
660
-
661
-    /**
662
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
663
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
664
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
665
-     * we return false.
666
-     *
667
-     * @param array  $props_n_values    incoming array of properties and their values
668
-     * @param string $classname         the classname of the child class
669
-     * @param string $timezone
670
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the
671
-     *                                  date_format and the second value is the time format
672
-     * @return mixed (EE_Base_Class|bool)
673
-     * @throws InvalidArgumentException
674
-     * @throws InvalidInterfaceException
675
-     * @throws InvalidDataTypeException
676
-     * @throws EE_Error
677
-     * @throws ReflectionException
678
-     * @throws ReflectionException
679
-     * @throws ReflectionException
680
-     */
681
-    protected static function _check_for_object($props_n_values, $classname, $timezone = '', $date_formats = [])
682
-    {
683
-        $existing = null;
684
-        $model    = self::_get_model($classname, $timezone);
685
-        if ($model->has_primary_key_field()) {
686
-            $primary_id_ref = self::_get_primary_key_name($classname);
687
-            if (
688
-                array_key_exists($primary_id_ref, $props_n_values)
689
-                && ! empty($props_n_values[ $primary_id_ref ])
690
-            ) {
691
-                $existing = $model->get_one_by_ID(
692
-                    $props_n_values[ $primary_id_ref ]
693
-                );
694
-            }
695
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
696
-            // no primary key on this model, but there's still a matching item in the DB
697
-            $existing = $model->get_one_by_ID(
698
-                $model->get_index_primary_key_string($props_n_values)
699
-            );
700
-        }
701
-        if ($existing) {
702
-            // set date formats if present before setting values
703
-            if (! empty($date_formats) && is_array($date_formats)) {
704
-                $existing->set_date_format($date_formats[0]);
705
-                $existing->set_time_format($date_formats[1]);
706
-            } else {
707
-                // set default formats for date and time
708
-                $existing->set_date_format(get_option('date_format'));
709
-                $existing->set_time_format(get_option('time_format'));
710
-            }
711
-            foreach ($props_n_values as $property => $field_value) {
712
-                $existing->set($property, $field_value);
713
-            }
714
-            return $existing;
715
-        }
716
-        return false;
717
-    }
718
-
719
-
720
-    /**
721
-     * This sets the internal date format to what is sent in to be used as the new default for the class
722
-     * internally instead of wp set date format options
723
-     *
724
-     * @param string $format should be a format recognizable by PHP date() functions.
725
-     * @since 4.6
726
-     */
727
-    public function set_date_format($format)
728
-    {
729
-        $this->_dt_frmt = $format;
730
-        // clear cached_properties because they won't be relevant now.
731
-        $this->_clear_cached_properties();
732
-    }
733
-
734
-
735
-    /**
736
-     * This sets the internal time format string to what is sent in to be used as the new default for the
737
-     * class internally instead of wp set time format options.
738
-     *
739
-     * @param string $format should be a format recognizable by PHP date() functions.
740
-     * @since 4.6
741
-     */
742
-    public function set_time_format($format)
743
-    {
744
-        $this->_tm_frmt = $format;
745
-        // clear cached_properties because they won't be relevant now.
746
-        $this->_clear_cached_properties();
747
-    }
748
-
749
-
750
-    /**
751
-     * This just takes care of clearing out the cached_properties
752
-     *
753
-     * @return void
754
-     */
755
-    protected function _clear_cached_properties()
756
-    {
757
-        $this->_cached_properties = [];
758
-    }
759
-
760
-
761
-    /**
762
-     * Sets whether or not this model object should be allowed to be saved to the DB.
763
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
764
-     * you got new information that somehow made you change your mind.
765
-     *
766
-     * @param boolean $allow_persist
767
-     * @return boolean
768
-     */
769
-    public function set_allow_persist($allow_persist)
770
-    {
771
-        return $this->_allow_persist = $allow_persist;
772
-    }
773
-
774
-
775
-    /**
776
-     * Gets the field's original value when this object was constructed during this request.
777
-     * This can be helpful when determining if a model object has changed or not
778
-     *
779
-     * @param string $field_name
780
-     * @return mixed|null
781
-     * @throws InvalidArgumentException
782
-     * @throws InvalidInterfaceException
783
-     * @throws InvalidDataTypeException
784
-     * @throws EE_Error
785
-     */
786
-    public function get_original($field_name)
787
-    {
788
-        if (
789
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
790
-            && $field_settings = $this->_model->field_settings_for($field_name)
791
-        ) {
792
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
793
-        }
794
-        return null;
795
-    }
796
-
797
-
798
-    /**
799
-     * @param EE_Base_Class $obj
800
-     * @return string
801
-     */
802
-    public function get_class($obj)
803
-    {
804
-        return get_class($obj);
805
-    }
806
-
807
-
808
-    /**
809
-     * Set custom select values for model.
810
-     *
811
-     * @param array $custom_select_values
812
-     */
813
-    public function setCustomSelectsValues(array $custom_select_values)
814
-    {
815
-        $this->custom_selection_results = $custom_select_values;
816
-    }
817
-
818
-
819
-    /**
820
-     * Returns the custom select value for the provided alias if its set.
821
-     * If not set, returns null.
822
-     *
823
-     * @param string $alias
824
-     * @return string|int|float|null
825
-     */
826
-    public function getCustomSelect($alias)
827
-    {
828
-        return isset($this->custom_selection_results[ $alias ])
829
-            ? $this->custom_selection_results[ $alias ]
830
-            : null;
831
-    }
832
-
833
-
834
-    /**
835
-     * This sets the field value on the db column if it exists for the given $column_name or
836
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
837
-     *
838
-     * @param string $field_name  Must be the exact column name.
839
-     * @param mixed  $field_value The value to set.
840
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
841
-     * @throws InvalidArgumentException
842
-     * @throws InvalidInterfaceException
843
-     * @throws InvalidDataTypeException
844
-     * @throws EE_Error
845
-     * @throws ReflectionException
846
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
847
-     */
848
-    public function set_field_or_extra_meta($field_name, $field_value)
849
-    {
850
-        if ($this->_model->has_field($field_name)) {
851
-            $this->set($field_name, $field_value);
852
-            return true;
853
-        }
854
-        // ensure this object is saved first so that extra meta can be properly related.
855
-        $this->save();
856
-        return $this->update_extra_meta($field_name, $field_value);
857
-    }
858
-
859
-
860
-    /**
861
-     *        Saves this object to the database. An array may be supplied to set some values on this
862
-     * object just before saving.
863
-     *
864
-     * @access public
865
-     * @param array $set_cols_n_values keys are field names, values are their new values,
866
-     *                                 if provided during the save() method (often client code will change the fields'
867
-     *                                 values before calling save)
868
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
869
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
870
-     * @throws InvalidInterfaceException
871
-     * @throws InvalidDataTypeException
872
-     * @throws EE_Error
873
-     * @throws InvalidArgumentException
874
-     * @throws ReflectionException
875
-     * @throws ReflectionException
876
-     * @throws ReflectionException
877
-     */
878
-    public function save($set_cols_n_values = [])
879
-    {
880
-        /**
881
-         * Filters the fields we're about to save on the model object
882
-         *
883
-         * @param array         $set_cols_n_values
884
-         * @param EE_Base_Class $model_object
885
-         */
886
-        $set_cols_n_values = (array) apply_filters(
887
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
888
-            $set_cols_n_values,
889
-            $this
890
-        );
891
-        // set attributes as provided in $set_cols_n_values
892
-        foreach ($set_cols_n_values as $column => $value) {
893
-            $this->set($column, $value);
894
-        }
895
-        // no changes ? then don't do anything
896
-        if (! $this->_has_changes && $this->ID() && $this->_model->get_primary_key_field()->is_auto_increment()) {
897
-            return 0;
898
-        }
899
-        /**
900
-         * Saving a model object.
901
-         * Before we perform a save, this action is fired.
902
-         *
903
-         * @param EE_Base_Class $model_object the model object about to be saved.
904
-         */
905
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
906
-        if (! $this->allow_persist()) {
907
-            return 0;
908
-        }
909
-        // now get current attribute values
910
-        $save_cols_n_values = $this->_fields;
911
-        // if the object already has an ID, update it. Otherwise, insert it
912
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
913
-        // They have been
914
-        $old_assumption_concerning_value_preparation = $this->_model
915
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
916
-        $this->_model->assume_values_already_prepared_by_model_object(true);
917
-        // does this model have an autoincrement PK?
918
-        if ($this->_model->has_primary_key_field()) {
919
-            if ($this->_model->get_primary_key_field()->is_auto_increment()) {
920
-                // ok check if it's set, if so: update; if not, insert
921
-                if (! empty($save_cols_n_values[ $this->_model->primary_key_name() ])) {
922
-                    $results = $this->_model->update_by_ID($save_cols_n_values, $this->ID());
923
-                } else {
924
-                    unset($save_cols_n_values[ $this->_model->primary_key_name() ]);
925
-                    $results = $this->_model->insert($save_cols_n_values);
926
-                    if ($results) {
927
-                        // if successful, set the primary key
928
-                        // but don't use the normal SET method, because it will check if
929
-                        // an item with the same ID exists in the mapper & db, then
930
-                        // will find it in the db (because we just added it) and THAT object
931
-                        // will get added to the mapper before we can add this one!
932
-                        // but if we just avoid using the SET method, all that headache can be avoided
933
-                        $pk_field_name                   = $this->_model->primary_key_name();
934
-                        $this->_fields[ $pk_field_name ] = $results;
935
-                        $this->_clear_cached_property($pk_field_name);
936
-                        $this->_model->add_to_entity_map($this);
937
-                        $this->_update_cached_related_model_objs_fks();
938
-                    }
939
-                }
940
-            } else {// PK is NOT auto-increment
941
-                // so check if one like it already exists in the db
942
-                if ($this->_model->exists_by_ID($this->ID())) {
943
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
944
-                        throw new EE_Error(
945
-                            sprintf(
946
-                                esc_html__(
947
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
948
-                                    'event_espresso'
949
-                                ),
950
-                                get_class($this),
951
-                                get_class($this->_model) . '::instance()->add_to_entity_map()',
952
-                                get_class($this->_model) . '::instance()->get_one_by_ID()',
953
-                                '<br />'
954
-                            )
955
-                        );
956
-                    }
957
-                    $results = $this->_model->update_by_ID($save_cols_n_values, $this->ID());
958
-                } else {
959
-                    $results = $this->_model->insert($save_cols_n_values);
960
-                    $this->_update_cached_related_model_objs_fks();
961
-                }
962
-            }
963
-        } else {// there is NO primary key
964
-            $already_in_db = false;
965
-            foreach ($this->_model->unique_indexes() as $index) {
966
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
967
-                if ($this->_model->exists([$uniqueness_where_params])) {
968
-                    $already_in_db = true;
969
-                }
970
-            }
971
-            if ($already_in_db) {
972
-                $combined_pk_fields_n_values = array_intersect_key(
973
-                    $save_cols_n_values,
974
-                    $this->_model->get_combined_primary_key_fields()
975
-                );
976
-                $results                     = $this->_model->update(
977
-                    $save_cols_n_values,
978
-                    $combined_pk_fields_n_values
979
-                );
980
-            } else {
981
-                $results = $this->_model->insert($save_cols_n_values);
982
-            }
983
-        }
984
-        // restore the old assumption about values being prepared by the model object
985
-        $this->_model->assume_values_already_prepared_by_model_object(
986
-            $old_assumption_concerning_value_preparation
987
-        );
988
-        /**
989
-         * After saving the model object this action is called
990
-         *
991
-         * @param EE_Base_Class $model_object which was just saved
992
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
993
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
994
-         */
995
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
996
-        $this->_has_changes = false;
997
-        return $results;
998
-    }
999
-
1000
-
1001
-    /**
1002
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
1003
-     * A $previous_value can be specified in case there are many meta rows with the same key
1004
-     *
1005
-     * @param string $meta_key
1006
-     * @param mixed  $meta_value
1007
-     * @param mixed  $previous_value
1008
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
1009
-     *                  NOTE: if the values haven't changed, returns 0
1010
-     * @throws InvalidArgumentException
1011
-     * @throws InvalidInterfaceException
1012
-     * @throws InvalidDataTypeException
1013
-     * @throws EE_Error
1014
-     * @throws ReflectionException
1015
-     */
1016
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
1017
-    {
1018
-        $query_params = [
1019
-            [
1020
-                'EXM_key'  => $meta_key,
1021
-                'OBJ_ID'   => $this->ID(),
1022
-                'EXM_type' => $this->_model->get_this_model_name(),
1023
-            ],
1024
-        ];
1025
-        if ($previous_value !== null) {
1026
-            $query_params[0]['EXM_value'] = $meta_value;
1027
-        }
1028
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
1029
-        if (! $existing_rows_like_that) {
1030
-            return $this->add_extra_meta($meta_key, $meta_value);
1031
-        }
1032
-        foreach ($existing_rows_like_that as $existing_row) {
1033
-            $existing_row->save(['EXM_value' => $meta_value]);
1034
-        }
1035
-        return count($existing_rows_like_that);
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
1041
-     *
1042
-     * @return boolean
1043
-     */
1044
-    public function allow_persist()
1045
-    {
1046
-        return $this->_allow_persist;
1047
-    }
1048
-
1049
-
1050
-    /**
1051
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1052
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1053
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1054
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1055
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1056
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1057
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1058
-     *
1059
-     * @return void
1060
-     * @throws ReflectionException
1061
-     * @throws InvalidArgumentException
1062
-     * @throws InvalidInterfaceException
1063
-     * @throws InvalidDataTypeException
1064
-     * @throws EE_Error
1065
-     */
1066
-    protected function _update_cached_related_model_objs_fks()
1067
-    {
1068
-        foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
1069
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1070
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1071
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1072
-                        $this->_model->get_this_model_name()
1073
-                    );
1074
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1075
-                    if ($related_model_obj_in_cache->ID()) {
1076
-                        $related_model_obj_in_cache->save();
1077
-                    }
1078
-                }
1079
-            }
1080
-        }
1081
-    }
1082
-
1083
-
1084
-    /**
1085
-     * in_entity_map
1086
-     * Checks if this model object has been proven to already be in the entity map
1087
-     *
1088
-     * @return boolean
1089
-     * @throws InvalidArgumentException
1090
-     * @throws InvalidInterfaceException
1091
-     * @throws InvalidDataTypeException
1092
-     * @throws EE_Error
1093
-     */
1094
-    public function in_entity_map()
1095
-    {
1096
-        // well, if we looked, did we find it in the entity map?
1097
-        return $this->ID() && $this->_model->get_from_entity_map($this->ID()) === $this;
1098
-    }
1099
-
1100
-
1101
-    /**
1102
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
1103
-     * no other extra meta for this model object have the same key. Returns TRUE if the
1104
-     * extra meta row was entered, false if not
1105
-     *
1106
-     * @param string  $meta_key
1107
-     * @param mixed   $meta_value
1108
-     * @param boolean $unique
1109
-     * @return boolean
1110
-     * @throws InvalidArgumentException
1111
-     * @throws InvalidInterfaceException
1112
-     * @throws InvalidDataTypeException
1113
-     * @throws EE_Error
1114
-     * @throws ReflectionException
1115
-     * @throws ReflectionException
1116
-     */
1117
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
1118
-    {
1119
-        if ($unique) {
1120
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
1121
-                [
1122
-                    [
1123
-                        'EXM_key'  => $meta_key,
1124
-                        'OBJ_ID'   => $this->ID(),
1125
-                        'EXM_type' => $this->_model->get_this_model_name(),
1126
-                    ],
1127
-                ]
1128
-            );
1129
-            if ($existing_extra_meta) {
1130
-                return false;
1131
-            }
1132
-        }
1133
-        $new_extra_meta = EE_Extra_Meta::new_instance(
1134
-            [
1135
-                'EXM_key'   => $meta_key,
1136
-                'EXM_value' => $meta_value,
1137
-                'OBJ_ID'    => $this->ID(),
1138
-                'EXM_type'  => $this->_model->get_this_model_name(),
1139
-            ]
1140
-        );
1141
-        $new_extra_meta->save();
1142
-        return true;
1143
-    }
1144
-
1145
-
1146
-    /**
1147
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
1148
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
1149
-     *
1150
-     * @param string $relationName
1151
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
1152
-     * @throws InvalidArgumentException
1153
-     * @throws InvalidInterfaceException
1154
-     * @throws InvalidDataTypeException
1155
-     * @throws EE_Error
1156
-     * @throws ReflectionException
1157
-     */
1158
-    public function get_all_from_cache($relationName)
1159
-    {
1160
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : [];
1161
-        // if the result is not an array, but exists, make it an array
1162
-        $objects = is_array($objects) ? $objects : [$objects];
1163
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
1164
-        // basically, if this model object was stored in the session, and these cached model objects
1165
-        // already have IDs, let's make sure they're in their model's entity mapper
1166
-        // otherwise we will have duplicates next time we call
1167
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
1168
-        $related_model = EE_Registry::instance()->load_model($relationName);
1169
-        foreach ($objects as $model_object) {
1170
-            if ($related_model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
1171
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
1172
-                if ($model_object->ID()) {
1173
-                    $related_model->add_to_entity_map($model_object);
1174
-                }
1175
-            } else {
1176
-                throw new EE_Error(
1177
-                    sprintf(
1178
-                        esc_html__(
1179
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
1180
-                            'event_espresso'
1181
-                        ),
1182
-                        $relationName,
1183
-                        gettype($model_object)
1184
-                    )
1185
-                );
1186
-            }
1187
-        }
1188
-        $this->updateTimezoneOnRelated($objects);
1189
-        return $objects;
1190
-    }
1191
-
1192
-
1193
-    /**
1194
-     * This retrieves the value of the db column set on this class or if that's not present
1195
-     * it will attempt to retrieve from extra_meta if found.
1196
-     * Example Usage:
1197
-     * Via EE_Message child class:
1198
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
1199
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
1200
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
1201
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
1202
-     * value for those extra fields dynamically via the EE_message object.
1203
-     *
1204
-     * @param string $field_name expecting the fully qualified field name.
1205
-     * @return mixed|null  value for the field if found.  null if not found.
1206
-     * @throws ReflectionException
1207
-     * @throws InvalidArgumentException
1208
-     * @throws InvalidInterfaceException
1209
-     * @throws InvalidDataTypeException
1210
-     * @throws EE_Error
1211
-     */
1212
-    public function get_field_or_extra_meta($field_name)
1213
-    {
1214
-        if ($this->_model->has_field($field_name)) {
1215
-            $column_value = $this->get($field_name);
1216
-        } else {
1217
-            // This isn't a column in the main table, let's see if it is in the extra meta.
1218
-            $column_value = $this->get_extra_meta($field_name, true);
1219
-        }
1220
-        return $column_value;
1221
-    }
1222
-
1223
-
1224
-    /**
1225
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
1226
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
1227
-     * You can specify $default is case you haven't found the extra meta
1228
-     *
1229
-     * @param string  $meta_key
1230
-     * @param boolean $single
1231
-     * @param mixed   $default if we don't find anything, what should we return?
1232
-     * @return mixed single value if $single; array if ! $single
1233
-     * @throws ReflectionException
1234
-     * @throws InvalidArgumentException
1235
-     * @throws InvalidInterfaceException
1236
-     * @throws InvalidDataTypeException
1237
-     * @throws EE_Error
1238
-     */
1239
-    public function get_extra_meta($meta_key, $single = false, $default = null)
1240
-    {
1241
-        if ($single) {
1242
-            $result = $this->get_first_related(
1243
-                'Extra_Meta',
1244
-                [['EXM_key' => $meta_key]]
1245
-            );
1246
-            if ($result instanceof EE_Extra_Meta) {
1247
-                return $result->value();
1248
-            }
1249
-        } else {
1250
-            $results = $this->get_many_related(
1251
-                'Extra_Meta',
1252
-                [['EXM_key' => $meta_key]]
1253
-            );
1254
-            if ($results) {
1255
-                $values = [];
1256
-                foreach ($results as $result) {
1257
-                    if ($result instanceof EE_Extra_Meta) {
1258
-                        $values[ $result->ID() ] = $result->value();
1259
-                    }
1260
-                }
1261
-                return $values;
1262
-            }
1263
-        }
1264
-        // if nothing discovered yet return default.
1265
-        return apply_filters(
1266
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
1267
-            $default,
1268
-            $meta_key,
1269
-            $single,
1270
-            $this
1271
-        );
1272
-    }
1273
-
1274
-
1275
-    /**
1276
-     * Gets the first (ie, one) related model object of the specified type.
1277
-     *
1278
-     * @param string $relationName key in the model's _model_relations array
1279
-     * @param array  $query_params @see
1280
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1281
-     * @return EE_Base_Class (not an array, a single object)
1282
-     * @throws ReflectionException
1283
-     * @throws InvalidArgumentException
1284
-     * @throws InvalidInterfaceException
1285
-     * @throws InvalidDataTypeException
1286
-     * @throws EE_Error
1287
-     */
1288
-    public function get_first_related($relationName, $query_params = [])
1289
-    {
1290
-        $model_relation = $this->_model->related_settings_for($relationName);
1291
-        if ($this->ID()) {
1292
-            // this exists in the DB, get from the cache OR the DB
1293
-            // if they've provided some query parameters, don't bother trying to cache the result
1294
-            // also make sure we're not caching the result of get_first_related
1295
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
1296
-            if (
1297
-                $query_params
1298
-                || ! $model_relation instanceof EE_Belongs_To_Relation
1299
-            ) {
1300
-                $related_model_object = $this->_model->get_first_related(
1301
-                    $this,
1302
-                    $relationName,
1303
-                    $query_params
1304
-                );
1305
-            } else {
1306
-                // first, check if we've already cached the result of this query
1307
-                $cached_result = $this->get_one_from_cache($relationName);
1308
-                if (! $cached_result) {
1309
-                    $related_model_object = $this->_model->get_first_related(
1310
-                        $this,
1311
-                        $relationName,
1312
-                        $query_params
1313
-                    );
1314
-                    $this->cache($relationName, $related_model_object);
1315
-                } else {
1316
-                    $related_model_object = $cached_result;
1317
-                }
1318
-            }
1319
-        } else {
1320
-            $related_model_object = null;
1321
-            // this doesn't exist in the Db,
1322
-            // but maybe the relation is of type belongs to, and so the related thing might
1323
-            if ($model_relation instanceof EE_Belongs_To_Relation) {
1324
-                $related_model_object = $this->_model->get_first_related(
1325
-                    $this,
1326
-                    $relationName,
1327
-                    $query_params
1328
-                );
1329
-            }
1330
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
1331
-            // just get what's cached on this object
1332
-            if (! $related_model_object) {
1333
-                $related_model_object = $this->get_one_from_cache($relationName);
1334
-            }
1335
-        }
1336
-        $this->updateTimezoneOnRelated($related_model_object);
1337
-        return $related_model_object;
1338
-    }
1339
-
1340
-
1341
-    /**
1342
-     * Gets all the related model objects of the specified type. Eg, if the current class if
1343
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
1344
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
1345
-     * because we want to get even deleted items etc.
1346
-     *
1347
-     * @param string $relationName key in the model's _model_relations array
1348
-     * @param array  $query_params @see
1349
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1350
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
1351
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
1352
-     *                             results if you want IDs
1353
-     * @throws ReflectionException
1354
-     * @throws InvalidArgumentException
1355
-     * @throws InvalidInterfaceException
1356
-     * @throws InvalidDataTypeException
1357
-     * @throws EE_Error
1358
-     */
1359
-    public function get_many_related($relationName, $query_params = [])
1360
-    {
1361
-        if ($this->ID()) {
1362
-            // this exists in the DB, so get the related things from either the cache or the DB
1363
-            // if there are query parameters, forget about caching the related model objects.
1364
-            if ($query_params) {
1365
-                $related_model_objects = $this->_model->get_all_related(
1366
-                    $this,
1367
-                    $relationName,
1368
-                    $query_params
1369
-                );
1370
-            } else {
1371
-                // did we already cache the result of this query?
1372
-                $cached_results = $this->get_all_from_cache($relationName);
1373
-                if (! $cached_results) {
1374
-                    $related_model_objects = $this->_model->get_all_related(
1375
-                        $this,
1376
-                        $relationName,
1377
-                        $query_params
1378
-                    );
1379
-                    // if no query parameters were passed, then we got all the related model objects
1380
-                    // for that relation. We can cache them then.
1381
-                    foreach ($related_model_objects as $related_model_object) {
1382
-                        $this->cache($relationName, $related_model_object);
1383
-                    }
1384
-                } else {
1385
-                    $related_model_objects = $cached_results;
1386
-                }
1387
-            }
1388
-        } else {
1389
-            // this doesn't exist in the DB, so just get the related things from the cache
1390
-            $related_model_objects = $this->get_all_from_cache($relationName);
1391
-        }
1392
-        $this->updateTimezoneOnRelated($related_model_objects);
1393
-        return $related_model_objects;
1394
-    }
1395
-
1396
-
1397
-    /**
1398
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
1399
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
1400
-     *
1401
-     * @param string $relationName
1402
-     * @return EE_Base_Class
1403
-     */
1404
-    public function get_one_from_cache($relationName)
1405
-    {
1406
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
1407
-            ? $this->_model_relations[ $relationName ]
1408
-            : null;
1409
-        if (is_array($cached_array_or_object)) {
1410
-            $cached_array_or_object = array_shift($cached_array_or_object);
1411
-        }
1412
-        $this->updateTimezoneOnRelated($cached_array_or_object);
1413
-        return $cached_array_or_object;
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * cache
1419
-     * stores the passed model object on the current model object.
1420
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
1421
-     *
1422
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
1423
-     *                                       'Registration' associated with this model object
1424
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
1425
-     *                                       that could be a payment or a registration)
1426
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
1427
-     *                                       items which will be stored in an array on this object
1428
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
1429
-     *                                       related thing, no array)
1430
-     * @throws InvalidArgumentException
1431
-     * @throws InvalidInterfaceException
1432
-     * @throws InvalidDataTypeException
1433
-     * @throws EE_Error
1434
-     */
1435
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
1436
-    {
1437
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
1438
-        if (! $object_to_cache instanceof EE_Base_Class) {
1439
-            return false;
1440
-        }
1441
-        // also get "how" the object is related, or throw an error
1442
-        if (! $relationship_to_model = $this->_model->related_settings_for($relationName)) {
1443
-            throw new EE_Error(
1444
-                sprintf(
1445
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
1446
-                    $relationName,
1447
-                    get_class($this)
1448
-                )
1449
-            );
1450
-        }
1451
-        // how many things are related ?
1452
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
1453
-            // if it's a "belongs to" relationship, then there's only one related model object
1454
-            // eg, if this is a registration, there's only 1 attendee for it
1455
-            // so for these model objects just set it to be cached
1456
-            $this->_model_relations[ $relationName ] = $object_to_cache;
1457
-            $return                                  = true;
1458
-        } else {
1459
-            // otherwise, this is the "many" side of a one to many relationship,
1460
-            // so we'll add the object to the array of related objects for that type.
1461
-            // eg: if this is an event, there are many registrations for that event,
1462
-            // so we cache the registrations in an array
1463
-            if (! is_array($this->_model_relations[ $relationName ])) {
1464
-                // if for some reason, the cached item is a model object,
1465
-                // then stick that in the array, otherwise start with an empty array
1466
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
1467
-                                                           instanceof
1468
-                                                           EE_Base_Class
1469
-                    ? [$this->_model_relations[ $relationName ]] : [];
1470
-            }
1471
-            // first check for a cache_id which is normally empty
1472
-            if (! empty($cache_id)) {
1473
-                // if the cache_id exists, then it means we are purposely trying to cache this
1474
-                // with a known key that can then be used to retrieve the object later on
1475
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
1476
-                $return                                               = $cache_id;
1477
-            } elseif ($object_to_cache->ID()) {
1478
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
1479
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
1480
-                $return                                                            = $object_to_cache->ID();
1481
-            } else {
1482
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
1483
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
1484
-                // move the internal pointer to the end of the array
1485
-                end($this->_model_relations[ $relationName ]);
1486
-                // and grab the key so that we can return it
1487
-                $return = key($this->_model_relations[ $relationName ]);
1488
-            }
1489
-        }
1490
-        return $return;
1491
-    }
1492
-
1493
-
1494
-    /**
1495
-     * This just returns whatever is set for the current timezone.
1496
-     *
1497
-     * @access public
1498
-     * @return string timezone string
1499
-     */
1500
-    public function get_timezone()
1501
-    {
1502
-        if (empty($this->_timezone)) {
1503
-            $this->set_timezone();
1504
-        }
1505
-        return $this->_timezone;
1506
-    }
1507
-
1508
-
1509
-    /**
1510
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
1511
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
1512
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
1513
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
1514
-     *
1515
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
1516
-     * @param bool   $only_if_not_set if true and $this->_timezone already has a value, then will not do anything
1517
-     * @return void
1518
-     */
1519
-    public function set_timezone($timezone = '', $only_if_not_set = false)
1520
-    {
1521
-        static $set_in_progress = false;
1522
-        // don't update the timezone if it's already set ?
1523
-        if (($only_if_not_set && $this->_timezone !== '') ) {
1524
-            return;
1525
-        }
1526
-        $valid_timezone = ! empty($timezone) && $this->_timezone && $timezone !== $this->_timezone
1527
-            ? EEH_DTT_Helper::get_valid_timezone_string($timezone)
1528
-            : $this->_timezone;
1529
-        // do NOT set the timezone if we are already in the process of setting the timezone
1530
-        // OR the existing timezone is already set and the incoming value is nothing (which gets set to default TZ)
1531
-        // OR the existing timezone is already set and the validated value is the same as the existing timezone
1532
-        if (
1533
-            $set_in_progress
1534
-            || (
1535
-                ! empty($this->_timezone)
1536
-                && (
1537
-                    empty($timezone) || $valid_timezone === $this->_timezone
1538
-                )
1539
-            )
1540
-        ) {
1541
-            return;
1542
-        }
1543
-        $set_in_progress = true;
1544
-        $this->_timezone = $valid_timezone ? $valid_timezone : EEH_DTT_Helper::get_valid_timezone_string();
1545
-        $TZ = new DateTimeZone($this->_timezone);
1546
-        // make sure we clear all cached properties because they won't be relevant now
1547
-        $this->_clear_cached_properties();
1548
-        // make sure we update field settings and the date for all EE_Datetime_Fields
1549
-        $model_fields = $this->_model->field_settings();
1550
-        foreach ($model_fields as $field_name => $field_obj) {
1551
-            if ($field_obj instanceof EE_Datetime_Field) {
1552
-                $field_obj->set_timezone($this->_timezone);
1553
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
1554
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], $TZ);
1555
-                }
1556
-            }
1557
-        }
1558
-        $set_in_progress = false;
1559
-    }
1560
-
1561
-
1562
-    /**
1563
-     * @param array|EE_Base_Class $related
1564
-     * @since $VID:$
1565
-     */
1566
-    private function updateTimezoneOnRelated($related)
1567
-    {
1568
-        if ($related instanceof EE_Base_Class && $related->get_timezone() !== $this->_timezone) {
1569
-            $related->set_timezone($this->_timezone);
1570
-            return;
1571
-        }
1572
-        if (is_array($related)) {
1573
-            foreach ($related as $object) {
1574
-                $this->updateTimezoneOnRelated($object);
1575
-            }
1576
-        }
1577
-    }
1578
-
1579
-
1580
-    /**
1581
-     * This returns the current internal set format for the date and time formats.
1582
-     *
1583
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
1584
-     *                             where the first value is the date format and the second value is the time format.
1585
-     * @return mixed string|array
1586
-     */
1587
-    public function get_format($full = true)
1588
-    {
1589
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
1590
-    }
1591
-
1592
-
1593
-    /**
1594
-     * update_cache_after_object_save
1595
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
1596
-     * obtained after being saved to the db
1597
-     *
1598
-     * @param string        $relationName       - the type of object that is cached
1599
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
1600
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
1601
-     * @return boolean TRUE on success, FALSE on fail
1602
-     * @throws InvalidArgumentException
1603
-     * @throws InvalidInterfaceException
1604
-     * @throws InvalidDataTypeException
1605
-     * @throws EE_Error
1606
-     */
1607
-    public function update_cache_after_object_save(
1608
-        $relationName,
1609
-        EE_Base_Class $newly_saved_object,
1610
-        $current_cache_id = ''
1611
-    ) {
1612
-        // verify that incoming object is of the correct type
1613
-        $obj_class = 'EE_' . $relationName;
1614
-        if ($newly_saved_object instanceof $obj_class) {
1615
-            $this->updateTimezoneOnRelated($newly_saved_object);
1616
-            // now get the type of relation
1617
-            $relationship_to_model = $this->_model->related_settings_for($relationName);
1618
-            // if this is a 1:1 relationship
1619
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
1620
-                // then just replace the cached object with the newly saved object
1621
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
1622
-                return true;
1623
-                // or if it's some kind of sordid feral polyamorous relationship...
1624
-            }
1625
-            if (
1626
-                is_array($this->_model_relations[ $relationName ])
1627
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
1628
-            ) {
1629
-                // then remove the current cached item
1630
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
1631
-                // and cache the newly saved object using it's new ID
1632
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
1633
-                return true;
1634
-            }
1635
-        }
1636
-        return false;
1637
-    }
1638
-
1639
-
1640
-    /**
1641
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1642
-     * matching the given query conditions.
1643
-     *
1644
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1645
-     * @param int   $limit              How many objects to return.
1646
-     * @param array $query_params       Any additional conditions on the query.
1647
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1648
-     *                                  you can indicate just the columns you want returned
1649
-     * @return array|EE_Base_Class[]
1650
-     * @throws ReflectionException
1651
-     * @throws InvalidArgumentException
1652
-     * @throws InvalidInterfaceException
1653
-     * @throws InvalidDataTypeException
1654
-     * @throws EE_Error
1655
-     */
1656
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = [], $columns_to_select = null)
1657
-    {
1658
-        $field         = empty($field_to_order_by) && $this->_model->has_primary_key_field()
1659
-            ? $this->_model->get_primary_key_field()->get_name()
1660
-            : $field_to_order_by;
1661
-        $current_value = ! empty($field) ? $this->get($field) : null;
1662
-        if (empty($field) || empty($current_value)) {
1663
-            return [];
1664
-        }
1665
-        return $this->_model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1666
-    }
1667
-
1668
-
1669
-    /**
1670
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1671
-     * matching the given query conditions.
1672
-     *
1673
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1674
-     * @param int   $limit              How many objects to return.
1675
-     * @param array $query_params       Any additional conditions on the query.
1676
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1677
-     *                                  you can indicate just the columns you want returned
1678
-     * @return array|EE_Base_Class[]
1679
-     * @throws ReflectionException
1680
-     * @throws InvalidArgumentException
1681
-     * @throws InvalidInterfaceException
1682
-     * @throws InvalidDataTypeException
1683
-     * @throws EE_Error
1684
-     */
1685
-    public function previous_x(
1686
-        $field_to_order_by = null,
1687
-        $limit = 1,
1688
-        $query_params = [],
1689
-        $columns_to_select = null
1690
-    ) {
1691
-        $field         = empty($field_to_order_by) && $this->_model->has_primary_key_field()
1692
-            ? $this->_model->get_primary_key_field()->get_name()
1693
-            : $field_to_order_by;
1694
-        $current_value = ! empty($field) ? $this->get($field) : null;
1695
-        if (empty($field) || empty($current_value)) {
1696
-            return [];
1697
-        }
1698
-        return $this->_model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1699
-    }
1700
-
1701
-
1702
-    /**
1703
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1704
-     * matching the given query conditions.
1705
-     *
1706
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1707
-     * @param array $query_params       Any additional conditions on the query.
1708
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1709
-     *                                  you can indicate just the columns you want returned
1710
-     * @return array|EE_Base_Class
1711
-     * @throws ReflectionException
1712
-     * @throws InvalidArgumentException
1713
-     * @throws InvalidInterfaceException
1714
-     * @throws InvalidDataTypeException
1715
-     * @throws EE_Error
1716
-     */
1717
-    public function next($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1718
-    {
1719
-        $field         = empty($field_to_order_by) && $this->_model->has_primary_key_field()
1720
-            ? $this->_model->get_primary_key_field()->get_name()
1721
-            : $field_to_order_by;
1722
-        $current_value = ! empty($field) ? $this->get($field) : null;
1723
-        if (empty($field) || empty($current_value)) {
1724
-            return [];
1725
-        }
1726
-        return $this->_model->next($current_value, $field, $query_params, $columns_to_select);
1727
-    }
1728
-
1729
-
1730
-    /**
1731
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1732
-     * matching the given query conditions.
1733
-     *
1734
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1735
-     * @param array $query_params       Any additional conditions on the query.
1736
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1737
-     *                                  you can indicate just the column you want returned
1738
-     * @return array|EE_Base_Class
1739
-     * @throws ReflectionException
1740
-     * @throws InvalidArgumentException
1741
-     * @throws InvalidInterfaceException
1742
-     * @throws InvalidDataTypeException
1743
-     * @throws EE_Error
1744
-     */
1745
-    public function previous($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1746
-    {
1747
-        $field         = empty($field_to_order_by) && $this->_model->has_primary_key_field()
1748
-            ? $this->_model->get_primary_key_field()->get_name()
1749
-            : $field_to_order_by;
1750
-        $current_value = ! empty($field) ? $this->get($field) : null;
1751
-        if (empty($field) || empty($current_value)) {
1752
-            return [];
1753
-        }
1754
-        return $this->_model->previous($current_value, $field, $query_params, $columns_to_select);
1755
-    }
1756
-
1757
-
1758
-    /**
1759
-     * This is used to return the internal DateTime object used for a field that is a
1760
-     * EE_Datetime_Field.
1761
-     *
1762
-     * @param string $field_name               The field name retrieving the DateTime object.
1763
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1764
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1765
-     *                                         EE_Datetime_Field and but the field value is null, then
1766
-     *                                         just null is returned (because that indicates that likely
1767
-     *                                         this field is nullable).
1768
-     * @throws InvalidArgumentException
1769
-     * @throws InvalidDataTypeException
1770
-     * @throws InvalidInterfaceException
1771
-     */
1772
-    public function get_DateTime_object($field_name)
1773
-    {
1774
-        $field_settings = $this->_model->field_settings_for($field_name);
1775
-        if (! $field_settings instanceof EE_Datetime_Field) {
1776
-            EE_Error::add_error(
1777
-                sprintf(
1778
-                    esc_html__(
1779
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1780
-                        'event_espresso'
1781
-                    ),
1782
-                    $field_name
1783
-                ),
1784
-                __FILE__,
1785
-                __FUNCTION__,
1786
-                __LINE__
1787
-            );
1788
-            return false;
1789
-        }
1790
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1791
-            ? clone $this->_fields[ $field_name ]
1792
-            : null;
1793
-    }
1794
-
1795
-
1796
-
1797
-
1798
-    /**
1799
-     * NOTE ABOUT BELOW:
1800
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1801
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1802
-     * you want to set both date and time at the same time, you can just use the models default set($field_name,$value)
1803
-     * method and make sure you send the entire datetime value for setting.
1804
-     */
1805
-
1806
-
1807
-    /**
1808
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1809
-     * can be easily used as the value of form input.
1810
-     *
1811
-     * @param string $field_name
1812
-     * @return void
1813
-     * @throws InvalidArgumentException
1814
-     * @throws InvalidInterfaceException
1815
-     * @throws InvalidDataTypeException
1816
-     * @throws EE_Error
1817
-     */
1818
-    public function f($field_name)
1819
-    {
1820
-        $this->e($field_name, 'form_input');
1821
-    }
1822
-
1823
-
1824
-    /**
1825
-     * To be used in template to immediately echo out the value, and format it for output.
1826
-     * Eg, should call stripslashes and whatnot before echoing
1827
-     *
1828
-     * @param string $field_name      the name of the field as it appears in the DB
1829
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1830
-     *                                (in cases where the same property may be used for different outputs
1831
-     *                                - i.e. datetime, money etc.)
1832
-     * @return void
1833
-     * @throws InvalidArgumentException
1834
-     * @throws InvalidInterfaceException
1835
-     * @throws InvalidDataTypeException
1836
-     * @throws EE_Error
1837
-     */
1838
-    public function e($field_name, $extra_cache_ref = null)
1839
-    {
1840
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1841
-    }
1842
-
1843
-
1844
-    /**
1845
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1846
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1847
-     * to see what options are available.
1848
-     *
1849
-     * @param string $field_name
1850
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1851
-     *                                (in cases where the same property may be used for different outputs
1852
-     *                                - i.e. datetime, money etc.)
1853
-     * @return mixed
1854
-     * @throws InvalidArgumentException
1855
-     * @throws InvalidInterfaceException
1856
-     * @throws InvalidDataTypeException
1857
-     * @throws EE_Error
1858
-     */
1859
-    public function get_pretty($field_name, $extra_cache_ref = null)
1860
-    {
1861
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1862
-    }
1863
-
1864
-
1865
-    /**
1866
-     * Same as `f()` but just returns the value instead of echoing it
1867
-     *
1868
-     * @param string $field_name
1869
-     * @return string
1870
-     * @throws InvalidArgumentException
1871
-     * @throws InvalidInterfaceException
1872
-     * @throws InvalidDataTypeException
1873
-     * @throws EE_Error
1874
-     */
1875
-    public function get_f($field_name)
1876
-    {
1877
-        return (string) $this->get_pretty($field_name, 'form_input');
1878
-    }
1879
-
1880
-
1881
-    /**
1882
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1883
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1884
-     * other echoes the pretty value for dtt)
1885
-     *
1886
-     * @param string $field_name name of model object datetime field holding the value
1887
-     * @param string $format     format for the date returned (if NULL we use default in dt_frmt property)
1888
-     * @return string            datetime value formatted
1889
-     * @throws InvalidArgumentException
1890
-     * @throws InvalidInterfaceException
1891
-     * @throws InvalidDataTypeException
1892
-     * @throws EE_Error
1893
-     */
1894
-    public function get_date($field_name, $format = '')
1895
-    {
1896
-        return $this->_get_datetime($field_name, $format, null, 'D');
1897
-    }
1898
-
1899
-
1900
-    /**
1901
-     * This simply returns the datetime for the given field name
1902
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1903
-     * (and the equivalent e_date, e_time, e_datetime).
1904
-     *
1905
-     * @access   protected
1906
-     * @param string  $field_name    Field on the instantiated EE_Base_Class child object
1907
-     * @param string  $date_format   valid datetime format used for date
1908
-     *                               (if '' then we just use the default on the field,
1909
-     *                               if NULL we use the last-used format)
1910
-     * @param string  $time_format   Same as above except this is for time format
1911
-     * @param string  $date_or_time  if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1912
-     * @param boolean $echo          Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1913
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1914
-     *                               if field is not a valid dtt field, or void if echoing
1915
-     * @throws InvalidArgumentException
1916
-     * @throws InvalidInterfaceException
1917
-     * @throws InvalidDataTypeException
1918
-     * @throws EE_Error
1919
-     */
1920
-    protected function _get_datetime(
1921
-        $field_name,
1922
-        $date_format = '',
1923
-        $time_format = '',
1924
-        $date_or_time = '',
1925
-        $echo = false
1926
-    ) {
1927
-        // clear cached property
1928
-        $this->_clear_cached_property($field_name);
1929
-        // reset format properties because they are used in get()
1930
-        $this->_dt_frmt = $date_format !== '' ? $date_format : $this->_dt_frmt;
1931
-        $this->_tm_frmt = $time_format !== '' ? $time_format : $this->_tm_frmt;
1932
-        if ($echo) {
1933
-            $this->e($field_name, $date_or_time);
1934
-            return '';
1935
-        }
1936
-        return $this->get($field_name, $date_or_time);
1937
-    }
1938
-
1939
-
1940
-    /**
1941
-     * @param        $field_name
1942
-     * @param string $format
1943
-     * @throws InvalidArgumentException
1944
-     * @throws InvalidInterfaceException
1945
-     * @throws InvalidDataTypeException
1946
-     * @throws EE_Error
1947
-     */
1948
-    public function e_date($field_name, $format = '')
1949
-    {
1950
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1951
-    }
1952
-
1953
-
1954
-    /**
1955
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1956
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1957
-     * other echoes the pretty value for dtt)
1958
-     *
1959
-     * @param string $field_name name of model object datetime field holding the value
1960
-     * @param string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1961
-     * @return string             datetime value formatted
1962
-     * @throws InvalidArgumentException
1963
-     * @throws InvalidInterfaceException
1964
-     * @throws InvalidDataTypeException
1965
-     * @throws EE_Error
1966
-     */
1967
-    public function get_time($field_name, $format = '')
1968
-    {
1969
-        return $this->_get_datetime($field_name, null, $format, 'T');
1970
-    }
1971
-
1972
-
1973
-    /**
1974
-     * @param        $field_name
1975
-     * @param string $format
1976
-     * @throws InvalidArgumentException
1977
-     * @throws InvalidInterfaceException
1978
-     * @throws InvalidDataTypeException
1979
-     * @throws EE_Error
1980
-     */
1981
-    public function e_time($field_name, $format = '')
1982
-    {
1983
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1984
-    }
1985
-
1986
-
1987
-    /**
1988
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1989
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1990
-     * other echoes the pretty value for dtt)
1991
-     *
1992
-     * @param string $field_name  name of model object datetime field holding the value
1993
-     * @param string $date_format format for the date returned (if NULL we use default in dt_frmt property)
1994
-     * @param string $time_format format for the time returned (if NULL we use default in tm_frmt property)
1995
-     * @return string             datetime value formatted
1996
-     * @throws InvalidArgumentException
1997
-     * @throws InvalidInterfaceException
1998
-     * @throws InvalidDataTypeException
1999
-     * @throws EE_Error
2000
-     */
2001
-    public function get_datetime($field_name, $date_format = '', $time_format = '')
2002
-    {
2003
-        return $this->_get_datetime($field_name, $date_format, $time_format);
2004
-    }
2005
-
2006
-
2007
-    /**
2008
-     * @param string $field_name
2009
-     * @param string $date_format
2010
-     * @param string $time_format
2011
-     * @throws InvalidArgumentException
2012
-     * @throws InvalidInterfaceException
2013
-     * @throws InvalidDataTypeException
2014
-     * @throws EE_Error
2015
-     */
2016
-    public function e_datetime($field_name, $date_format = '', $time_format = '')
2017
-    {
2018
-        $this->_get_datetime($field_name, $date_format, $time_format, null, true);
2019
-    }
2020
-
2021
-
2022
-    /**
2023
-     * Get the i8ln value for a date using the WordPress @param string $field_name The EE_Datetime_Field reference for
2024
-     *                           the date being retrieved.
2025
-     *
2026
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
2027
-     *                           on the object will be used.
2028
-     * @return string Date and time string in set locale or false if no field exists for the given
2029
-     * @throws InvalidArgumentException
2030
-     * @throws InvalidInterfaceException
2031
-     * @throws InvalidDataTypeException
2032
-     * @throws EE_Error
2033
-     *                           field name.
2034
-     * @see date_i18n function.
2035
-     */
2036
-    public function get_i18n_datetime($field_name, $format = '')
2037
-    {
2038
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
2039
-        return date_i18n(
2040
-            $format,
2041
-            EEH_DTT_Helper::get_timestamp_with_offset(
2042
-                $this->get_raw($field_name),
2043
-                $this->get_timezone()
2044
-            )
2045
-        );
2046
-    }
2047
-
2048
-
2049
-    /**
2050
-     * This method simply returns the RAW unprocessed value for the given property in this class
2051
-     *
2052
-     * @param string $field_name A valid field name
2053
-     * @return mixed              Whatever the raw value stored on the property is.
2054
-     * @throws InvalidArgumentException
2055
-     * @throws InvalidInterfaceException
2056
-     * @throws InvalidDataTypeException
2057
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
2058
-     */
2059
-    public function get_raw($field_name)
2060
-    {
2061
-        $field_settings = $this->_model->field_settings_for($field_name);
2062
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
2063
-            ? $this->_fields[ $field_name ]->format('U')
2064
-            : $this->_fields[ $field_name ];
2065
-    }
2066
-
2067
-
2068
-    /**
2069
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
2070
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
2071
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
2072
-     * that could lead to some unexpected results!
2073
-     *
2074
-     * @access public
2075
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
2076
-     *                                         value being returned.
2077
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
2078
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
2079
-     * @param string $prepend                  You can include something to prepend on the timestamp
2080
-     * @param string $append                   You can include something to append on the timestamp
2081
-     * @return string timestamp
2082
-     * @throws InvalidArgumentException
2083
-     * @throws InvalidInterfaceException
2084
-     * @throws InvalidDataTypeException
2085
-     * @throws EE_Error
2086
-     */
2087
-    public function display_in_my_timezone(
2088
-        $field_name,
2089
-        $callback = 'get_datetime',
2090
-        $args = null,
2091
-        $prepend = '',
2092
-        $append = ''
2093
-    ) {
2094
-        $timezone = EEH_DTT_Helper::get_timezone();
2095
-        if ($timezone === $this->_timezone) {
2096
-            return '';
2097
-        }
2098
-        $original_timezone = $this->_timezone;
2099
-        $this->set_timezone($timezone);
2100
-        $fn   = (array) $field_name;
2101
-        $args = array_merge($fn, (array) $args);
2102
-        if (! method_exists($this, $callback)) {
2103
-            throw new EE_Error(
2104
-                sprintf(
2105
-                    esc_html__(
2106
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
2107
-                        'event_espresso'
2108
-                    ),
2109
-                    $callback
2110
-                )
2111
-            );
2112
-        }
2113
-        $args   = (array) $args;
2114
-        $return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
2115
-        $this->set_timezone($original_timezone);
2116
-        return $return;
2117
-    }
2118
-
2119
-
2120
-    /**
2121
-     * Deletes this model object.
2122
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
2123
-     * override
2124
-     * `EE_Base_Class::_delete` NOT this class.
2125
-     *
2126
-     * @return boolean | int
2127
-     * @throws ReflectionException
2128
-     * @throws InvalidArgumentException
2129
-     * @throws InvalidInterfaceException
2130
-     * @throws InvalidDataTypeException
2131
-     * @throws EE_Error
2132
-     */
2133
-    public function delete()
2134
-    {
2135
-        /**
2136
-         * Called just before the `EE_Base_Class::_delete` method call.
2137
-         * Note:
2138
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
2139
-         * should be aware that `_delete` may not always result in a permanent delete.
2140
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
2141
-         * soft deletes (trash) the object and does not permanently delete it.
2142
-         *
2143
-         * @param EE_Base_Class $model_object about to be 'deleted'
2144
-         */
2145
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
2146
-        $result = $this->_delete();
2147
-        /**
2148
-         * Called just after the `EE_Base_Class::_delete` method call.
2149
-         * Note:
2150
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
2151
-         * should be aware that `_delete` may not always result in a permanent delete.
2152
-         * For example `EE_Soft_Base_Class::_delete`
2153
-         * soft deletes (trash) the object and does not permanently delete it.
2154
-         *
2155
-         * @param EE_Base_Class $model_object that was just 'deleted'
2156
-         * @param boolean       $result
2157
-         */
2158
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
2159
-        return $result;
2160
-    }
2161
-
2162
-
2163
-    /**
2164
-     * Calls the specific delete method for the instantiated class.
2165
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
2166
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
2167
-     * `EE_Base_Class::delete`
2168
-     *
2169
-     * @return bool|int
2170
-     * @throws ReflectionException
2171
-     * @throws InvalidArgumentException
2172
-     * @throws InvalidInterfaceException
2173
-     * @throws InvalidDataTypeException
2174
-     * @throws EE_Error
2175
-     */
2176
-    protected function _delete()
2177
-    {
2178
-        return $this->delete_permanently();
2179
-    }
2180
-
2181
-
2182
-    /**
2183
-     * Deletes this model object permanently from db
2184
-     * (but keep in mind related models may block the delete and return an error)
2185
-     *
2186
-     * @return bool | int
2187
-     * @throws ReflectionException
2188
-     * @throws InvalidArgumentException
2189
-     * @throws InvalidInterfaceException
2190
-     * @throws InvalidDataTypeException
2191
-     * @throws EE_Error
2192
-     */
2193
-    public function delete_permanently()
2194
-    {
2195
-        /**
2196
-         * Called just before HARD deleting a model object
2197
-         *
2198
-         * @param EE_Base_Class $model_object about to be 'deleted'
2199
-         */
2200
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
2201
-        $result = $this->_model->delete_permanently_by_ID($this->ID());
2202
-        $this->refresh_cache_of_related_objects();
2203
-        /**
2204
-         * Called just after HARD deleting a model object
2205
-         *
2206
-         * @param EE_Base_Class $model_object that was just 'deleted'
2207
-         * @param boolean       $result
2208
-         */
2209
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
2210
-        return $result;
2211
-    }
2212
-
2213
-
2214
-    /**
2215
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
2216
-     * related model objects
2217
-     *
2218
-     * @throws ReflectionException
2219
-     * @throws InvalidArgumentException
2220
-     * @throws InvalidInterfaceException
2221
-     * @throws InvalidDataTypeException
2222
-     * @throws EE_Error
2223
-     */
2224
-    public function refresh_cache_of_related_objects()
2225
-    {
2226
-        foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
2227
-            if (! empty($this->_model_relations[ $relation_name ])) {
2228
-                $related_objects = $this->_model_relations[ $relation_name ];
2229
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
2230
-                    // this relation only stores a single model object, not an array
2231
-                    // but let's make it consistent
2232
-                    $related_objects = [$related_objects];
2233
-                }
2234
-                foreach ($related_objects as $related_object) {
2235
-                    // only refresh their cache if they're in memory
2236
-                    if ($related_object instanceof EE_Base_Class) {
2237
-                        $related_object->clear_cache(
2238
-                            $this->_model->get_this_model_name(),
2239
-                            $this
2240
-                        );
2241
-                    }
2242
-                }
2243
-            }
2244
-        }
2245
-    }
2246
-
2247
-
2248
-    /**
2249
-     * Forgets the cached model of the given relation Name. So the next time we request it,
2250
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
2251
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
2252
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
2253
-     *
2254
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
2255
-     *                                                     Eg 'Registration'
2256
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
2257
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
2258
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
2259
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
2260
-     *                                                     this is HasMany or HABTM.
2261
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
2262
-     *                                                     relation from all
2263
-     * @throws InvalidArgumentException
2264
-     * @throws InvalidInterfaceException
2265
-     * @throws InvalidDataTypeException
2266
-     * @throws EE_Error
2267
-     * @throws ReflectionException
2268
-     */
2269
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
2270
-    {
2271
-        $relationship_to_model = $this->_model->related_settings_for($relationName);
2272
-        $index_in_cache        = '';
2273
-        if (! $relationship_to_model) {
2274
-            throw new EE_Error(
2275
-                sprintf(
2276
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
2277
-                    $relationName,
2278
-                    get_class($this)
2279
-                )
2280
-            );
2281
-        }
2282
-        if ($clear_all) {
2283
-            $obj_removed                             = true;
2284
-            $this->_model_relations[ $relationName ] = null;
2285
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
2286
-            $obj_removed                             = $this->_model_relations[ $relationName ];
2287
-            $this->_model_relations[ $relationName ] = null;
2288
-        } else {
2289
-            if (
2290
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
2291
-                && $object_to_remove_or_index_into_array->ID()
2292
-            ) {
2293
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
2294
-                if (
2295
-                    is_array($this->_model_relations[ $relationName ])
2296
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
2297
-                ) {
2298
-                    $index_found_at = null;
2299
-                    // find this object in the array even though it has a different key
2300
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
2301
-                        /** @noinspection TypeUnsafeComparisonInspection */
2302
-                        if (
2303
-                            $obj instanceof EE_Base_Class
2304
-                            && (
2305
-                                $obj == $object_to_remove_or_index_into_array
2306
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
2307
-                            )
2308
-                        ) {
2309
-                            $index_found_at = $index;
2310
-                            break;
2311
-                        }
2312
-                    }
2313
-                    if ($index_found_at) {
2314
-                        $index_in_cache = $index_found_at;
2315
-                    } else {
2316
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
2317
-                        // if it wasn't in it to begin with. So we're done
2318
-                        return $object_to_remove_or_index_into_array;
2319
-                    }
2320
-                }
2321
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
2322
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
2323
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
2324
-                    /** @noinspection TypeUnsafeComparisonInspection */
2325
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
2326
-                        $index_in_cache = $index;
2327
-                    }
2328
-                }
2329
-            } else {
2330
-                $index_in_cache = $object_to_remove_or_index_into_array;
2331
-            }
2332
-            // supposedly we've found it. But it could just be that the client code
2333
-            // provided a bad index/object
2334
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
2335
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
2336
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
2337
-            } else {
2338
-                // that thing was never cached anyways.
2339
-                $obj_removed = null;
2340
-            }
2341
-        }
2342
-        return $obj_removed;
2343
-    }
2344
-
2345
-
2346
-    /**
2347
-     * Saves this model object and its NEW cached relations to the database.
2348
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
2349
-     * In order for that to work, we would need to mark model objects as dirty/clean...
2350
-     * because otherwise, there's a potential for infinite looping of saving
2351
-     * Saves the cached related model objects, and ensures the relation between them
2352
-     * and this object and properly setup
2353
-     *
2354
-     * @return int ID of new model object on save; 0 on failure+
2355
-     * @throws ReflectionException
2356
-     * @throws InvalidArgumentException
2357
-     * @throws InvalidInterfaceException
2358
-     * @throws InvalidDataTypeException
2359
-     * @throws EE_Error
2360
-     */
2361
-    public function save_new_cached_related_model_objs()
2362
-    {
2363
-        // make sure this has been saved
2364
-        if (! $this->ID()) {
2365
-            $id = $this->save();
2366
-        } else {
2367
-            $id = $this->ID();
2368
-        }
2369
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
2370
-        foreach ($this->_model->relation_settings() as $relationName => $relationObj) {
2371
-            if ($this->_model_relations[ $relationName ]) {
2372
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2373
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2374
-                /* @var $related_model_obj EE_Base_Class */
2375
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2376
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2377
-                    // but ONLY if it DOES NOT exist in the DB
2378
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2379
-                    // if( ! $related_model_obj->ID()){
2380
-                    $this->_add_relation_to($related_model_obj, $relationName);
2381
-                    $related_model_obj->save_new_cached_related_model_objs();
2382
-                    // }
2383
-                } else {
2384
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2385
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2386
-                        // but ONLY if it DOES NOT exist in the DB
2387
-                        // if( ! $related_model_obj->ID()){
2388
-                        $this->_add_relation_to($related_model_obj, $relationName);
2389
-                        $related_model_obj->save_new_cached_related_model_objs();
2390
-                        // }
2391
-                    }
2392
-                }
2393
-            }
2394
-        }
2395
-        return $id;
2396
-    }
2397
-
2398
-
2399
-    /**
2400
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2401
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2402
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2403
-     *
2404
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2405
-     * @param string $relationName                     eg 'Events','Question',etc.
2406
-     *                                                 an attendee to a group, you also want to specify which role they
2407
-     *                                                 will have in that group. So you would use this parameter to
2408
-     *                                                 specify array('role-column-name'=>'role-id')
2409
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2410
-     *                                                 allow you to further constrict the relation to being added.
2411
-     *                                                 However, keep in mind that the columns (keys) given must match a
2412
-     *                                                 column on the JOIN table and currently only the HABTM models
2413
-     *                                                 accept these additional conditions.  Also remember that if an
2414
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2415
-     *                                                 NEW row is created in the join table.
2416
-     * @param null   $cache_id
2417
-     * @return EE_Base_Class the object the relation was added to
2418
-     * @throws ReflectionException
2419
-     * @throws InvalidArgumentException
2420
-     * @throws InvalidInterfaceException
2421
-     * @throws InvalidDataTypeException
2422
-     * @throws EE_Error
2423
-     */
2424
-    public function _add_relation_to(
2425
-        $otherObjectModelObjectOrID,
2426
-        $relationName,
2427
-        $extra_join_model_fields_n_values = [],
2428
-        $cache_id = null
2429
-    ) {
2430
-        // if this thing exists in the DB, save the relation to the DB
2431
-        if ($this->ID()) {
2432
-            $otherObject = $this->_model->add_relationship_to(
2433
-                $this,
2434
-                $otherObjectModelObjectOrID,
2435
-                $relationName,
2436
-                $extra_join_model_fields_n_values
2437
-            );
2438
-            // clear cache so future get_many_related and get_first_related() return new results.
2439
-            $this->clear_cache($relationName, $otherObject, true);
2440
-            if ($otherObject instanceof EE_Base_Class) {
2441
-                $otherObject->clear_cache($this->_model->get_this_model_name(), $this);
2442
-            }
2443
-        } else {
2444
-            // this thing doesn't exist in the DB,  so just cache it
2445
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2446
-                throw new EE_Error(
2447
-                    sprintf(
2448
-                        esc_html__(
2449
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2450
-                            'event_espresso'
2451
-                        ),
2452
-                        $otherObjectModelObjectOrID,
2453
-                        get_class($this)
2454
-                    )
2455
-                );
2456
-            }
2457
-            $otherObject = $otherObjectModelObjectOrID;
2458
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2459
-        }
2460
-        if ($otherObject instanceof EE_Base_Class) {
2461
-            // fix the reciprocal relation too
2462
-            if ($otherObject->ID()) {
2463
-                // its saved so assumed relations exist in the DB, so we can just
2464
-                // clear the cache so future queries use the updated info in the DB
2465
-                $otherObject->clear_cache(
2466
-                    $this->_model->get_this_model_name(),
2467
-                    null,
2468
-                    true
2469
-                );
2470
-            } else {
2471
-                // it's not saved, so it caches relations like this
2472
-                $otherObject->cache($this->_model->get_this_model_name(), $this);
2473
-            }
2474
-        }
2475
-        return $otherObject;
2476
-    }
2477
-
2478
-
2479
-    /**
2480
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2481
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2482
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2483
-     * from the cache
2484
-     *
2485
-     * @param mixed  $otherObjectModelObjectOrID
2486
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2487
-     *                to the DB yet
2488
-     * @param string $relationName
2489
-     * @param array  $where_query
2490
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2491
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2492
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2493
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2494
-     *                deleted.
2495
-     * @return EE_Base_Class the relation was removed from
2496
-     * @throws ReflectionException
2497
-     * @throws InvalidArgumentException
2498
-     * @throws InvalidInterfaceException
2499
-     * @throws InvalidDataTypeException
2500
-     * @throws EE_Error
2501
-     */
2502
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
2503
-    {
2504
-        if ($this->ID()) {
2505
-            // if this exists in the DB, save the relation change to the DB too
2506
-            $otherObject = $this->_model->remove_relationship_to(
2507
-                $this,
2508
-                $otherObjectModelObjectOrID,
2509
-                $relationName,
2510
-                $where_query
2511
-            );
2512
-            $this->clear_cache(
2513
-                $relationName,
2514
-                $otherObject
2515
-            );
2516
-        } else {
2517
-            // this doesn't exist in the DB, just remove it from the cache
2518
-            $otherObject = $this->clear_cache(
2519
-                $relationName,
2520
-                $otherObjectModelObjectOrID
2521
-            );
2522
-        }
2523
-        if ($otherObject instanceof EE_Base_Class) {
2524
-            $otherObject->clear_cache(
2525
-                $this->_model->get_this_model_name(),
2526
-                $this
2527
-            );
2528
-        }
2529
-        return $otherObject;
2530
-    }
2531
-
2532
-
2533
-    /**
2534
-     * Removes ALL the related things for the $relationName.
2535
-     *
2536
-     * @param string $relationName
2537
-     * @param array  $where_query_params @see
2538
-     *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2539
-     * @return EE_Base_Class
2540
-     * @throws ReflectionException
2541
-     * @throws InvalidArgumentException
2542
-     * @throws InvalidInterfaceException
2543
-     * @throws InvalidDataTypeException
2544
-     * @throws EE_Error
2545
-     */
2546
-    public function _remove_relations($relationName, $where_query_params = [])
2547
-    {
2548
-        if ($this->ID()) {
2549
-            // if this exists in the DB, save the relation change to the DB too
2550
-            $otherObjects = $this->_model->remove_relations(
2551
-                $this,
2552
-                $relationName,
2553
-                $where_query_params
2554
-            );
2555
-            $this->clear_cache(
2556
-                $relationName,
2557
-                null,
2558
-                true
2559
-            );
2560
-        } else {
2561
-            // this doesn't exist in the DB, just remove it from the cache
2562
-            $otherObjects = $this->clear_cache(
2563
-                $relationName,
2564
-                null,
2565
-                true
2566
-            );
2567
-        }
2568
-        if (is_array($otherObjects)) {
2569
-            foreach ($otherObjects as $otherObject) {
2570
-                $otherObject->clear_cache(
2571
-                    $this->_model->get_this_model_name(),
2572
-                    $this
2573
-                );
2574
-            }
2575
-        }
2576
-        return $otherObjects;
2577
-    }
2578
-
2579
-
2580
-    /**
2581
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2582
-     * unless otherwise specified in the $query_params
2583
-     *
2584
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2585
-     * @param array  $query_params   @see
2586
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2587
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2588
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2589
-     *                               that by the setting $distinct to TRUE;
2590
-     * @return int
2591
-     * @throws ReflectionException
2592
-     * @throws InvalidArgumentException
2593
-     * @throws InvalidInterfaceException
2594
-     * @throws InvalidDataTypeException
2595
-     * @throws EE_Error
2596
-     */
2597
-    public function count_related($relation_name, $query_params = [], $field_to_count = null, $distinct = false)
2598
-    {
2599
-        return $this->_model->count_related(
2600
-            $this,
2601
-            $relation_name,
2602
-            $query_params,
2603
-            $field_to_count,
2604
-            $distinct
2605
-        );
2606
-    }
2607
-
2608
-
2609
-    /**
2610
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2611
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2612
-     *
2613
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2614
-     * @param array  $query_params  @see
2615
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2616
-     * @param string $field_to_sum  name of field to count by.
2617
-     *                              By default, uses primary key
2618
-     *                              (which doesn't make much sense, so you should probably change it)
2619
-     * @return int
2620
-     * @throws ReflectionException
2621
-     * @throws InvalidArgumentException
2622
-     * @throws InvalidInterfaceException
2623
-     * @throws InvalidDataTypeException
2624
-     * @throws EE_Error
2625
-     */
2626
-    public function sum_related($relation_name, $query_params = [], $field_to_sum = null)
2627
-    {
2628
-        return $this->_model->sum_related(
2629
-            $this,
2630
-            $relation_name,
2631
-            $query_params,
2632
-            $field_to_sum
2633
-        );
2634
-    }
2635
-
2636
-
2637
-    /**
2638
-     * Does a delete on all related objects of type $relationName and removes
2639
-     * the current model object's relation to them. If they can't be deleted (because
2640
-     * of blocking related model objects) does nothing. If the related model objects are
2641
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2642
-     * If this model object doesn't exist yet in the DB, just removes its related things
2643
-     *
2644
-     * @param string $relationName
2645
-     * @param array  $query_params @see
2646
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2647
-     * @return int how many deleted
2648
-     * @throws ReflectionException
2649
-     * @throws InvalidArgumentException
2650
-     * @throws InvalidInterfaceException
2651
-     * @throws InvalidDataTypeException
2652
-     * @throws EE_Error
2653
-     */
2654
-    public function delete_related($relationName, $query_params = [])
2655
-    {
2656
-        if ($this->ID()) {
2657
-            $count = $this->_model->delete_related(
2658
-                $this,
2659
-                $relationName,
2660
-                $query_params
2661
-            );
2662
-        } else {
2663
-            $count = count($this->get_all_from_cache($relationName));
2664
-            $this->clear_cache($relationName, null, true);
2665
-        }
2666
-        return $count;
2667
-    }
2668
-
2669
-
2670
-    /**
2671
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2672
-     * the current model object's relation to them. If they can't be deleted (because
2673
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2674
-     * If the related thing isn't a soft-deletable model object, this function is identical
2675
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2676
-     *
2677
-     * @param string $relationName
2678
-     * @param array  $query_params @see
2679
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2680
-     * @return int how many deleted (including those soft deleted)
2681
-     * @throws ReflectionException
2682
-     * @throws InvalidArgumentException
2683
-     * @throws InvalidInterfaceException
2684
-     * @throws InvalidDataTypeException
2685
-     * @throws EE_Error
2686
-     */
2687
-    public function delete_related_permanently($relationName, $query_params = [])
2688
-    {
2689
-        if ($this->ID()) {
2690
-            $count = $this->_model->delete_related_permanently(
2691
-                $this,
2692
-                $relationName,
2693
-                $query_params
2694
-            );
2695
-        } else {
2696
-            $count = count($this->get_all_from_cache($relationName));
2697
-        }
2698
-        $this->clear_cache($relationName, null, true);
2699
-        return $count;
2700
-    }
2701
-
2702
-
2703
-    /**
2704
-     * is_set
2705
-     * Just a simple utility function children can use for checking if property exists
2706
-     *
2707
-     * @access  public
2708
-     * @param string $field_name property to check
2709
-     * @return bool                              TRUE if existing,FALSE if not.
2710
-     */
2711
-    public function is_set($field_name)
2712
-    {
2713
-        return isset($this->_fields[ $field_name ]);
2714
-    }
2715
-
2716
-
2717
-    /**
2718
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2719
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2720
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2721
-     * Instead of requiring a plugin to extend the EE_Base_Class
2722
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2723
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2724
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2725
-     * and accepts 2 arguments: the object on which the function was called,
2726
-     * and an array of the original arguments passed to the function.
2727
-     * Whatever their callback function returns will be returned by this function.
2728
-     * Example: in functions.php (or in a plugin):
2729
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2730
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2731
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2732
-     *          return $previousReturnValue.$returnString;
2733
-     *      }
2734
-     * require('EE_Answer.class.php');
2735
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2736
-     * echo $answer->my_callback('monkeys',100);
2737
-     * //will output "you called my_callback! and passed args:monkeys,100"
2738
-     *
2739
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2740
-     * @param array  $args       array of original arguments passed to the function
2741
-     * @return mixed whatever the plugin which calls add_filter decides
2742
-     * @throws EE_Error
2743
-     */
2744
-    public function __call($methodName, $args)
2745
-    {
2746
-        $className = get_class($this);
2747
-        $tagName   = "FHEE__{$className}__{$methodName}";
2748
-        if (! has_filter($tagName)) {
2749
-            throw new EE_Error(
2750
-                sprintf(
2751
-                    esc_html__(
2752
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2753
-                        'event_espresso'
2754
-                    ),
2755
-                    $methodName,
2756
-                    $className,
2757
-                    $tagName
2758
-                )
2759
-            );
2760
-        }
2761
-        return apply_filters($tagName, null, $this, $args);
2762
-    }
2763
-
2764
-
2765
-    /**
2766
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2767
-     * is specified, only deletes extra meta records with that value.
2768
-     *
2769
-     * @param string $meta_key
2770
-     * @param mixed  $meta_value
2771
-     * @return int number of extra meta rows deleted
2772
-     * @throws InvalidArgumentException
2773
-     * @throws InvalidInterfaceException
2774
-     * @throws InvalidDataTypeException
2775
-     * @throws EE_Error
2776
-     * @throws ReflectionException
2777
-     */
2778
-    public function delete_extra_meta($meta_key, $meta_value = null)
2779
-    {
2780
-        $query_params = [
2781
-            [
2782
-                'EXM_key'  => $meta_key,
2783
-                'OBJ_ID'   => $this->ID(),
2784
-                'EXM_type' => $this->_model->get_this_model_name(),
2785
-            ],
2786
-        ];
2787
-        if ($meta_value !== null) {
2788
-            $query_params[0]['EXM_value'] = $meta_value;
2789
-        }
2790
-        return EEM_Extra_Meta::instance()->delete($query_params);
2791
-    }
2792
-
2793
-
2794
-    /**
2795
-     * Returns a simple array of all the extra meta associated with this model object.
2796
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2797
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2798
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2799
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2800
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2801
-     * finally the extra meta's value as each sub-value. (eg
2802
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2803
-     *
2804
-     * @param boolean $one_of_each_key
2805
-     * @return array
2806
-     * @throws ReflectionException
2807
-     * @throws InvalidArgumentException
2808
-     * @throws InvalidInterfaceException
2809
-     * @throws InvalidDataTypeException
2810
-     * @throws EE_Error
2811
-     */
2812
-    public function all_extra_meta_array($one_of_each_key = true)
2813
-    {
2814
-        $return_array = [];
2815
-        if ($one_of_each_key) {
2816
-            $extra_meta_objs = $this->get_many_related(
2817
-                'Extra_Meta',
2818
-                ['group_by' => 'EXM_key']
2819
-            );
2820
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2821
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2822
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2823
-                }
2824
-            }
2825
-        } else {
2826
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2827
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2828
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2829
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2830
-                        $return_array[ $extra_meta_obj->key() ] = [];
2831
-                    }
2832
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2833
-                }
2834
-            }
2835
-        }
2836
-        return $return_array;
2837
-    }
2838
-
2839
-
2840
-    /**
2841
-     * refresh_from_db
2842
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2843
-     *
2844
-     * @throws ReflectionException
2845
-     * @throws InvalidArgumentException
2846
-     * @throws InvalidInterfaceException
2847
-     * @throws InvalidDataTypeException
2848
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2849
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2850
-     */
2851
-    public function refresh_from_db()
2852
-    {
2853
-        if ($this->ID() && $this->in_entity_map()) {
2854
-            $this->_model->refresh_entity_map_from_db($this->ID());
2855
-        } else {
2856
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2857
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
2858
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2859
-            // absolutely nothing in it for this ID
2860
-            if (WP_DEBUG) {
2861
-                throw new EE_Error(
2862
-                    sprintf(
2863
-                        esc_html__(
2864
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2865
-                            'event_espresso'
2866
-                        ),
2867
-                        $this->ID(),
2868
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2869
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2870
-                    )
2871
-                );
2872
-            }
2873
-        }
2874
-    }
2875
-
2876
-
2877
-    /**
2878
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
2879
-     * Does not allow negative values, however.
2880
-     *
2881
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
2882
-     *                                   (positive or negative). One important gotcha: all these values must be
2883
-     *                                   on the same table (eg don't pass in one field for the posts table and
2884
-     *                                   another for the event meta table.)
2885
-     * @return bool
2886
-     * @throws EE_Error
2887
-     * @throws InvalidArgumentException
2888
-     * @throws InvalidDataTypeException
2889
-     * @throws InvalidInterfaceException
2890
-     * @throws ReflectionException
2891
-     * @since 4.9.80.p
2892
-     */
2893
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
2894
-    {
2895
-        global $wpdb;
2896
-        if (empty($fields_n_quantities)) {
2897
-            // No fields to update? Well sure, we updated them to that value just fine.
2898
-            return true;
2899
-        }
2900
-        $fields             = [];
2901
-        $set_sql_statements = [];
2902
-        foreach ($fields_n_quantities as $field_name => $quantity) {
2903
-            $field       = $this->_model->field_settings_for($field_name);
2904
-            $fields[]    = $field;
2905
-            $column_name = $field->get_table_column();
2906
-
2907
-            $abs_qty = absint($quantity);
2908
-            if ($quantity > 0) {
2909
-                // don't let the value be negative as often these fields are unsigned
2910
-                $set_sql_statements[] = $wpdb->prepare(
2911
-                    "`{$column_name}` = `{$column_name}` + %d",
2912
-                    $abs_qty
2913
-                );
2914
-            } else {
2915
-                $set_sql_statements[] = $wpdb->prepare(
2916
-                    "`{$column_name}` = CASE
16
+	/**
17
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
18
+	 * For example, we might create model objects intended to only be used for the duration
19
+	 * of this request and to be thrown away, and if they were accidentally saved
20
+	 * it would be a bug.
21
+	 */
22
+	protected $_allow_persist = true;
23
+
24
+	/**
25
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
26
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
27
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
28
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
29
+	 *
30
+	 * @var array
31
+	 */
32
+	protected $_cached_properties = [];
33
+
34
+	/**
35
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
36
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
37
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
38
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
39
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
40
+	 * array as:
41
+	 * array(
42
+	 *  'Registration_Count' => 24
43
+	 * );
44
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
45
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
46
+	 * info)
47
+	 *
48
+	 * @var array
49
+	 */
50
+	protected $custom_selection_results = [];
51
+
52
+	/**
53
+	 * date format
54
+	 * pattern or format for displaying dates
55
+	 *
56
+	 * @var string $_dt_frmt
57
+	 */
58
+	protected $_dt_frmt;
59
+
60
+	/**
61
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
62
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
63
+	 *
64
+	 * @var array
65
+	 */
66
+	protected $_fields = [];
67
+
68
+	/**
69
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
70
+	 */
71
+	protected $_has_changes = false;
72
+
73
+	/**
74
+	 * @var EEM_Base
75
+	 */
76
+	protected $_model;
77
+
78
+
79
+	/**
80
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
81
+	 * single
82
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
83
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
84
+	 * all others have an array)
85
+	 *
86
+	 * @var array
87
+	 */
88
+	protected $_model_relations = [];
89
+
90
+	/**
91
+	 * This is an array of the original properties and values provided during construction
92
+	 * of this model object. (keys are model field names, values are their values).
93
+	 * This list is important to remember so that when we are merging data from the db, we know
94
+	 * which values to override and which to not override.
95
+	 *
96
+	 * @var array
97
+	 */
98
+	protected $_props_n_values_provided_in_constructor;
99
+
100
+	/**
101
+	 * Timezone
102
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
103
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
104
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
105
+	 * access to it.
106
+	 *
107
+	 * @var string
108
+	 */
109
+	protected $_timezone;
110
+
111
+	/**
112
+	 * time format
113
+	 * pattern or format for displaying time
114
+	 *
115
+	 * @var string $_tm_frmt
116
+	 */
117
+	protected $_tm_frmt;
118
+
119
+
120
+	/**
121
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
122
+	 * play nice
123
+	 *
124
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
125
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
126
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
127
+	 * @param boolean $by_db                                   a flag for setting if the class is instantiated by the
128
+	 *                                                         corresponding db model or not.
129
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
130
+	 *                                                         be in when instantiating a EE_Base_Class object.
131
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
132
+	 *                                                         value is the date_format and second value is the time
133
+	 *                                                         format.
134
+	 * @throws InvalidArgumentException
135
+	 * @throws InvalidInterfaceException
136
+	 * @throws InvalidDataTypeException
137
+	 * @throws EE_Error
138
+	 * @throws ReflectionException
139
+	 */
140
+	protected function __construct($fieldValues = [], $by_db = false, $timezone = '', $date_formats = [])
141
+	{
142
+		$className = get_class($this);
143
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
144
+		$this->_model = $this->get_model();
145
+		$model_fields = $this->_model->field_settings();
146
+		// ensure $fieldValues is an array
147
+		$fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
148
+		// verify client code has not passed any invalid field names
149
+		foreach ($fieldValues as $field_name => $field_value) {
150
+			if (! isset($model_fields[ $field_name ])) {
151
+				throw new EE_Error(
152
+					sprintf(
153
+						esc_html__(
154
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
155
+							'event_espresso'
156
+						),
157
+						$field_name,
158
+						get_class($this),
159
+						implode(', ', array_keys($model_fields))
160
+					)
161
+				);
162
+			}
163
+		}
164
+		$this->set_timezone($timezone);
165
+		if (! empty($date_formats) && is_array($date_formats)) {
166
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
167
+		} else {
168
+			// set default formats for date and time
169
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
170
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
171
+		}
172
+		// if db model is instantiating
173
+		if ($by_db) {
174
+			// client code has indicated these field values are from the database
175
+			foreach ($model_fields as $fieldName => $field) {
176
+				$this->set_from_db(
177
+					$fieldName,
178
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
179
+				);
180
+			}
181
+		} else {
182
+			// we're constructing a brand
183
+			// new instance of the model object. Generally, this means we'll need to do more field validation
184
+			foreach ($model_fields as $fieldName => $field) {
185
+				$this->set(
186
+					$fieldName,
187
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
188
+					true
189
+				);
190
+			}
191
+		}
192
+		// remember what values were passed to this constructor
193
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
194
+		// remember in entity mapper
195
+		if (! $by_db && $this->_model->has_primary_key_field() && $this->ID()) {
196
+			$this->_model->add_to_entity_map($this);
197
+		}
198
+		// setup all the relations
199
+		foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
200
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
+				$this->_model_relations[ $relation_name ] = null;
202
+			} else {
203
+				$this->_model_relations[ $relation_name ] = [];
204
+			}
205
+		}
206
+		/**
207
+		 * Action done at the end of each model object construction
208
+		 *
209
+		 * @param EE_Base_Class $this the model object just created
210
+		 */
211
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
+	}
213
+
214
+
215
+	/**
216
+	 * for getting a model while instantiated.
217
+	 *
218
+	 * @return EEM_Base | EEM_CPT_Base
219
+	 * @throws ReflectionException
220
+	 * @throws InvalidArgumentException
221
+	 * @throws InvalidInterfaceException
222
+	 * @throws InvalidDataTypeException
223
+	 * @throws EE_Error
224
+	 */
225
+	public function get_model()
226
+	{
227
+		if (! $this->_model) {
228
+			$modelName    = self::_get_model_classname(get_class($this));
229
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
230
+		}
231
+		return $this->_model;
232
+	}
233
+
234
+
235
+	/**
236
+	 * Overrides parent because parent expects old models.
237
+	 * This also doesn't do any validation, and won't work for serialized arrays
238
+	 *
239
+	 * @param string $field_name
240
+	 * @param mixed  $field_value_from_db
241
+	 * @throws InvalidArgumentException
242
+	 * @throws InvalidInterfaceException
243
+	 * @throws InvalidDataTypeException
244
+	 * @throws EE_Error
245
+	 */
246
+	public function set_from_db($field_name, $field_value_from_db)
247
+	{
248
+		$field_obj = $this->_model->field_settings_for($field_name);
249
+		if ($field_obj instanceof EE_Model_Field_Base) {
250
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
251
+			// eg, a CPT model object could have an entry in the posts table, but no
252
+			// entry in the meta table. Meaning that all its columns in the meta table
253
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
254
+			if ($field_value_from_db === null) {
255
+				if ($field_obj->is_nullable()) {
256
+					// if the field allows nulls, then let it be null
257
+					$field_value = null;
258
+				} else {
259
+					$field_value = $field_obj->get_default_value();
260
+				}
261
+			} else {
262
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
263
+			}
264
+			$this->_fields[ $field_name ] = $field_value;
265
+			$this->_clear_cached_property($field_name);
266
+		}
267
+	}
268
+
269
+
270
+	/**
271
+	 * Overrides parent because parent expects old models.
272
+	 * This also doesn't do any validation, and won't work for serialized arrays
273
+	 *
274
+	 * @param string $field_name
275
+	 * @param mixed  $field_value
276
+	 * @param bool   $use_default
277
+	 * @throws InvalidArgumentException
278
+	 * @throws InvalidInterfaceException
279
+	 * @throws InvalidDataTypeException
280
+	 * @throws EE_Error
281
+	 * @throws ReflectionException
282
+	 * @throws ReflectionException
283
+	 * @throws ReflectionException
284
+	 */
285
+	public function set($field_name, $field_value, $use_default = false)
286
+	{
287
+		// if not using default and nothing has changed, and object has already been setup (has ID),
288
+		// then don't do anything
289
+		if (
290
+			! $use_default
291
+			&& $this->_fields[ $field_name ] === $field_value
292
+			&& $this->ID()
293
+		) {
294
+			return;
295
+		}
296
+		$this->_has_changes = true;
297
+		$field_obj          = $this->_model->field_settings_for($field_name);
298
+		if ($field_obj instanceof EE_Model_Field_Base) {
299
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
300
+			if ($field_obj instanceof EE_Datetime_Field) {
301
+				$field_obj->set_timezone($this->_timezone);
302
+				$field_obj->set_date_format($this->_dt_frmt);
303
+				$field_obj->set_time_format($this->_tm_frmt);
304
+			}
305
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
306
+			// should the value be null?
307
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
308
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
309
+				/**
310
+				 * To save having to refactor all the models, if a default value is used for a
311
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
312
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
313
+				 * object.
314
+				 *
315
+				 * @since 4.6.10+
316
+				 */
317
+				if (
318
+					$field_obj instanceof EE_Datetime_Field
319
+					&& $this->_fields[ $field_name ] !== null
320
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
321
+				) {
322
+					empty($this->_fields[ $field_name ])
323
+						? $this->set($field_name, time())
324
+						: $this->set($field_name, $this->_fields[ $field_name ]);
325
+				}
326
+			} else {
327
+				$this->_fields[ $field_name ] = $holder_of_value;
328
+			}
329
+			// if we're not in the constructor...
330
+			// now check if what we set was a primary key
331
+			if (
332
+				// note: props_n_values_provided_in_constructor is only set at the END of the constructor
333
+				$this->_props_n_values_provided_in_constructor
334
+				&& $field_value
335
+				&& $field_name === $this->_model->primary_key_name()
336
+			) {
337
+				// if so, we want all this object's fields to be filled either with
338
+				// what we've explicitly set on this model
339
+				// or what we have in the db
340
+				// echo "setting primary key!";
341
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
342
+				$obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
343
+				foreach ($fields_on_model as $field_obj) {
344
+					if (
345
+						! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
346
+						&& $field_obj->get_name() !== $field_name
347
+					) {
348
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
349
+					}
350
+				}
351
+				// oh this model object has an ID? well make sure its in the entity mapper
352
+				$this->_model->add_to_entity_map($this);
353
+			}
354
+			// let's unset any cache for this field_name from the $_cached_properties property.
355
+			$this->_clear_cached_property($field_name);
356
+		} else {
357
+			throw new EE_Error(
358
+				sprintf(
359
+					esc_html__(
360
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
361
+						'event_espresso'
362
+					),
363
+					$field_name
364
+				)
365
+			);
366
+		}
367
+	}
368
+
369
+
370
+	/**
371
+	 * Gets the value of the primary key.
372
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
373
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
374
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
375
+	 *
376
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
377
+	 * @throws InvalidArgumentException
378
+	 * @throws InvalidInterfaceException
379
+	 * @throws InvalidDataTypeException
380
+	 * @throws EE_Error
381
+	 */
382
+	public function ID()
383
+	{
384
+		// now that we know the name of the variable, use a variable variable to get its value and return its
385
+		if ($this->_model->has_primary_key_field()) {
386
+			return $this->_fields[ $this->_model->primary_key_name() ];
387
+		}
388
+		return $this->_model->get_index_primary_key_string($this->_fields);
389
+	}
390
+
391
+
392
+	/**
393
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
394
+	 * Also works if a model class's classname is provided (eg EE_Registration).
395
+	 *
396
+	 * @param null $model_name
397
+	 * @return string like EEM_Attendee
398
+	 */
399
+	private static function _get_model_classname($model_name = null)
400
+	{
401
+		if (strpos($model_name, 'EE_') === 0) {
402
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
403
+		} else {
404
+			$model_classname = 'EEM_' . $model_name;
405
+		}
406
+		return $model_classname;
407
+	}
408
+
409
+
410
+	/**
411
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
412
+	 *
413
+	 * @param string $model_classname
414
+	 * @param string $timezone
415
+	 * @return EEM_Base
416
+	 * @throws ReflectionException
417
+	 * @throws InvalidArgumentException
418
+	 * @throws InvalidInterfaceException
419
+	 * @throws InvalidDataTypeException
420
+	 * @throws EE_Error
421
+	 */
422
+	protected static function _get_model_instance_with_name($model_classname, $timezone = '')
423
+	{
424
+		$model_classname = str_replace('EEM_', '', $model_classname);
425
+		$model           = EE_Registry::instance()->load_model($model_classname);
426
+		$model->set_timezone($timezone);
427
+		return $model;
428
+	}
429
+
430
+
431
+	/**
432
+	 * This just clears out ONE property if it exists in the cache
433
+	 *
434
+	 * @param string $property_name the property to remove if it exists (from the _cached_properties array)
435
+	 * @return void
436
+	 */
437
+	protected function _clear_cached_property($property_name)
438
+	{
439
+		if (isset($this->_cached_properties[ $property_name ])) {
440
+			unset($this->_cached_properties[ $property_name ]);
441
+		}
442
+	}
443
+
444
+
445
+	/**
446
+	 * Gets the EEM_*_Model for this class
447
+	 *
448
+	 * @param string $classname
449
+	 * @param string $timezone
450
+	 * @return EEM_Base
451
+	 * @throws InvalidArgumentException
452
+	 * @throws InvalidInterfaceException
453
+	 * @throws InvalidDataTypeException
454
+	 * @throws EE_Error
455
+	 * @throws ReflectionException
456
+	 */
457
+	protected static function _get_model($classname, $timezone = '')
458
+	{
459
+		// find model for this class
460
+		if (! $classname) {
461
+			throw new EE_Error(
462
+				sprintf(
463
+					esc_html__(
464
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
465
+						'event_espresso'
466
+					),
467
+					$classname
468
+				)
469
+			);
470
+		}
471
+		$modelName = self::_get_model_classname($classname);
472
+		return self::_get_model_instance_with_name($modelName, $timezone);
473
+	}
474
+
475
+
476
+	/**
477
+	 * verifies that the specified field is of the correct type
478
+	 *
479
+	 * @param string $field_name
480
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
481
+	 *                                (in cases where the same property may be used for different outputs
482
+	 *                                - i.e. datetime, money etc.)
483
+	 * @return mixed
484
+	 * @throws InvalidArgumentException
485
+	 * @throws InvalidInterfaceException
486
+	 * @throws InvalidDataTypeException
487
+	 * @throws EE_Error
488
+	 */
489
+	public function get($field_name, $extra_cache_ref = null)
490
+	{
491
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
492
+	}
493
+
494
+
495
+	/**
496
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
497
+	 * This also SETS the cache if we return the actual property!
498
+	 *
499
+	 * @param string $field_name       the name of the property we're trying to retrieve
500
+	 * @param bool   $pretty
501
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
502
+	 *                                 (in cases where the same property may be used for different outputs
503
+	 *                                 - i.e. datetime, money etc.)
504
+	 *                                 It can also accept certain pre-defined "schema" strings
505
+	 *                                 to define how to output the property.
506
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
507
+	 * @return mixed                   whatever the value for the property is we're retrieving
508
+	 * @throws InvalidArgumentException
509
+	 * @throws InvalidInterfaceException
510
+	 * @throws InvalidDataTypeException
511
+	 * @throws EE_Error
512
+	 */
513
+	protected function _get_cached_property($field_name, $pretty = false, $extra_cache_ref = null)
514
+	{
515
+		// verify the field exists
516
+		$this->_model->field_settings_for($field_name);
517
+		$cache_type = $pretty ? 'pretty' : 'standard';
518
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
519
+		if (isset($this->_cached_properties[ $field_name ][ $cache_type ])) {
520
+			return $this->_cached_properties[ $field_name ][ $cache_type ];
521
+		}
522
+		$value = $this->_get_fresh_property($field_name, $pretty, $extra_cache_ref);
523
+		$this->_set_cached_property($field_name, $value, $cache_type);
524
+		return $value;
525
+	}
526
+
527
+
528
+	/**
529
+	 * If the cache didn't fetch the needed item, this fetches it.
530
+	 *
531
+	 * @param string $field_name
532
+	 * @param bool   $pretty
533
+	 * @param string $extra_cache_ref
534
+	 * @return mixed
535
+	 * @throws InvalidArgumentException
536
+	 * @throws InvalidInterfaceException
537
+	 * @throws InvalidDataTypeException
538
+	 * @throws EE_Error
539
+	 */
540
+	protected function _get_fresh_property($field_name, $pretty = false, $extra_cache_ref = null)
541
+	{
542
+		$field_obj = $this->_model->field_settings_for($field_name);
543
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
544
+		if ($field_obj instanceof EE_Datetime_Field) {
545
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
546
+		}
547
+		if (! isset($this->_fields[ $field_name ])) {
548
+			$this->_fields[ $field_name ] = null;
549
+		}
550
+		return $pretty
551
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $field_name ], $extra_cache_ref)
552
+			: $field_obj->prepare_for_get($this->_fields[ $field_name ]);
553
+	}
554
+
555
+
556
+	/**
557
+	 * For adding an item to the cached_properties property.
558
+	 *
559
+	 * @access protected
560
+	 * @param string      $field_name the property item the corresponding value is for.
561
+	 * @param mixed       $value      The value we are caching.
562
+	 * @param string|null $cache_type
563
+	 * @return void
564
+	 * @throws InvalidArgumentException
565
+	 * @throws InvalidInterfaceException
566
+	 * @throws InvalidDataTypeException
567
+	 * @throws EE_Error
568
+	 */
569
+	protected function _set_cached_property($field_name, $value, $cache_type = null)
570
+	{
571
+		// first make sure this property exists
572
+		$this->_model->field_settings_for($field_name);
573
+		$cache_type                                             = empty($cache_type) ? 'standard' : $cache_type;
574
+		$this->_cached_properties[ $field_name ][ $cache_type ] = $value;
575
+	}
576
+
577
+
578
+	/**
579
+	 * set timezone, formats, and output for EE_Datetime_Field objects
580
+	 *
581
+	 * @param EE_Datetime_Field $datetime_field
582
+	 * @param bool              $pretty
583
+	 * @param null              $date_or_time
584
+	 * @return void
585
+	 * @throws InvalidArgumentException
586
+	 * @throws InvalidInterfaceException
587
+	 * @throws InvalidDataTypeException
588
+	 */
589
+	protected function _prepare_datetime_field(
590
+		EE_Datetime_Field $datetime_field,
591
+		$pretty = false,
592
+		$date_or_time = null
593
+	) {
594
+		$datetime_field->set_timezone($this->_timezone);
595
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
596
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
597
+		// set the output returned
598
+		switch ($date_or_time) {
599
+			case 'D':
600
+				$datetime_field->set_date_time_output('date');
601
+				break;
602
+			case 'T':
603
+				$datetime_field->set_date_time_output('time');
604
+				break;
605
+			default:
606
+				$datetime_field->set_date_time_output();
607
+		}
608
+	}
609
+
610
+
611
+	/**
612
+	 * @param $props_n_values
613
+	 * @param $classname
614
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
615
+	 * @throws ReflectionException
616
+	 * @throws InvalidArgumentException
617
+	 * @throws InvalidInterfaceException
618
+	 * @throws InvalidDataTypeException
619
+	 * @throws EE_Error
620
+	 */
621
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
622
+	{
623
+		// TODO: will not work for Term_Relationships because they have no PK!
624
+		$primary_id_ref = self::_get_primary_key_name($classname);
625
+		if (
626
+			array_key_exists($primary_id_ref, $props_n_values)
627
+			&& ! empty($props_n_values[ $primary_id_ref ])
628
+		) {
629
+			$id = $props_n_values[ $primary_id_ref ];
630
+			return self::_get_model($classname)->get_from_entity_map($id);
631
+		}
632
+		return false;
633
+	}
634
+
635
+
636
+	/**
637
+	 * returns the name of the primary key attribute
638
+	 *
639
+	 * @param null $classname
640
+	 * @return string
641
+	 * @throws InvalidArgumentException
642
+	 * @throws InvalidInterfaceException
643
+	 * @throws InvalidDataTypeException
644
+	 * @throws EE_Error
645
+	 * @throws ReflectionException
646
+	 */
647
+	protected static function _get_primary_key_name($classname = null)
648
+	{
649
+		if (! $classname) {
650
+			throw new EE_Error(
651
+				sprintf(
652
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
653
+					$classname
654
+				)
655
+			);
656
+		}
657
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
658
+	}
659
+
660
+
661
+	/**
662
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
663
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
664
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
665
+	 * we return false.
666
+	 *
667
+	 * @param array  $props_n_values    incoming array of properties and their values
668
+	 * @param string $classname         the classname of the child class
669
+	 * @param string $timezone
670
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the
671
+	 *                                  date_format and the second value is the time format
672
+	 * @return mixed (EE_Base_Class|bool)
673
+	 * @throws InvalidArgumentException
674
+	 * @throws InvalidInterfaceException
675
+	 * @throws InvalidDataTypeException
676
+	 * @throws EE_Error
677
+	 * @throws ReflectionException
678
+	 * @throws ReflectionException
679
+	 * @throws ReflectionException
680
+	 */
681
+	protected static function _check_for_object($props_n_values, $classname, $timezone = '', $date_formats = [])
682
+	{
683
+		$existing = null;
684
+		$model    = self::_get_model($classname, $timezone);
685
+		if ($model->has_primary_key_field()) {
686
+			$primary_id_ref = self::_get_primary_key_name($classname);
687
+			if (
688
+				array_key_exists($primary_id_ref, $props_n_values)
689
+				&& ! empty($props_n_values[ $primary_id_ref ])
690
+			) {
691
+				$existing = $model->get_one_by_ID(
692
+					$props_n_values[ $primary_id_ref ]
693
+				);
694
+			}
695
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
696
+			// no primary key on this model, but there's still a matching item in the DB
697
+			$existing = $model->get_one_by_ID(
698
+				$model->get_index_primary_key_string($props_n_values)
699
+			);
700
+		}
701
+		if ($existing) {
702
+			// set date formats if present before setting values
703
+			if (! empty($date_formats) && is_array($date_formats)) {
704
+				$existing->set_date_format($date_formats[0]);
705
+				$existing->set_time_format($date_formats[1]);
706
+			} else {
707
+				// set default formats for date and time
708
+				$existing->set_date_format(get_option('date_format'));
709
+				$existing->set_time_format(get_option('time_format'));
710
+			}
711
+			foreach ($props_n_values as $property => $field_value) {
712
+				$existing->set($property, $field_value);
713
+			}
714
+			return $existing;
715
+		}
716
+		return false;
717
+	}
718
+
719
+
720
+	/**
721
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
722
+	 * internally instead of wp set date format options
723
+	 *
724
+	 * @param string $format should be a format recognizable by PHP date() functions.
725
+	 * @since 4.6
726
+	 */
727
+	public function set_date_format($format)
728
+	{
729
+		$this->_dt_frmt = $format;
730
+		// clear cached_properties because they won't be relevant now.
731
+		$this->_clear_cached_properties();
732
+	}
733
+
734
+
735
+	/**
736
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
737
+	 * class internally instead of wp set time format options.
738
+	 *
739
+	 * @param string $format should be a format recognizable by PHP date() functions.
740
+	 * @since 4.6
741
+	 */
742
+	public function set_time_format($format)
743
+	{
744
+		$this->_tm_frmt = $format;
745
+		// clear cached_properties because they won't be relevant now.
746
+		$this->_clear_cached_properties();
747
+	}
748
+
749
+
750
+	/**
751
+	 * This just takes care of clearing out the cached_properties
752
+	 *
753
+	 * @return void
754
+	 */
755
+	protected function _clear_cached_properties()
756
+	{
757
+		$this->_cached_properties = [];
758
+	}
759
+
760
+
761
+	/**
762
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
763
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
764
+	 * you got new information that somehow made you change your mind.
765
+	 *
766
+	 * @param boolean $allow_persist
767
+	 * @return boolean
768
+	 */
769
+	public function set_allow_persist($allow_persist)
770
+	{
771
+		return $this->_allow_persist = $allow_persist;
772
+	}
773
+
774
+
775
+	/**
776
+	 * Gets the field's original value when this object was constructed during this request.
777
+	 * This can be helpful when determining if a model object has changed or not
778
+	 *
779
+	 * @param string $field_name
780
+	 * @return mixed|null
781
+	 * @throws InvalidArgumentException
782
+	 * @throws InvalidInterfaceException
783
+	 * @throws InvalidDataTypeException
784
+	 * @throws EE_Error
785
+	 */
786
+	public function get_original($field_name)
787
+	{
788
+		if (
789
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
790
+			&& $field_settings = $this->_model->field_settings_for($field_name)
791
+		) {
792
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
793
+		}
794
+		return null;
795
+	}
796
+
797
+
798
+	/**
799
+	 * @param EE_Base_Class $obj
800
+	 * @return string
801
+	 */
802
+	public function get_class($obj)
803
+	{
804
+		return get_class($obj);
805
+	}
806
+
807
+
808
+	/**
809
+	 * Set custom select values for model.
810
+	 *
811
+	 * @param array $custom_select_values
812
+	 */
813
+	public function setCustomSelectsValues(array $custom_select_values)
814
+	{
815
+		$this->custom_selection_results = $custom_select_values;
816
+	}
817
+
818
+
819
+	/**
820
+	 * Returns the custom select value for the provided alias if its set.
821
+	 * If not set, returns null.
822
+	 *
823
+	 * @param string $alias
824
+	 * @return string|int|float|null
825
+	 */
826
+	public function getCustomSelect($alias)
827
+	{
828
+		return isset($this->custom_selection_results[ $alias ])
829
+			? $this->custom_selection_results[ $alias ]
830
+			: null;
831
+	}
832
+
833
+
834
+	/**
835
+	 * This sets the field value on the db column if it exists for the given $column_name or
836
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
837
+	 *
838
+	 * @param string $field_name  Must be the exact column name.
839
+	 * @param mixed  $field_value The value to set.
840
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
841
+	 * @throws InvalidArgumentException
842
+	 * @throws InvalidInterfaceException
843
+	 * @throws InvalidDataTypeException
844
+	 * @throws EE_Error
845
+	 * @throws ReflectionException
846
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
847
+	 */
848
+	public function set_field_or_extra_meta($field_name, $field_value)
849
+	{
850
+		if ($this->_model->has_field($field_name)) {
851
+			$this->set($field_name, $field_value);
852
+			return true;
853
+		}
854
+		// ensure this object is saved first so that extra meta can be properly related.
855
+		$this->save();
856
+		return $this->update_extra_meta($field_name, $field_value);
857
+	}
858
+
859
+
860
+	/**
861
+	 *        Saves this object to the database. An array may be supplied to set some values on this
862
+	 * object just before saving.
863
+	 *
864
+	 * @access public
865
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
866
+	 *                                 if provided during the save() method (often client code will change the fields'
867
+	 *                                 values before calling save)
868
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
869
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
870
+	 * @throws InvalidInterfaceException
871
+	 * @throws InvalidDataTypeException
872
+	 * @throws EE_Error
873
+	 * @throws InvalidArgumentException
874
+	 * @throws ReflectionException
875
+	 * @throws ReflectionException
876
+	 * @throws ReflectionException
877
+	 */
878
+	public function save($set_cols_n_values = [])
879
+	{
880
+		/**
881
+		 * Filters the fields we're about to save on the model object
882
+		 *
883
+		 * @param array         $set_cols_n_values
884
+		 * @param EE_Base_Class $model_object
885
+		 */
886
+		$set_cols_n_values = (array) apply_filters(
887
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
888
+			$set_cols_n_values,
889
+			$this
890
+		);
891
+		// set attributes as provided in $set_cols_n_values
892
+		foreach ($set_cols_n_values as $column => $value) {
893
+			$this->set($column, $value);
894
+		}
895
+		// no changes ? then don't do anything
896
+		if (! $this->_has_changes && $this->ID() && $this->_model->get_primary_key_field()->is_auto_increment()) {
897
+			return 0;
898
+		}
899
+		/**
900
+		 * Saving a model object.
901
+		 * Before we perform a save, this action is fired.
902
+		 *
903
+		 * @param EE_Base_Class $model_object the model object about to be saved.
904
+		 */
905
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
906
+		if (! $this->allow_persist()) {
907
+			return 0;
908
+		}
909
+		// now get current attribute values
910
+		$save_cols_n_values = $this->_fields;
911
+		// if the object already has an ID, update it. Otherwise, insert it
912
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
913
+		// They have been
914
+		$old_assumption_concerning_value_preparation = $this->_model
915
+			->get_assumption_concerning_values_already_prepared_by_model_object();
916
+		$this->_model->assume_values_already_prepared_by_model_object(true);
917
+		// does this model have an autoincrement PK?
918
+		if ($this->_model->has_primary_key_field()) {
919
+			if ($this->_model->get_primary_key_field()->is_auto_increment()) {
920
+				// ok check if it's set, if so: update; if not, insert
921
+				if (! empty($save_cols_n_values[ $this->_model->primary_key_name() ])) {
922
+					$results = $this->_model->update_by_ID($save_cols_n_values, $this->ID());
923
+				} else {
924
+					unset($save_cols_n_values[ $this->_model->primary_key_name() ]);
925
+					$results = $this->_model->insert($save_cols_n_values);
926
+					if ($results) {
927
+						// if successful, set the primary key
928
+						// but don't use the normal SET method, because it will check if
929
+						// an item with the same ID exists in the mapper & db, then
930
+						// will find it in the db (because we just added it) and THAT object
931
+						// will get added to the mapper before we can add this one!
932
+						// but if we just avoid using the SET method, all that headache can be avoided
933
+						$pk_field_name                   = $this->_model->primary_key_name();
934
+						$this->_fields[ $pk_field_name ] = $results;
935
+						$this->_clear_cached_property($pk_field_name);
936
+						$this->_model->add_to_entity_map($this);
937
+						$this->_update_cached_related_model_objs_fks();
938
+					}
939
+				}
940
+			} else {// PK is NOT auto-increment
941
+				// so check if one like it already exists in the db
942
+				if ($this->_model->exists_by_ID($this->ID())) {
943
+					if (WP_DEBUG && ! $this->in_entity_map()) {
944
+						throw new EE_Error(
945
+							sprintf(
946
+								esc_html__(
947
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
948
+									'event_espresso'
949
+								),
950
+								get_class($this),
951
+								get_class($this->_model) . '::instance()->add_to_entity_map()',
952
+								get_class($this->_model) . '::instance()->get_one_by_ID()',
953
+								'<br />'
954
+							)
955
+						);
956
+					}
957
+					$results = $this->_model->update_by_ID($save_cols_n_values, $this->ID());
958
+				} else {
959
+					$results = $this->_model->insert($save_cols_n_values);
960
+					$this->_update_cached_related_model_objs_fks();
961
+				}
962
+			}
963
+		} else {// there is NO primary key
964
+			$already_in_db = false;
965
+			foreach ($this->_model->unique_indexes() as $index) {
966
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
967
+				if ($this->_model->exists([$uniqueness_where_params])) {
968
+					$already_in_db = true;
969
+				}
970
+			}
971
+			if ($already_in_db) {
972
+				$combined_pk_fields_n_values = array_intersect_key(
973
+					$save_cols_n_values,
974
+					$this->_model->get_combined_primary_key_fields()
975
+				);
976
+				$results                     = $this->_model->update(
977
+					$save_cols_n_values,
978
+					$combined_pk_fields_n_values
979
+				);
980
+			} else {
981
+				$results = $this->_model->insert($save_cols_n_values);
982
+			}
983
+		}
984
+		// restore the old assumption about values being prepared by the model object
985
+		$this->_model->assume_values_already_prepared_by_model_object(
986
+			$old_assumption_concerning_value_preparation
987
+		);
988
+		/**
989
+		 * After saving the model object this action is called
990
+		 *
991
+		 * @param EE_Base_Class $model_object which was just saved
992
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
993
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
994
+		 */
995
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
996
+		$this->_has_changes = false;
997
+		return $results;
998
+	}
999
+
1000
+
1001
+	/**
1002
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
1003
+	 * A $previous_value can be specified in case there are many meta rows with the same key
1004
+	 *
1005
+	 * @param string $meta_key
1006
+	 * @param mixed  $meta_value
1007
+	 * @param mixed  $previous_value
1008
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
1009
+	 *                  NOTE: if the values haven't changed, returns 0
1010
+	 * @throws InvalidArgumentException
1011
+	 * @throws InvalidInterfaceException
1012
+	 * @throws InvalidDataTypeException
1013
+	 * @throws EE_Error
1014
+	 * @throws ReflectionException
1015
+	 */
1016
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
1017
+	{
1018
+		$query_params = [
1019
+			[
1020
+				'EXM_key'  => $meta_key,
1021
+				'OBJ_ID'   => $this->ID(),
1022
+				'EXM_type' => $this->_model->get_this_model_name(),
1023
+			],
1024
+		];
1025
+		if ($previous_value !== null) {
1026
+			$query_params[0]['EXM_value'] = $meta_value;
1027
+		}
1028
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
1029
+		if (! $existing_rows_like_that) {
1030
+			return $this->add_extra_meta($meta_key, $meta_value);
1031
+		}
1032
+		foreach ($existing_rows_like_that as $existing_row) {
1033
+			$existing_row->save(['EXM_value' => $meta_value]);
1034
+		}
1035
+		return count($existing_rows_like_that);
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
1041
+	 *
1042
+	 * @return boolean
1043
+	 */
1044
+	public function allow_persist()
1045
+	{
1046
+		return $this->_allow_persist;
1047
+	}
1048
+
1049
+
1050
+	/**
1051
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1052
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1053
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1054
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1055
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1056
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1057
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1058
+	 *
1059
+	 * @return void
1060
+	 * @throws ReflectionException
1061
+	 * @throws InvalidArgumentException
1062
+	 * @throws InvalidInterfaceException
1063
+	 * @throws InvalidDataTypeException
1064
+	 * @throws EE_Error
1065
+	 */
1066
+	protected function _update_cached_related_model_objs_fks()
1067
+	{
1068
+		foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
1069
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1070
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1071
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1072
+						$this->_model->get_this_model_name()
1073
+					);
1074
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1075
+					if ($related_model_obj_in_cache->ID()) {
1076
+						$related_model_obj_in_cache->save();
1077
+					}
1078
+				}
1079
+			}
1080
+		}
1081
+	}
1082
+
1083
+
1084
+	/**
1085
+	 * in_entity_map
1086
+	 * Checks if this model object has been proven to already be in the entity map
1087
+	 *
1088
+	 * @return boolean
1089
+	 * @throws InvalidArgumentException
1090
+	 * @throws InvalidInterfaceException
1091
+	 * @throws InvalidDataTypeException
1092
+	 * @throws EE_Error
1093
+	 */
1094
+	public function in_entity_map()
1095
+	{
1096
+		// well, if we looked, did we find it in the entity map?
1097
+		return $this->ID() && $this->_model->get_from_entity_map($this->ID()) === $this;
1098
+	}
1099
+
1100
+
1101
+	/**
1102
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
1103
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
1104
+	 * extra meta row was entered, false if not
1105
+	 *
1106
+	 * @param string  $meta_key
1107
+	 * @param mixed   $meta_value
1108
+	 * @param boolean $unique
1109
+	 * @return boolean
1110
+	 * @throws InvalidArgumentException
1111
+	 * @throws InvalidInterfaceException
1112
+	 * @throws InvalidDataTypeException
1113
+	 * @throws EE_Error
1114
+	 * @throws ReflectionException
1115
+	 * @throws ReflectionException
1116
+	 */
1117
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
1118
+	{
1119
+		if ($unique) {
1120
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
1121
+				[
1122
+					[
1123
+						'EXM_key'  => $meta_key,
1124
+						'OBJ_ID'   => $this->ID(),
1125
+						'EXM_type' => $this->_model->get_this_model_name(),
1126
+					],
1127
+				]
1128
+			);
1129
+			if ($existing_extra_meta) {
1130
+				return false;
1131
+			}
1132
+		}
1133
+		$new_extra_meta = EE_Extra_Meta::new_instance(
1134
+			[
1135
+				'EXM_key'   => $meta_key,
1136
+				'EXM_value' => $meta_value,
1137
+				'OBJ_ID'    => $this->ID(),
1138
+				'EXM_type'  => $this->_model->get_this_model_name(),
1139
+			]
1140
+		);
1141
+		$new_extra_meta->save();
1142
+		return true;
1143
+	}
1144
+
1145
+
1146
+	/**
1147
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
1148
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
1149
+	 *
1150
+	 * @param string $relationName
1151
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
1152
+	 * @throws InvalidArgumentException
1153
+	 * @throws InvalidInterfaceException
1154
+	 * @throws InvalidDataTypeException
1155
+	 * @throws EE_Error
1156
+	 * @throws ReflectionException
1157
+	 */
1158
+	public function get_all_from_cache($relationName)
1159
+	{
1160
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : [];
1161
+		// if the result is not an array, but exists, make it an array
1162
+		$objects = is_array($objects) ? $objects : [$objects];
1163
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
1164
+		// basically, if this model object was stored in the session, and these cached model objects
1165
+		// already have IDs, let's make sure they're in their model's entity mapper
1166
+		// otherwise we will have duplicates next time we call
1167
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
1168
+		$related_model = EE_Registry::instance()->load_model($relationName);
1169
+		foreach ($objects as $model_object) {
1170
+			if ($related_model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
1171
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
1172
+				if ($model_object->ID()) {
1173
+					$related_model->add_to_entity_map($model_object);
1174
+				}
1175
+			} else {
1176
+				throw new EE_Error(
1177
+					sprintf(
1178
+						esc_html__(
1179
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
1180
+							'event_espresso'
1181
+						),
1182
+						$relationName,
1183
+						gettype($model_object)
1184
+					)
1185
+				);
1186
+			}
1187
+		}
1188
+		$this->updateTimezoneOnRelated($objects);
1189
+		return $objects;
1190
+	}
1191
+
1192
+
1193
+	/**
1194
+	 * This retrieves the value of the db column set on this class or if that's not present
1195
+	 * it will attempt to retrieve from extra_meta if found.
1196
+	 * Example Usage:
1197
+	 * Via EE_Message child class:
1198
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
1199
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
1200
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
1201
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
1202
+	 * value for those extra fields dynamically via the EE_message object.
1203
+	 *
1204
+	 * @param string $field_name expecting the fully qualified field name.
1205
+	 * @return mixed|null  value for the field if found.  null if not found.
1206
+	 * @throws ReflectionException
1207
+	 * @throws InvalidArgumentException
1208
+	 * @throws InvalidInterfaceException
1209
+	 * @throws InvalidDataTypeException
1210
+	 * @throws EE_Error
1211
+	 */
1212
+	public function get_field_or_extra_meta($field_name)
1213
+	{
1214
+		if ($this->_model->has_field($field_name)) {
1215
+			$column_value = $this->get($field_name);
1216
+		} else {
1217
+			// This isn't a column in the main table, let's see if it is in the extra meta.
1218
+			$column_value = $this->get_extra_meta($field_name, true);
1219
+		}
1220
+		return $column_value;
1221
+	}
1222
+
1223
+
1224
+	/**
1225
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
1226
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
1227
+	 * You can specify $default is case you haven't found the extra meta
1228
+	 *
1229
+	 * @param string  $meta_key
1230
+	 * @param boolean $single
1231
+	 * @param mixed   $default if we don't find anything, what should we return?
1232
+	 * @return mixed single value if $single; array if ! $single
1233
+	 * @throws ReflectionException
1234
+	 * @throws InvalidArgumentException
1235
+	 * @throws InvalidInterfaceException
1236
+	 * @throws InvalidDataTypeException
1237
+	 * @throws EE_Error
1238
+	 */
1239
+	public function get_extra_meta($meta_key, $single = false, $default = null)
1240
+	{
1241
+		if ($single) {
1242
+			$result = $this->get_first_related(
1243
+				'Extra_Meta',
1244
+				[['EXM_key' => $meta_key]]
1245
+			);
1246
+			if ($result instanceof EE_Extra_Meta) {
1247
+				return $result->value();
1248
+			}
1249
+		} else {
1250
+			$results = $this->get_many_related(
1251
+				'Extra_Meta',
1252
+				[['EXM_key' => $meta_key]]
1253
+			);
1254
+			if ($results) {
1255
+				$values = [];
1256
+				foreach ($results as $result) {
1257
+					if ($result instanceof EE_Extra_Meta) {
1258
+						$values[ $result->ID() ] = $result->value();
1259
+					}
1260
+				}
1261
+				return $values;
1262
+			}
1263
+		}
1264
+		// if nothing discovered yet return default.
1265
+		return apply_filters(
1266
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
1267
+			$default,
1268
+			$meta_key,
1269
+			$single,
1270
+			$this
1271
+		);
1272
+	}
1273
+
1274
+
1275
+	/**
1276
+	 * Gets the first (ie, one) related model object of the specified type.
1277
+	 *
1278
+	 * @param string $relationName key in the model's _model_relations array
1279
+	 * @param array  $query_params @see
1280
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1281
+	 * @return EE_Base_Class (not an array, a single object)
1282
+	 * @throws ReflectionException
1283
+	 * @throws InvalidArgumentException
1284
+	 * @throws InvalidInterfaceException
1285
+	 * @throws InvalidDataTypeException
1286
+	 * @throws EE_Error
1287
+	 */
1288
+	public function get_first_related($relationName, $query_params = [])
1289
+	{
1290
+		$model_relation = $this->_model->related_settings_for($relationName);
1291
+		if ($this->ID()) {
1292
+			// this exists in the DB, get from the cache OR the DB
1293
+			// if they've provided some query parameters, don't bother trying to cache the result
1294
+			// also make sure we're not caching the result of get_first_related
1295
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
1296
+			if (
1297
+				$query_params
1298
+				|| ! $model_relation instanceof EE_Belongs_To_Relation
1299
+			) {
1300
+				$related_model_object = $this->_model->get_first_related(
1301
+					$this,
1302
+					$relationName,
1303
+					$query_params
1304
+				);
1305
+			} else {
1306
+				// first, check if we've already cached the result of this query
1307
+				$cached_result = $this->get_one_from_cache($relationName);
1308
+				if (! $cached_result) {
1309
+					$related_model_object = $this->_model->get_first_related(
1310
+						$this,
1311
+						$relationName,
1312
+						$query_params
1313
+					);
1314
+					$this->cache($relationName, $related_model_object);
1315
+				} else {
1316
+					$related_model_object = $cached_result;
1317
+				}
1318
+			}
1319
+		} else {
1320
+			$related_model_object = null;
1321
+			// this doesn't exist in the Db,
1322
+			// but maybe the relation is of type belongs to, and so the related thing might
1323
+			if ($model_relation instanceof EE_Belongs_To_Relation) {
1324
+				$related_model_object = $this->_model->get_first_related(
1325
+					$this,
1326
+					$relationName,
1327
+					$query_params
1328
+				);
1329
+			}
1330
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
1331
+			// just get what's cached on this object
1332
+			if (! $related_model_object) {
1333
+				$related_model_object = $this->get_one_from_cache($relationName);
1334
+			}
1335
+		}
1336
+		$this->updateTimezoneOnRelated($related_model_object);
1337
+		return $related_model_object;
1338
+	}
1339
+
1340
+
1341
+	/**
1342
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
1343
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
1344
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
1345
+	 * because we want to get even deleted items etc.
1346
+	 *
1347
+	 * @param string $relationName key in the model's _model_relations array
1348
+	 * @param array  $query_params @see
1349
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1350
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
1351
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
1352
+	 *                             results if you want IDs
1353
+	 * @throws ReflectionException
1354
+	 * @throws InvalidArgumentException
1355
+	 * @throws InvalidInterfaceException
1356
+	 * @throws InvalidDataTypeException
1357
+	 * @throws EE_Error
1358
+	 */
1359
+	public function get_many_related($relationName, $query_params = [])
1360
+	{
1361
+		if ($this->ID()) {
1362
+			// this exists in the DB, so get the related things from either the cache or the DB
1363
+			// if there are query parameters, forget about caching the related model objects.
1364
+			if ($query_params) {
1365
+				$related_model_objects = $this->_model->get_all_related(
1366
+					$this,
1367
+					$relationName,
1368
+					$query_params
1369
+				);
1370
+			} else {
1371
+				// did we already cache the result of this query?
1372
+				$cached_results = $this->get_all_from_cache($relationName);
1373
+				if (! $cached_results) {
1374
+					$related_model_objects = $this->_model->get_all_related(
1375
+						$this,
1376
+						$relationName,
1377
+						$query_params
1378
+					);
1379
+					// if no query parameters were passed, then we got all the related model objects
1380
+					// for that relation. We can cache them then.
1381
+					foreach ($related_model_objects as $related_model_object) {
1382
+						$this->cache($relationName, $related_model_object);
1383
+					}
1384
+				} else {
1385
+					$related_model_objects = $cached_results;
1386
+				}
1387
+			}
1388
+		} else {
1389
+			// this doesn't exist in the DB, so just get the related things from the cache
1390
+			$related_model_objects = $this->get_all_from_cache($relationName);
1391
+		}
1392
+		$this->updateTimezoneOnRelated($related_model_objects);
1393
+		return $related_model_objects;
1394
+	}
1395
+
1396
+
1397
+	/**
1398
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
1399
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
1400
+	 *
1401
+	 * @param string $relationName
1402
+	 * @return EE_Base_Class
1403
+	 */
1404
+	public function get_one_from_cache($relationName)
1405
+	{
1406
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
1407
+			? $this->_model_relations[ $relationName ]
1408
+			: null;
1409
+		if (is_array($cached_array_or_object)) {
1410
+			$cached_array_or_object = array_shift($cached_array_or_object);
1411
+		}
1412
+		$this->updateTimezoneOnRelated($cached_array_or_object);
1413
+		return $cached_array_or_object;
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * cache
1419
+	 * stores the passed model object on the current model object.
1420
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
1421
+	 *
1422
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
1423
+	 *                                       'Registration' associated with this model object
1424
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
1425
+	 *                                       that could be a payment or a registration)
1426
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
1427
+	 *                                       items which will be stored in an array on this object
1428
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
1429
+	 *                                       related thing, no array)
1430
+	 * @throws InvalidArgumentException
1431
+	 * @throws InvalidInterfaceException
1432
+	 * @throws InvalidDataTypeException
1433
+	 * @throws EE_Error
1434
+	 */
1435
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
1436
+	{
1437
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
1438
+		if (! $object_to_cache instanceof EE_Base_Class) {
1439
+			return false;
1440
+		}
1441
+		// also get "how" the object is related, or throw an error
1442
+		if (! $relationship_to_model = $this->_model->related_settings_for($relationName)) {
1443
+			throw new EE_Error(
1444
+				sprintf(
1445
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
1446
+					$relationName,
1447
+					get_class($this)
1448
+				)
1449
+			);
1450
+		}
1451
+		// how many things are related ?
1452
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
1453
+			// if it's a "belongs to" relationship, then there's only one related model object
1454
+			// eg, if this is a registration, there's only 1 attendee for it
1455
+			// so for these model objects just set it to be cached
1456
+			$this->_model_relations[ $relationName ] = $object_to_cache;
1457
+			$return                                  = true;
1458
+		} else {
1459
+			// otherwise, this is the "many" side of a one to many relationship,
1460
+			// so we'll add the object to the array of related objects for that type.
1461
+			// eg: if this is an event, there are many registrations for that event,
1462
+			// so we cache the registrations in an array
1463
+			if (! is_array($this->_model_relations[ $relationName ])) {
1464
+				// if for some reason, the cached item is a model object,
1465
+				// then stick that in the array, otherwise start with an empty array
1466
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
1467
+														   instanceof
1468
+														   EE_Base_Class
1469
+					? [$this->_model_relations[ $relationName ]] : [];
1470
+			}
1471
+			// first check for a cache_id which is normally empty
1472
+			if (! empty($cache_id)) {
1473
+				// if the cache_id exists, then it means we are purposely trying to cache this
1474
+				// with a known key that can then be used to retrieve the object later on
1475
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
1476
+				$return                                               = $cache_id;
1477
+			} elseif ($object_to_cache->ID()) {
1478
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
1479
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
1480
+				$return                                                            = $object_to_cache->ID();
1481
+			} else {
1482
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
1483
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
1484
+				// move the internal pointer to the end of the array
1485
+				end($this->_model_relations[ $relationName ]);
1486
+				// and grab the key so that we can return it
1487
+				$return = key($this->_model_relations[ $relationName ]);
1488
+			}
1489
+		}
1490
+		return $return;
1491
+	}
1492
+
1493
+
1494
+	/**
1495
+	 * This just returns whatever is set for the current timezone.
1496
+	 *
1497
+	 * @access public
1498
+	 * @return string timezone string
1499
+	 */
1500
+	public function get_timezone()
1501
+	{
1502
+		if (empty($this->_timezone)) {
1503
+			$this->set_timezone();
1504
+		}
1505
+		return $this->_timezone;
1506
+	}
1507
+
1508
+
1509
+	/**
1510
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
1511
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
1512
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
1513
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
1514
+	 *
1515
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
1516
+	 * @param bool   $only_if_not_set if true and $this->_timezone already has a value, then will not do anything
1517
+	 * @return void
1518
+	 */
1519
+	public function set_timezone($timezone = '', $only_if_not_set = false)
1520
+	{
1521
+		static $set_in_progress = false;
1522
+		// don't update the timezone if it's already set ?
1523
+		if (($only_if_not_set && $this->_timezone !== '') ) {
1524
+			return;
1525
+		}
1526
+		$valid_timezone = ! empty($timezone) && $this->_timezone && $timezone !== $this->_timezone
1527
+			? EEH_DTT_Helper::get_valid_timezone_string($timezone)
1528
+			: $this->_timezone;
1529
+		// do NOT set the timezone if we are already in the process of setting the timezone
1530
+		// OR the existing timezone is already set and the incoming value is nothing (which gets set to default TZ)
1531
+		// OR the existing timezone is already set and the validated value is the same as the existing timezone
1532
+		if (
1533
+			$set_in_progress
1534
+			|| (
1535
+				! empty($this->_timezone)
1536
+				&& (
1537
+					empty($timezone) || $valid_timezone === $this->_timezone
1538
+				)
1539
+			)
1540
+		) {
1541
+			return;
1542
+		}
1543
+		$set_in_progress = true;
1544
+		$this->_timezone = $valid_timezone ? $valid_timezone : EEH_DTT_Helper::get_valid_timezone_string();
1545
+		$TZ = new DateTimeZone($this->_timezone);
1546
+		// make sure we clear all cached properties because they won't be relevant now
1547
+		$this->_clear_cached_properties();
1548
+		// make sure we update field settings and the date for all EE_Datetime_Fields
1549
+		$model_fields = $this->_model->field_settings();
1550
+		foreach ($model_fields as $field_name => $field_obj) {
1551
+			if ($field_obj instanceof EE_Datetime_Field) {
1552
+				$field_obj->set_timezone($this->_timezone);
1553
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
1554
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], $TZ);
1555
+				}
1556
+			}
1557
+		}
1558
+		$set_in_progress = false;
1559
+	}
1560
+
1561
+
1562
+	/**
1563
+	 * @param array|EE_Base_Class $related
1564
+	 * @since $VID:$
1565
+	 */
1566
+	private function updateTimezoneOnRelated($related)
1567
+	{
1568
+		if ($related instanceof EE_Base_Class && $related->get_timezone() !== $this->_timezone) {
1569
+			$related->set_timezone($this->_timezone);
1570
+			return;
1571
+		}
1572
+		if (is_array($related)) {
1573
+			foreach ($related as $object) {
1574
+				$this->updateTimezoneOnRelated($object);
1575
+			}
1576
+		}
1577
+	}
1578
+
1579
+
1580
+	/**
1581
+	 * This returns the current internal set format for the date and time formats.
1582
+	 *
1583
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
1584
+	 *                             where the first value is the date format and the second value is the time format.
1585
+	 * @return mixed string|array
1586
+	 */
1587
+	public function get_format($full = true)
1588
+	{
1589
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
1590
+	}
1591
+
1592
+
1593
+	/**
1594
+	 * update_cache_after_object_save
1595
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
1596
+	 * obtained after being saved to the db
1597
+	 *
1598
+	 * @param string        $relationName       - the type of object that is cached
1599
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
1600
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
1601
+	 * @return boolean TRUE on success, FALSE on fail
1602
+	 * @throws InvalidArgumentException
1603
+	 * @throws InvalidInterfaceException
1604
+	 * @throws InvalidDataTypeException
1605
+	 * @throws EE_Error
1606
+	 */
1607
+	public function update_cache_after_object_save(
1608
+		$relationName,
1609
+		EE_Base_Class $newly_saved_object,
1610
+		$current_cache_id = ''
1611
+	) {
1612
+		// verify that incoming object is of the correct type
1613
+		$obj_class = 'EE_' . $relationName;
1614
+		if ($newly_saved_object instanceof $obj_class) {
1615
+			$this->updateTimezoneOnRelated($newly_saved_object);
1616
+			// now get the type of relation
1617
+			$relationship_to_model = $this->_model->related_settings_for($relationName);
1618
+			// if this is a 1:1 relationship
1619
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
1620
+				// then just replace the cached object with the newly saved object
1621
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
1622
+				return true;
1623
+				// or if it's some kind of sordid feral polyamorous relationship...
1624
+			}
1625
+			if (
1626
+				is_array($this->_model_relations[ $relationName ])
1627
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
1628
+			) {
1629
+				// then remove the current cached item
1630
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
1631
+				// and cache the newly saved object using it's new ID
1632
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
1633
+				return true;
1634
+			}
1635
+		}
1636
+		return false;
1637
+	}
1638
+
1639
+
1640
+	/**
1641
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1642
+	 * matching the given query conditions.
1643
+	 *
1644
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1645
+	 * @param int   $limit              How many objects to return.
1646
+	 * @param array $query_params       Any additional conditions on the query.
1647
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1648
+	 *                                  you can indicate just the columns you want returned
1649
+	 * @return array|EE_Base_Class[]
1650
+	 * @throws ReflectionException
1651
+	 * @throws InvalidArgumentException
1652
+	 * @throws InvalidInterfaceException
1653
+	 * @throws InvalidDataTypeException
1654
+	 * @throws EE_Error
1655
+	 */
1656
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = [], $columns_to_select = null)
1657
+	{
1658
+		$field         = empty($field_to_order_by) && $this->_model->has_primary_key_field()
1659
+			? $this->_model->get_primary_key_field()->get_name()
1660
+			: $field_to_order_by;
1661
+		$current_value = ! empty($field) ? $this->get($field) : null;
1662
+		if (empty($field) || empty($current_value)) {
1663
+			return [];
1664
+		}
1665
+		return $this->_model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1666
+	}
1667
+
1668
+
1669
+	/**
1670
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1671
+	 * matching the given query conditions.
1672
+	 *
1673
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1674
+	 * @param int   $limit              How many objects to return.
1675
+	 * @param array $query_params       Any additional conditions on the query.
1676
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1677
+	 *                                  you can indicate just the columns you want returned
1678
+	 * @return array|EE_Base_Class[]
1679
+	 * @throws ReflectionException
1680
+	 * @throws InvalidArgumentException
1681
+	 * @throws InvalidInterfaceException
1682
+	 * @throws InvalidDataTypeException
1683
+	 * @throws EE_Error
1684
+	 */
1685
+	public function previous_x(
1686
+		$field_to_order_by = null,
1687
+		$limit = 1,
1688
+		$query_params = [],
1689
+		$columns_to_select = null
1690
+	) {
1691
+		$field         = empty($field_to_order_by) && $this->_model->has_primary_key_field()
1692
+			? $this->_model->get_primary_key_field()->get_name()
1693
+			: $field_to_order_by;
1694
+		$current_value = ! empty($field) ? $this->get($field) : null;
1695
+		if (empty($field) || empty($current_value)) {
1696
+			return [];
1697
+		}
1698
+		return $this->_model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1699
+	}
1700
+
1701
+
1702
+	/**
1703
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1704
+	 * matching the given query conditions.
1705
+	 *
1706
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1707
+	 * @param array $query_params       Any additional conditions on the query.
1708
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1709
+	 *                                  you can indicate just the columns you want returned
1710
+	 * @return array|EE_Base_Class
1711
+	 * @throws ReflectionException
1712
+	 * @throws InvalidArgumentException
1713
+	 * @throws InvalidInterfaceException
1714
+	 * @throws InvalidDataTypeException
1715
+	 * @throws EE_Error
1716
+	 */
1717
+	public function next($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1718
+	{
1719
+		$field         = empty($field_to_order_by) && $this->_model->has_primary_key_field()
1720
+			? $this->_model->get_primary_key_field()->get_name()
1721
+			: $field_to_order_by;
1722
+		$current_value = ! empty($field) ? $this->get($field) : null;
1723
+		if (empty($field) || empty($current_value)) {
1724
+			return [];
1725
+		}
1726
+		return $this->_model->next($current_value, $field, $query_params, $columns_to_select);
1727
+	}
1728
+
1729
+
1730
+	/**
1731
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1732
+	 * matching the given query conditions.
1733
+	 *
1734
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1735
+	 * @param array $query_params       Any additional conditions on the query.
1736
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1737
+	 *                                  you can indicate just the column you want returned
1738
+	 * @return array|EE_Base_Class
1739
+	 * @throws ReflectionException
1740
+	 * @throws InvalidArgumentException
1741
+	 * @throws InvalidInterfaceException
1742
+	 * @throws InvalidDataTypeException
1743
+	 * @throws EE_Error
1744
+	 */
1745
+	public function previous($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1746
+	{
1747
+		$field         = empty($field_to_order_by) && $this->_model->has_primary_key_field()
1748
+			? $this->_model->get_primary_key_field()->get_name()
1749
+			: $field_to_order_by;
1750
+		$current_value = ! empty($field) ? $this->get($field) : null;
1751
+		if (empty($field) || empty($current_value)) {
1752
+			return [];
1753
+		}
1754
+		return $this->_model->previous($current_value, $field, $query_params, $columns_to_select);
1755
+	}
1756
+
1757
+
1758
+	/**
1759
+	 * This is used to return the internal DateTime object used for a field that is a
1760
+	 * EE_Datetime_Field.
1761
+	 *
1762
+	 * @param string $field_name               The field name retrieving the DateTime object.
1763
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1764
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1765
+	 *                                         EE_Datetime_Field and but the field value is null, then
1766
+	 *                                         just null is returned (because that indicates that likely
1767
+	 *                                         this field is nullable).
1768
+	 * @throws InvalidArgumentException
1769
+	 * @throws InvalidDataTypeException
1770
+	 * @throws InvalidInterfaceException
1771
+	 */
1772
+	public function get_DateTime_object($field_name)
1773
+	{
1774
+		$field_settings = $this->_model->field_settings_for($field_name);
1775
+		if (! $field_settings instanceof EE_Datetime_Field) {
1776
+			EE_Error::add_error(
1777
+				sprintf(
1778
+					esc_html__(
1779
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1780
+						'event_espresso'
1781
+					),
1782
+					$field_name
1783
+				),
1784
+				__FILE__,
1785
+				__FUNCTION__,
1786
+				__LINE__
1787
+			);
1788
+			return false;
1789
+		}
1790
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1791
+			? clone $this->_fields[ $field_name ]
1792
+			: null;
1793
+	}
1794
+
1795
+
1796
+
1797
+
1798
+	/**
1799
+	 * NOTE ABOUT BELOW:
1800
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1801
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1802
+	 * you want to set both date and time at the same time, you can just use the models default set($field_name,$value)
1803
+	 * method and make sure you send the entire datetime value for setting.
1804
+	 */
1805
+
1806
+
1807
+	/**
1808
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1809
+	 * can be easily used as the value of form input.
1810
+	 *
1811
+	 * @param string $field_name
1812
+	 * @return void
1813
+	 * @throws InvalidArgumentException
1814
+	 * @throws InvalidInterfaceException
1815
+	 * @throws InvalidDataTypeException
1816
+	 * @throws EE_Error
1817
+	 */
1818
+	public function f($field_name)
1819
+	{
1820
+		$this->e($field_name, 'form_input');
1821
+	}
1822
+
1823
+
1824
+	/**
1825
+	 * To be used in template to immediately echo out the value, and format it for output.
1826
+	 * Eg, should call stripslashes and whatnot before echoing
1827
+	 *
1828
+	 * @param string $field_name      the name of the field as it appears in the DB
1829
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1830
+	 *                                (in cases where the same property may be used for different outputs
1831
+	 *                                - i.e. datetime, money etc.)
1832
+	 * @return void
1833
+	 * @throws InvalidArgumentException
1834
+	 * @throws InvalidInterfaceException
1835
+	 * @throws InvalidDataTypeException
1836
+	 * @throws EE_Error
1837
+	 */
1838
+	public function e($field_name, $extra_cache_ref = null)
1839
+	{
1840
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1841
+	}
1842
+
1843
+
1844
+	/**
1845
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1846
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1847
+	 * to see what options are available.
1848
+	 *
1849
+	 * @param string $field_name
1850
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1851
+	 *                                (in cases where the same property may be used for different outputs
1852
+	 *                                - i.e. datetime, money etc.)
1853
+	 * @return mixed
1854
+	 * @throws InvalidArgumentException
1855
+	 * @throws InvalidInterfaceException
1856
+	 * @throws InvalidDataTypeException
1857
+	 * @throws EE_Error
1858
+	 */
1859
+	public function get_pretty($field_name, $extra_cache_ref = null)
1860
+	{
1861
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1862
+	}
1863
+
1864
+
1865
+	/**
1866
+	 * Same as `f()` but just returns the value instead of echoing it
1867
+	 *
1868
+	 * @param string $field_name
1869
+	 * @return string
1870
+	 * @throws InvalidArgumentException
1871
+	 * @throws InvalidInterfaceException
1872
+	 * @throws InvalidDataTypeException
1873
+	 * @throws EE_Error
1874
+	 */
1875
+	public function get_f($field_name)
1876
+	{
1877
+		return (string) $this->get_pretty($field_name, 'form_input');
1878
+	}
1879
+
1880
+
1881
+	/**
1882
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1883
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1884
+	 * other echoes the pretty value for dtt)
1885
+	 *
1886
+	 * @param string $field_name name of model object datetime field holding the value
1887
+	 * @param string $format     format for the date returned (if NULL we use default in dt_frmt property)
1888
+	 * @return string            datetime value formatted
1889
+	 * @throws InvalidArgumentException
1890
+	 * @throws InvalidInterfaceException
1891
+	 * @throws InvalidDataTypeException
1892
+	 * @throws EE_Error
1893
+	 */
1894
+	public function get_date($field_name, $format = '')
1895
+	{
1896
+		return $this->_get_datetime($field_name, $format, null, 'D');
1897
+	}
1898
+
1899
+
1900
+	/**
1901
+	 * This simply returns the datetime for the given field name
1902
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1903
+	 * (and the equivalent e_date, e_time, e_datetime).
1904
+	 *
1905
+	 * @access   protected
1906
+	 * @param string  $field_name    Field on the instantiated EE_Base_Class child object
1907
+	 * @param string  $date_format   valid datetime format used for date
1908
+	 *                               (if '' then we just use the default on the field,
1909
+	 *                               if NULL we use the last-used format)
1910
+	 * @param string  $time_format   Same as above except this is for time format
1911
+	 * @param string  $date_or_time  if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1912
+	 * @param boolean $echo          Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1913
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1914
+	 *                               if field is not a valid dtt field, or void if echoing
1915
+	 * @throws InvalidArgumentException
1916
+	 * @throws InvalidInterfaceException
1917
+	 * @throws InvalidDataTypeException
1918
+	 * @throws EE_Error
1919
+	 */
1920
+	protected function _get_datetime(
1921
+		$field_name,
1922
+		$date_format = '',
1923
+		$time_format = '',
1924
+		$date_or_time = '',
1925
+		$echo = false
1926
+	) {
1927
+		// clear cached property
1928
+		$this->_clear_cached_property($field_name);
1929
+		// reset format properties because they are used in get()
1930
+		$this->_dt_frmt = $date_format !== '' ? $date_format : $this->_dt_frmt;
1931
+		$this->_tm_frmt = $time_format !== '' ? $time_format : $this->_tm_frmt;
1932
+		if ($echo) {
1933
+			$this->e($field_name, $date_or_time);
1934
+			return '';
1935
+		}
1936
+		return $this->get($field_name, $date_or_time);
1937
+	}
1938
+
1939
+
1940
+	/**
1941
+	 * @param        $field_name
1942
+	 * @param string $format
1943
+	 * @throws InvalidArgumentException
1944
+	 * @throws InvalidInterfaceException
1945
+	 * @throws InvalidDataTypeException
1946
+	 * @throws EE_Error
1947
+	 */
1948
+	public function e_date($field_name, $format = '')
1949
+	{
1950
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1951
+	}
1952
+
1953
+
1954
+	/**
1955
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1956
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1957
+	 * other echoes the pretty value for dtt)
1958
+	 *
1959
+	 * @param string $field_name name of model object datetime field holding the value
1960
+	 * @param string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1961
+	 * @return string             datetime value formatted
1962
+	 * @throws InvalidArgumentException
1963
+	 * @throws InvalidInterfaceException
1964
+	 * @throws InvalidDataTypeException
1965
+	 * @throws EE_Error
1966
+	 */
1967
+	public function get_time($field_name, $format = '')
1968
+	{
1969
+		return $this->_get_datetime($field_name, null, $format, 'T');
1970
+	}
1971
+
1972
+
1973
+	/**
1974
+	 * @param        $field_name
1975
+	 * @param string $format
1976
+	 * @throws InvalidArgumentException
1977
+	 * @throws InvalidInterfaceException
1978
+	 * @throws InvalidDataTypeException
1979
+	 * @throws EE_Error
1980
+	 */
1981
+	public function e_time($field_name, $format = '')
1982
+	{
1983
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1984
+	}
1985
+
1986
+
1987
+	/**
1988
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1989
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1990
+	 * other echoes the pretty value for dtt)
1991
+	 *
1992
+	 * @param string $field_name  name of model object datetime field holding the value
1993
+	 * @param string $date_format format for the date returned (if NULL we use default in dt_frmt property)
1994
+	 * @param string $time_format format for the time returned (if NULL we use default in tm_frmt property)
1995
+	 * @return string             datetime value formatted
1996
+	 * @throws InvalidArgumentException
1997
+	 * @throws InvalidInterfaceException
1998
+	 * @throws InvalidDataTypeException
1999
+	 * @throws EE_Error
2000
+	 */
2001
+	public function get_datetime($field_name, $date_format = '', $time_format = '')
2002
+	{
2003
+		return $this->_get_datetime($field_name, $date_format, $time_format);
2004
+	}
2005
+
2006
+
2007
+	/**
2008
+	 * @param string $field_name
2009
+	 * @param string $date_format
2010
+	 * @param string $time_format
2011
+	 * @throws InvalidArgumentException
2012
+	 * @throws InvalidInterfaceException
2013
+	 * @throws InvalidDataTypeException
2014
+	 * @throws EE_Error
2015
+	 */
2016
+	public function e_datetime($field_name, $date_format = '', $time_format = '')
2017
+	{
2018
+		$this->_get_datetime($field_name, $date_format, $time_format, null, true);
2019
+	}
2020
+
2021
+
2022
+	/**
2023
+	 * Get the i8ln value for a date using the WordPress @param string $field_name The EE_Datetime_Field reference for
2024
+	 *                           the date being retrieved.
2025
+	 *
2026
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
2027
+	 *                           on the object will be used.
2028
+	 * @return string Date and time string in set locale or false if no field exists for the given
2029
+	 * @throws InvalidArgumentException
2030
+	 * @throws InvalidInterfaceException
2031
+	 * @throws InvalidDataTypeException
2032
+	 * @throws EE_Error
2033
+	 *                           field name.
2034
+	 * @see date_i18n function.
2035
+	 */
2036
+	public function get_i18n_datetime($field_name, $format = '')
2037
+	{
2038
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
2039
+		return date_i18n(
2040
+			$format,
2041
+			EEH_DTT_Helper::get_timestamp_with_offset(
2042
+				$this->get_raw($field_name),
2043
+				$this->get_timezone()
2044
+			)
2045
+		);
2046
+	}
2047
+
2048
+
2049
+	/**
2050
+	 * This method simply returns the RAW unprocessed value for the given property in this class
2051
+	 *
2052
+	 * @param string $field_name A valid field name
2053
+	 * @return mixed              Whatever the raw value stored on the property is.
2054
+	 * @throws InvalidArgumentException
2055
+	 * @throws InvalidInterfaceException
2056
+	 * @throws InvalidDataTypeException
2057
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
2058
+	 */
2059
+	public function get_raw($field_name)
2060
+	{
2061
+		$field_settings = $this->_model->field_settings_for($field_name);
2062
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
2063
+			? $this->_fields[ $field_name ]->format('U')
2064
+			: $this->_fields[ $field_name ];
2065
+	}
2066
+
2067
+
2068
+	/**
2069
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
2070
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
2071
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
2072
+	 * that could lead to some unexpected results!
2073
+	 *
2074
+	 * @access public
2075
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
2076
+	 *                                         value being returned.
2077
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
2078
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
2079
+	 * @param string $prepend                  You can include something to prepend on the timestamp
2080
+	 * @param string $append                   You can include something to append on the timestamp
2081
+	 * @return string timestamp
2082
+	 * @throws InvalidArgumentException
2083
+	 * @throws InvalidInterfaceException
2084
+	 * @throws InvalidDataTypeException
2085
+	 * @throws EE_Error
2086
+	 */
2087
+	public function display_in_my_timezone(
2088
+		$field_name,
2089
+		$callback = 'get_datetime',
2090
+		$args = null,
2091
+		$prepend = '',
2092
+		$append = ''
2093
+	) {
2094
+		$timezone = EEH_DTT_Helper::get_timezone();
2095
+		if ($timezone === $this->_timezone) {
2096
+			return '';
2097
+		}
2098
+		$original_timezone = $this->_timezone;
2099
+		$this->set_timezone($timezone);
2100
+		$fn   = (array) $field_name;
2101
+		$args = array_merge($fn, (array) $args);
2102
+		if (! method_exists($this, $callback)) {
2103
+			throw new EE_Error(
2104
+				sprintf(
2105
+					esc_html__(
2106
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
2107
+						'event_espresso'
2108
+					),
2109
+					$callback
2110
+				)
2111
+			);
2112
+		}
2113
+		$args   = (array) $args;
2114
+		$return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
2115
+		$this->set_timezone($original_timezone);
2116
+		return $return;
2117
+	}
2118
+
2119
+
2120
+	/**
2121
+	 * Deletes this model object.
2122
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
2123
+	 * override
2124
+	 * `EE_Base_Class::_delete` NOT this class.
2125
+	 *
2126
+	 * @return boolean | int
2127
+	 * @throws ReflectionException
2128
+	 * @throws InvalidArgumentException
2129
+	 * @throws InvalidInterfaceException
2130
+	 * @throws InvalidDataTypeException
2131
+	 * @throws EE_Error
2132
+	 */
2133
+	public function delete()
2134
+	{
2135
+		/**
2136
+		 * Called just before the `EE_Base_Class::_delete` method call.
2137
+		 * Note:
2138
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
2139
+		 * should be aware that `_delete` may not always result in a permanent delete.
2140
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
2141
+		 * soft deletes (trash) the object and does not permanently delete it.
2142
+		 *
2143
+		 * @param EE_Base_Class $model_object about to be 'deleted'
2144
+		 */
2145
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
2146
+		$result = $this->_delete();
2147
+		/**
2148
+		 * Called just after the `EE_Base_Class::_delete` method call.
2149
+		 * Note:
2150
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
2151
+		 * should be aware that `_delete` may not always result in a permanent delete.
2152
+		 * For example `EE_Soft_Base_Class::_delete`
2153
+		 * soft deletes (trash) the object and does not permanently delete it.
2154
+		 *
2155
+		 * @param EE_Base_Class $model_object that was just 'deleted'
2156
+		 * @param boolean       $result
2157
+		 */
2158
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
2159
+		return $result;
2160
+	}
2161
+
2162
+
2163
+	/**
2164
+	 * Calls the specific delete method for the instantiated class.
2165
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
2166
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
2167
+	 * `EE_Base_Class::delete`
2168
+	 *
2169
+	 * @return bool|int
2170
+	 * @throws ReflectionException
2171
+	 * @throws InvalidArgumentException
2172
+	 * @throws InvalidInterfaceException
2173
+	 * @throws InvalidDataTypeException
2174
+	 * @throws EE_Error
2175
+	 */
2176
+	protected function _delete()
2177
+	{
2178
+		return $this->delete_permanently();
2179
+	}
2180
+
2181
+
2182
+	/**
2183
+	 * Deletes this model object permanently from db
2184
+	 * (but keep in mind related models may block the delete and return an error)
2185
+	 *
2186
+	 * @return bool | int
2187
+	 * @throws ReflectionException
2188
+	 * @throws InvalidArgumentException
2189
+	 * @throws InvalidInterfaceException
2190
+	 * @throws InvalidDataTypeException
2191
+	 * @throws EE_Error
2192
+	 */
2193
+	public function delete_permanently()
2194
+	{
2195
+		/**
2196
+		 * Called just before HARD deleting a model object
2197
+		 *
2198
+		 * @param EE_Base_Class $model_object about to be 'deleted'
2199
+		 */
2200
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
2201
+		$result = $this->_model->delete_permanently_by_ID($this->ID());
2202
+		$this->refresh_cache_of_related_objects();
2203
+		/**
2204
+		 * Called just after HARD deleting a model object
2205
+		 *
2206
+		 * @param EE_Base_Class $model_object that was just 'deleted'
2207
+		 * @param boolean       $result
2208
+		 */
2209
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
2210
+		return $result;
2211
+	}
2212
+
2213
+
2214
+	/**
2215
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
2216
+	 * related model objects
2217
+	 *
2218
+	 * @throws ReflectionException
2219
+	 * @throws InvalidArgumentException
2220
+	 * @throws InvalidInterfaceException
2221
+	 * @throws InvalidDataTypeException
2222
+	 * @throws EE_Error
2223
+	 */
2224
+	public function refresh_cache_of_related_objects()
2225
+	{
2226
+		foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
2227
+			if (! empty($this->_model_relations[ $relation_name ])) {
2228
+				$related_objects = $this->_model_relations[ $relation_name ];
2229
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
2230
+					// this relation only stores a single model object, not an array
2231
+					// but let's make it consistent
2232
+					$related_objects = [$related_objects];
2233
+				}
2234
+				foreach ($related_objects as $related_object) {
2235
+					// only refresh their cache if they're in memory
2236
+					if ($related_object instanceof EE_Base_Class) {
2237
+						$related_object->clear_cache(
2238
+							$this->_model->get_this_model_name(),
2239
+							$this
2240
+						);
2241
+					}
2242
+				}
2243
+			}
2244
+		}
2245
+	}
2246
+
2247
+
2248
+	/**
2249
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
2250
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
2251
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
2252
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
2253
+	 *
2254
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
2255
+	 *                                                     Eg 'Registration'
2256
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
2257
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
2258
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
2259
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
2260
+	 *                                                     this is HasMany or HABTM.
2261
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
2262
+	 *                                                     relation from all
2263
+	 * @throws InvalidArgumentException
2264
+	 * @throws InvalidInterfaceException
2265
+	 * @throws InvalidDataTypeException
2266
+	 * @throws EE_Error
2267
+	 * @throws ReflectionException
2268
+	 */
2269
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
2270
+	{
2271
+		$relationship_to_model = $this->_model->related_settings_for($relationName);
2272
+		$index_in_cache        = '';
2273
+		if (! $relationship_to_model) {
2274
+			throw new EE_Error(
2275
+				sprintf(
2276
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
2277
+					$relationName,
2278
+					get_class($this)
2279
+				)
2280
+			);
2281
+		}
2282
+		if ($clear_all) {
2283
+			$obj_removed                             = true;
2284
+			$this->_model_relations[ $relationName ] = null;
2285
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
2286
+			$obj_removed                             = $this->_model_relations[ $relationName ];
2287
+			$this->_model_relations[ $relationName ] = null;
2288
+		} else {
2289
+			if (
2290
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
2291
+				&& $object_to_remove_or_index_into_array->ID()
2292
+			) {
2293
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
2294
+				if (
2295
+					is_array($this->_model_relations[ $relationName ])
2296
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
2297
+				) {
2298
+					$index_found_at = null;
2299
+					// find this object in the array even though it has a different key
2300
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
2301
+						/** @noinspection TypeUnsafeComparisonInspection */
2302
+						if (
2303
+							$obj instanceof EE_Base_Class
2304
+							&& (
2305
+								$obj == $object_to_remove_or_index_into_array
2306
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
2307
+							)
2308
+						) {
2309
+							$index_found_at = $index;
2310
+							break;
2311
+						}
2312
+					}
2313
+					if ($index_found_at) {
2314
+						$index_in_cache = $index_found_at;
2315
+					} else {
2316
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
2317
+						// if it wasn't in it to begin with. So we're done
2318
+						return $object_to_remove_or_index_into_array;
2319
+					}
2320
+				}
2321
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
2322
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
2323
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
2324
+					/** @noinspection TypeUnsafeComparisonInspection */
2325
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
2326
+						$index_in_cache = $index;
2327
+					}
2328
+				}
2329
+			} else {
2330
+				$index_in_cache = $object_to_remove_or_index_into_array;
2331
+			}
2332
+			// supposedly we've found it. But it could just be that the client code
2333
+			// provided a bad index/object
2334
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
2335
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
2336
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
2337
+			} else {
2338
+				// that thing was never cached anyways.
2339
+				$obj_removed = null;
2340
+			}
2341
+		}
2342
+		return $obj_removed;
2343
+	}
2344
+
2345
+
2346
+	/**
2347
+	 * Saves this model object and its NEW cached relations to the database.
2348
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
2349
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
2350
+	 * because otherwise, there's a potential for infinite looping of saving
2351
+	 * Saves the cached related model objects, and ensures the relation between them
2352
+	 * and this object and properly setup
2353
+	 *
2354
+	 * @return int ID of new model object on save; 0 on failure+
2355
+	 * @throws ReflectionException
2356
+	 * @throws InvalidArgumentException
2357
+	 * @throws InvalidInterfaceException
2358
+	 * @throws InvalidDataTypeException
2359
+	 * @throws EE_Error
2360
+	 */
2361
+	public function save_new_cached_related_model_objs()
2362
+	{
2363
+		// make sure this has been saved
2364
+		if (! $this->ID()) {
2365
+			$id = $this->save();
2366
+		} else {
2367
+			$id = $this->ID();
2368
+		}
2369
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
2370
+		foreach ($this->_model->relation_settings() as $relationName => $relationObj) {
2371
+			if ($this->_model_relations[ $relationName ]) {
2372
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2373
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2374
+				/* @var $related_model_obj EE_Base_Class */
2375
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2376
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2377
+					// but ONLY if it DOES NOT exist in the DB
2378
+					$related_model_obj = $this->_model_relations[ $relationName ];
2379
+					// if( ! $related_model_obj->ID()){
2380
+					$this->_add_relation_to($related_model_obj, $relationName);
2381
+					$related_model_obj->save_new_cached_related_model_objs();
2382
+					// }
2383
+				} else {
2384
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2385
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2386
+						// but ONLY if it DOES NOT exist in the DB
2387
+						// if( ! $related_model_obj->ID()){
2388
+						$this->_add_relation_to($related_model_obj, $relationName);
2389
+						$related_model_obj->save_new_cached_related_model_objs();
2390
+						// }
2391
+					}
2392
+				}
2393
+			}
2394
+		}
2395
+		return $id;
2396
+	}
2397
+
2398
+
2399
+	/**
2400
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2401
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2402
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2403
+	 *
2404
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2405
+	 * @param string $relationName                     eg 'Events','Question',etc.
2406
+	 *                                                 an attendee to a group, you also want to specify which role they
2407
+	 *                                                 will have in that group. So you would use this parameter to
2408
+	 *                                                 specify array('role-column-name'=>'role-id')
2409
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2410
+	 *                                                 allow you to further constrict the relation to being added.
2411
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2412
+	 *                                                 column on the JOIN table and currently only the HABTM models
2413
+	 *                                                 accept these additional conditions.  Also remember that if an
2414
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2415
+	 *                                                 NEW row is created in the join table.
2416
+	 * @param null   $cache_id
2417
+	 * @return EE_Base_Class the object the relation was added to
2418
+	 * @throws ReflectionException
2419
+	 * @throws InvalidArgumentException
2420
+	 * @throws InvalidInterfaceException
2421
+	 * @throws InvalidDataTypeException
2422
+	 * @throws EE_Error
2423
+	 */
2424
+	public function _add_relation_to(
2425
+		$otherObjectModelObjectOrID,
2426
+		$relationName,
2427
+		$extra_join_model_fields_n_values = [],
2428
+		$cache_id = null
2429
+	) {
2430
+		// if this thing exists in the DB, save the relation to the DB
2431
+		if ($this->ID()) {
2432
+			$otherObject = $this->_model->add_relationship_to(
2433
+				$this,
2434
+				$otherObjectModelObjectOrID,
2435
+				$relationName,
2436
+				$extra_join_model_fields_n_values
2437
+			);
2438
+			// clear cache so future get_many_related and get_first_related() return new results.
2439
+			$this->clear_cache($relationName, $otherObject, true);
2440
+			if ($otherObject instanceof EE_Base_Class) {
2441
+				$otherObject->clear_cache($this->_model->get_this_model_name(), $this);
2442
+			}
2443
+		} else {
2444
+			// this thing doesn't exist in the DB,  so just cache it
2445
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2446
+				throw new EE_Error(
2447
+					sprintf(
2448
+						esc_html__(
2449
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2450
+							'event_espresso'
2451
+						),
2452
+						$otherObjectModelObjectOrID,
2453
+						get_class($this)
2454
+					)
2455
+				);
2456
+			}
2457
+			$otherObject = $otherObjectModelObjectOrID;
2458
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2459
+		}
2460
+		if ($otherObject instanceof EE_Base_Class) {
2461
+			// fix the reciprocal relation too
2462
+			if ($otherObject->ID()) {
2463
+				// its saved so assumed relations exist in the DB, so we can just
2464
+				// clear the cache so future queries use the updated info in the DB
2465
+				$otherObject->clear_cache(
2466
+					$this->_model->get_this_model_name(),
2467
+					null,
2468
+					true
2469
+				);
2470
+			} else {
2471
+				// it's not saved, so it caches relations like this
2472
+				$otherObject->cache($this->_model->get_this_model_name(), $this);
2473
+			}
2474
+		}
2475
+		return $otherObject;
2476
+	}
2477
+
2478
+
2479
+	/**
2480
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2481
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2482
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2483
+	 * from the cache
2484
+	 *
2485
+	 * @param mixed  $otherObjectModelObjectOrID
2486
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2487
+	 *                to the DB yet
2488
+	 * @param string $relationName
2489
+	 * @param array  $where_query
2490
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2491
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2492
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2493
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2494
+	 *                deleted.
2495
+	 * @return EE_Base_Class the relation was removed from
2496
+	 * @throws ReflectionException
2497
+	 * @throws InvalidArgumentException
2498
+	 * @throws InvalidInterfaceException
2499
+	 * @throws InvalidDataTypeException
2500
+	 * @throws EE_Error
2501
+	 */
2502
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
2503
+	{
2504
+		if ($this->ID()) {
2505
+			// if this exists in the DB, save the relation change to the DB too
2506
+			$otherObject = $this->_model->remove_relationship_to(
2507
+				$this,
2508
+				$otherObjectModelObjectOrID,
2509
+				$relationName,
2510
+				$where_query
2511
+			);
2512
+			$this->clear_cache(
2513
+				$relationName,
2514
+				$otherObject
2515
+			);
2516
+		} else {
2517
+			// this doesn't exist in the DB, just remove it from the cache
2518
+			$otherObject = $this->clear_cache(
2519
+				$relationName,
2520
+				$otherObjectModelObjectOrID
2521
+			);
2522
+		}
2523
+		if ($otherObject instanceof EE_Base_Class) {
2524
+			$otherObject->clear_cache(
2525
+				$this->_model->get_this_model_name(),
2526
+				$this
2527
+			);
2528
+		}
2529
+		return $otherObject;
2530
+	}
2531
+
2532
+
2533
+	/**
2534
+	 * Removes ALL the related things for the $relationName.
2535
+	 *
2536
+	 * @param string $relationName
2537
+	 * @param array  $where_query_params @see
2538
+	 *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2539
+	 * @return EE_Base_Class
2540
+	 * @throws ReflectionException
2541
+	 * @throws InvalidArgumentException
2542
+	 * @throws InvalidInterfaceException
2543
+	 * @throws InvalidDataTypeException
2544
+	 * @throws EE_Error
2545
+	 */
2546
+	public function _remove_relations($relationName, $where_query_params = [])
2547
+	{
2548
+		if ($this->ID()) {
2549
+			// if this exists in the DB, save the relation change to the DB too
2550
+			$otherObjects = $this->_model->remove_relations(
2551
+				$this,
2552
+				$relationName,
2553
+				$where_query_params
2554
+			);
2555
+			$this->clear_cache(
2556
+				$relationName,
2557
+				null,
2558
+				true
2559
+			);
2560
+		} else {
2561
+			// this doesn't exist in the DB, just remove it from the cache
2562
+			$otherObjects = $this->clear_cache(
2563
+				$relationName,
2564
+				null,
2565
+				true
2566
+			);
2567
+		}
2568
+		if (is_array($otherObjects)) {
2569
+			foreach ($otherObjects as $otherObject) {
2570
+				$otherObject->clear_cache(
2571
+					$this->_model->get_this_model_name(),
2572
+					$this
2573
+				);
2574
+			}
2575
+		}
2576
+		return $otherObjects;
2577
+	}
2578
+
2579
+
2580
+	/**
2581
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2582
+	 * unless otherwise specified in the $query_params
2583
+	 *
2584
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2585
+	 * @param array  $query_params   @see
2586
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2587
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2588
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2589
+	 *                               that by the setting $distinct to TRUE;
2590
+	 * @return int
2591
+	 * @throws ReflectionException
2592
+	 * @throws InvalidArgumentException
2593
+	 * @throws InvalidInterfaceException
2594
+	 * @throws InvalidDataTypeException
2595
+	 * @throws EE_Error
2596
+	 */
2597
+	public function count_related($relation_name, $query_params = [], $field_to_count = null, $distinct = false)
2598
+	{
2599
+		return $this->_model->count_related(
2600
+			$this,
2601
+			$relation_name,
2602
+			$query_params,
2603
+			$field_to_count,
2604
+			$distinct
2605
+		);
2606
+	}
2607
+
2608
+
2609
+	/**
2610
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2611
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2612
+	 *
2613
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2614
+	 * @param array  $query_params  @see
2615
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2616
+	 * @param string $field_to_sum  name of field to count by.
2617
+	 *                              By default, uses primary key
2618
+	 *                              (which doesn't make much sense, so you should probably change it)
2619
+	 * @return int
2620
+	 * @throws ReflectionException
2621
+	 * @throws InvalidArgumentException
2622
+	 * @throws InvalidInterfaceException
2623
+	 * @throws InvalidDataTypeException
2624
+	 * @throws EE_Error
2625
+	 */
2626
+	public function sum_related($relation_name, $query_params = [], $field_to_sum = null)
2627
+	{
2628
+		return $this->_model->sum_related(
2629
+			$this,
2630
+			$relation_name,
2631
+			$query_params,
2632
+			$field_to_sum
2633
+		);
2634
+	}
2635
+
2636
+
2637
+	/**
2638
+	 * Does a delete on all related objects of type $relationName and removes
2639
+	 * the current model object's relation to them. If they can't be deleted (because
2640
+	 * of blocking related model objects) does nothing. If the related model objects are
2641
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2642
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2643
+	 *
2644
+	 * @param string $relationName
2645
+	 * @param array  $query_params @see
2646
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2647
+	 * @return int how many deleted
2648
+	 * @throws ReflectionException
2649
+	 * @throws InvalidArgumentException
2650
+	 * @throws InvalidInterfaceException
2651
+	 * @throws InvalidDataTypeException
2652
+	 * @throws EE_Error
2653
+	 */
2654
+	public function delete_related($relationName, $query_params = [])
2655
+	{
2656
+		if ($this->ID()) {
2657
+			$count = $this->_model->delete_related(
2658
+				$this,
2659
+				$relationName,
2660
+				$query_params
2661
+			);
2662
+		} else {
2663
+			$count = count($this->get_all_from_cache($relationName));
2664
+			$this->clear_cache($relationName, null, true);
2665
+		}
2666
+		return $count;
2667
+	}
2668
+
2669
+
2670
+	/**
2671
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2672
+	 * the current model object's relation to them. If they can't be deleted (because
2673
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2674
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2675
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2676
+	 *
2677
+	 * @param string $relationName
2678
+	 * @param array  $query_params @see
2679
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2680
+	 * @return int how many deleted (including those soft deleted)
2681
+	 * @throws ReflectionException
2682
+	 * @throws InvalidArgumentException
2683
+	 * @throws InvalidInterfaceException
2684
+	 * @throws InvalidDataTypeException
2685
+	 * @throws EE_Error
2686
+	 */
2687
+	public function delete_related_permanently($relationName, $query_params = [])
2688
+	{
2689
+		if ($this->ID()) {
2690
+			$count = $this->_model->delete_related_permanently(
2691
+				$this,
2692
+				$relationName,
2693
+				$query_params
2694
+			);
2695
+		} else {
2696
+			$count = count($this->get_all_from_cache($relationName));
2697
+		}
2698
+		$this->clear_cache($relationName, null, true);
2699
+		return $count;
2700
+	}
2701
+
2702
+
2703
+	/**
2704
+	 * is_set
2705
+	 * Just a simple utility function children can use for checking if property exists
2706
+	 *
2707
+	 * @access  public
2708
+	 * @param string $field_name property to check
2709
+	 * @return bool                              TRUE if existing,FALSE if not.
2710
+	 */
2711
+	public function is_set($field_name)
2712
+	{
2713
+		return isset($this->_fields[ $field_name ]);
2714
+	}
2715
+
2716
+
2717
+	/**
2718
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2719
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2720
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2721
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2722
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2723
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2724
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2725
+	 * and accepts 2 arguments: the object on which the function was called,
2726
+	 * and an array of the original arguments passed to the function.
2727
+	 * Whatever their callback function returns will be returned by this function.
2728
+	 * Example: in functions.php (or in a plugin):
2729
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2730
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2731
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2732
+	 *          return $previousReturnValue.$returnString;
2733
+	 *      }
2734
+	 * require('EE_Answer.class.php');
2735
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2736
+	 * echo $answer->my_callback('monkeys',100);
2737
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2738
+	 *
2739
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2740
+	 * @param array  $args       array of original arguments passed to the function
2741
+	 * @return mixed whatever the plugin which calls add_filter decides
2742
+	 * @throws EE_Error
2743
+	 */
2744
+	public function __call($methodName, $args)
2745
+	{
2746
+		$className = get_class($this);
2747
+		$tagName   = "FHEE__{$className}__{$methodName}";
2748
+		if (! has_filter($tagName)) {
2749
+			throw new EE_Error(
2750
+				sprintf(
2751
+					esc_html__(
2752
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2753
+						'event_espresso'
2754
+					),
2755
+					$methodName,
2756
+					$className,
2757
+					$tagName
2758
+				)
2759
+			);
2760
+		}
2761
+		return apply_filters($tagName, null, $this, $args);
2762
+	}
2763
+
2764
+
2765
+	/**
2766
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2767
+	 * is specified, only deletes extra meta records with that value.
2768
+	 *
2769
+	 * @param string $meta_key
2770
+	 * @param mixed  $meta_value
2771
+	 * @return int number of extra meta rows deleted
2772
+	 * @throws InvalidArgumentException
2773
+	 * @throws InvalidInterfaceException
2774
+	 * @throws InvalidDataTypeException
2775
+	 * @throws EE_Error
2776
+	 * @throws ReflectionException
2777
+	 */
2778
+	public function delete_extra_meta($meta_key, $meta_value = null)
2779
+	{
2780
+		$query_params = [
2781
+			[
2782
+				'EXM_key'  => $meta_key,
2783
+				'OBJ_ID'   => $this->ID(),
2784
+				'EXM_type' => $this->_model->get_this_model_name(),
2785
+			],
2786
+		];
2787
+		if ($meta_value !== null) {
2788
+			$query_params[0]['EXM_value'] = $meta_value;
2789
+		}
2790
+		return EEM_Extra_Meta::instance()->delete($query_params);
2791
+	}
2792
+
2793
+
2794
+	/**
2795
+	 * Returns a simple array of all the extra meta associated with this model object.
2796
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2797
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2798
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2799
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2800
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2801
+	 * finally the extra meta's value as each sub-value. (eg
2802
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2803
+	 *
2804
+	 * @param boolean $one_of_each_key
2805
+	 * @return array
2806
+	 * @throws ReflectionException
2807
+	 * @throws InvalidArgumentException
2808
+	 * @throws InvalidInterfaceException
2809
+	 * @throws InvalidDataTypeException
2810
+	 * @throws EE_Error
2811
+	 */
2812
+	public function all_extra_meta_array($one_of_each_key = true)
2813
+	{
2814
+		$return_array = [];
2815
+		if ($one_of_each_key) {
2816
+			$extra_meta_objs = $this->get_many_related(
2817
+				'Extra_Meta',
2818
+				['group_by' => 'EXM_key']
2819
+			);
2820
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2821
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2822
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2823
+				}
2824
+			}
2825
+		} else {
2826
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2827
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2828
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2829
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2830
+						$return_array[ $extra_meta_obj->key() ] = [];
2831
+					}
2832
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2833
+				}
2834
+			}
2835
+		}
2836
+		return $return_array;
2837
+	}
2838
+
2839
+
2840
+	/**
2841
+	 * refresh_from_db
2842
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2843
+	 *
2844
+	 * @throws ReflectionException
2845
+	 * @throws InvalidArgumentException
2846
+	 * @throws InvalidInterfaceException
2847
+	 * @throws InvalidDataTypeException
2848
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2849
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2850
+	 */
2851
+	public function refresh_from_db()
2852
+	{
2853
+		if ($this->ID() && $this->in_entity_map()) {
2854
+			$this->_model->refresh_entity_map_from_db($this->ID());
2855
+		} else {
2856
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2857
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
2858
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2859
+			// absolutely nothing in it for this ID
2860
+			if (WP_DEBUG) {
2861
+				throw new EE_Error(
2862
+					sprintf(
2863
+						esc_html__(
2864
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2865
+							'event_espresso'
2866
+						),
2867
+						$this->ID(),
2868
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2869
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2870
+					)
2871
+				);
2872
+			}
2873
+		}
2874
+	}
2875
+
2876
+
2877
+	/**
2878
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
2879
+	 * Does not allow negative values, however.
2880
+	 *
2881
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
2882
+	 *                                   (positive or negative). One important gotcha: all these values must be
2883
+	 *                                   on the same table (eg don't pass in one field for the posts table and
2884
+	 *                                   another for the event meta table.)
2885
+	 * @return bool
2886
+	 * @throws EE_Error
2887
+	 * @throws InvalidArgumentException
2888
+	 * @throws InvalidDataTypeException
2889
+	 * @throws InvalidInterfaceException
2890
+	 * @throws ReflectionException
2891
+	 * @since 4.9.80.p
2892
+	 */
2893
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
2894
+	{
2895
+		global $wpdb;
2896
+		if (empty($fields_n_quantities)) {
2897
+			// No fields to update? Well sure, we updated them to that value just fine.
2898
+			return true;
2899
+		}
2900
+		$fields             = [];
2901
+		$set_sql_statements = [];
2902
+		foreach ($fields_n_quantities as $field_name => $quantity) {
2903
+			$field       = $this->_model->field_settings_for($field_name);
2904
+			$fields[]    = $field;
2905
+			$column_name = $field->get_table_column();
2906
+
2907
+			$abs_qty = absint($quantity);
2908
+			if ($quantity > 0) {
2909
+				// don't let the value be negative as often these fields are unsigned
2910
+				$set_sql_statements[] = $wpdb->prepare(
2911
+					"`{$column_name}` = `{$column_name}` + %d",
2912
+					$abs_qty
2913
+				);
2914
+			} else {
2915
+				$set_sql_statements[] = $wpdb->prepare(
2916
+					"`{$column_name}` = CASE
2917 2917
                        WHEN (`{$column_name}` >= %d)
2918 2918
                        THEN `{$column_name}` - %d
2919 2919
                        ELSE 0
2920 2920
                     END",
2921
-                    $abs_qty,
2922
-                    $abs_qty
2923
-                );
2924
-            }
2925
-        }
2926
-        return $this->updateFieldsInDB(
2927
-            $fields,
2928
-            implode(', ', $set_sql_statements)
2929
-        );
2930
-    }
2931
-
2932
-
2933
-    /**
2934
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
2935
-     *
2936
-     * @param EE_Model_Field_Base[] $fields
2937
-     * @param string                $new_value_sql
2938
-     *          example: 'column_name=123',
2939
-     *          or 'column_name=column_name+1',
2940
-     *          or 'column_name= CASE
2941
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
2942
-     *          THEN `column_name` + 5
2943
-     *          ELSE `column_name`
2944
-     *          END'
2945
-     *          Also updates $field on this model object with the latest value from the database.
2946
-     * @return bool
2947
-     * @throws EE_Error
2948
-     * @throws InvalidArgumentException
2949
-     * @throws InvalidDataTypeException
2950
-     * @throws InvalidInterfaceException
2951
-     * @throws ReflectionException
2952
-     * @since 4.9.80.p
2953
-     */
2954
-    protected function updateFieldsInDB($fields, $new_value_sql)
2955
-    {
2956
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
2957
-        // if it wasn't even there to start off.
2958
-        if (! $this->ID()) {
2959
-            $this->save();
2960
-        }
2961
-        global $wpdb;
2962
-        if (empty($fields)) {
2963
-            throw new InvalidArgumentException(
2964
-                esc_html__(
2965
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
2966
-                    'event_espresso'
2967
-                )
2968
-            );
2969
-        }
2970
-        $first_field = reset($fields);
2971
-        $table_alias = $first_field->get_table_alias();
2972
-        foreach ($fields as $field) {
2973
-            if ($table_alias !== $field->get_table_alias()) {
2974
-                throw new InvalidArgumentException(
2975
-                    sprintf(
2976
-                        esc_html__(
2977
-                        // @codingStandardsIgnoreStart
2978
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
2979
-                            // @codingStandardsIgnoreEnd
2980
-                            'event_espresso'
2981
-                        ),
2982
-                        $table_alias,
2983
-                        $field->get_table_alias()
2984
-                    )
2985
-                );
2986
-            }
2987
-        }
2988
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
2989
-        $table_obj      = $this->_model->get_table_obj_by_alias($table_alias);
2990
-        $table_pk_value = $this->ID();
2991
-        $table_name     = $table_obj->get_table_name();
2992
-        if ($table_obj instanceof EE_Secondary_Table) {
2993
-            $table_pk_field_name = $table_obj->get_fk_on_table();
2994
-        } else {
2995
-            $table_pk_field_name = $table_obj->get_pk_column();
2996
-        }
2997
-
2998
-        $query  =
2999
-            "UPDATE `{$table_name}`
2921
+					$abs_qty,
2922
+					$abs_qty
2923
+				);
2924
+			}
2925
+		}
2926
+		return $this->updateFieldsInDB(
2927
+			$fields,
2928
+			implode(', ', $set_sql_statements)
2929
+		);
2930
+	}
2931
+
2932
+
2933
+	/**
2934
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
2935
+	 *
2936
+	 * @param EE_Model_Field_Base[] $fields
2937
+	 * @param string                $new_value_sql
2938
+	 *          example: 'column_name=123',
2939
+	 *          or 'column_name=column_name+1',
2940
+	 *          or 'column_name= CASE
2941
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
2942
+	 *          THEN `column_name` + 5
2943
+	 *          ELSE `column_name`
2944
+	 *          END'
2945
+	 *          Also updates $field on this model object with the latest value from the database.
2946
+	 * @return bool
2947
+	 * @throws EE_Error
2948
+	 * @throws InvalidArgumentException
2949
+	 * @throws InvalidDataTypeException
2950
+	 * @throws InvalidInterfaceException
2951
+	 * @throws ReflectionException
2952
+	 * @since 4.9.80.p
2953
+	 */
2954
+	protected function updateFieldsInDB($fields, $new_value_sql)
2955
+	{
2956
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
2957
+		// if it wasn't even there to start off.
2958
+		if (! $this->ID()) {
2959
+			$this->save();
2960
+		}
2961
+		global $wpdb;
2962
+		if (empty($fields)) {
2963
+			throw new InvalidArgumentException(
2964
+				esc_html__(
2965
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
2966
+					'event_espresso'
2967
+				)
2968
+			);
2969
+		}
2970
+		$first_field = reset($fields);
2971
+		$table_alias = $first_field->get_table_alias();
2972
+		foreach ($fields as $field) {
2973
+			if ($table_alias !== $field->get_table_alias()) {
2974
+				throw new InvalidArgumentException(
2975
+					sprintf(
2976
+						esc_html__(
2977
+						// @codingStandardsIgnoreStart
2978
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
2979
+							// @codingStandardsIgnoreEnd
2980
+							'event_espresso'
2981
+						),
2982
+						$table_alias,
2983
+						$field->get_table_alias()
2984
+					)
2985
+				);
2986
+			}
2987
+		}
2988
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
2989
+		$table_obj      = $this->_model->get_table_obj_by_alias($table_alias);
2990
+		$table_pk_value = $this->ID();
2991
+		$table_name     = $table_obj->get_table_name();
2992
+		if ($table_obj instanceof EE_Secondary_Table) {
2993
+			$table_pk_field_name = $table_obj->get_fk_on_table();
2994
+		} else {
2995
+			$table_pk_field_name = $table_obj->get_pk_column();
2996
+		}
2997
+
2998
+		$query  =
2999
+			"UPDATE `{$table_name}`
3000 3000
             SET "
3001
-            . $new_value_sql
3002
-            . $wpdb->prepare(
3003
-                "
3001
+			. $new_value_sql
3002
+			. $wpdb->prepare(
3003
+				"
3004 3004
             WHERE `{$table_pk_field_name}` = %d;",
3005
-                $table_pk_value
3006
-            );
3007
-        $result = $wpdb->query($query);
3008
-        foreach ($fields as $field) {
3009
-            // If it was successful, we'd like to know the new value.
3010
-            // If it failed, we'd also like to know the new value.
3011
-            $new_value = $this->_model->get_var(
3012
-                $this->_model->alter_query_params_to_restrict_by_ID(
3013
-                    $this->_model->get_index_primary_key_string(
3014
-                        $this->model_field_array()
3015
-                    ),
3016
-                    [
3017
-                        'default_where_conditions' => 'minimum',
3018
-                    ]
3019
-                ),
3020
-                $field->get_name()
3021
-            );
3022
-            $this->set_from_db(
3023
-                $field->get_name(),
3024
-                $new_value
3025
-            );
3026
-        }
3027
-        return (bool) $result;
3028
-    }
3029
-
3030
-
3031
-    /**
3032
-     * This simply returns an array of model fields for this object
3033
-     *
3034
-     * @return array
3035
-     * @throws InvalidArgumentException
3036
-     * @throws InvalidInterfaceException
3037
-     * @throws InvalidDataTypeException
3038
-     * @throws EE_Error
3039
-     */
3040
-    public function model_field_array()
3041
-    {
3042
-        $fields     = $this->_model->field_settings();
3043
-        $properties = [];
3044
-        // remove prepended underscore
3045
-        foreach ($fields as $field_name => $settings) {
3046
-            $properties[ $field_name ] = $this->get($field_name);
3047
-        }
3048
-        return $properties;
3049
-    }
3050
-
3051
-
3052
-    /**
3053
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3054
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3055
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3056
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3057
-     * Otherwise returns false.
3058
-     *
3059
-     * @param string $field_name_to_bump
3060
-     * @param string $field_name_affecting_total
3061
-     * @param string $limit_field_name
3062
-     * @param int    $quantity
3063
-     * @return bool
3064
-     * @throws EE_Error
3065
-     * @throws InvalidArgumentException
3066
-     * @throws InvalidDataTypeException
3067
-     * @throws InvalidInterfaceException
3068
-     * @throws ReflectionException
3069
-     * @since 4.9.80.p
3070
-     */
3071
-    public function incrementFieldConditionallyInDb(
3072
-        $field_name_to_bump,
3073
-        $field_name_affecting_total,
3074
-        $limit_field_name,
3075
-        $quantity
3076
-    ) {
3077
-        global $wpdb;
3078
-        $field       = $this->_model->field_settings_for($field_name_to_bump);
3079
-        $column_name = $field->get_table_column();
3080
-
3081
-        $field_affecting_total  = $this->_model->field_settings_for($field_name_affecting_total);
3082
-        $column_affecting_total = $field_affecting_total->get_table_column();
3083
-
3084
-        $limiting_field  = $this->_model->field_settings_for($limit_field_name);
3085
-        $limiting_column = $limiting_field->get_table_column();
3086
-        return $this->updateFieldsInDB(
3087
-            [$field],
3088
-            $wpdb->prepare(
3089
-                "`{$column_name}` =
3005
+				$table_pk_value
3006
+			);
3007
+		$result = $wpdb->query($query);
3008
+		foreach ($fields as $field) {
3009
+			// If it was successful, we'd like to know the new value.
3010
+			// If it failed, we'd also like to know the new value.
3011
+			$new_value = $this->_model->get_var(
3012
+				$this->_model->alter_query_params_to_restrict_by_ID(
3013
+					$this->_model->get_index_primary_key_string(
3014
+						$this->model_field_array()
3015
+					),
3016
+					[
3017
+						'default_where_conditions' => 'minimum',
3018
+					]
3019
+				),
3020
+				$field->get_name()
3021
+			);
3022
+			$this->set_from_db(
3023
+				$field->get_name(),
3024
+				$new_value
3025
+			);
3026
+		}
3027
+		return (bool) $result;
3028
+	}
3029
+
3030
+
3031
+	/**
3032
+	 * This simply returns an array of model fields for this object
3033
+	 *
3034
+	 * @return array
3035
+	 * @throws InvalidArgumentException
3036
+	 * @throws InvalidInterfaceException
3037
+	 * @throws InvalidDataTypeException
3038
+	 * @throws EE_Error
3039
+	 */
3040
+	public function model_field_array()
3041
+	{
3042
+		$fields     = $this->_model->field_settings();
3043
+		$properties = [];
3044
+		// remove prepended underscore
3045
+		foreach ($fields as $field_name => $settings) {
3046
+			$properties[ $field_name ] = $this->get($field_name);
3047
+		}
3048
+		return $properties;
3049
+	}
3050
+
3051
+
3052
+	/**
3053
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3054
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3055
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3056
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3057
+	 * Otherwise returns false.
3058
+	 *
3059
+	 * @param string $field_name_to_bump
3060
+	 * @param string $field_name_affecting_total
3061
+	 * @param string $limit_field_name
3062
+	 * @param int    $quantity
3063
+	 * @return bool
3064
+	 * @throws EE_Error
3065
+	 * @throws InvalidArgumentException
3066
+	 * @throws InvalidDataTypeException
3067
+	 * @throws InvalidInterfaceException
3068
+	 * @throws ReflectionException
3069
+	 * @since 4.9.80.p
3070
+	 */
3071
+	public function incrementFieldConditionallyInDb(
3072
+		$field_name_to_bump,
3073
+		$field_name_affecting_total,
3074
+		$limit_field_name,
3075
+		$quantity
3076
+	) {
3077
+		global $wpdb;
3078
+		$field       = $this->_model->field_settings_for($field_name_to_bump);
3079
+		$column_name = $field->get_table_column();
3080
+
3081
+		$field_affecting_total  = $this->_model->field_settings_for($field_name_affecting_total);
3082
+		$column_affecting_total = $field_affecting_total->get_table_column();
3083
+
3084
+		$limiting_field  = $this->_model->field_settings_for($limit_field_name);
3085
+		$limiting_column = $limiting_field->get_table_column();
3086
+		return $this->updateFieldsInDB(
3087
+			[$field],
3088
+			$wpdb->prepare(
3089
+				"`{$column_name}` =
3090 3090
             CASE
3091 3091
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3092 3092
                THEN `{$column_name}` + %d
3093 3093
                ELSE `{$column_name}`
3094 3094
             END",
3095
-                $quantity,
3096
-                EE_INF_IN_DB,
3097
-                $quantity
3098
-            )
3099
-        );
3100
-    }
3101
-
3102
-
3103
-    /**
3104
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3105
-     * (probably a bad assumption they have made, oh well)
3106
-     *
3107
-     * @return string
3108
-     */
3109
-    public function __toString()
3110
-    {
3111
-        try {
3112
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3113
-        } catch (Exception $e) {
3114
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3115
-            return '';
3116
-        }
3117
-    }
3118
-
3119
-
3120
-    /**
3121
-     * Gets a pretty nice displayable nice for this model object. Often overridden
3122
-     *
3123
-     * @return string
3124
-     * @throws InvalidArgumentException
3125
-     * @throws InvalidInterfaceException
3126
-     * @throws InvalidDataTypeException
3127
-     * @throws EE_Error
3128
-     */
3129
-    public function name()
3130
-    {
3131
-        // find a field that's not a text field
3132
-        $field_we_can_use = $this->_model->get_a_field_of_type('EE_Text_Field_Base');
3133
-        if ($field_we_can_use) {
3134
-            return $this->get($field_we_can_use->get_name());
3135
-        }
3136
-        $first_few_properties = $this->model_field_array();
3137
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3138
-        $name_parts           = [];
3139
-        foreach ($first_few_properties as $name => $value) {
3140
-            $name_parts[] = "$name:$value";
3141
-        }
3142
-        return implode(',', $name_parts);
3143
-    }
3144
-
3145
-
3146
-    /**
3147
-     * Clear related model objects if they're already in the DB, because otherwise when we
3148
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3149
-     * This means if we have made changes to those related model objects, and want to unserialize
3150
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3151
-     * Instead, those related model objects should be directly serialized and stored.
3152
-     * Eg, the following won't work:
3153
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3154
-     * $att = $reg->attendee();
3155
-     * $att->set( 'ATT_fname', 'Dirk' );
3156
-     * update_option( 'my_option', serialize( $reg ) );
3157
-     * //END REQUEST
3158
-     * //START NEXT REQUEST
3159
-     * $reg = get_option( 'my_option' );
3160
-     * $reg->attendee()->save();
3161
-     * And would need to be replace with:
3162
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3163
-     * $att = $reg->attendee();
3164
-     * $att->set( 'ATT_fname', 'Dirk' );
3165
-     * update_option( 'my_option', serialize( $reg ) );
3166
-     * //END REQUEST
3167
-     * //START NEXT REQUEST
3168
-     * $att = get_option( 'my_option' );
3169
-     * $att->save();
3170
-     *
3171
-     * @return array
3172
-     * @throws ReflectionException
3173
-     * @throws InvalidArgumentException
3174
-     * @throws InvalidInterfaceException
3175
-     * @throws InvalidDataTypeException
3176
-     * @throws EE_Error
3177
-     */
3178
-    public function __sleep()
3179
-    {
3180
-        foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
3181
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3182
-                $classname = 'EE_' . $this->_model->get_this_model_name();
3183
-                if (
3184
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3185
-                    && $this->get_one_from_cache($relation_name)->ID()
3186
-                ) {
3187
-                    $this->clear_cache(
3188
-                        $relation_name,
3189
-                        $this->get_one_from_cache($relation_name)->ID()
3190
-                    );
3191
-                }
3192
-            }
3193
-        }
3194
-        $this->_props_n_values_provided_in_constructor = [];
3195
-        $properties_to_serialize                       = get_object_vars($this);
3196
-        // don't serialize the model. It's big and that risks recursion
3197
-        unset($properties_to_serialize['_model']);
3198
-        return array_keys($properties_to_serialize);
3199
-    }
3200
-
3201
-
3202
-    /**
3203
-     * restore _props_n_values_provided_in_constructor
3204
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3205
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3206
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3207
-     *
3208
-     * @throws EE_Error
3209
-     * @throws ReflectionException
3210
-     */
3211
-    public function __wakeup()
3212
-    {
3213
-        $this->_model = $this->get_model();
3214
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3215
-    }
3216
-
3217
-
3218
-    /**
3219
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3220
-     * distinct with the clone host instance are also cloned.
3221
-     */
3222
-    public function __clone()
3223
-    {
3224
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3225
-        foreach ($this->_fields as $field => $value) {
3226
-            if ($value instanceof DateTime) {
3227
-                $this->_fields[ $field ] = clone $value;
3228
-            }
3229
-        }
3230
-    }
3231
-
3232
-
3233
-    /**
3234
-     * Ensures that this related thing is a model object.
3235
-     *
3236
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
3237
-     * @param string $model_name   name of the related thing, eg 'Attendee',
3238
-     * @return EE_Base_Class
3239
-     * @throws ReflectionException
3240
-     * @throws InvalidArgumentException
3241
-     * @throws InvalidInterfaceException
3242
-     * @throws InvalidDataTypeException
3243
-     * @throws EE_Error
3244
-     */
3245
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
3246
-    {
3247
-        $other_model_instance = self::_get_model_instance_with_name(
3248
-            self::_get_model_classname($model_name),
3249
-            $this->_timezone
3250
-        );
3251
-        return $other_model_instance->ensure_is_obj($object_or_id);
3252
-    }
3253
-
3254
-
3255
-    /**
3256
-     * sets the time on a datetime property
3257
-     *
3258
-     * @access protected
3259
-     * @param string|Datetime $time       a valid time string for php datetime functions (or DateTime object)
3260
-     * @param string          $field_name the name of the field the time is being set on (must match a
3261
-     *                                    EE_Datetime_Field)
3262
-     * @throws InvalidArgumentException
3263
-     * @throws InvalidInterfaceException
3264
-     * @throws InvalidDataTypeException
3265
-     * @throws EE_Error
3266
-     */
3267
-    protected function _set_time_for($time, $field_name)
3268
-    {
3269
-        $this->_set_date_time('T', $time, $field_name);
3270
-    }
3271
-
3272
-
3273
-    /**
3274
-     * This takes care of setting a date or time independently on a given model object property. This method also
3275
-     * verifies that the given field name matches a model object property and is for a EE_Datetime_Field field
3276
-     *
3277
-     * @access protected
3278
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
3279
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
3280
-     * @param string          $field_name     the name of the field the date OR time is being set on (must match a
3281
-     *                                        EE_Datetime_Field property)
3282
-     * @throws InvalidArgumentException
3283
-     * @throws InvalidInterfaceException
3284
-     * @throws InvalidDataTypeException
3285
-     * @throws EE_Error
3286
-     */
3287
-    protected function _set_date_time($what, $datetime_value, $field_name)
3288
-    {
3289
-        $field = $this->_get_dtt_field_settings($field_name);
3290
-        $field->set_timezone($this->_timezone);
3291
-        $field->set_date_format($this->_dt_frmt);
3292
-        $field->set_time_format($this->_tm_frmt);
3293
-        $what = in_array($what, ['T', 'D', 'B']) ? $what : 'T';
3294
-        switch ($what) {
3295
-            case 'T':
3296
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
3297
-                    $datetime_value,
3298
-                    $this->_fields[ $field_name ]
3299
-                );
3300
-                $this->_has_changes           = true;
3301
-                break;
3302
-            case 'D':
3303
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
3304
-                    $datetime_value,
3305
-                    $this->_fields[ $field_name ]
3306
-                );
3307
-                $this->_has_changes           = true;
3308
-                break;
3309
-            case 'B':
3310
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
3311
-                $this->_has_changes           = true;
3312
-                break;
3313
-        }
3314
-        $this->_clear_cached_property($field_name);
3315
-    }
3316
-
3317
-
3318
-    /**
3319
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
3320
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
3321
-     * thrown.
3322
-     *
3323
-     * @param string $field_name The field name being checked
3324
-     * @return EE_Datetime_Field
3325
-     * @throws InvalidArgumentException
3326
-     * @throws InvalidInterfaceException
3327
-     * @throws InvalidDataTypeException
3328
-     * @throws EE_Error
3329
-     */
3330
-    protected function _get_dtt_field_settings($field_name)
3331
-    {
3332
-        $field = $this->_model->field_settings_for($field_name);
3333
-        // check if field is dtt
3334
-        if ($field instanceof EE_Datetime_Field) {
3335
-            return $field;
3336
-        }
3337
-        throw new EE_Error(
3338
-            sprintf(
3339
-                esc_html__(
3340
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
3341
-                    'event_espresso'
3342
-                ),
3343
-                $field_name,
3344
-                self::_get_model_classname(get_class($this))
3345
-            )
3346
-        );
3347
-    }
3348
-
3349
-
3350
-    /**
3351
-     * sets the date on a datetime property
3352
-     *
3353
-     * @access protected
3354
-     * @param string|DateTime $date       a valid date string for php datetime functions ( or DateTime object)
3355
-     * @param string          $field_name the name of the field the date is being set on (must match a
3356
-     *                                    EE_Datetime_Field)
3357
-     * @throws InvalidArgumentException
3358
-     * @throws InvalidInterfaceException
3359
-     * @throws InvalidDataTypeException
3360
-     * @throws EE_Error
3361
-     */
3362
-    protected function _set_date_for($date, $field_name)
3363
-    {
3364
-        $this->_set_date_time('D', $date, $field_name);
3365
-    }
3366
-
3367
-
3368
-    /**
3369
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
3370
-     * EE_Error exception if they don't
3371
-     *
3372
-     * @param mixed (string|array) $properties properties to check
3373
-     * @return bool                              TRUE if existing, throw EE_Error if not.
3374
-     * @throws EE_Error
3375
-     */
3376
-    protected function _property_exists($properties)
3377
-    {
3378
-        foreach ((array) $properties as $property_name) {
3379
-            // first make sure this property exists
3380
-            if (! $this->_fields[ $property_name ]) {
3381
-                throw new EE_Error(
3382
-                    sprintf(
3383
-                        esc_html__(
3384
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
3385
-                            'event_espresso'
3386
-                        ),
3387
-                        $property_name
3388
-                    )
3389
-                );
3390
-            }
3391
-        }
3392
-        return true;
3393
-    }
3095
+				$quantity,
3096
+				EE_INF_IN_DB,
3097
+				$quantity
3098
+			)
3099
+		);
3100
+	}
3101
+
3102
+
3103
+	/**
3104
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3105
+	 * (probably a bad assumption they have made, oh well)
3106
+	 *
3107
+	 * @return string
3108
+	 */
3109
+	public function __toString()
3110
+	{
3111
+		try {
3112
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3113
+		} catch (Exception $e) {
3114
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3115
+			return '';
3116
+		}
3117
+	}
3118
+
3119
+
3120
+	/**
3121
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
3122
+	 *
3123
+	 * @return string
3124
+	 * @throws InvalidArgumentException
3125
+	 * @throws InvalidInterfaceException
3126
+	 * @throws InvalidDataTypeException
3127
+	 * @throws EE_Error
3128
+	 */
3129
+	public function name()
3130
+	{
3131
+		// find a field that's not a text field
3132
+		$field_we_can_use = $this->_model->get_a_field_of_type('EE_Text_Field_Base');
3133
+		if ($field_we_can_use) {
3134
+			return $this->get($field_we_can_use->get_name());
3135
+		}
3136
+		$first_few_properties = $this->model_field_array();
3137
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3138
+		$name_parts           = [];
3139
+		foreach ($first_few_properties as $name => $value) {
3140
+			$name_parts[] = "$name:$value";
3141
+		}
3142
+		return implode(',', $name_parts);
3143
+	}
3144
+
3145
+
3146
+	/**
3147
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3148
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3149
+	 * This means if we have made changes to those related model objects, and want to unserialize
3150
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3151
+	 * Instead, those related model objects should be directly serialized and stored.
3152
+	 * Eg, the following won't work:
3153
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3154
+	 * $att = $reg->attendee();
3155
+	 * $att->set( 'ATT_fname', 'Dirk' );
3156
+	 * update_option( 'my_option', serialize( $reg ) );
3157
+	 * //END REQUEST
3158
+	 * //START NEXT REQUEST
3159
+	 * $reg = get_option( 'my_option' );
3160
+	 * $reg->attendee()->save();
3161
+	 * And would need to be replace with:
3162
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3163
+	 * $att = $reg->attendee();
3164
+	 * $att->set( 'ATT_fname', 'Dirk' );
3165
+	 * update_option( 'my_option', serialize( $reg ) );
3166
+	 * //END REQUEST
3167
+	 * //START NEXT REQUEST
3168
+	 * $att = get_option( 'my_option' );
3169
+	 * $att->save();
3170
+	 *
3171
+	 * @return array
3172
+	 * @throws ReflectionException
3173
+	 * @throws InvalidArgumentException
3174
+	 * @throws InvalidInterfaceException
3175
+	 * @throws InvalidDataTypeException
3176
+	 * @throws EE_Error
3177
+	 */
3178
+	public function __sleep()
3179
+	{
3180
+		foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
3181
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3182
+				$classname = 'EE_' . $this->_model->get_this_model_name();
3183
+				if (
3184
+					$this->get_one_from_cache($relation_name) instanceof $classname
3185
+					&& $this->get_one_from_cache($relation_name)->ID()
3186
+				) {
3187
+					$this->clear_cache(
3188
+						$relation_name,
3189
+						$this->get_one_from_cache($relation_name)->ID()
3190
+					);
3191
+				}
3192
+			}
3193
+		}
3194
+		$this->_props_n_values_provided_in_constructor = [];
3195
+		$properties_to_serialize                       = get_object_vars($this);
3196
+		// don't serialize the model. It's big and that risks recursion
3197
+		unset($properties_to_serialize['_model']);
3198
+		return array_keys($properties_to_serialize);
3199
+	}
3200
+
3201
+
3202
+	/**
3203
+	 * restore _props_n_values_provided_in_constructor
3204
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3205
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3206
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3207
+	 *
3208
+	 * @throws EE_Error
3209
+	 * @throws ReflectionException
3210
+	 */
3211
+	public function __wakeup()
3212
+	{
3213
+		$this->_model = $this->get_model();
3214
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3215
+	}
3216
+
3217
+
3218
+	/**
3219
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3220
+	 * distinct with the clone host instance are also cloned.
3221
+	 */
3222
+	public function __clone()
3223
+	{
3224
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3225
+		foreach ($this->_fields as $field => $value) {
3226
+			if ($value instanceof DateTime) {
3227
+				$this->_fields[ $field ] = clone $value;
3228
+			}
3229
+		}
3230
+	}
3231
+
3232
+
3233
+	/**
3234
+	 * Ensures that this related thing is a model object.
3235
+	 *
3236
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
3237
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
3238
+	 * @return EE_Base_Class
3239
+	 * @throws ReflectionException
3240
+	 * @throws InvalidArgumentException
3241
+	 * @throws InvalidInterfaceException
3242
+	 * @throws InvalidDataTypeException
3243
+	 * @throws EE_Error
3244
+	 */
3245
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
3246
+	{
3247
+		$other_model_instance = self::_get_model_instance_with_name(
3248
+			self::_get_model_classname($model_name),
3249
+			$this->_timezone
3250
+		);
3251
+		return $other_model_instance->ensure_is_obj($object_or_id);
3252
+	}
3253
+
3254
+
3255
+	/**
3256
+	 * sets the time on a datetime property
3257
+	 *
3258
+	 * @access protected
3259
+	 * @param string|Datetime $time       a valid time string for php datetime functions (or DateTime object)
3260
+	 * @param string          $field_name the name of the field the time is being set on (must match a
3261
+	 *                                    EE_Datetime_Field)
3262
+	 * @throws InvalidArgumentException
3263
+	 * @throws InvalidInterfaceException
3264
+	 * @throws InvalidDataTypeException
3265
+	 * @throws EE_Error
3266
+	 */
3267
+	protected function _set_time_for($time, $field_name)
3268
+	{
3269
+		$this->_set_date_time('T', $time, $field_name);
3270
+	}
3271
+
3272
+
3273
+	/**
3274
+	 * This takes care of setting a date or time independently on a given model object property. This method also
3275
+	 * verifies that the given field name matches a model object property and is for a EE_Datetime_Field field
3276
+	 *
3277
+	 * @access protected
3278
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
3279
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
3280
+	 * @param string          $field_name     the name of the field the date OR time is being set on (must match a
3281
+	 *                                        EE_Datetime_Field property)
3282
+	 * @throws InvalidArgumentException
3283
+	 * @throws InvalidInterfaceException
3284
+	 * @throws InvalidDataTypeException
3285
+	 * @throws EE_Error
3286
+	 */
3287
+	protected function _set_date_time($what, $datetime_value, $field_name)
3288
+	{
3289
+		$field = $this->_get_dtt_field_settings($field_name);
3290
+		$field->set_timezone($this->_timezone);
3291
+		$field->set_date_format($this->_dt_frmt);
3292
+		$field->set_time_format($this->_tm_frmt);
3293
+		$what = in_array($what, ['T', 'D', 'B']) ? $what : 'T';
3294
+		switch ($what) {
3295
+			case 'T':
3296
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
3297
+					$datetime_value,
3298
+					$this->_fields[ $field_name ]
3299
+				);
3300
+				$this->_has_changes           = true;
3301
+				break;
3302
+			case 'D':
3303
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
3304
+					$datetime_value,
3305
+					$this->_fields[ $field_name ]
3306
+				);
3307
+				$this->_has_changes           = true;
3308
+				break;
3309
+			case 'B':
3310
+				$this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
3311
+				$this->_has_changes           = true;
3312
+				break;
3313
+		}
3314
+		$this->_clear_cached_property($field_name);
3315
+	}
3316
+
3317
+
3318
+	/**
3319
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
3320
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
3321
+	 * thrown.
3322
+	 *
3323
+	 * @param string $field_name The field name being checked
3324
+	 * @return EE_Datetime_Field
3325
+	 * @throws InvalidArgumentException
3326
+	 * @throws InvalidInterfaceException
3327
+	 * @throws InvalidDataTypeException
3328
+	 * @throws EE_Error
3329
+	 */
3330
+	protected function _get_dtt_field_settings($field_name)
3331
+	{
3332
+		$field = $this->_model->field_settings_for($field_name);
3333
+		// check if field is dtt
3334
+		if ($field instanceof EE_Datetime_Field) {
3335
+			return $field;
3336
+		}
3337
+		throw new EE_Error(
3338
+			sprintf(
3339
+				esc_html__(
3340
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
3341
+					'event_espresso'
3342
+				),
3343
+				$field_name,
3344
+				self::_get_model_classname(get_class($this))
3345
+			)
3346
+		);
3347
+	}
3348
+
3349
+
3350
+	/**
3351
+	 * sets the date on a datetime property
3352
+	 *
3353
+	 * @access protected
3354
+	 * @param string|DateTime $date       a valid date string for php datetime functions ( or DateTime object)
3355
+	 * @param string          $field_name the name of the field the date is being set on (must match a
3356
+	 *                                    EE_Datetime_Field)
3357
+	 * @throws InvalidArgumentException
3358
+	 * @throws InvalidInterfaceException
3359
+	 * @throws InvalidDataTypeException
3360
+	 * @throws EE_Error
3361
+	 */
3362
+	protected function _set_date_for($date, $field_name)
3363
+	{
3364
+		$this->_set_date_time('D', $date, $field_name);
3365
+	}
3366
+
3367
+
3368
+	/**
3369
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
3370
+	 * EE_Error exception if they don't
3371
+	 *
3372
+	 * @param mixed (string|array) $properties properties to check
3373
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
3374
+	 * @throws EE_Error
3375
+	 */
3376
+	protected function _property_exists($properties)
3377
+	{
3378
+		foreach ((array) $properties as $property_name) {
3379
+			// first make sure this property exists
3380
+			if (! $this->_fields[ $property_name ]) {
3381
+				throw new EE_Error(
3382
+					sprintf(
3383
+						esc_html__(
3384
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
3385
+							'event_espresso'
3386
+						),
3387
+						$property_name
3388
+					)
3389
+				);
3390
+			}
3391
+		}
3392
+		return true;
3393
+	}
3394 3394
 }
Please login to merge, or discard this patch.
Spacing   +122 added lines, -122 removed lines patch added patch discarded remove patch
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
         $fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
148 148
         // verify client code has not passed any invalid field names
149 149
         foreach ($fieldValues as $field_name => $field_value) {
150
-            if (! isset($model_fields[ $field_name ])) {
150
+            if ( ! isset($model_fields[$field_name])) {
151 151
                 throw new EE_Error(
152 152
                     sprintf(
153 153
                         esc_html__(
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
             }
163 163
         }
164 164
         $this->set_timezone($timezone);
165
-        if (! empty($date_formats) && is_array($date_formats)) {
165
+        if ( ! empty($date_formats) && is_array($date_formats)) {
166 166
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
167 167
         } else {
168 168
             // set default formats for date and time
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
             foreach ($model_fields as $fieldName => $field) {
176 176
                 $this->set_from_db(
177 177
                     $fieldName,
178
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null
179 179
                 );
180 180
             }
181 181
         } else {
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
             foreach ($model_fields as $fieldName => $field) {
185 185
                 $this->set(
186 186
                     $fieldName,
187
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null,
188 188
                     true
189 189
                 );
190 190
             }
@@ -192,15 +192,15 @@  discard block
 block discarded – undo
192 192
         // remember what values were passed to this constructor
193 193
         $this->_props_n_values_provided_in_constructor = $fieldValues;
194 194
         // remember in entity mapper
195
-        if (! $by_db && $this->_model->has_primary_key_field() && $this->ID()) {
195
+        if ( ! $by_db && $this->_model->has_primary_key_field() && $this->ID()) {
196 196
             $this->_model->add_to_entity_map($this);
197 197
         }
198 198
         // setup all the relations
199 199
         foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
200 200
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
201
+                $this->_model_relations[$relation_name] = null;
202 202
             } else {
203
-                $this->_model_relations[ $relation_name ] = [];
203
+                $this->_model_relations[$relation_name] = [];
204 204
             }
205 205
         }
206 206
         /**
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
      */
225 225
     public function get_model()
226 226
     {
227
-        if (! $this->_model) {
227
+        if ( ! $this->_model) {
228 228
             $modelName    = self::_get_model_classname(get_class($this));
229 229
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
230 230
         }
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
             } else {
262 262
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
263 263
             }
264
-            $this->_fields[ $field_name ] = $field_value;
264
+            $this->_fields[$field_name] = $field_value;
265 265
             $this->_clear_cached_property($field_name);
266 266
         }
267 267
     }
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
         // then don't do anything
289 289
         if (
290 290
             ! $use_default
291
-            && $this->_fields[ $field_name ] === $field_value
291
+            && $this->_fields[$field_name] === $field_value
292 292
             && $this->ID()
293 293
         ) {
294 294
             return;
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
             $holder_of_value = $field_obj->prepare_for_set($field_value);
306 306
             // should the value be null?
307 307
             if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
308
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
308
+                $this->_fields[$field_name] = $field_obj->get_default_value();
309 309
                 /**
310 310
                  * To save having to refactor all the models, if a default value is used for a
311 311
                  * EE_Datetime_Field, and that value is not null nor is it a DateTime
@@ -316,15 +316,15 @@  discard block
 block discarded – undo
316 316
                  */
317 317
                 if (
318 318
                     $field_obj instanceof EE_Datetime_Field
319
-                    && $this->_fields[ $field_name ] !== null
320
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
319
+                    && $this->_fields[$field_name] !== null
320
+                    && ! $this->_fields[$field_name] instanceof DateTime
321 321
                 ) {
322
-                    empty($this->_fields[ $field_name ])
322
+                    empty($this->_fields[$field_name])
323 323
                         ? $this->set($field_name, time())
324
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
324
+                        : $this->set($field_name, $this->_fields[$field_name]);
325 325
                 }
326 326
             } else {
327
-                $this->_fields[ $field_name ] = $holder_of_value;
327
+                $this->_fields[$field_name] = $holder_of_value;
328 328
             }
329 329
             // if we're not in the constructor...
330 330
             // now check if what we set was a primary key
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
     {
384 384
         // now that we know the name of the variable, use a variable variable to get its value and return its
385 385
         if ($this->_model->has_primary_key_field()) {
386
-            return $this->_fields[ $this->_model->primary_key_name() ];
386
+            return $this->_fields[$this->_model->primary_key_name()];
387 387
         }
388 388
         return $this->_model->get_index_primary_key_string($this->_fields);
389 389
     }
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
         if (strpos($model_name, 'EE_') === 0) {
402 402
             $model_classname = str_replace('EE_', 'EEM_', $model_name);
403 403
         } else {
404
-            $model_classname = 'EEM_' . $model_name;
404
+            $model_classname = 'EEM_'.$model_name;
405 405
         }
406 406
         return $model_classname;
407 407
     }
@@ -436,8 +436,8 @@  discard block
 block discarded – undo
436 436
      */
437 437
     protected function _clear_cached_property($property_name)
438 438
     {
439
-        if (isset($this->_cached_properties[ $property_name ])) {
440
-            unset($this->_cached_properties[ $property_name ]);
439
+        if (isset($this->_cached_properties[$property_name])) {
440
+            unset($this->_cached_properties[$property_name]);
441 441
         }
442 442
     }
443 443
 
@@ -457,7 +457,7 @@  discard block
 block discarded – undo
457 457
     protected static function _get_model($classname, $timezone = '')
458 458
     {
459 459
         // find model for this class
460
-        if (! $classname) {
460
+        if ( ! $classname) {
461 461
             throw new EE_Error(
462 462
                 sprintf(
463 463
                     esc_html__(
@@ -515,9 +515,9 @@  discard block
 block discarded – undo
515 515
         // verify the field exists
516 516
         $this->_model->field_settings_for($field_name);
517 517
         $cache_type = $pretty ? 'pretty' : 'standard';
518
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
519
-        if (isset($this->_cached_properties[ $field_name ][ $cache_type ])) {
520
-            return $this->_cached_properties[ $field_name ][ $cache_type ];
518
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
519
+        if (isset($this->_cached_properties[$field_name][$cache_type])) {
520
+            return $this->_cached_properties[$field_name][$cache_type];
521 521
         }
522 522
         $value = $this->_get_fresh_property($field_name, $pretty, $extra_cache_ref);
523 523
         $this->_set_cached_property($field_name, $value, $cache_type);
@@ -544,12 +544,12 @@  discard block
 block discarded – undo
544 544
         if ($field_obj instanceof EE_Datetime_Field) {
545 545
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
546 546
         }
547
-        if (! isset($this->_fields[ $field_name ])) {
548
-            $this->_fields[ $field_name ] = null;
547
+        if ( ! isset($this->_fields[$field_name])) {
548
+            $this->_fields[$field_name] = null;
549 549
         }
550 550
         return $pretty
551
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $field_name ], $extra_cache_ref)
552
-            : $field_obj->prepare_for_get($this->_fields[ $field_name ]);
551
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$field_name], $extra_cache_ref)
552
+            : $field_obj->prepare_for_get($this->_fields[$field_name]);
553 553
     }
554 554
 
555 555
 
@@ -571,7 +571,7 @@  discard block
 block discarded – undo
571 571
         // first make sure this property exists
572 572
         $this->_model->field_settings_for($field_name);
573 573
         $cache_type                                             = empty($cache_type) ? 'standard' : $cache_type;
574
-        $this->_cached_properties[ $field_name ][ $cache_type ] = $value;
574
+        $this->_cached_properties[$field_name][$cache_type] = $value;
575 575
     }
576 576
 
577 577
 
@@ -624,9 +624,9 @@  discard block
 block discarded – undo
624 624
         $primary_id_ref = self::_get_primary_key_name($classname);
625 625
         if (
626 626
             array_key_exists($primary_id_ref, $props_n_values)
627
-            && ! empty($props_n_values[ $primary_id_ref ])
627
+            && ! empty($props_n_values[$primary_id_ref])
628 628
         ) {
629
-            $id = $props_n_values[ $primary_id_ref ];
629
+            $id = $props_n_values[$primary_id_ref];
630 630
             return self::_get_model($classname)->get_from_entity_map($id);
631 631
         }
632 632
         return false;
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
      */
647 647
     protected static function _get_primary_key_name($classname = null)
648 648
     {
649
-        if (! $classname) {
649
+        if ( ! $classname) {
650 650
             throw new EE_Error(
651 651
                 sprintf(
652 652
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -686,10 +686,10 @@  discard block
 block discarded – undo
686 686
             $primary_id_ref = self::_get_primary_key_name($classname);
687 687
             if (
688 688
                 array_key_exists($primary_id_ref, $props_n_values)
689
-                && ! empty($props_n_values[ $primary_id_ref ])
689
+                && ! empty($props_n_values[$primary_id_ref])
690 690
             ) {
691 691
                 $existing = $model->get_one_by_ID(
692
-                    $props_n_values[ $primary_id_ref ]
692
+                    $props_n_values[$primary_id_ref]
693 693
                 );
694 694
             }
695 695
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
         }
701 701
         if ($existing) {
702 702
             // set date formats if present before setting values
703
-            if (! empty($date_formats) && is_array($date_formats)) {
703
+            if ( ! empty($date_formats) && is_array($date_formats)) {
704 704
                 $existing->set_date_format($date_formats[0]);
705 705
                 $existing->set_time_format($date_formats[1]);
706 706
             } else {
@@ -786,10 +786,10 @@  discard block
 block discarded – undo
786 786
     public function get_original($field_name)
787 787
     {
788 788
         if (
789
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
789
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
790 790
             && $field_settings = $this->_model->field_settings_for($field_name)
791 791
         ) {
792
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
792
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
793 793
         }
794 794
         return null;
795 795
     }
@@ -825,8 +825,8 @@  discard block
 block discarded – undo
825 825
      */
826 826
     public function getCustomSelect($alias)
827 827
     {
828
-        return isset($this->custom_selection_results[ $alias ])
829
-            ? $this->custom_selection_results[ $alias ]
828
+        return isset($this->custom_selection_results[$alias])
829
+            ? $this->custom_selection_results[$alias]
830 830
             : null;
831 831
     }
832 832
 
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
             $this->set($column, $value);
894 894
         }
895 895
         // no changes ? then don't do anything
896
-        if (! $this->_has_changes && $this->ID() && $this->_model->get_primary_key_field()->is_auto_increment()) {
896
+        if ( ! $this->_has_changes && $this->ID() && $this->_model->get_primary_key_field()->is_auto_increment()) {
897 897
             return 0;
898 898
         }
899 899
         /**
@@ -903,7 +903,7 @@  discard block
 block discarded – undo
903 903
          * @param EE_Base_Class $model_object the model object about to be saved.
904 904
          */
905 905
         do_action('AHEE__EE_Base_Class__save__begin', $this);
906
-        if (! $this->allow_persist()) {
906
+        if ( ! $this->allow_persist()) {
907 907
             return 0;
908 908
         }
909 909
         // now get current attribute values
@@ -918,10 +918,10 @@  discard block
 block discarded – undo
918 918
         if ($this->_model->has_primary_key_field()) {
919 919
             if ($this->_model->get_primary_key_field()->is_auto_increment()) {
920 920
                 // ok check if it's set, if so: update; if not, insert
921
-                if (! empty($save_cols_n_values[ $this->_model->primary_key_name() ])) {
921
+                if ( ! empty($save_cols_n_values[$this->_model->primary_key_name()])) {
922 922
                     $results = $this->_model->update_by_ID($save_cols_n_values, $this->ID());
923 923
                 } else {
924
-                    unset($save_cols_n_values[ $this->_model->primary_key_name() ]);
924
+                    unset($save_cols_n_values[$this->_model->primary_key_name()]);
925 925
                     $results = $this->_model->insert($save_cols_n_values);
926 926
                     if ($results) {
927 927
                         // if successful, set the primary key
@@ -931,7 +931,7 @@  discard block
 block discarded – undo
931 931
                         // will get added to the mapper before we can add this one!
932 932
                         // but if we just avoid using the SET method, all that headache can be avoided
933 933
                         $pk_field_name                   = $this->_model->primary_key_name();
934
-                        $this->_fields[ $pk_field_name ] = $results;
934
+                        $this->_fields[$pk_field_name] = $results;
935 935
                         $this->_clear_cached_property($pk_field_name);
936 936
                         $this->_model->add_to_entity_map($this);
937 937
                         $this->_update_cached_related_model_objs_fks();
@@ -948,8 +948,8 @@  discard block
 block discarded – undo
948 948
                                     'event_espresso'
949 949
                                 ),
950 950
                                 get_class($this),
951
-                                get_class($this->_model) . '::instance()->add_to_entity_map()',
952
-                                get_class($this->_model) . '::instance()->get_one_by_ID()',
951
+                                get_class($this->_model).'::instance()->add_to_entity_map()',
952
+                                get_class($this->_model).'::instance()->get_one_by_ID()',
953 953
                                 '<br />'
954 954
                             )
955 955
                         );
@@ -973,7 +973,7 @@  discard block
 block discarded – undo
973 973
                     $save_cols_n_values,
974 974
                     $this->_model->get_combined_primary_key_fields()
975 975
                 );
976
-                $results                     = $this->_model->update(
976
+                $results = $this->_model->update(
977 977
                     $save_cols_n_values,
978 978
                     $combined_pk_fields_n_values
979 979
                 );
@@ -1026,7 +1026,7 @@  discard block
 block discarded – undo
1026 1026
             $query_params[0]['EXM_value'] = $meta_value;
1027 1027
         }
1028 1028
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
1029
-        if (! $existing_rows_like_that) {
1029
+        if ( ! $existing_rows_like_that) {
1030 1030
             return $this->add_extra_meta($meta_key, $meta_value);
1031 1031
         }
1032 1032
         foreach ($existing_rows_like_that as $existing_row) {
@@ -1157,7 +1157,7 @@  discard block
 block discarded – undo
1157 1157
      */
1158 1158
     public function get_all_from_cache($relationName)
1159 1159
     {
1160
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : [];
1160
+        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : [];
1161 1161
         // if the result is not an array, but exists, make it an array
1162 1162
         $objects = is_array($objects) ? $objects : [$objects];
1163 1163
         // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
@@ -1255,7 +1255,7 @@  discard block
 block discarded – undo
1255 1255
                 $values = [];
1256 1256
                 foreach ($results as $result) {
1257 1257
                     if ($result instanceof EE_Extra_Meta) {
1258
-                        $values[ $result->ID() ] = $result->value();
1258
+                        $values[$result->ID()] = $result->value();
1259 1259
                     }
1260 1260
                 }
1261 1261
                 return $values;
@@ -1305,7 +1305,7 @@  discard block
 block discarded – undo
1305 1305
             } else {
1306 1306
                 // first, check if we've already cached the result of this query
1307 1307
                 $cached_result = $this->get_one_from_cache($relationName);
1308
-                if (! $cached_result) {
1308
+                if ( ! $cached_result) {
1309 1309
                     $related_model_object = $this->_model->get_first_related(
1310 1310
                         $this,
1311 1311
                         $relationName,
@@ -1329,7 +1329,7 @@  discard block
 block discarded – undo
1329 1329
             }
1330 1330
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
1331 1331
             // just get what's cached on this object
1332
-            if (! $related_model_object) {
1332
+            if ( ! $related_model_object) {
1333 1333
                 $related_model_object = $this->get_one_from_cache($relationName);
1334 1334
             }
1335 1335
         }
@@ -1370,7 +1370,7 @@  discard block
 block discarded – undo
1370 1370
             } else {
1371 1371
                 // did we already cache the result of this query?
1372 1372
                 $cached_results = $this->get_all_from_cache($relationName);
1373
-                if (! $cached_results) {
1373
+                if ( ! $cached_results) {
1374 1374
                     $related_model_objects = $this->_model->get_all_related(
1375 1375
                         $this,
1376 1376
                         $relationName,
@@ -1403,8 +1403,8 @@  discard block
 block discarded – undo
1403 1403
      */
1404 1404
     public function get_one_from_cache($relationName)
1405 1405
     {
1406
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
1407
-            ? $this->_model_relations[ $relationName ]
1406
+        $cached_array_or_object = isset($this->_model_relations[$relationName])
1407
+            ? $this->_model_relations[$relationName]
1408 1408
             : null;
1409 1409
         if (is_array($cached_array_or_object)) {
1410 1410
             $cached_array_or_object = array_shift($cached_array_or_object);
@@ -1435,11 +1435,11 @@  discard block
 block discarded – undo
1435 1435
     public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
1436 1436
     {
1437 1437
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
1438
-        if (! $object_to_cache instanceof EE_Base_Class) {
1438
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
1439 1439
             return false;
1440 1440
         }
1441 1441
         // also get "how" the object is related, or throw an error
1442
-        if (! $relationship_to_model = $this->_model->related_settings_for($relationName)) {
1442
+        if ( ! $relationship_to_model = $this->_model->related_settings_for($relationName)) {
1443 1443
             throw new EE_Error(
1444 1444
                 sprintf(
1445 1445
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -1453,38 +1453,38 @@  discard block
 block discarded – undo
1453 1453
             // if it's a "belongs to" relationship, then there's only one related model object
1454 1454
             // eg, if this is a registration, there's only 1 attendee for it
1455 1455
             // so for these model objects just set it to be cached
1456
-            $this->_model_relations[ $relationName ] = $object_to_cache;
1456
+            $this->_model_relations[$relationName] = $object_to_cache;
1457 1457
             $return                                  = true;
1458 1458
         } else {
1459 1459
             // otherwise, this is the "many" side of a one to many relationship,
1460 1460
             // so we'll add the object to the array of related objects for that type.
1461 1461
             // eg: if this is an event, there are many registrations for that event,
1462 1462
             // so we cache the registrations in an array
1463
-            if (! is_array($this->_model_relations[ $relationName ])) {
1463
+            if ( ! is_array($this->_model_relations[$relationName])) {
1464 1464
                 // if for some reason, the cached item is a model object,
1465 1465
                 // then stick that in the array, otherwise start with an empty array
1466
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
1466
+                $this->_model_relations[$relationName] = $this->_model_relations[$relationName]
1467 1467
                                                            instanceof
1468 1468
                                                            EE_Base_Class
1469
-                    ? [$this->_model_relations[ $relationName ]] : [];
1469
+                    ? [$this->_model_relations[$relationName]] : [];
1470 1470
             }
1471 1471
             // first check for a cache_id which is normally empty
1472
-            if (! empty($cache_id)) {
1472
+            if ( ! empty($cache_id)) {
1473 1473
                 // if the cache_id exists, then it means we are purposely trying to cache this
1474 1474
                 // with a known key that can then be used to retrieve the object later on
1475
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
1475
+                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
1476 1476
                 $return                                               = $cache_id;
1477 1477
             } elseif ($object_to_cache->ID()) {
1478 1478
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
1479
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
1479
+                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
1480 1480
                 $return                                                            = $object_to_cache->ID();
1481 1481
             } else {
1482 1482
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
1483
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
1483
+                $this->_model_relations[$relationName][] = $object_to_cache;
1484 1484
                 // move the internal pointer to the end of the array
1485
-                end($this->_model_relations[ $relationName ]);
1485
+                end($this->_model_relations[$relationName]);
1486 1486
                 // and grab the key so that we can return it
1487
-                $return = key($this->_model_relations[ $relationName ]);
1487
+                $return = key($this->_model_relations[$relationName]);
1488 1488
             }
1489 1489
         }
1490 1490
         return $return;
@@ -1520,7 +1520,7 @@  discard block
 block discarded – undo
1520 1520
     {
1521 1521
         static $set_in_progress = false;
1522 1522
         // don't update the timezone if it's already set ?
1523
-        if (($only_if_not_set && $this->_timezone !== '') ) {
1523
+        if (($only_if_not_set && $this->_timezone !== '')) {
1524 1524
             return;
1525 1525
         }
1526 1526
         $valid_timezone = ! empty($timezone) && $this->_timezone && $timezone !== $this->_timezone
@@ -1550,8 +1550,8 @@  discard block
 block discarded – undo
1550 1550
         foreach ($model_fields as $field_name => $field_obj) {
1551 1551
             if ($field_obj instanceof EE_Datetime_Field) {
1552 1552
                 $field_obj->set_timezone($this->_timezone);
1553
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
1554
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], $TZ);
1553
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
1554
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], $TZ);
1555 1555
                 }
1556 1556
             }
1557 1557
         }
@@ -1586,7 +1586,7 @@  discard block
 block discarded – undo
1586 1586
      */
1587 1587
     public function get_format($full = true)
1588 1588
     {
1589
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
1589
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
1590 1590
     }
1591 1591
 
1592 1592
 
@@ -1610,7 +1610,7 @@  discard block
 block discarded – undo
1610 1610
         $current_cache_id = ''
1611 1611
     ) {
1612 1612
         // verify that incoming object is of the correct type
1613
-        $obj_class = 'EE_' . $relationName;
1613
+        $obj_class = 'EE_'.$relationName;
1614 1614
         if ($newly_saved_object instanceof $obj_class) {
1615 1615
             $this->updateTimezoneOnRelated($newly_saved_object);
1616 1616
             // now get the type of relation
@@ -1618,18 +1618,18 @@  discard block
 block discarded – undo
1618 1618
             // if this is a 1:1 relationship
1619 1619
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
1620 1620
                 // then just replace the cached object with the newly saved object
1621
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
1621
+                $this->_model_relations[$relationName] = $newly_saved_object;
1622 1622
                 return true;
1623 1623
                 // or if it's some kind of sordid feral polyamorous relationship...
1624 1624
             }
1625 1625
             if (
1626
-                is_array($this->_model_relations[ $relationName ])
1627
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
1626
+                is_array($this->_model_relations[$relationName])
1627
+                && isset($this->_model_relations[$relationName][$current_cache_id])
1628 1628
             ) {
1629 1629
                 // then remove the current cached item
1630
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
1630
+                unset($this->_model_relations[$relationName][$current_cache_id]);
1631 1631
                 // and cache the newly saved object using it's new ID
1632
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
1632
+                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
1633 1633
                 return true;
1634 1634
             }
1635 1635
         }
@@ -1772,7 +1772,7 @@  discard block
 block discarded – undo
1772 1772
     public function get_DateTime_object($field_name)
1773 1773
     {
1774 1774
         $field_settings = $this->_model->field_settings_for($field_name);
1775
-        if (! $field_settings instanceof EE_Datetime_Field) {
1775
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1776 1776
             EE_Error::add_error(
1777 1777
                 sprintf(
1778 1778
                     esc_html__(
@@ -1787,8 +1787,8 @@  discard block
 block discarded – undo
1787 1787
             );
1788 1788
             return false;
1789 1789
         }
1790
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1791
-            ? clone $this->_fields[ $field_name ]
1790
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1791
+            ? clone $this->_fields[$field_name]
1792 1792
             : null;
1793 1793
     }
1794 1794
 
@@ -2035,7 +2035,7 @@  discard block
 block discarded – undo
2035 2035
      */
2036 2036
     public function get_i18n_datetime($field_name, $format = '')
2037 2037
     {
2038
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
2038
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
2039 2039
         return date_i18n(
2040 2040
             $format,
2041 2041
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -2059,9 +2059,9 @@  discard block
 block discarded – undo
2059 2059
     public function get_raw($field_name)
2060 2060
     {
2061 2061
         $field_settings = $this->_model->field_settings_for($field_name);
2062
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
2063
-            ? $this->_fields[ $field_name ]->format('U')
2064
-            : $this->_fields[ $field_name ];
2062
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
2063
+            ? $this->_fields[$field_name]->format('U')
2064
+            : $this->_fields[$field_name];
2065 2065
     }
2066 2066
 
2067 2067
 
@@ -2099,7 +2099,7 @@  discard block
 block discarded – undo
2099 2099
         $this->set_timezone($timezone);
2100 2100
         $fn   = (array) $field_name;
2101 2101
         $args = array_merge($fn, (array) $args);
2102
-        if (! method_exists($this, $callback)) {
2102
+        if ( ! method_exists($this, $callback)) {
2103 2103
             throw new EE_Error(
2104 2104
                 sprintf(
2105 2105
                     esc_html__(
@@ -2111,7 +2111,7 @@  discard block
 block discarded – undo
2111 2111
             );
2112 2112
         }
2113 2113
         $args   = (array) $args;
2114
-        $return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
2114
+        $return = $prepend.call_user_func_array([$this, $callback], $args).$append;
2115 2115
         $this->set_timezone($original_timezone);
2116 2116
         return $return;
2117 2117
     }
@@ -2224,8 +2224,8 @@  discard block
 block discarded – undo
2224 2224
     public function refresh_cache_of_related_objects()
2225 2225
     {
2226 2226
         foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
2227
-            if (! empty($this->_model_relations[ $relation_name ])) {
2228
-                $related_objects = $this->_model_relations[ $relation_name ];
2227
+            if ( ! empty($this->_model_relations[$relation_name])) {
2228
+                $related_objects = $this->_model_relations[$relation_name];
2229 2229
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
2230 2230
                     // this relation only stores a single model object, not an array
2231 2231
                     // but let's make it consistent
@@ -2270,7 +2270,7 @@  discard block
 block discarded – undo
2270 2270
     {
2271 2271
         $relationship_to_model = $this->_model->related_settings_for($relationName);
2272 2272
         $index_in_cache        = '';
2273
-        if (! $relationship_to_model) {
2273
+        if ( ! $relationship_to_model) {
2274 2274
             throw new EE_Error(
2275 2275
                 sprintf(
2276 2276
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -2281,10 +2281,10 @@  discard block
 block discarded – undo
2281 2281
         }
2282 2282
         if ($clear_all) {
2283 2283
             $obj_removed                             = true;
2284
-            $this->_model_relations[ $relationName ] = null;
2284
+            $this->_model_relations[$relationName] = null;
2285 2285
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
2286
-            $obj_removed                             = $this->_model_relations[ $relationName ];
2287
-            $this->_model_relations[ $relationName ] = null;
2286
+            $obj_removed                             = $this->_model_relations[$relationName];
2287
+            $this->_model_relations[$relationName] = null;
2288 2288
         } else {
2289 2289
             if (
2290 2290
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -2292,12 +2292,12 @@  discard block
 block discarded – undo
2292 2292
             ) {
2293 2293
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
2294 2294
                 if (
2295
-                    is_array($this->_model_relations[ $relationName ])
2296
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
2295
+                    is_array($this->_model_relations[$relationName])
2296
+                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
2297 2297
                 ) {
2298 2298
                     $index_found_at = null;
2299 2299
                     // find this object in the array even though it has a different key
2300
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
2300
+                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
2301 2301
                         /** @noinspection TypeUnsafeComparisonInspection */
2302 2302
                         if (
2303 2303
                             $obj instanceof EE_Base_Class
@@ -2331,9 +2331,9 @@  discard block
 block discarded – undo
2331 2331
             }
2332 2332
             // supposedly we've found it. But it could just be that the client code
2333 2333
             // provided a bad index/object
2334
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
2335
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
2336
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
2334
+            if (isset($this->_model_relations[$relationName][$index_in_cache])) {
2335
+                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
2336
+                unset($this->_model_relations[$relationName][$index_in_cache]);
2337 2337
             } else {
2338 2338
                 // that thing was never cached anyways.
2339 2339
                 $obj_removed = null;
@@ -2361,27 +2361,27 @@  discard block
 block discarded – undo
2361 2361
     public function save_new_cached_related_model_objs()
2362 2362
     {
2363 2363
         // make sure this has been saved
2364
-        if (! $this->ID()) {
2364
+        if ( ! $this->ID()) {
2365 2365
             $id = $this->save();
2366 2366
         } else {
2367 2367
             $id = $this->ID();
2368 2368
         }
2369 2369
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
2370 2370
         foreach ($this->_model->relation_settings() as $relationName => $relationObj) {
2371
-            if ($this->_model_relations[ $relationName ]) {
2371
+            if ($this->_model_relations[$relationName]) {
2372 2372
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2373 2373
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2374 2374
                 /* @var $related_model_obj EE_Base_Class */
2375 2375
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
2376 2376
                     // add a relation to that relation type (which saves the appropriate thing in the process)
2377 2377
                     // but ONLY if it DOES NOT exist in the DB
2378
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2378
+                    $related_model_obj = $this->_model_relations[$relationName];
2379 2379
                     // if( ! $related_model_obj->ID()){
2380 2380
                     $this->_add_relation_to($related_model_obj, $relationName);
2381 2381
                     $related_model_obj->save_new_cached_related_model_objs();
2382 2382
                     // }
2383 2383
                 } else {
2384
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2384
+                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
2385 2385
                         // add a relation to that relation type (which saves the appropriate thing in the process)
2386 2386
                         // but ONLY if it DOES NOT exist in the DB
2387 2387
                         // if( ! $related_model_obj->ID()){
@@ -2442,7 +2442,7 @@  discard block
 block discarded – undo
2442 2442
             }
2443 2443
         } else {
2444 2444
             // this thing doesn't exist in the DB,  so just cache it
2445
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2445
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2446 2446
                 throw new EE_Error(
2447 2447
                     sprintf(
2448 2448
                         esc_html__(
@@ -2710,7 +2710,7 @@  discard block
 block discarded – undo
2710 2710
      */
2711 2711
     public function is_set($field_name)
2712 2712
     {
2713
-        return isset($this->_fields[ $field_name ]);
2713
+        return isset($this->_fields[$field_name]);
2714 2714
     }
2715 2715
 
2716 2716
 
@@ -2745,7 +2745,7 @@  discard block
 block discarded – undo
2745 2745
     {
2746 2746
         $className = get_class($this);
2747 2747
         $tagName   = "FHEE__{$className}__{$methodName}";
2748
-        if (! has_filter($tagName)) {
2748
+        if ( ! has_filter($tagName)) {
2749 2749
             throw new EE_Error(
2750 2750
                 sprintf(
2751 2751
                     esc_html__(
@@ -2819,17 +2819,17 @@  discard block
 block discarded – undo
2819 2819
             );
2820 2820
             foreach ($extra_meta_objs as $extra_meta_obj) {
2821 2821
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2822
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2822
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2823 2823
                 }
2824 2824
             }
2825 2825
         } else {
2826 2826
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2827 2827
             foreach ($extra_meta_objs as $extra_meta_obj) {
2828 2828
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2829
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2830
-                        $return_array[ $extra_meta_obj->key() ] = [];
2829
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2830
+                        $return_array[$extra_meta_obj->key()] = [];
2831 2831
                     }
2832
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2832
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2833 2833
                 }
2834 2834
             }
2835 2835
         }
@@ -2865,8 +2865,8 @@  discard block
 block discarded – undo
2865 2865
                             'event_espresso'
2866 2866
                         ),
2867 2867
                         $this->ID(),
2868
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2869
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2868
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
2869
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
2870 2870
                     )
2871 2871
                 );
2872 2872
             }
@@ -2955,7 +2955,7 @@  discard block
 block discarded – undo
2955 2955
     {
2956 2956
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
2957 2957
         // if it wasn't even there to start off.
2958
-        if (! $this->ID()) {
2958
+        if ( ! $this->ID()) {
2959 2959
             $this->save();
2960 2960
         }
2961 2961
         global $wpdb;
@@ -2995,7 +2995,7 @@  discard block
 block discarded – undo
2995 2995
             $table_pk_field_name = $table_obj->get_pk_column();
2996 2996
         }
2997 2997
 
2998
-        $query  =
2998
+        $query =
2999 2999
             "UPDATE `{$table_name}`
3000 3000
             SET "
3001 3001
             . $new_value_sql
@@ -3043,7 +3043,7 @@  discard block
 block discarded – undo
3043 3043
         $properties = [];
3044 3044
         // remove prepended underscore
3045 3045
         foreach ($fields as $field_name => $settings) {
3046
-            $properties[ $field_name ] = $this->get($field_name);
3046
+            $properties[$field_name] = $this->get($field_name);
3047 3047
         }
3048 3048
         return $properties;
3049 3049
     }
@@ -3179,7 +3179,7 @@  discard block
 block discarded – undo
3179 3179
     {
3180 3180
         foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
3181 3181
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3182
-                $classname = 'EE_' . $this->_model->get_this_model_name();
3182
+                $classname = 'EE_'.$this->_model->get_this_model_name();
3183 3183
                 if (
3184 3184
                     $this->get_one_from_cache($relation_name) instanceof $classname
3185 3185
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3224,7 +3224,7 @@  discard block
 block discarded – undo
3224 3224
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3225 3225
         foreach ($this->_fields as $field => $value) {
3226 3226
             if ($value instanceof DateTime) {
3227
-                $this->_fields[ $field ] = clone $value;
3227
+                $this->_fields[$field] = clone $value;
3228 3228
             }
3229 3229
         }
3230 3230
     }
@@ -3293,21 +3293,21 @@  discard block
 block discarded – undo
3293 3293
         $what = in_array($what, ['T', 'D', 'B']) ? $what : 'T';
3294 3294
         switch ($what) {
3295 3295
             case 'T':
3296
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
3296
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_time(
3297 3297
                     $datetime_value,
3298
-                    $this->_fields[ $field_name ]
3298
+                    $this->_fields[$field_name]
3299 3299
                 );
3300 3300
                 $this->_has_changes           = true;
3301 3301
                 break;
3302 3302
             case 'D':
3303
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
3303
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_date(
3304 3304
                     $datetime_value,
3305
-                    $this->_fields[ $field_name ]
3305
+                    $this->_fields[$field_name]
3306 3306
                 );
3307 3307
                 $this->_has_changes           = true;
3308 3308
                 break;
3309 3309
             case 'B':
3310
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
3310
+                $this->_fields[$field_name] = $field->prepare_for_set($datetime_value);
3311 3311
                 $this->_has_changes           = true;
3312 3312
                 break;
3313 3313
         }
@@ -3377,7 +3377,7 @@  discard block
 block discarded – undo
3377 3377
     {
3378 3378
         foreach ((array) $properties as $property_name) {
3379 3379
             // first make sure this property exists
3380
-            if (! $this->_fields[ $property_name ]) {
3380
+            if ( ! $this->_fields[$property_name]) {
3381 3381
                 throw new EE_Error(
3382 3382
                     sprintf(
3383 3383
                         esc_html__(
Please login to merge, or discard this patch.