Completed
Branch master (89fa75)
by
unknown
05:04
created
core/services/database/WpdbDataFormat.php 1 patch
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -8,65 +8,65 @@
 block discarded – undo
8 8
 
9 9
 class WpdbDataFormat
10 10
 {
11
-    /**
12
-     * used for table/field names
13
-     */
14
-    const IDENTIFIER = '%i';
11
+	/**
12
+	 * used for table/field names
13
+	 */
14
+	const IDENTIFIER = '%i';
15 15
 
16
-    const INTEGER    = '%d';
16
+	const INTEGER    = '%d';
17 17
 
18
-    const FLOAT      = '%f';
18
+	const FLOAT      = '%f';
19 19
 
20
-    const STRING     = '%s';
20
+	const STRING     = '%s';
21 21
 
22 22
 
23
-    /**
24
-     * Return `%d`, `%s` or `%f` to indicate the data type for the field that should be indicated in wpdb queries.
25
-     *
26
-     * @param string $type Included if a specific type is requested.
27
-     * @return string
28
-     * @uses get_schema_type()
29
-     */
30
-    public static function getWpdbDataType(string $type = ''): string
31
-    {
32
-        switch ($type) {
33
-            case SchemaType::BOOLEAN:
34
-            case SchemaType::INTEGER:
35
-                return WpdbDataFormat::INTEGER; // '%d'
36
-            case SchemaType::DB_FIELD:
37
-                return WpdbDataFormat::IDENTIFIER; // '%i'
38
-            case SchemaType::NUMBER:
39
-                return WpdbDataFormat::FLOAT; // '%f'
40
-            case SchemaType::STRING:
41
-            default:
42
-                return WpdbDataFormat::STRING; // '%s'
43
-        }
44
-    }
23
+	/**
24
+	 * Return `%d`, `%s` or `%f` to indicate the data type for the field that should be indicated in wpdb queries.
25
+	 *
26
+	 * @param string $type Included if a specific type is requested.
27
+	 * @return string
28
+	 * @uses get_schema_type()
29
+	 */
30
+	public static function getWpdbDataType(string $type = ''): string
31
+	{
32
+		switch ($type) {
33
+			case SchemaType::BOOLEAN:
34
+			case SchemaType::INTEGER:
35
+				return WpdbDataFormat::INTEGER; // '%d'
36
+			case SchemaType::DB_FIELD:
37
+				return WpdbDataFormat::IDENTIFIER; // '%i'
38
+			case SchemaType::NUMBER:
39
+				return WpdbDataFormat::FLOAT; // '%f'
40
+			case SchemaType::STRING:
41
+			default:
42
+				return WpdbDataFormat::STRING; // '%s'
43
+		}
44
+	}
45 45
 
46 46
 
47
-    public static function getWpdbDataTypeForTypeArray(array $type): string
48
-    {
49
-        // first let's flip because then we can do a faster key check
50
-        $type = array_flip($type);
47
+	public static function getWpdbDataTypeForTypeArray(array $type): string
48
+	{
49
+		// first let's flip because then we can do a faster key check
50
+		$type = array_flip($type);
51 51
 
52
-        // check for things that mean '%s'
53
-        if (isset($type[SchemaType::STRING], $type[SchemaType::OBJECT], $type[SchemaType::ARRAY])) {
54
-            return WpdbDataFormat::STRING;
55
-        }
52
+		// check for things that mean '%s'
53
+		if (isset($type[SchemaType::STRING], $type[SchemaType::OBJECT], $type[SchemaType::ARRAY])) {
54
+			return WpdbDataFormat::STRING;
55
+		}
56 56
 
57
-        // if makes it past the above condition and there's float in the array
58
-        // then the type is %f
59
-        if (isset($type[SchemaType::NUMBER])) {
60
-            return WpdbDataFormat::FLOAT;
61
-        }
57
+		// if makes it past the above condition and there's float in the array
58
+		// then the type is %f
59
+		if (isset($type[SchemaType::NUMBER])) {
60
+			return WpdbDataFormat::FLOAT;
61
+		}
62 62
 
63
-        // if it makes it past the above conditions and there is an integer in the array
64
-        // then the type is %d
65
-        if (isset($type[SchemaType::INTEGER])) {
66
-            return WpdbDataFormat::INTEGER;
67
-        }
63
+		// if it makes it past the above conditions and there is an integer in the array
64
+		// then the type is %d
65
+		if (isset($type[SchemaType::INTEGER])) {
66
+			return WpdbDataFormat::INTEGER;
67
+		}
68 68
 
69
-        // anything else is a string
70
-        return WpdbDataFormat::STRING;
71
-    }
69
+		// anything else is a string
70
+		return WpdbDataFormat::STRING;
71
+	}
72 72
 }
Please login to merge, or discard this patch.
core/EE_Registry.core.php 1 patch
Indentation   +1700 added lines, -1700 removed lines patch added patch discarded remove patch
@@ -22,1704 +22,1704 @@
 block discarded – undo
22 22
  */
23 23
 class EE_Registry implements ResettableInterface
24 24
 {
25
-    private static ?EE_Registry $_instance = null;
26
-
27
-    protected EE_Dependency_Map $_dependency_map;
28
-
29
-    private Mirror $mirror;
30
-
31
-    private ClassInterfaceCache $class_cache;
32
-
33
-    private ObjectIdentifier $object_identifier;
34
-
35
-    protected array $_class_abbreviations = [];
36
-
37
-    public ?CommandBusInterface $BUS = null;
38
-
39
-    public ?EE_Cart $CART = null;
40
-
41
-    public ?EE_Config $CFG = null;
42
-
43
-    public ?EE_Network_Config $NET_CFG = null;
44
-
45
-    /**
46
-     * RegistryContainer for storing library classes in
47
-     *
48
-     * @var RegistryContainer|null $LIB
49
-     */
50
-    public ?RegistryContainer $LIB = null;
51
-
52
-    /**
53
-     * @var EE_Request_Handler|null $REQ
54
-     * @deprecated 4.10.14.p
55
-     */
56
-    public ?EE_Request_Handler $REQ = null;
57
-
58
-    public ?EE_Session $SSN = null;
59
-
60
-    /**
61
-     * @since 4.5.0
62
-     * @var EE_Capabilities|null $CAP
63
-     */
64
-    public ?EE_Capabilities$CAP = null;
65
-
66
-    /**
67
-     * @since 4.9.0
68
-     * @var EE_Message_Resource_Manager|null $MRM
69
-     */
70
-    public ?EE_Message_Resource_Manager $MRM = null;
71
-
72
-    public ?Registry $AssetsRegistry = null;
73
-
74
-    /**
75
-     * RegistryContainer for holding addons which have registered themselves to work with EE core
76
-     *
77
-     * @var RegistryContainer|EE_Addon[] $addons
78
-     */
79
-    public $addons = [];
80
-
81
-    /**
82
-     * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
83
-     *
84
-     * @var EEM_Base[] $models
85
-     */
86
-    public array $models = [];
87
-
88
-    /**
89
-     * @var RegistryContainer|EED_Module[] $modules
90
-     */
91
-    public $modules = [];
92
-
93
-    /**
94
-     * @var RegistryContainer|EES_Shortcode[] $shortcodes
95
-     */
96
-    public $shortcodes = [];
97
-
98
-    /**
99
-     * @var RegistryContainer|WP_Widget[] $widgets
100
-     */
101
-    public $widgets = [];
102
-
103
-    /**
104
-     * this is an array of all implemented model names (i.e. not the parent abstract models, or models
105
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
106
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
107
-     * classnames (eg "EEM_Event")
108
-     *
109
-     * @var array $non_abstract_db_models
110
-     */
111
-    public array $non_abstract_db_models = [];
112
-
113
-    /**
114
-     * internationalization for JS strings
115
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
116
-     *    in js file:  var translatedString = eei18n.string_key;
117
-     *
118
-     * @var array $i18n_js_strings
119
-     */
120
-    public static array $i18n_js_strings = [];
121
-
122
-    /**
123
-     * $main_file - path to espresso.php
124
-     *
125
-     * @var string $main_file
126
-     */
127
-    public string $main_file = '';
128
-
129
-    /**
130
-     * boolean flag to indicate whether to load/save dependencies from/to the cache
131
-     *
132
-     * @var bool $_cache_on
133
-     */
134
-    protected bool $_cache_on = true;
135
-
136
-
137
-    /**
138
-     * @singleton method used to instantiate class object
139
-     * @param EE_Dependency_Map|null   $dependency_map
140
-     * @param Mirror|null              $mirror
141
-     * @param ClassInterfaceCache|null $class_cache
142
-     * @param ObjectIdentifier|null    $object_identifier
143
-     * @return EE_Registry instance
144
-     */
145
-    public static function instance(
146
-        EE_Dependency_Map $dependency_map = null,
147
-        Mirror $mirror = null,
148
-        ClassInterfaceCache $class_cache = null,
149
-        ObjectIdentifier $object_identifier = null
150
-    ): EE_Registry {
151
-        // check if class object is instantiated
152
-        if (
153
-            ! self::$_instance instanceof EE_Registry
154
-            && $dependency_map instanceof EE_Dependency_Map
155
-            && $mirror instanceof Mirror
156
-            && $class_cache instanceof ClassInterfaceCache
157
-            && $object_identifier instanceof ObjectIdentifier
158
-        ) {
159
-            self::$_instance = new self(
160
-                $dependency_map,
161
-                $mirror,
162
-                $class_cache,
163
-                $object_identifier
164
-            );
165
-        }
166
-        return self::$_instance;
167
-    }
168
-
169
-
170
-    /**
171
-     * protected constructor to prevent direct creation
172
-     *
173
-     * @Constructor
174
-     * @param EE_Dependency_Map   $dependency_map
175
-     * @param Mirror              $mirror
176
-     * @param ClassInterfaceCache $class_cache
177
-     * @param ObjectIdentifier    $object_identifier
178
-     */
179
-    protected function __construct(
180
-        EE_Dependency_Map $dependency_map,
181
-        Mirror $mirror,
182
-        ClassInterfaceCache $class_cache,
183
-        ObjectIdentifier $object_identifier
184
-    ) {
185
-        $this->_dependency_map   = $dependency_map;
186
-        $this->mirror            = $mirror;
187
-        $this->class_cache       = $class_cache;
188
-        $this->object_identifier = $object_identifier;
189
-
190
-        $this->LIB        = new RegistryContainer();
191
-        $this->addons     = new RegistryContainer();
192
-        $this->modules    = new RegistryContainer();
193
-        $this->shortcodes = new RegistryContainer();
194
-        $this->widgets    = new RegistryContainer();
195
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', [$this, 'initialize']);
196
-    }
197
-
198
-
199
-    /**
200
-     * initialize
201
-     *
202
-     * @throws OutOfBoundsException
203
-     * @throws InvalidArgumentException
204
-     * @throws InvalidInterfaceException
205
-     * @throws InvalidDataTypeException
206
-     * @throws EE_Error
207
-     * @throws ReflectionException
208
-     */
209
-    public function initialize()
210
-    {
211
-        $this->_class_abbreviations = apply_filters(
212
-            'FHEE__EE_Registry____construct___class_abbreviations',
213
-            [
214
-                'EE_Config'                                       => 'CFG',
215
-                'EE_Session'                                      => 'SSN',
216
-                'EE_Capabilities'                                 => 'CAP',
217
-                'EE_Cart'                                         => 'CART',
218
-                'EE_Network_Config'                               => 'NET_CFG',
219
-                'EE_Request_Handler'                              => 'REQ',
220
-                'EE_Message_Resource_Manager'                     => 'MRM',
221
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
222
-                'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
223
-            ]
224
-        );
225
-        $this->load_core('Base', [], true);
226
-        // add our request and response objects to the cache
227
-        $request_loader = $this->_dependency_map->class_loader(
228
-            'EventEspresso\core\services\request\Request'
229
-        );
230
-        $this->_set_cached_class(
231
-            $request_loader(),
232
-            'EventEspresso\core\services\request\Request'
233
-        );
234
-        $response_loader = $this->_dependency_map->class_loader(
235
-            'EventEspresso\core\services\request\Response'
236
-        );
237
-        $this->_set_cached_class(
238
-            $response_loader(),
239
-            'EventEspresso\core\services\request\Response'
240
-        );
241
-        add_action('AHEE__EE_System__set_hooks_for_core', [$this, 'init']);
242
-    }
243
-
244
-
245
-    /**
246
-     * @return void
247
-     */
248
-    public function init()
249
-    {
250
-        // Get current page protocol
251
-        $protocol = is_ssl() ? 'https://' : 'http://';
252
-        // Output admin-ajax.php URL with same protocol as current page
253
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
254
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') && WP_DEBUG;
255
-    }
256
-
257
-
258
-    /**
259
-     * @return array
260
-     */
261
-    public static function sanitize_i18n_js_strings(): array
262
-    {
263
-        array_walk(EE_Registry::$i18n_js_strings, function (&$value) {
264
-            if (is_scalar($value)) {
265
-                $value = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
266
-                // replace all escaped instances of \n with actual new lines
267
-                $value = str_replace("\\n", "\n", $value);
268
-            }
269
-        });
270
-        // sort the array by key in a case-insensitive manner
271
-        ksort(EE_Registry::$i18n_js_strings, SORT_NATURAL | SORT_FLAG_CASE);
272
-        return EE_Registry::$i18n_js_strings;
273
-    }
274
-
275
-
276
-    /**
277
-     * localize_i18n_js_strings
278
-     *
279
-     * @return string
280
-     */
281
-    public static function localize_i18n_js_strings(): string
282
-    {
283
-        $i18n_js_strings = wp_json_encode(EE_Registry::sanitize_i18n_js_strings());
284
-        return "/* <![CDATA[ */ var eei18n = $i18n_js_strings; /* ]]> */";
285
-    }
286
-
287
-
288
-    /**
289
-     * @param mixed string | EED_Module $module
290
-     * @throws OutOfBoundsException
291
-     * @throws InvalidArgumentException
292
-     * @throws InvalidInterfaceException
293
-     * @throws InvalidDataTypeException
294
-     * @throws EE_Error
295
-     * @throws ReflectionException
296
-     */
297
-    public function add_module($module)
298
-    {
299
-        if ($module instanceof EED_Module) {
300
-            $module_class = get_class($module);
301
-            $this->modules->add($module_class, $module);
302
-        } else {
303
-            if (! class_exists('EE_Module_Request_Router', false)) {
304
-                $this->load_core('Module_Request_Router');
305
-            }
306
-            EE_Module_Request_Router::module_factory($module);
307
-        }
308
-    }
309
-
310
-
311
-    /**
312
-     * @param string $module_name
313
-     * @return mixed EED_Module | NULL
314
-     */
315
-    public function get_module(string $module_name = '')
316
-    {
317
-        return $this->modules->get($module_name);
318
-    }
319
-
320
-
321
-    /**
322
-     * loads core classes - must be singletons
323
-     *
324
-     * @param string $class_name - simple class name ie: session
325
-     * @param mixed  $arguments
326
-     * @param bool   $load_only
327
-     * @return bool|null|object
328
-     * @throws InvalidInterfaceException
329
-     * @throws InvalidDataTypeException
330
-     * @throws EE_Error
331
-     * @throws ReflectionException
332
-     * @throws InvalidArgumentException
333
-     */
334
-    public function load_core(string $class_name, $arguments = [], bool $load_only = false)
335
-    {
336
-        $core_paths = (array) apply_filters(
337
-            'FHEE__EE_Registry__load_core__core_paths',
338
-            [
339
-                EE_CORE,
340
-                EE_ADMIN,
341
-                EE_CPTS,
342
-                EE_CORE . 'CPTs/',
343
-                EE_CORE . 'data_migration_scripts/',
344
-                EE_CORE . 'request_stack/',
345
-                EE_CORE . 'middleware/',
346
-            ]
347
-        );
348
-        // retrieve instantiated class
349
-        return $this->_load(
350
-            $core_paths,
351
-            'EE_',
352
-            $class_name,
353
-            'core',
354
-            $arguments,
355
-            false,
356
-            true,
357
-            $load_only
358
-        );
359
-    }
360
-
361
-
362
-    /**
363
-     * loads service classes
364
-     *
365
-     * @param string $class_name - simple class name ie: session
366
-     * @param mixed  $arguments
367
-     * @param bool   $load_only
368
-     * @return bool|null|object
369
-     * @throws InvalidInterfaceException
370
-     * @throws InvalidDataTypeException
371
-     * @throws EE_Error
372
-     * @throws ReflectionException
373
-     * @throws InvalidArgumentException
374
-     * @deprecated  4.10.33.p
375
-     */
376
-    public function load_service(string $class_name, $arguments = [], bool $load_only = false)
377
-    {
378
-        $service_paths = (array) apply_filters(
379
-            'FHEE__EE_Registry__load_service__service_paths',
380
-            [
381
-                EE_CORE . 'services/',
382
-            ]
383
-        );
384
-        // retrieve instantiated class
385
-        return $this->_load(
386
-            $service_paths,
387
-            'EE_',
388
-            $class_name,
389
-            'class',
390
-            $arguments,
391
-            false,
392
-            true,
393
-            $load_only
394
-        );
395
-    }
396
-
397
-
398
-    /**
399
-     * loads data_migration_scripts
400
-     *
401
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
402
-     * @param mixed  $arguments
403
-     * @return bool|null|object
404
-     * @throws InvalidInterfaceException
405
-     * @throws InvalidDataTypeException
406
-     * @throws EE_Error
407
-     * @throws ReflectionException
408
-     * @throws InvalidArgumentException
409
-     */
410
-    public function load_dms(string $class_name, $arguments = [])
411
-    {
412
-        // retrieve instantiated class
413
-        return $this->_load(
414
-            EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
415
-            'EE_DMS_',
416
-            $class_name,
417
-            'dms',
418
-            $arguments,
419
-            false,
420
-            false
421
-        );
422
-    }
423
-
424
-
425
-    /**
426
-     * loads object creating classes - must be singletons
427
-     *
428
-     * @param string $class_name - simple class name ie: attendee
429
-     * @param mixed  $arguments  - an array of arguments to pass to the class
430
-     * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
431
-     *                           instantiate
432
-     * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
433
-     *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
434
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
435
-     *                           (default)
436
-     * @return EE_Base_Class|object|bool|null
437
-     * @throws InvalidInterfaceException
438
-     * @throws InvalidDataTypeException
439
-     * @throws EE_Error
440
-     * @throws ReflectionException
441
-     * @throws InvalidArgumentException
442
-     */
443
-    public function load_class(
444
-        string $class_name,
445
-        $arguments = [],
446
-        bool $from_db = false,
447
-        bool $cache = true,
448
-        bool $load_only = false
449
-    ) {
450
-        $paths = (array) apply_filters(
451
-            'FHEE__EE_Registry__load_class__paths',
452
-            [
453
-                EE_CORE,
454
-                EE_CLASSES,
455
-                EE_BUSINESS,
456
-            ]
457
-        );
458
-        // retrieve instantiated class
459
-        return $this->_load(
460
-            $paths,
461
-            'EE_',
462
-            $class_name,
463
-            'class',
464
-            $arguments,
465
-            $from_db,
466
-            $cache,
467
-            $load_only
468
-        );
469
-    }
470
-
471
-
472
-    /**
473
-     * loads helper classes - must be singletons
474
-     *
475
-     * @param string $class_name - simple class name ie: price
476
-     * @param mixed  $arguments
477
-     * @param bool   $load_only
478
-     * @return bool|null|object
479
-     * @throws InvalidInterfaceException
480
-     * @throws InvalidDataTypeException
481
-     * @throws EE_Error
482
-     * @throws ReflectionException
483
-     * @throws InvalidArgumentException
484
-     */
485
-    public function load_helper(string $class_name, $arguments = [], bool $load_only = true)
486
-    {
487
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
488
-        $helper_paths = (array) apply_filters('FHEE__EE_Registry__load_helper__helper_paths', [EE_HELPERS]);
489
-        // retrieve instantiated class
490
-        return $this->_load(
491
-            $helper_paths,
492
-            'EEH_',
493
-            $class_name,
494
-            'helper',
495
-            $arguments,
496
-            false,
497
-            true,
498
-            $load_only
499
-        );
500
-    }
501
-
502
-
503
-    /**
504
-     * loads core classes - must be singletons
505
-     *
506
-     * @param string $class_name - simple class name ie: session
507
-     * @param mixed  $arguments
508
-     * @param bool   $load_only
509
-     * @param bool   $cache      whether to cache the object or not.
510
-     * @return bool|null|object
511
-     * @throws InvalidInterfaceException
512
-     * @throws InvalidDataTypeException
513
-     * @throws EE_Error
514
-     * @throws ReflectionException
515
-     * @throws InvalidArgumentException
516
-     */
517
-    public function load_lib(string $class_name, $arguments = [], bool $load_only = false, bool $cache = true)
518
-    {
519
-        $paths = [
520
-            EE_LIBRARIES,
521
-            EE_LIBRARIES . 'messages/',
522
-            EE_LIBRARIES . 'shortcodes/',
523
-            EE_LIBRARIES . 'qtips/',
524
-            EE_LIBRARIES . 'payment_methods/',
525
-        ];
526
-        // retrieve instantiated class
527
-        return $this->_load(
528
-            $paths,
529
-            'EE_',
530
-            $class_name,
531
-            'lib',
532
-            $arguments,
533
-            false,
534
-            $cache,
535
-            $load_only
536
-        );
537
-    }
538
-
539
-
540
-    /**
541
-     * loads model classes - must be singletons
542
-     *
543
-     * @param string $class_name - simple class name ie: price
544
-     * @param mixed  $arguments
545
-     * @param bool   $load_only
546
-     * @return EEM_Base|null
547
-     * @throws InvalidInterfaceException
548
-     * @throws InvalidDataTypeException
549
-     * @throws EE_Error
550
-     * @throws ReflectionException
551
-     * @throws InvalidArgumentException
552
-     */
553
-    public function load_model(string $class_name, $arguments = [], bool $load_only = false): ?EEM_Base
554
-    {
555
-        // retrieve instantiated class
556
-        $model = $this->_load(
557
-            (array) apply_filters(
558
-                'FHEE__EE_Registry__load_model__paths',
559
-                [
560
-                    EE_MODELS,
561
-                    EE_CORE,
562
-                ]
563
-            ),
564
-            'EEM_',
565
-            $class_name,
566
-            'model',
567
-            $arguments,
568
-            false,
569
-            true,
570
-            $load_only
571
-        );
572
-        return $model instanceof EEM_Base ? $model : null;
573
-    }
574
-
575
-
576
-    /**
577
-     * loads model classes - must be singletons
578
-     *
579
-     * @param string $class_name - simple class name ie: price
580
-     * @param mixed  $arguments
581
-     * @param bool   $load_only
582
-     * @return bool|null|object
583
-     * @throws InvalidInterfaceException
584
-     * @throws InvalidDataTypeException
585
-     * @throws EE_Error
586
-     * @throws ReflectionException
587
-     * @throws InvalidArgumentException
588
-     * @deprecated  4.10.33.p
589
-     */
590
-    public function load_model_class(string $class_name, $arguments = [], bool $load_only = true)
591
-    {
592
-        $paths = [
593
-            EE_MODELS . 'fields/',
594
-            EE_MODELS . 'helpers/',
595
-            EE_MODELS . 'relations/',
596
-            EE_MODELS . 'strategies/',
597
-        ];
598
-        // retrieve instantiated class
599
-        return $this->_load(
600
-            $paths,
601
-            'EE_',
602
-            $class_name,
603
-            '',
604
-            $arguments,
605
-            false,
606
-            true,
607
-            $load_only
608
-        );
609
-    }
610
-
611
-
612
-    /**
613
-     * Determines if $model_name is the name of an actual EE model.
614
-     *
615
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
616
-     * @return boolean
617
-     */
618
-    public function is_model_name(string $model_name): bool
619
-    {
620
-        return isset($this->models[ $model_name ]);
621
-    }
622
-
623
-
624
-    /**
625
-     * generic class loader
626
-     *
627
-     * @param string $path_to_file - directory path to file location, not including filename
628
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
629
-     * @param string $type         - file type - core? class? helper? model?
630
-     * @param mixed  $arguments
631
-     * @param bool   $load_only
632
-     * @return bool|null|object
633
-     * @throws InvalidInterfaceException
634
-     * @throws InvalidDataTypeException
635
-     * @throws EE_Error
636
-     * @throws ReflectionException
637
-     * @throws InvalidArgumentException
638
-     */
639
-    public function load_file(
640
-        string $path_to_file,
641
-        string $file_name,
642
-        string $type = '',
643
-        $arguments = [],
644
-        bool $load_only = true
645
-    ) {
646
-        // retrieve instantiated class
647
-        return $this->_load(
648
-            (array) $path_to_file,
649
-            '',
650
-            $file_name,
651
-            $type,
652
-            $arguments,
653
-            false,
654
-            true,
655
-            $load_only
656
-        );
657
-    }
658
-
659
-
660
-    /**
661
-     * @param string $path_to_file - directory path to file location, not including filename
662
-     * @param string $class_name   - full class name  ie:  My_Class
663
-     * @param string $type         - file type - core? class? helper? model?
664
-     * @param mixed  $arguments
665
-     * @param bool   $load_only
666
-     * @return bool|null|object
667
-     * @throws InvalidInterfaceException
668
-     * @throws InvalidDataTypeException
669
-     * @throws EE_Error
670
-     * @throws ReflectionException
671
-     * @throws InvalidArgumentException
672
-     * @deprecated  4.10.33.p
673
-     */
674
-    public function load_addon(
675
-        string $path_to_file,
676
-        string $class_name,
677
-        string $type = 'class',
678
-        $arguments = [],
679
-        bool $load_only = false
680
-    ) {
681
-        // retrieve instantiated class
682
-        return $this->_load(
683
-            (array) $path_to_file,
684
-            'addon',
685
-            $class_name,
686
-            $type,
687
-            $arguments,
688
-            false,
689
-            true,
690
-            $load_only
691
-        );
692
-    }
693
-
694
-
695
-    /**
696
-     * instantiates, caches, and automatically resolves dependencies
697
-     * for classes that use a Fully Qualified Class Name.
698
-     * if the class is not capable of being loaded using PSR-4 autoloading,
699
-     * then you need to use one of the existing load_*() methods
700
-     * which can resolve the classname and filepath from the passed arguments
701
-     *
702
-     * @param string      $class_name Fully Qualified Class Name
703
-     * @param array       $arguments  an argument, or array of arguments to pass to the class upon instantiation
704
-     * @param bool        $cache      whether to cache the instantiated object for reuse
705
-     * @param bool        $from_db    some classes are instantiated from the db
706
-     *                                and thus call a different method to instantiate
707
-     * @param bool        $load_only  if true, will only load the file, but will NOT instantiate an object
708
-     * @param bool|string $addon      if true, will cache the object in the EE_Registry->$addons array
709
-     * @return bool|null|mixed     null = failure to load or instantiate class object.
710
-     *                                object = class loaded and instantiated successfully.
711
-     *                                bool = fail or success when $load_only is true
712
-     * @throws InvalidInterfaceException
713
-     * @throws InvalidDataTypeException
714
-     * @throws EE_Error
715
-     * @throws ReflectionException
716
-     * @throws InvalidArgumentException
717
-     */
718
-    public function create(
719
-        string $class_name = '',
720
-        array $arguments = [],
721
-        bool $cache = false,
722
-        bool $from_db = false,
723
-        bool $load_only = false,
724
-        bool $addon = false
725
-    ) {
726
-        $class_name   = ltrim($class_name, '\\');
727
-        $class_name   = $this->class_cache->getFqnForAlias($class_name);
728
-        $class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
729
-        // if a non-FQCN was passed, then
730
-        // verifyClassExists() might return an object
731
-        // or it could return null if the class just could not be found anywhere
732
-        if ($class_exists instanceof $class_name || $class_exists === null) {
733
-            // either way, return the results
734
-            return $class_exists;
735
-        }
736
-        $class_name = $class_exists;
737
-        // if we're only loading the class and it already exists, then let's just return true immediately
738
-        if ($load_only) {
739
-            return true;
740
-        }
741
-        $addon = $addon ? 'addon' : '';
742
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
743
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
744
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
745
-        if ($this->_cache_on && $cache) {
746
-            // return object if it's already cached
747
-            $cached_class = $this->_get_cached_class($class_name, $addon, $arguments);
748
-            if ($cached_class !== null) {
749
-                return $cached_class;
750
-            }
751
-        }                                                           // obtain the loader method from the dependency map
752
-        $loader = $this->_dependency_map->class_loader($class_name);// instantiate the requested object
753
-        if ($loader instanceof Closure) {
754
-            $class_obj = $loader($arguments);
755
-        } else {
756
-            if ($loader && method_exists($this, $loader)) {
757
-                $class_obj = $this->{$loader}($class_name, $arguments);
758
-            } else {
759
-                $class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
760
-            }
761
-        }
762
-        if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
763
-            // save it for later... kinda like gum  { : $
764
-            $this->_set_cached_class(
765
-                $class_obj,
766
-                $class_name,
767
-                $addon,
768
-                $from_db,
769
-                $arguments
770
-            );
771
-        }
772
-        $this->_cache_on = true;
773
-        return $class_obj;
774
-    }
775
-
776
-
777
-    /**
778
-     * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
779
-     *
780
-     * @param string|mixed $class_name
781
-     * @param array        $arguments
782
-     * @param int          $attempt
783
-     * @return mixed
784
-     */
785
-    private function loadOrVerifyClassExists($class_name, array $arguments, int $attempt = 1)
786
-    {
787
-        if (is_object($class_name) || class_exists($class_name)) {
788
-            return $class_name;
789
-        }
790
-        switch ($attempt) {
791
-            case 1:
792
-                // if it's a FQCN then maybe the class is registered with a preceding \
793
-                $class_name = strpos($class_name, '\\') !== false
794
-                    ? '\\' . ltrim($class_name, '\\')
795
-                    : $class_name;
796
-                break;
797
-            case 2:
798
-                //
799
-                $loader = $this->_dependency_map->class_loader($class_name);
800
-                if ($loader && method_exists($this, $loader)) {
801
-                    return $this->{$loader}($class_name, $arguments);
802
-                }
803
-                break;
804
-            case 3:
805
-            default:
806
-                return null;
807
-        }
808
-        $attempt++;
809
-        return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
810
-    }
811
-
812
-
813
-    /**
814
-     * instantiates, caches, and injects dependencies for classes
815
-     *
816
-     * @param array  $file_paths         an array of paths to folders to look in
817
-     * @param string $class_prefix       EE  or EEM or... ???
818
-     * @param string $class_name         $class name
819
-     * @param string $type               file type - core? class? helper? model?
820
-     * @param mixed  $arguments          an argument or array of arguments to pass to the class upon instantiation
821
-     * @param bool   $from_db            some classes are instantiated from the db
822
-     *                                   and thus call a different method to instantiate
823
-     * @param bool   $cache              whether to cache the instantiated object for reuse
824
-     * @param bool   $load_only          if true, will only load the file, but will NOT instantiate an object
825
-     * @return bool|null|object          null   = failure to load or instantiate class object.
826
-     *                                   object = class loaded and instantiated successfully.
827
-     *                                   bool   = fail or success when $load_only is true
828
-     * @throws EE_Error
829
-     * @throws ReflectionException
830
-     * @throws InvalidInterfaceException
831
-     * @throws InvalidDataTypeException
832
-     * @throws InvalidArgumentException
833
-     */
834
-    protected function _load(
835
-        array $file_paths = [],
836
-        string $class_prefix = 'EE_',
837
-        string $class_name = '',
838
-        string $type = 'class',
839
-        array $arguments = [],
840
-        bool $from_db = false,
841
-        bool $cache = true,
842
-        bool $load_only = false
843
-    ) {
844
-        $class_name = ltrim($class_name, '\\');
845
-        // strip php file extension
846
-        $class_name = str_replace('.php', '', trim($class_name));
847
-        // does the class have a prefix ?
848
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
849
-            // make sure $class_prefix is uppercase
850
-            $class_prefix = strtoupper(trim($class_prefix));
851
-            // add class prefix ONCE!!!
852
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
853
-        }
854
-        $class_name   = $this->class_cache->getFqnForAlias($class_name);
855
-        $class_exists = class_exists($class_name, false);
856
-        // if we're only loading the class and it already exists, then let's just return true immediately
857
-        if ($load_only && $class_exists) {
858
-            return true;
859
-        }
860
-        $arguments = is_array($arguments) ? $arguments : [$arguments];
861
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
862
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
863
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
864
-        if ($this->_cache_on && $cache && ! $load_only) {
865
-            // return object if it's already cached
866
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix, $arguments);
867
-            if ($cached_class !== null) {
868
-                return $cached_class;
869
-            }
870
-        }
871
-        // if the class doesn't already exist.. then we need to try and find the file and load it
872
-        if (! $class_exists) {
873
-            // get full path to file
874
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
875
-            // load the file
876
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
877
-            // if we are only loading a file but NOT instantiating an object
878
-            // then return boolean for whether class was loaded or not
879
-            if ($load_only) {
880
-                return $loaded;
881
-            }
882
-            // if an object was expected but loading failed, then return nothing
883
-            if (! $loaded) {
884
-                return null;
885
-            }
886
-        }
887
-        // instantiate the requested object
888
-        $class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
889
-        if ($this->_cache_on && $cache) {
890
-            // save it for later... kinda like gum  { : $
891
-            $this->_set_cached_class(
892
-                $class_obj,
893
-                $class_name,
894
-                $class_prefix,
895
-                $from_db,
896
-                $arguments
897
-            );
898
-        }
899
-        $this->_cache_on = true;
900
-        return $class_obj;
901
-    }
902
-
903
-
904
-    /**
905
-     * @param string $class_name
906
-     * @param string $default have to specify something, but not anything that will conflict
907
-     * @return mixed|string
908
-     */
909
-    protected function get_class_abbreviation(string $class_name, string $default = 'FANCY_BATMAN_PANTS')
910
-    {
911
-        return $this->_class_abbreviations[ $class_name ] ?? $default;
912
-    }
913
-
914
-
915
-    /**
916
-     * attempts to find a cached version of the requested class
917
-     * by looking in the following places:
918
-     *        $this->{$class_abbreviation}            ie:    $this->CART
919
-     *        $this->{$class_name}                        ie:    $this->Some_Class
920
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
921
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
922
-     *
923
-     * @param string $class_name
924
-     * @param string $class_prefix
925
-     * @param array  $arguments
926
-     * @return mixed
927
-     */
928
-    protected function _get_cached_class(
929
-        string $class_name,
930
-        string $class_prefix = '',
931
-        array $arguments = []
932
-    ) {
933
-        if ($class_name === 'EE_Registry') {
934
-            return $this;
935
-        }
936
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
937
-        // check if class has already been loaded, and return it if it has been
938
-        if (isset($this->{$class_abbreviation})) {
939
-            return $this->{$class_abbreviation};
940
-        }
941
-        $class_name = str_replace('\\', '_', $class_name);
942
-        if (isset($this->{$class_name})) {
943
-            return $this->{$class_name};
944
-        }
945
-        if ($class_prefix === 'addon' && $this->addons->has($class_name)) {
946
-            return $this->addons->get($class_name);
947
-        }
948
-        $object_identifier = $this->object_identifier->getIdentifier($class_name, $arguments);
949
-        if ($this->LIB->has($object_identifier)) {
950
-            return $this->LIB->get($object_identifier);
951
-        }
952
-        foreach ($this->LIB as $key => $object) {
953
-            if (
954
-                // request does not contain new arguments and therefore no args identifier
955
-                ! $this->object_identifier->hasArguments($object_identifier)
956
-                // but previously cached class with args was found
957
-                && $this->object_identifier->fqcnMatchesObjectIdentifier($class_name, $key)
958
-            ) {
959
-                return $object;
960
-            }
961
-        }
962
-        return null;
963
-    }
964
-
965
-
966
-    /**
967
-     * removes a cached version of the requested class
968
-     *
969
-     * @param string  $class_name
970
-     * @param boolean $addon
971
-     * @param array   $arguments
972
-     * @return boolean
973
-     */
974
-    public function clear_cached_class(
975
-        string $class_name,
976
-        bool $addon = false,
977
-        array $arguments = []
978
-    ): bool {
979
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
980
-        // check if class has already been loaded, and return it if it has been
981
-        if (isset($this->{$class_abbreviation})) {
982
-            $this->{$class_abbreviation} = null;
983
-            return true;
984
-        }
985
-        $class_name = str_replace('\\', '_', $class_name);
986
-        if (isset($this->{$class_name})) {
987
-            $this->{$class_name} = null;
988
-            return true;
989
-        }
990
-        if ($addon && $this->addons->has($class_name)) {
991
-            $this->addons->remove($class_name);
992
-            return true;
993
-        }
994
-        $class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
995
-        if ($this->LIB->has($class_name)) {
996
-            $this->LIB->remove($class_name);
997
-            return true;
998
-        }
999
-        return false;
1000
-    }
1001
-
1002
-
1003
-    /**
1004
-     * _set_cached_class
1005
-     * attempts to cache the instantiated class locally
1006
-     * in one of the following places, in the following order:
1007
-     *        $this->{class_abbreviation}   ie:    $this->CART
1008
-     *        $this->{$class_name}          ie:    $this->Some_Class
1009
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1010
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1011
-     *
1012
-     * @param object $class_obj
1013
-     * @param string $class_name
1014
-     * @param string $class_prefix
1015
-     * @param bool   $from_db
1016
-     * @param array  $arguments
1017
-     * @return void
1018
-     */
1019
-    protected function _set_cached_class(
1020
-        $class_obj,
1021
-        string $class_name,
1022
-        string $class_prefix = '',
1023
-        bool $from_db = false,
1024
-        array $arguments = []
1025
-    ) {
1026
-        if ($class_name === 'EE_Registry' || empty($class_obj)) {
1027
-            return;
1028
-        }
1029
-        // return newly instantiated class
1030
-        $class_abbreviation = $this->get_class_abbreviation($class_name, '');
1031
-        if ($class_abbreviation) {
1032
-            $this->{$class_abbreviation} = $class_obj;
1033
-            return;
1034
-        }
1035
-        $class_name = str_replace('\\', '_', $class_name);
1036
-        if (property_exists($this, $class_name)) {
1037
-            $this->{$class_name} = $class_obj;
1038
-            return;
1039
-        }
1040
-        if ($class_prefix === 'addon') {
1041
-            $this->addons->add($class_name, $class_obj);
1042
-            return;
1043
-        }
1044
-        if (! $from_db) {
1045
-            $class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1046
-            $this->LIB->add($class_name, $class_obj);
1047
-        }
1048
-    }
1049
-
1050
-
1051
-    /**
1052
-     * attempts to find a full valid filepath for the requested class.
1053
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
1054
-     * then returns that path if the target file has been found and is readable
1055
-     *
1056
-     * @param string $class_name
1057
-     * @param string $type
1058
-     * @param array  $file_paths
1059
-     * @return string | bool
1060
-     */
1061
-    protected function _resolve_path(string $class_name, string $type = '', array $file_paths = [])
1062
-    {
1063
-        // make sure $file_paths is an array
1064
-        $file_paths = is_array($file_paths)
1065
-            ? $file_paths
1066
-            : [$file_paths];
1067
-        // cycle thru paths
1068
-        foreach ($file_paths as $key => $file_path) {
1069
-            // convert all separators to proper /, if no filepath, then use EE_CLASSES
1070
-            $file_path = $file_path
1071
-                ? str_replace(['/', '\\'], '/', $file_path)
1072
-                : EE_CLASSES;
1073
-            // prep file type
1074
-            $type = ! empty($type)
1075
-                ? trim($type, '.') . '.'
1076
-                : '';
1077
-            // build full file path
1078
-            $file_paths[ $key ] = rtrim($file_path, '/') . '/' . $class_name . '.' . $type . 'php';
1079
-            // does the file exist and can be read ?
1080
-            if (is_readable($file_paths[ $key ])) {
1081
-                return $file_paths[ $key ];
1082
-            }
1083
-        }
1084
-        return false;
1085
-    }
1086
-
1087
-
1088
-    /**
1089
-     * basically just performs a require_once()
1090
-     * but with some error handling
1091
-     *
1092
-     * @param string $path
1093
-     * @param string $class_name
1094
-     * @param string $type
1095
-     * @param array  $file_paths
1096
-     * @return bool
1097
-     * @throws EE_Error
1098
-     * @throws ReflectionException
1099
-     */
1100
-    protected function _require_file(string $path, string $class_name, string $type = '', array $file_paths = []): bool
1101
-    {
1102
-        $this->resolve_legacy_class_parent($class_name);
1103
-        // don't give up! you gotta...
1104
-        try {
1105
-            // does the file exist and can it be read ?
1106
-            if (! $path) {
1107
-                // just in case the file has already been autoloaded,
1108
-                // but discrepancies in the naming schema are preventing it from
1109
-                // being loaded via one of the EE_Registry::load_*() methods,
1110
-                // then let's try one last hail mary before throwing an exception
1111
-                // and call class_exists() again, but with autoloading turned ON
1112
-                if (class_exists($class_name)) {
1113
-                    return true;
1114
-                }
1115
-                // so sorry, can't find the file
1116
-                throw new EE_Error(
1117
-                    sprintf(
1118
-                        esc_html__(
1119
-                            'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
1120
-                            'event_espresso'
1121
-                        ),
1122
-                        trim($type, '.'),
1123
-                        $class_name,
1124
-                        '<br />' . implode(',<br />', $file_paths)
1125
-                    )
1126
-                );
1127
-            }
1128
-            // get the file
1129
-            require_once($path);
1130
-            // if the class isn't already declared somewhere
1131
-            if (class_exists($class_name, false) === false) {
1132
-                // so sorry, not a class
1133
-                throw new EE_Error(
1134
-                    sprintf(
1135
-                        esc_html__(
1136
-                            'The %s file %s does not appear to contain the %s Class.',
1137
-                            'event_espresso'
1138
-                        ),
1139
-                        $type,
1140
-                        $path,
1141
-                        $class_name
1142
-                    )
1143
-                );
1144
-            }
1145
-        } catch (EE_Error $e) {
1146
-            $e->get_error();
1147
-            return false;
1148
-        }
1149
-        return true;
1150
-    }
1151
-
1152
-
1153
-    /**
1154
-     * Some of our legacy classes that extended a parent class would simply use a require() statement
1155
-     * before their class declaration in order to ensure that the parent class was loaded.
1156
-     * This is not ideal, but it's nearly impossible to determine the parent class of a non-namespaced class,
1157
-     * without triggering a fatal error because the parent class has yet to be loaded and therefore doesn't exist.
1158
-     *
1159
-     * @param string $class_name
1160
-     */
1161
-    protected function resolve_legacy_class_parent(string $class_name = '')
1162
-    {
1163
-        try {
1164
-            $legacy_parent_class_map = [
1165
-                'EE_Payment_Processor' => 'core/business/EE_Processor_Base.class.php',
1166
-            ];
1167
-            if (isset($legacy_parent_class_map[ $class_name ])) {
1168
-                require_once EE_PLUGIN_DIR_PATH . $legacy_parent_class_map[ $class_name ];
1169
-            }
1170
-        } catch (Exception $exception) {
1171
-        }
1172
-    }
1173
-
1174
-
1175
-    /**
1176
-     * _create_object
1177
-     * Attempts to instantiate the requested class via any of the
1178
-     * commonly used instantiation methods employed throughout EE.
1179
-     * The priority for instantiation is as follows:
1180
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1181
-     *        - model objects via their 'new_instance_from_db' method
1182
-     *        - model objects via their 'new_instance' method
1183
-     *        - "singleton" classes" via their 'instance' method
1184
-     *    - standard instantiable classes via their __constructor
1185
-     * Prior to instantiation, if the classname exists in the dependency_map,
1186
-     * then the constructor for the requested class will be examined to determine
1187
-     * if any dependencies exist, and if they can be injected.
1188
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1189
-     *
1190
-     * @param string $class_name
1191
-     * @param array  $arguments
1192
-     * @param string $type
1193
-     * @param bool   $from_db
1194
-     * @return null|object|bool
1195
-     * @throws InvalidArgumentException
1196
-     * @throws InvalidInterfaceException
1197
-     * @throws EE_Error
1198
-     * @throws ReflectionException
1199
-     * @throws InvalidDataTypeException
1200
-     */
1201
-    protected function _create_object(
1202
-        string $class_name,
1203
-        array $arguments = [],
1204
-        string $type = '',
1205
-        bool $from_db = false
1206
-    ) {
1207
-        // create reflection
1208
-        $reflector = $this->mirror->getReflectionClass($class_name);
1209
-        // make sure arguments are an array
1210
-        $arguments = is_array($arguments)
1211
-            ? $arguments
1212
-            : [$arguments];
1213
-        // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1214
-        // else wrap it in an additional array so that it doesn't get split into multiple parameters
1215
-        $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1216
-            ? $arguments
1217
-            : [$arguments];
1218
-        // attempt to inject dependencies ?
1219
-        if ($this->_dependency_map->has($class_name)) {
1220
-            $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1221
-        }
1222
-        // instantiate the class if possible
1223
-        if ($reflector->isAbstract()) {
1224
-            // nothing to instantiate, loading file was enough
1225
-            // does not throw an exception so $instantiation_mode is unused
1226
-            // $instantiation_mode = "1) no constructor abstract class";
1227
-            return true;
1228
-        }
1229
-        if (
1230
-            empty($arguments)
1231
-            && $this->mirror->getConstructorFromReflection($reflector) === null
1232
-            && $reflector->isInstantiable()
1233
-        ) {
1234
-            // no constructor = static methods only... nothing to instantiate, loading file was enough
1235
-            // $instantiation_mode = "2) no constructor but instantiable";
1236
-            return $reflector->newInstance();
1237
-        }
1238
-        if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1239
-            // $instantiation_mode = "3) new_instance_from_db()";
1240
-            return call_user_func_array([$class_name, 'new_instance_from_db'], $arguments);
1241
-        }
1242
-        if (method_exists($class_name, 'new_instance')) {
1243
-            // $instantiation_mode = "4) new_instance()";
1244
-            return call_user_func_array([$class_name, 'new_instance'], $arguments);
1245
-        }
1246
-        if (method_exists($class_name, 'instance')) {
1247
-            // $instantiation_mode = "5) instance()";
1248
-            return call_user_func_array([$class_name, 'instance'], $arguments);
1249
-        }
1250
-        if ($reflector->isInstantiable()) {
1251
-            $args_passed_count = count($arguments);
1252
-            $args_required_count = count($this->mirror->getRequiredParameters($class_name));
1253
-            if ($args_passed_count < $args_required_count) {
1254
-                throw new RuntimeException(
1255
-                    sprintf(
1256
-                        __(
1257
-                            'Invalid arguments supplied for the %1$s class, %2$s were required but %3$s were passed.',
1258
-                            'event_espresso'
1259
-                        ),
1260
-                        $class_name,
1261
-                        $args_required_count,
1262
-                        $args_passed_count
1263
-                    )
1264
-                );
1265
-            }
1266
-            // $instantiation_mode = "6) constructor";
1267
-            return $reflector->newInstanceArgs($arguments);
1268
-        }
1269
-        // heh ? something's not right !
1270
-        throw new EE_Error(
1271
-            sprintf(
1272
-                esc_html__('The %s file %s could not be instantiated.', 'event_espresso'),
1273
-                $type,
1274
-                $class_name
1275
-            )
1276
-        );
1277
-    }
1278
-
1279
-
1280
-    /**
1281
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1282
-     * @param array $array
1283
-     * @return bool
1284
-     */
1285
-    protected function _array_is_numerically_and_sequentially_indexed(array $array): bool
1286
-    {
1287
-        return empty($array) || array_keys($array) === range(0, count($array) - 1);
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     * _resolve_dependencies
1293
-     * examines the constructor for the requested class to determine
1294
-     * if any dependencies exist, and if they can be injected.
1295
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1296
-     * PLZ NOTE: this is achieved by type hinting the constructor params
1297
-     * For example:
1298
-     *        if attempting to load a class "Foo" with the following constructor:
1299
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
1300
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
1301
-     *        but only IF they are NOT already present in the incoming arguments array,
1302
-     *        and the correct classes can be loaded
1303
-     *
1304
-     * @param ReflectionClass $reflector
1305
-     * @param string          $class_name
1306
-     * @param array           $arguments
1307
-     * @return array
1308
-     * @throws InvalidArgumentException
1309
-     * @throws InvalidDataTypeException
1310
-     * @throws InvalidInterfaceException
1311
-     * @throws ReflectionException
1312
-     */
1313
-    protected function _resolve_dependencies(
1314
-        ReflectionClass $reflector,
1315
-        string $class_name,
1316
-        array $arguments = []
1317
-    ): array {
1318
-        // let's examine the constructor
1319
-        $constructor = $this->mirror->getConstructorFromReflection($reflector);
1320
-        // whu? huh? nothing?
1321
-        if (! $constructor) {
1322
-            return $arguments;
1323
-        }
1324
-        // get constructor parameters
1325
-        $params = $this->mirror->getParametersFromReflection($reflector);
1326
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1327
-        $argument_keys = array_keys($arguments);
1328
-        // now loop thru all the constructors' expected parameters
1329
-        foreach ($params as $index => $param) {
1330
-            try {
1331
-                // is this a dependency for a specific class ?
1332
-                $param_class = $this->mirror->getParameterClassName($param, $class_name, $index);
1333
-            } catch (ReflectionException $exception) {
1334
-                // uh-oh... most likely a legacy class that has not been autoloaded
1335
-                // let's try to derive the classname from what we have now
1336
-                // and hope that the property var name is close to the class name
1337
-                $param_class = $param->getName();
1338
-                $param_class = str_replace('_', ' ', $param_class);
1339
-                $param_class = ucwords($param_class);
1340
-                $param_class = str_replace(' ', '_', $param_class);
1341
-            }
1342
-            // BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1343
-            $param_class = $this->class_cache->isAlias($param_class, $class_name)
1344
-                ? $this->class_cache->getFqnForAlias($param_class, $class_name)
1345
-                : $param_class;
1346
-            if (
1347
-                // param is not even a class
1348
-                ($param_class === null || $this->parameterIsPrimitive($param_class))
1349
-                // and something already exists in the incoming arguments for this param
1350
-                && array_key_exists($index, $argument_keys)
1351
-                && isset($arguments[ $argument_keys[ $index ] ])
1352
-            ) {
1353
-                // so let's skip this argument and move on to the next
1354
-                continue;
1355
-            }
1356
-            // parameter is type hinted as a class
1357
-            if ($param_class !== null) {
1358
-                // parameter exists as an incoming argument, AND it's the correct class
1359
-                if (
1360
-                    array_key_exists($index, $argument_keys)
1361
-                    && isset($arguments[ $argument_keys[ $index ] ])
1362
-                    && $arguments[ $argument_keys[ $index ] ] instanceof $param_class
1363
-                ) {
1364
-                    // skip this argument and move on to the next
1365
-                    continue;
1366
-                }
1367
-                // parameter should be injected
1368
-                if ($this->_dependency_map->has_dependency_for_class($class_name, $param_class)) {
1369
-                    $arguments = $this->_resolve_dependency(
1370
-                        $class_name,
1371
-                        $param_class,
1372
-                        $arguments,
1373
-                        $index
1374
-                    );
1375
-                }
1376
-            }
1377
-            if (empty($arguments[ $index ])) {
1378
-                $default_value = $this->mirror->getParameterDefaultValue(
1379
-                    $param,
1380
-                    $class_name,
1381
-                    $index
1382
-                );
1383
-                // if there's no default value, and the incoming argument is an array (albeit empty), then use that
1384
-                $arguments[ $index ] = $default_value === null
1385
-                                       && isset($arguments[ $index ])
1386
-                                       && is_array($arguments[ $index ])
1387
-                    ? $arguments[ $index ]
1388
-                    : $default_value;
1389
-            }
1390
-        }
1391
-        return $arguments;
1392
-    }
1393
-
1394
-
1395
-    /**
1396
-     * @param string $class_name
1397
-     * @param string $param_class
1398
-     * @param array  $arguments
1399
-     * @param mixed  $index
1400
-     * @return array
1401
-     * @throws InvalidArgumentException
1402
-     * @throws InvalidInterfaceException
1403
-     * @throws InvalidDataTypeException
1404
-     */
1405
-    protected function _resolve_dependency(string $class_name, string $param_class, array $arguments, $index): array
1406
-    {
1407
-        $dependency = null;
1408
-        // should dependency be loaded from cache ?
1409
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1410
-            $class_name,
1411
-            $param_class
1412
-        );
1413
-        $cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1414
-        // we might have a dependency...
1415
-        // let's MAYBE try and find it in our cache if that's what's been requested
1416
-        $cached_class = $cache_on
1417
-            ? $this->_get_cached_class($param_class)
1418
-            : null;
1419
-        // and grab it if it exists
1420
-        if ($cached_class instanceof $param_class) {
1421
-            $dependency = $cached_class;
1422
-        } elseif ($param_class !== $class_name) {
1423
-            // obtain the loader method from the dependency map
1424
-            $loader = $this->_dependency_map->class_loader($param_class);
1425
-            // is loader a custom closure ?
1426
-            if ($loader instanceof Closure) {
1427
-                $dependency = $loader($arguments);
1428
-            } else {
1429
-                // set the cache on property for the recursive loading call
1430
-                $this->_cache_on = $cache_on;
1431
-                // if not, then let's try and load it via the registry
1432
-                if ($loader && method_exists($this, $loader)) {
1433
-                    $dependency = $this->{$loader}($param_class);
1434
-                } else {
1435
-                    $dependency = LoaderFactory::getLoader()->load(
1436
-                        $param_class,
1437
-                        [],
1438
-                        $cache_on
1439
-                    );
1440
-                }
1441
-            }
1442
-        }
1443
-        // did we successfully find the correct dependency ?
1444
-        if ($dependency instanceof $param_class) {
1445
-            // then let's inject it into the incoming array of arguments at the correct location
1446
-            $arguments[ $index ] = $dependency;
1447
-        }
1448
-        return $arguments;
1449
-    }
1450
-
1451
-
1452
-    /**
1453
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1454
-     *
1455
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1456
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1457
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1458
-     * @param array  $arguments
1459
-     * @return object
1460
-     */
1461
-    public static function factory(string $classname, array $arguments = [])
1462
-    {
1463
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1464
-        if ($loader instanceof Closure) {
1465
-            return $loader($arguments);
1466
-        }
1467
-        if (method_exists(self::instance(), $loader)) {
1468
-            return self::instance()->{$loader}($classname, $arguments);
1469
-        }
1470
-        return null;
1471
-    }
1472
-
1473
-
1474
-    /**
1475
-     * Gets the addon by its class name
1476
-     *
1477
-     * @param string $class_name
1478
-     * @return EE_Addon
1479
-     */
1480
-    public function getAddon(string $class_name): ?EE_Addon
1481
-    {
1482
-        $class_name = str_replace('\\', '_', $class_name);
1483
-        return $this->addons->{$class_name} ?? null;
1484
-    }
1485
-
1486
-
1487
-    /**
1488
-     * removes the addon from the internal cache
1489
-     *
1490
-     * @param string $class_name
1491
-     * @return void
1492
-     */
1493
-    public function removeAddon(string $class_name)
1494
-    {
1495
-        $class_name = str_replace('\\', '_', $class_name);
1496
-        $this->addons->remove($class_name);
1497
-    }
1498
-
1499
-
1500
-    /**
1501
-     * Gets the addon by its name/slug (not classname. For that, just
1502
-     * use the get_addon() method above
1503
-     *
1504
-     * @param string $name
1505
-     * @return EE_Addon
1506
-     */
1507
-    public function get_addon_by_name(string $name): ?EE_Addon
1508
-    {
1509
-        foreach ($this->addons as $addon) {
1510
-            if ($addon->name() === $name) {
1511
-                return $addon;
1512
-            }
1513
-        }
1514
-        return null;
1515
-    }
1516
-
1517
-
1518
-    /**
1519
-     * Gets an array of all the registered addons, where the keys are their names.
1520
-     * (ie, what each returns for their name() function)
1521
-     * They're already available on EE_Registry::instance()->addons as properties,
1522
-     * where each property's name is the addon's classname,
1523
-     * So if you just want to get the addon by classname,
1524
-     * OR use the get_addon() method above.
1525
-     * PLEASE  NOTE:
1526
-     * addons with Fully Qualified Class Names
1527
-     * have had the namespace separators converted to underscores,
1528
-     * so a classname like Fully\Qualified\ClassName
1529
-     * would have been converted to Fully_Qualified_ClassName
1530
-     *
1531
-     * @return EE_Addon[] where the KEYS are the addon's name()
1532
-     */
1533
-    public function get_addons_by_name(): array
1534
-    {
1535
-        $addons = [];
1536
-        foreach ($this->addons as $addon) {
1537
-            $addons[ $addon->name() ] = $addon;
1538
-        }
1539
-        return $addons;
1540
-    }
1541
-
1542
-
1543
-    /**
1544
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1545
-     * a stale copy of it around
1546
-     *
1547
-     * @param string $model_name
1548
-     * @return EEM_Base
1549
-     * @throws EE_Error
1550
-     * @throws ReflectionException
1551
-     */
1552
-    public function reset_model(string $model_name): ?EEM_Base
1553
-    {
1554
-        $model_class_name = strpos($model_name, 'EEM_') !== 0
1555
-            ? "EEM_$model_name"
1556
-            : $model_name;
1557
-        if (! $this->LIB->has($model_class_name)) {
1558
-            return null;
1559
-        }
1560
-        $model = $this->LIB->get($model_class_name);
1561
-        if (! $model instanceof EEM_Base) {
1562
-            return null;
1563
-        }
1564
-        // get that model reset it and make sure we nuke the old reference to it
1565
-        if ($model instanceof $model_class_name && is_callable([$model_class_name, 'reset'])) {
1566
-            $this->LIB->remove($model_class_name);
1567
-            $this->LIB->add($model_class_name, $model->reset());
1568
-        } else {
1569
-            throw new EE_Error(
1570
-                sprintf(
1571
-                    esc_html__('Model %s does not have a method "reset"', 'event_espresso'),
1572
-                    $model_name
1573
-                )
1574
-            );
1575
-        }
1576
-        return $model;
1577
-    }
1578
-
1579
-
1580
-    /**
1581
-     * Resets the registry.
1582
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when
1583
-     * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1584
-     * - $_dependency_map
1585
-     * - $_class_abbreviations
1586
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1587
-     * - $REQ:  Still on the same request so no need to change.
1588
-     * - $CAP: There is no site specific state in the EE_Capability class.
1589
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1590
-     * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1591
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1592
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1593
-     *             switch or on the restore.
1594
-     * - $modules
1595
-     * - $shortcodes
1596
-     * - $widgets
1597
-     *
1598
-     * @param boolean $hard             [deprecated]
1599
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1600
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1601
-     *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1602
-     * @param bool    $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1603
-     *                                  client
1604
-     *                                  code instead can just change the model context to a different blog id if
1605
-     *                                  necessary
1606
-     * @return EE_Registry
1607
-     * @throws EE_Error
1608
-     * @throws ReflectionException
1609
-     */
1610
-    public static function reset(bool $hard = false, bool $reinstantiate = true, bool $reset_models = true): EE_Registry
1611
-    {
1612
-        $instance            = self::instance();
1613
-        $instance->_cache_on = true;
1614
-        // reset some "special" classes
1615
-        EEH_Activation::reset();
1616
-        $hard = apply_filters('FHEE__EE_Registry__reset__hard', $hard);
1617
-        $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1618
-        $instance->CART = null;
1619
-        $instance->MRM = null;
1620
-        // messages reset
1621
-        EED_Messages::reset();
1622
-        // handle of objects cached on LIB
1623
-        foreach (['LIB', 'modules'] as $cache) {
1624
-            foreach ($instance->{$cache} as $class_name => $class) {
1625
-                if (self::_reset_and_unset_object($class, $reset_models)) {
1626
-                    unset($instance->{$cache}->{$class_name});
1627
-                }
1628
-            }
1629
-        }
1630
-        return $instance;
1631
-    }
1632
-
1633
-
1634
-    /**
1635
-     * if passed object implements ResettableInterface, then call it's reset() method
1636
-     * if passed object implements InterminableInterface, then return false,
1637
-     * to indicate that it should NOT be cleared from the Registry cache
1638
-     *
1639
-     * @param      $object
1640
-     * @param bool $reset_models
1641
-     * @return bool returns true if cached object should be unset
1642
-     * @throws EE_Error
1643
-     * @throws ReflectionException
1644
-     */
1645
-    private static function _reset_and_unset_object($object, bool $reset_models): bool
1646
-    {
1647
-        if (! is_object($object)) {
1648
-            // don't unset anything that's not an object
1649
-            return false;
1650
-        }
1651
-        if ($object instanceof EED_Module) {
1652
-            $object::reset();
1653
-            // don't unset modules
1654
-            return false;
1655
-        }
1656
-        if ($object instanceof ResettableInterface) {
1657
-            if ($object instanceof EEM_Base) {
1658
-                if ($reset_models) {
1659
-                    $object->reset();
1660
-                    return true;
1661
-                }
1662
-                return false;
1663
-            }
1664
-            $object->reset();
1665
-            return true;
1666
-        }
1667
-        if (! $object instanceof InterminableInterface) {
1668
-            return true;
1669
-        }
1670
-        return false;
1671
-    }
1672
-
1673
-
1674
-    /**
1675
-     * Gets all the custom post type models defined
1676
-     *
1677
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1678
-     */
1679
-    public function cpt_models(): array
1680
-    {
1681
-        $cpt_models = [];
1682
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1683
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1684
-                $cpt_models[ $short_name ] = $classname;
1685
-            }
1686
-        }
1687
-        return $cpt_models;
1688
-    }
1689
-
1690
-
1691
-    /**
1692
-     * @return EE_Config
1693
-     */
1694
-    public static function CFG(): EE_Config
1695
-    {
1696
-        return self::instance()->CFG;
1697
-    }
1698
-
1699
-
1700
-    /**
1701
-     * @param string $class_name
1702
-     * @return ReflectionClass
1703
-     * @throws ReflectionException
1704
-     * @throws InvalidDataTypeException
1705
-     * @deprecated 4.9.62.p
1706
-     */
1707
-    public function get_ReflectionClass(string $class_name): ReflectionClass
1708
-    {
1709
-        return $this->mirror->getReflectionClass($class_name);
1710
-    }
1711
-
1712
-    private function parameterIsPrimitive(?string $param_class): bool
1713
-    {
1714
-        return in_array(
1715
-            $param_class,
1716
-            [
1717
-                'array',
1718
-                'bool',
1719
-                'float',
1720
-                'int',
1721
-                'string',
1722
-            ]
1723
-        );
1724
-    }
25
+	private static ?EE_Registry $_instance = null;
26
+
27
+	protected EE_Dependency_Map $_dependency_map;
28
+
29
+	private Mirror $mirror;
30
+
31
+	private ClassInterfaceCache $class_cache;
32
+
33
+	private ObjectIdentifier $object_identifier;
34
+
35
+	protected array $_class_abbreviations = [];
36
+
37
+	public ?CommandBusInterface $BUS = null;
38
+
39
+	public ?EE_Cart $CART = null;
40
+
41
+	public ?EE_Config $CFG = null;
42
+
43
+	public ?EE_Network_Config $NET_CFG = null;
44
+
45
+	/**
46
+	 * RegistryContainer for storing library classes in
47
+	 *
48
+	 * @var RegistryContainer|null $LIB
49
+	 */
50
+	public ?RegistryContainer $LIB = null;
51
+
52
+	/**
53
+	 * @var EE_Request_Handler|null $REQ
54
+	 * @deprecated 4.10.14.p
55
+	 */
56
+	public ?EE_Request_Handler $REQ = null;
57
+
58
+	public ?EE_Session $SSN = null;
59
+
60
+	/**
61
+	 * @since 4.5.0
62
+	 * @var EE_Capabilities|null $CAP
63
+	 */
64
+	public ?EE_Capabilities$CAP = null;
65
+
66
+	/**
67
+	 * @since 4.9.0
68
+	 * @var EE_Message_Resource_Manager|null $MRM
69
+	 */
70
+	public ?EE_Message_Resource_Manager $MRM = null;
71
+
72
+	public ?Registry $AssetsRegistry = null;
73
+
74
+	/**
75
+	 * RegistryContainer for holding addons which have registered themselves to work with EE core
76
+	 *
77
+	 * @var RegistryContainer|EE_Addon[] $addons
78
+	 */
79
+	public $addons = [];
80
+
81
+	/**
82
+	 * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
83
+	 *
84
+	 * @var EEM_Base[] $models
85
+	 */
86
+	public array $models = [];
87
+
88
+	/**
89
+	 * @var RegistryContainer|EED_Module[] $modules
90
+	 */
91
+	public $modules = [];
92
+
93
+	/**
94
+	 * @var RegistryContainer|EES_Shortcode[] $shortcodes
95
+	 */
96
+	public $shortcodes = [];
97
+
98
+	/**
99
+	 * @var RegistryContainer|WP_Widget[] $widgets
100
+	 */
101
+	public $widgets = [];
102
+
103
+	/**
104
+	 * this is an array of all implemented model names (i.e. not the parent abstract models, or models
105
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
106
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
107
+	 * classnames (eg "EEM_Event")
108
+	 *
109
+	 * @var array $non_abstract_db_models
110
+	 */
111
+	public array $non_abstract_db_models = [];
112
+
113
+	/**
114
+	 * internationalization for JS strings
115
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
116
+	 *    in js file:  var translatedString = eei18n.string_key;
117
+	 *
118
+	 * @var array $i18n_js_strings
119
+	 */
120
+	public static array $i18n_js_strings = [];
121
+
122
+	/**
123
+	 * $main_file - path to espresso.php
124
+	 *
125
+	 * @var string $main_file
126
+	 */
127
+	public string $main_file = '';
128
+
129
+	/**
130
+	 * boolean flag to indicate whether to load/save dependencies from/to the cache
131
+	 *
132
+	 * @var bool $_cache_on
133
+	 */
134
+	protected bool $_cache_on = true;
135
+
136
+
137
+	/**
138
+	 * @singleton method used to instantiate class object
139
+	 * @param EE_Dependency_Map|null   $dependency_map
140
+	 * @param Mirror|null              $mirror
141
+	 * @param ClassInterfaceCache|null $class_cache
142
+	 * @param ObjectIdentifier|null    $object_identifier
143
+	 * @return EE_Registry instance
144
+	 */
145
+	public static function instance(
146
+		EE_Dependency_Map $dependency_map = null,
147
+		Mirror $mirror = null,
148
+		ClassInterfaceCache $class_cache = null,
149
+		ObjectIdentifier $object_identifier = null
150
+	): EE_Registry {
151
+		// check if class object is instantiated
152
+		if (
153
+			! self::$_instance instanceof EE_Registry
154
+			&& $dependency_map instanceof EE_Dependency_Map
155
+			&& $mirror instanceof Mirror
156
+			&& $class_cache instanceof ClassInterfaceCache
157
+			&& $object_identifier instanceof ObjectIdentifier
158
+		) {
159
+			self::$_instance = new self(
160
+				$dependency_map,
161
+				$mirror,
162
+				$class_cache,
163
+				$object_identifier
164
+			);
165
+		}
166
+		return self::$_instance;
167
+	}
168
+
169
+
170
+	/**
171
+	 * protected constructor to prevent direct creation
172
+	 *
173
+	 * @Constructor
174
+	 * @param EE_Dependency_Map   $dependency_map
175
+	 * @param Mirror              $mirror
176
+	 * @param ClassInterfaceCache $class_cache
177
+	 * @param ObjectIdentifier    $object_identifier
178
+	 */
179
+	protected function __construct(
180
+		EE_Dependency_Map $dependency_map,
181
+		Mirror $mirror,
182
+		ClassInterfaceCache $class_cache,
183
+		ObjectIdentifier $object_identifier
184
+	) {
185
+		$this->_dependency_map   = $dependency_map;
186
+		$this->mirror            = $mirror;
187
+		$this->class_cache       = $class_cache;
188
+		$this->object_identifier = $object_identifier;
189
+
190
+		$this->LIB        = new RegistryContainer();
191
+		$this->addons     = new RegistryContainer();
192
+		$this->modules    = new RegistryContainer();
193
+		$this->shortcodes = new RegistryContainer();
194
+		$this->widgets    = new RegistryContainer();
195
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', [$this, 'initialize']);
196
+	}
197
+
198
+
199
+	/**
200
+	 * initialize
201
+	 *
202
+	 * @throws OutOfBoundsException
203
+	 * @throws InvalidArgumentException
204
+	 * @throws InvalidInterfaceException
205
+	 * @throws InvalidDataTypeException
206
+	 * @throws EE_Error
207
+	 * @throws ReflectionException
208
+	 */
209
+	public function initialize()
210
+	{
211
+		$this->_class_abbreviations = apply_filters(
212
+			'FHEE__EE_Registry____construct___class_abbreviations',
213
+			[
214
+				'EE_Config'                                       => 'CFG',
215
+				'EE_Session'                                      => 'SSN',
216
+				'EE_Capabilities'                                 => 'CAP',
217
+				'EE_Cart'                                         => 'CART',
218
+				'EE_Network_Config'                               => 'NET_CFG',
219
+				'EE_Request_Handler'                              => 'REQ',
220
+				'EE_Message_Resource_Manager'                     => 'MRM',
221
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
222
+				'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
223
+			]
224
+		);
225
+		$this->load_core('Base', [], true);
226
+		// add our request and response objects to the cache
227
+		$request_loader = $this->_dependency_map->class_loader(
228
+			'EventEspresso\core\services\request\Request'
229
+		);
230
+		$this->_set_cached_class(
231
+			$request_loader(),
232
+			'EventEspresso\core\services\request\Request'
233
+		);
234
+		$response_loader = $this->_dependency_map->class_loader(
235
+			'EventEspresso\core\services\request\Response'
236
+		);
237
+		$this->_set_cached_class(
238
+			$response_loader(),
239
+			'EventEspresso\core\services\request\Response'
240
+		);
241
+		add_action('AHEE__EE_System__set_hooks_for_core', [$this, 'init']);
242
+	}
243
+
244
+
245
+	/**
246
+	 * @return void
247
+	 */
248
+	public function init()
249
+	{
250
+		// Get current page protocol
251
+		$protocol = is_ssl() ? 'https://' : 'http://';
252
+		// Output admin-ajax.php URL with same protocol as current page
253
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
254
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') && WP_DEBUG;
255
+	}
256
+
257
+
258
+	/**
259
+	 * @return array
260
+	 */
261
+	public static function sanitize_i18n_js_strings(): array
262
+	{
263
+		array_walk(EE_Registry::$i18n_js_strings, function (&$value) {
264
+			if (is_scalar($value)) {
265
+				$value = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
266
+				// replace all escaped instances of \n with actual new lines
267
+				$value = str_replace("\\n", "\n", $value);
268
+			}
269
+		});
270
+		// sort the array by key in a case-insensitive manner
271
+		ksort(EE_Registry::$i18n_js_strings, SORT_NATURAL | SORT_FLAG_CASE);
272
+		return EE_Registry::$i18n_js_strings;
273
+	}
274
+
275
+
276
+	/**
277
+	 * localize_i18n_js_strings
278
+	 *
279
+	 * @return string
280
+	 */
281
+	public static function localize_i18n_js_strings(): string
282
+	{
283
+		$i18n_js_strings = wp_json_encode(EE_Registry::sanitize_i18n_js_strings());
284
+		return "/* <![CDATA[ */ var eei18n = $i18n_js_strings; /* ]]> */";
285
+	}
286
+
287
+
288
+	/**
289
+	 * @param mixed string | EED_Module $module
290
+	 * @throws OutOfBoundsException
291
+	 * @throws InvalidArgumentException
292
+	 * @throws InvalidInterfaceException
293
+	 * @throws InvalidDataTypeException
294
+	 * @throws EE_Error
295
+	 * @throws ReflectionException
296
+	 */
297
+	public function add_module($module)
298
+	{
299
+		if ($module instanceof EED_Module) {
300
+			$module_class = get_class($module);
301
+			$this->modules->add($module_class, $module);
302
+		} else {
303
+			if (! class_exists('EE_Module_Request_Router', false)) {
304
+				$this->load_core('Module_Request_Router');
305
+			}
306
+			EE_Module_Request_Router::module_factory($module);
307
+		}
308
+	}
309
+
310
+
311
+	/**
312
+	 * @param string $module_name
313
+	 * @return mixed EED_Module | NULL
314
+	 */
315
+	public function get_module(string $module_name = '')
316
+	{
317
+		return $this->modules->get($module_name);
318
+	}
319
+
320
+
321
+	/**
322
+	 * loads core classes - must be singletons
323
+	 *
324
+	 * @param string $class_name - simple class name ie: session
325
+	 * @param mixed  $arguments
326
+	 * @param bool   $load_only
327
+	 * @return bool|null|object
328
+	 * @throws InvalidInterfaceException
329
+	 * @throws InvalidDataTypeException
330
+	 * @throws EE_Error
331
+	 * @throws ReflectionException
332
+	 * @throws InvalidArgumentException
333
+	 */
334
+	public function load_core(string $class_name, $arguments = [], bool $load_only = false)
335
+	{
336
+		$core_paths = (array) apply_filters(
337
+			'FHEE__EE_Registry__load_core__core_paths',
338
+			[
339
+				EE_CORE,
340
+				EE_ADMIN,
341
+				EE_CPTS,
342
+				EE_CORE . 'CPTs/',
343
+				EE_CORE . 'data_migration_scripts/',
344
+				EE_CORE . 'request_stack/',
345
+				EE_CORE . 'middleware/',
346
+			]
347
+		);
348
+		// retrieve instantiated class
349
+		return $this->_load(
350
+			$core_paths,
351
+			'EE_',
352
+			$class_name,
353
+			'core',
354
+			$arguments,
355
+			false,
356
+			true,
357
+			$load_only
358
+		);
359
+	}
360
+
361
+
362
+	/**
363
+	 * loads service classes
364
+	 *
365
+	 * @param string $class_name - simple class name ie: session
366
+	 * @param mixed  $arguments
367
+	 * @param bool   $load_only
368
+	 * @return bool|null|object
369
+	 * @throws InvalidInterfaceException
370
+	 * @throws InvalidDataTypeException
371
+	 * @throws EE_Error
372
+	 * @throws ReflectionException
373
+	 * @throws InvalidArgumentException
374
+	 * @deprecated  4.10.33.p
375
+	 */
376
+	public function load_service(string $class_name, $arguments = [], bool $load_only = false)
377
+	{
378
+		$service_paths = (array) apply_filters(
379
+			'FHEE__EE_Registry__load_service__service_paths',
380
+			[
381
+				EE_CORE . 'services/',
382
+			]
383
+		);
384
+		// retrieve instantiated class
385
+		return $this->_load(
386
+			$service_paths,
387
+			'EE_',
388
+			$class_name,
389
+			'class',
390
+			$arguments,
391
+			false,
392
+			true,
393
+			$load_only
394
+		);
395
+	}
396
+
397
+
398
+	/**
399
+	 * loads data_migration_scripts
400
+	 *
401
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
402
+	 * @param mixed  $arguments
403
+	 * @return bool|null|object
404
+	 * @throws InvalidInterfaceException
405
+	 * @throws InvalidDataTypeException
406
+	 * @throws EE_Error
407
+	 * @throws ReflectionException
408
+	 * @throws InvalidArgumentException
409
+	 */
410
+	public function load_dms(string $class_name, $arguments = [])
411
+	{
412
+		// retrieve instantiated class
413
+		return $this->_load(
414
+			EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
415
+			'EE_DMS_',
416
+			$class_name,
417
+			'dms',
418
+			$arguments,
419
+			false,
420
+			false
421
+		);
422
+	}
423
+
424
+
425
+	/**
426
+	 * loads object creating classes - must be singletons
427
+	 *
428
+	 * @param string $class_name - simple class name ie: attendee
429
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
430
+	 * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
431
+	 *                           instantiate
432
+	 * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
433
+	 *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
434
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
435
+	 *                           (default)
436
+	 * @return EE_Base_Class|object|bool|null
437
+	 * @throws InvalidInterfaceException
438
+	 * @throws InvalidDataTypeException
439
+	 * @throws EE_Error
440
+	 * @throws ReflectionException
441
+	 * @throws InvalidArgumentException
442
+	 */
443
+	public function load_class(
444
+		string $class_name,
445
+		$arguments = [],
446
+		bool $from_db = false,
447
+		bool $cache = true,
448
+		bool $load_only = false
449
+	) {
450
+		$paths = (array) apply_filters(
451
+			'FHEE__EE_Registry__load_class__paths',
452
+			[
453
+				EE_CORE,
454
+				EE_CLASSES,
455
+				EE_BUSINESS,
456
+			]
457
+		);
458
+		// retrieve instantiated class
459
+		return $this->_load(
460
+			$paths,
461
+			'EE_',
462
+			$class_name,
463
+			'class',
464
+			$arguments,
465
+			$from_db,
466
+			$cache,
467
+			$load_only
468
+		);
469
+	}
470
+
471
+
472
+	/**
473
+	 * loads helper classes - must be singletons
474
+	 *
475
+	 * @param string $class_name - simple class name ie: price
476
+	 * @param mixed  $arguments
477
+	 * @param bool   $load_only
478
+	 * @return bool|null|object
479
+	 * @throws InvalidInterfaceException
480
+	 * @throws InvalidDataTypeException
481
+	 * @throws EE_Error
482
+	 * @throws ReflectionException
483
+	 * @throws InvalidArgumentException
484
+	 */
485
+	public function load_helper(string $class_name, $arguments = [], bool $load_only = true)
486
+	{
487
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
488
+		$helper_paths = (array) apply_filters('FHEE__EE_Registry__load_helper__helper_paths', [EE_HELPERS]);
489
+		// retrieve instantiated class
490
+		return $this->_load(
491
+			$helper_paths,
492
+			'EEH_',
493
+			$class_name,
494
+			'helper',
495
+			$arguments,
496
+			false,
497
+			true,
498
+			$load_only
499
+		);
500
+	}
501
+
502
+
503
+	/**
504
+	 * loads core classes - must be singletons
505
+	 *
506
+	 * @param string $class_name - simple class name ie: session
507
+	 * @param mixed  $arguments
508
+	 * @param bool   $load_only
509
+	 * @param bool   $cache      whether to cache the object or not.
510
+	 * @return bool|null|object
511
+	 * @throws InvalidInterfaceException
512
+	 * @throws InvalidDataTypeException
513
+	 * @throws EE_Error
514
+	 * @throws ReflectionException
515
+	 * @throws InvalidArgumentException
516
+	 */
517
+	public function load_lib(string $class_name, $arguments = [], bool $load_only = false, bool $cache = true)
518
+	{
519
+		$paths = [
520
+			EE_LIBRARIES,
521
+			EE_LIBRARIES . 'messages/',
522
+			EE_LIBRARIES . 'shortcodes/',
523
+			EE_LIBRARIES . 'qtips/',
524
+			EE_LIBRARIES . 'payment_methods/',
525
+		];
526
+		// retrieve instantiated class
527
+		return $this->_load(
528
+			$paths,
529
+			'EE_',
530
+			$class_name,
531
+			'lib',
532
+			$arguments,
533
+			false,
534
+			$cache,
535
+			$load_only
536
+		);
537
+	}
538
+
539
+
540
+	/**
541
+	 * loads model classes - must be singletons
542
+	 *
543
+	 * @param string $class_name - simple class name ie: price
544
+	 * @param mixed  $arguments
545
+	 * @param bool   $load_only
546
+	 * @return EEM_Base|null
547
+	 * @throws InvalidInterfaceException
548
+	 * @throws InvalidDataTypeException
549
+	 * @throws EE_Error
550
+	 * @throws ReflectionException
551
+	 * @throws InvalidArgumentException
552
+	 */
553
+	public function load_model(string $class_name, $arguments = [], bool $load_only = false): ?EEM_Base
554
+	{
555
+		// retrieve instantiated class
556
+		$model = $this->_load(
557
+			(array) apply_filters(
558
+				'FHEE__EE_Registry__load_model__paths',
559
+				[
560
+					EE_MODELS,
561
+					EE_CORE,
562
+				]
563
+			),
564
+			'EEM_',
565
+			$class_name,
566
+			'model',
567
+			$arguments,
568
+			false,
569
+			true,
570
+			$load_only
571
+		);
572
+		return $model instanceof EEM_Base ? $model : null;
573
+	}
574
+
575
+
576
+	/**
577
+	 * loads model classes - must be singletons
578
+	 *
579
+	 * @param string $class_name - simple class name ie: price
580
+	 * @param mixed  $arguments
581
+	 * @param bool   $load_only
582
+	 * @return bool|null|object
583
+	 * @throws InvalidInterfaceException
584
+	 * @throws InvalidDataTypeException
585
+	 * @throws EE_Error
586
+	 * @throws ReflectionException
587
+	 * @throws InvalidArgumentException
588
+	 * @deprecated  4.10.33.p
589
+	 */
590
+	public function load_model_class(string $class_name, $arguments = [], bool $load_only = true)
591
+	{
592
+		$paths = [
593
+			EE_MODELS . 'fields/',
594
+			EE_MODELS . 'helpers/',
595
+			EE_MODELS . 'relations/',
596
+			EE_MODELS . 'strategies/',
597
+		];
598
+		// retrieve instantiated class
599
+		return $this->_load(
600
+			$paths,
601
+			'EE_',
602
+			$class_name,
603
+			'',
604
+			$arguments,
605
+			false,
606
+			true,
607
+			$load_only
608
+		);
609
+	}
610
+
611
+
612
+	/**
613
+	 * Determines if $model_name is the name of an actual EE model.
614
+	 *
615
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
616
+	 * @return boolean
617
+	 */
618
+	public function is_model_name(string $model_name): bool
619
+	{
620
+		return isset($this->models[ $model_name ]);
621
+	}
622
+
623
+
624
+	/**
625
+	 * generic class loader
626
+	 *
627
+	 * @param string $path_to_file - directory path to file location, not including filename
628
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
629
+	 * @param string $type         - file type - core? class? helper? model?
630
+	 * @param mixed  $arguments
631
+	 * @param bool   $load_only
632
+	 * @return bool|null|object
633
+	 * @throws InvalidInterfaceException
634
+	 * @throws InvalidDataTypeException
635
+	 * @throws EE_Error
636
+	 * @throws ReflectionException
637
+	 * @throws InvalidArgumentException
638
+	 */
639
+	public function load_file(
640
+		string $path_to_file,
641
+		string $file_name,
642
+		string $type = '',
643
+		$arguments = [],
644
+		bool $load_only = true
645
+	) {
646
+		// retrieve instantiated class
647
+		return $this->_load(
648
+			(array) $path_to_file,
649
+			'',
650
+			$file_name,
651
+			$type,
652
+			$arguments,
653
+			false,
654
+			true,
655
+			$load_only
656
+		);
657
+	}
658
+
659
+
660
+	/**
661
+	 * @param string $path_to_file - directory path to file location, not including filename
662
+	 * @param string $class_name   - full class name  ie:  My_Class
663
+	 * @param string $type         - file type - core? class? helper? model?
664
+	 * @param mixed  $arguments
665
+	 * @param bool   $load_only
666
+	 * @return bool|null|object
667
+	 * @throws InvalidInterfaceException
668
+	 * @throws InvalidDataTypeException
669
+	 * @throws EE_Error
670
+	 * @throws ReflectionException
671
+	 * @throws InvalidArgumentException
672
+	 * @deprecated  4.10.33.p
673
+	 */
674
+	public function load_addon(
675
+		string $path_to_file,
676
+		string $class_name,
677
+		string $type = 'class',
678
+		$arguments = [],
679
+		bool $load_only = false
680
+	) {
681
+		// retrieve instantiated class
682
+		return $this->_load(
683
+			(array) $path_to_file,
684
+			'addon',
685
+			$class_name,
686
+			$type,
687
+			$arguments,
688
+			false,
689
+			true,
690
+			$load_only
691
+		);
692
+	}
693
+
694
+
695
+	/**
696
+	 * instantiates, caches, and automatically resolves dependencies
697
+	 * for classes that use a Fully Qualified Class Name.
698
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
699
+	 * then you need to use one of the existing load_*() methods
700
+	 * which can resolve the classname and filepath from the passed arguments
701
+	 *
702
+	 * @param string      $class_name Fully Qualified Class Name
703
+	 * @param array       $arguments  an argument, or array of arguments to pass to the class upon instantiation
704
+	 * @param bool        $cache      whether to cache the instantiated object for reuse
705
+	 * @param bool        $from_db    some classes are instantiated from the db
706
+	 *                                and thus call a different method to instantiate
707
+	 * @param bool        $load_only  if true, will only load the file, but will NOT instantiate an object
708
+	 * @param bool|string $addon      if true, will cache the object in the EE_Registry->$addons array
709
+	 * @return bool|null|mixed     null = failure to load or instantiate class object.
710
+	 *                                object = class loaded and instantiated successfully.
711
+	 *                                bool = fail or success when $load_only is true
712
+	 * @throws InvalidInterfaceException
713
+	 * @throws InvalidDataTypeException
714
+	 * @throws EE_Error
715
+	 * @throws ReflectionException
716
+	 * @throws InvalidArgumentException
717
+	 */
718
+	public function create(
719
+		string $class_name = '',
720
+		array $arguments = [],
721
+		bool $cache = false,
722
+		bool $from_db = false,
723
+		bool $load_only = false,
724
+		bool $addon = false
725
+	) {
726
+		$class_name   = ltrim($class_name, '\\');
727
+		$class_name   = $this->class_cache->getFqnForAlias($class_name);
728
+		$class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
729
+		// if a non-FQCN was passed, then
730
+		// verifyClassExists() might return an object
731
+		// or it could return null if the class just could not be found anywhere
732
+		if ($class_exists instanceof $class_name || $class_exists === null) {
733
+			// either way, return the results
734
+			return $class_exists;
735
+		}
736
+		$class_name = $class_exists;
737
+		// if we're only loading the class and it already exists, then let's just return true immediately
738
+		if ($load_only) {
739
+			return true;
740
+		}
741
+		$addon = $addon ? 'addon' : '';
742
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
743
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
744
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
745
+		if ($this->_cache_on && $cache) {
746
+			// return object if it's already cached
747
+			$cached_class = $this->_get_cached_class($class_name, $addon, $arguments);
748
+			if ($cached_class !== null) {
749
+				return $cached_class;
750
+			}
751
+		}                                                           // obtain the loader method from the dependency map
752
+		$loader = $this->_dependency_map->class_loader($class_name);// instantiate the requested object
753
+		if ($loader instanceof Closure) {
754
+			$class_obj = $loader($arguments);
755
+		} else {
756
+			if ($loader && method_exists($this, $loader)) {
757
+				$class_obj = $this->{$loader}($class_name, $arguments);
758
+			} else {
759
+				$class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
760
+			}
761
+		}
762
+		if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
763
+			// save it for later... kinda like gum  { : $
764
+			$this->_set_cached_class(
765
+				$class_obj,
766
+				$class_name,
767
+				$addon,
768
+				$from_db,
769
+				$arguments
770
+			);
771
+		}
772
+		$this->_cache_on = true;
773
+		return $class_obj;
774
+	}
775
+
776
+
777
+	/**
778
+	 * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
779
+	 *
780
+	 * @param string|mixed $class_name
781
+	 * @param array        $arguments
782
+	 * @param int          $attempt
783
+	 * @return mixed
784
+	 */
785
+	private function loadOrVerifyClassExists($class_name, array $arguments, int $attempt = 1)
786
+	{
787
+		if (is_object($class_name) || class_exists($class_name)) {
788
+			return $class_name;
789
+		}
790
+		switch ($attempt) {
791
+			case 1:
792
+				// if it's a FQCN then maybe the class is registered with a preceding \
793
+				$class_name = strpos($class_name, '\\') !== false
794
+					? '\\' . ltrim($class_name, '\\')
795
+					: $class_name;
796
+				break;
797
+			case 2:
798
+				//
799
+				$loader = $this->_dependency_map->class_loader($class_name);
800
+				if ($loader && method_exists($this, $loader)) {
801
+					return $this->{$loader}($class_name, $arguments);
802
+				}
803
+				break;
804
+			case 3:
805
+			default:
806
+				return null;
807
+		}
808
+		$attempt++;
809
+		return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
810
+	}
811
+
812
+
813
+	/**
814
+	 * instantiates, caches, and injects dependencies for classes
815
+	 *
816
+	 * @param array  $file_paths         an array of paths to folders to look in
817
+	 * @param string $class_prefix       EE  or EEM or... ???
818
+	 * @param string $class_name         $class name
819
+	 * @param string $type               file type - core? class? helper? model?
820
+	 * @param mixed  $arguments          an argument or array of arguments to pass to the class upon instantiation
821
+	 * @param bool   $from_db            some classes are instantiated from the db
822
+	 *                                   and thus call a different method to instantiate
823
+	 * @param bool   $cache              whether to cache the instantiated object for reuse
824
+	 * @param bool   $load_only          if true, will only load the file, but will NOT instantiate an object
825
+	 * @return bool|null|object          null   = failure to load or instantiate class object.
826
+	 *                                   object = class loaded and instantiated successfully.
827
+	 *                                   bool   = fail or success when $load_only is true
828
+	 * @throws EE_Error
829
+	 * @throws ReflectionException
830
+	 * @throws InvalidInterfaceException
831
+	 * @throws InvalidDataTypeException
832
+	 * @throws InvalidArgumentException
833
+	 */
834
+	protected function _load(
835
+		array $file_paths = [],
836
+		string $class_prefix = 'EE_',
837
+		string $class_name = '',
838
+		string $type = 'class',
839
+		array $arguments = [],
840
+		bool $from_db = false,
841
+		bool $cache = true,
842
+		bool $load_only = false
843
+	) {
844
+		$class_name = ltrim($class_name, '\\');
845
+		// strip php file extension
846
+		$class_name = str_replace('.php', '', trim($class_name));
847
+		// does the class have a prefix ?
848
+		if (! empty($class_prefix) && $class_prefix !== 'addon') {
849
+			// make sure $class_prefix is uppercase
850
+			$class_prefix = strtoupper(trim($class_prefix));
851
+			// add class prefix ONCE!!!
852
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
853
+		}
854
+		$class_name   = $this->class_cache->getFqnForAlias($class_name);
855
+		$class_exists = class_exists($class_name, false);
856
+		// if we're only loading the class and it already exists, then let's just return true immediately
857
+		if ($load_only && $class_exists) {
858
+			return true;
859
+		}
860
+		$arguments = is_array($arguments) ? $arguments : [$arguments];
861
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
862
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
863
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
864
+		if ($this->_cache_on && $cache && ! $load_only) {
865
+			// return object if it's already cached
866
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix, $arguments);
867
+			if ($cached_class !== null) {
868
+				return $cached_class;
869
+			}
870
+		}
871
+		// if the class doesn't already exist.. then we need to try and find the file and load it
872
+		if (! $class_exists) {
873
+			// get full path to file
874
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
875
+			// load the file
876
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
877
+			// if we are only loading a file but NOT instantiating an object
878
+			// then return boolean for whether class was loaded or not
879
+			if ($load_only) {
880
+				return $loaded;
881
+			}
882
+			// if an object was expected but loading failed, then return nothing
883
+			if (! $loaded) {
884
+				return null;
885
+			}
886
+		}
887
+		// instantiate the requested object
888
+		$class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
889
+		if ($this->_cache_on && $cache) {
890
+			// save it for later... kinda like gum  { : $
891
+			$this->_set_cached_class(
892
+				$class_obj,
893
+				$class_name,
894
+				$class_prefix,
895
+				$from_db,
896
+				$arguments
897
+			);
898
+		}
899
+		$this->_cache_on = true;
900
+		return $class_obj;
901
+	}
902
+
903
+
904
+	/**
905
+	 * @param string $class_name
906
+	 * @param string $default have to specify something, but not anything that will conflict
907
+	 * @return mixed|string
908
+	 */
909
+	protected function get_class_abbreviation(string $class_name, string $default = 'FANCY_BATMAN_PANTS')
910
+	{
911
+		return $this->_class_abbreviations[ $class_name ] ?? $default;
912
+	}
913
+
914
+
915
+	/**
916
+	 * attempts to find a cached version of the requested class
917
+	 * by looking in the following places:
918
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
919
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
920
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
921
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
922
+	 *
923
+	 * @param string $class_name
924
+	 * @param string $class_prefix
925
+	 * @param array  $arguments
926
+	 * @return mixed
927
+	 */
928
+	protected function _get_cached_class(
929
+		string $class_name,
930
+		string $class_prefix = '',
931
+		array $arguments = []
932
+	) {
933
+		if ($class_name === 'EE_Registry') {
934
+			return $this;
935
+		}
936
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
937
+		// check if class has already been loaded, and return it if it has been
938
+		if (isset($this->{$class_abbreviation})) {
939
+			return $this->{$class_abbreviation};
940
+		}
941
+		$class_name = str_replace('\\', '_', $class_name);
942
+		if (isset($this->{$class_name})) {
943
+			return $this->{$class_name};
944
+		}
945
+		if ($class_prefix === 'addon' && $this->addons->has($class_name)) {
946
+			return $this->addons->get($class_name);
947
+		}
948
+		$object_identifier = $this->object_identifier->getIdentifier($class_name, $arguments);
949
+		if ($this->LIB->has($object_identifier)) {
950
+			return $this->LIB->get($object_identifier);
951
+		}
952
+		foreach ($this->LIB as $key => $object) {
953
+			if (
954
+				// request does not contain new arguments and therefore no args identifier
955
+				! $this->object_identifier->hasArguments($object_identifier)
956
+				// but previously cached class with args was found
957
+				&& $this->object_identifier->fqcnMatchesObjectIdentifier($class_name, $key)
958
+			) {
959
+				return $object;
960
+			}
961
+		}
962
+		return null;
963
+	}
964
+
965
+
966
+	/**
967
+	 * removes a cached version of the requested class
968
+	 *
969
+	 * @param string  $class_name
970
+	 * @param boolean $addon
971
+	 * @param array   $arguments
972
+	 * @return boolean
973
+	 */
974
+	public function clear_cached_class(
975
+		string $class_name,
976
+		bool $addon = false,
977
+		array $arguments = []
978
+	): bool {
979
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
980
+		// check if class has already been loaded, and return it if it has been
981
+		if (isset($this->{$class_abbreviation})) {
982
+			$this->{$class_abbreviation} = null;
983
+			return true;
984
+		}
985
+		$class_name = str_replace('\\', '_', $class_name);
986
+		if (isset($this->{$class_name})) {
987
+			$this->{$class_name} = null;
988
+			return true;
989
+		}
990
+		if ($addon && $this->addons->has($class_name)) {
991
+			$this->addons->remove($class_name);
992
+			return true;
993
+		}
994
+		$class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
995
+		if ($this->LIB->has($class_name)) {
996
+			$this->LIB->remove($class_name);
997
+			return true;
998
+		}
999
+		return false;
1000
+	}
1001
+
1002
+
1003
+	/**
1004
+	 * _set_cached_class
1005
+	 * attempts to cache the instantiated class locally
1006
+	 * in one of the following places, in the following order:
1007
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1008
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1009
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1010
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1011
+	 *
1012
+	 * @param object $class_obj
1013
+	 * @param string $class_name
1014
+	 * @param string $class_prefix
1015
+	 * @param bool   $from_db
1016
+	 * @param array  $arguments
1017
+	 * @return void
1018
+	 */
1019
+	protected function _set_cached_class(
1020
+		$class_obj,
1021
+		string $class_name,
1022
+		string $class_prefix = '',
1023
+		bool $from_db = false,
1024
+		array $arguments = []
1025
+	) {
1026
+		if ($class_name === 'EE_Registry' || empty($class_obj)) {
1027
+			return;
1028
+		}
1029
+		// return newly instantiated class
1030
+		$class_abbreviation = $this->get_class_abbreviation($class_name, '');
1031
+		if ($class_abbreviation) {
1032
+			$this->{$class_abbreviation} = $class_obj;
1033
+			return;
1034
+		}
1035
+		$class_name = str_replace('\\', '_', $class_name);
1036
+		if (property_exists($this, $class_name)) {
1037
+			$this->{$class_name} = $class_obj;
1038
+			return;
1039
+		}
1040
+		if ($class_prefix === 'addon') {
1041
+			$this->addons->add($class_name, $class_obj);
1042
+			return;
1043
+		}
1044
+		if (! $from_db) {
1045
+			$class_name = $this->object_identifier->getIdentifier($class_name, $arguments);
1046
+			$this->LIB->add($class_name, $class_obj);
1047
+		}
1048
+	}
1049
+
1050
+
1051
+	/**
1052
+	 * attempts to find a full valid filepath for the requested class.
1053
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
1054
+	 * then returns that path if the target file has been found and is readable
1055
+	 *
1056
+	 * @param string $class_name
1057
+	 * @param string $type
1058
+	 * @param array  $file_paths
1059
+	 * @return string | bool
1060
+	 */
1061
+	protected function _resolve_path(string $class_name, string $type = '', array $file_paths = [])
1062
+	{
1063
+		// make sure $file_paths is an array
1064
+		$file_paths = is_array($file_paths)
1065
+			? $file_paths
1066
+			: [$file_paths];
1067
+		// cycle thru paths
1068
+		foreach ($file_paths as $key => $file_path) {
1069
+			// convert all separators to proper /, if no filepath, then use EE_CLASSES
1070
+			$file_path = $file_path
1071
+				? str_replace(['/', '\\'], '/', $file_path)
1072
+				: EE_CLASSES;
1073
+			// prep file type
1074
+			$type = ! empty($type)
1075
+				? trim($type, '.') . '.'
1076
+				: '';
1077
+			// build full file path
1078
+			$file_paths[ $key ] = rtrim($file_path, '/') . '/' . $class_name . '.' . $type . 'php';
1079
+			// does the file exist and can be read ?
1080
+			if (is_readable($file_paths[ $key ])) {
1081
+				return $file_paths[ $key ];
1082
+			}
1083
+		}
1084
+		return false;
1085
+	}
1086
+
1087
+
1088
+	/**
1089
+	 * basically just performs a require_once()
1090
+	 * but with some error handling
1091
+	 *
1092
+	 * @param string $path
1093
+	 * @param string $class_name
1094
+	 * @param string $type
1095
+	 * @param array  $file_paths
1096
+	 * @return bool
1097
+	 * @throws EE_Error
1098
+	 * @throws ReflectionException
1099
+	 */
1100
+	protected function _require_file(string $path, string $class_name, string $type = '', array $file_paths = []): bool
1101
+	{
1102
+		$this->resolve_legacy_class_parent($class_name);
1103
+		// don't give up! you gotta...
1104
+		try {
1105
+			// does the file exist and can it be read ?
1106
+			if (! $path) {
1107
+				// just in case the file has already been autoloaded,
1108
+				// but discrepancies in the naming schema are preventing it from
1109
+				// being loaded via one of the EE_Registry::load_*() methods,
1110
+				// then let's try one last hail mary before throwing an exception
1111
+				// and call class_exists() again, but with autoloading turned ON
1112
+				if (class_exists($class_name)) {
1113
+					return true;
1114
+				}
1115
+				// so sorry, can't find the file
1116
+				throw new EE_Error(
1117
+					sprintf(
1118
+						esc_html__(
1119
+							'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
1120
+							'event_espresso'
1121
+						),
1122
+						trim($type, '.'),
1123
+						$class_name,
1124
+						'<br />' . implode(',<br />', $file_paths)
1125
+					)
1126
+				);
1127
+			}
1128
+			// get the file
1129
+			require_once($path);
1130
+			// if the class isn't already declared somewhere
1131
+			if (class_exists($class_name, false) === false) {
1132
+				// so sorry, not a class
1133
+				throw new EE_Error(
1134
+					sprintf(
1135
+						esc_html__(
1136
+							'The %s file %s does not appear to contain the %s Class.',
1137
+							'event_espresso'
1138
+						),
1139
+						$type,
1140
+						$path,
1141
+						$class_name
1142
+					)
1143
+				);
1144
+			}
1145
+		} catch (EE_Error $e) {
1146
+			$e->get_error();
1147
+			return false;
1148
+		}
1149
+		return true;
1150
+	}
1151
+
1152
+
1153
+	/**
1154
+	 * Some of our legacy classes that extended a parent class would simply use a require() statement
1155
+	 * before their class declaration in order to ensure that the parent class was loaded.
1156
+	 * This is not ideal, but it's nearly impossible to determine the parent class of a non-namespaced class,
1157
+	 * without triggering a fatal error because the parent class has yet to be loaded and therefore doesn't exist.
1158
+	 *
1159
+	 * @param string $class_name
1160
+	 */
1161
+	protected function resolve_legacy_class_parent(string $class_name = '')
1162
+	{
1163
+		try {
1164
+			$legacy_parent_class_map = [
1165
+				'EE_Payment_Processor' => 'core/business/EE_Processor_Base.class.php',
1166
+			];
1167
+			if (isset($legacy_parent_class_map[ $class_name ])) {
1168
+				require_once EE_PLUGIN_DIR_PATH . $legacy_parent_class_map[ $class_name ];
1169
+			}
1170
+		} catch (Exception $exception) {
1171
+		}
1172
+	}
1173
+
1174
+
1175
+	/**
1176
+	 * _create_object
1177
+	 * Attempts to instantiate the requested class via any of the
1178
+	 * commonly used instantiation methods employed throughout EE.
1179
+	 * The priority for instantiation is as follows:
1180
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1181
+	 *        - model objects via their 'new_instance_from_db' method
1182
+	 *        - model objects via their 'new_instance' method
1183
+	 *        - "singleton" classes" via their 'instance' method
1184
+	 *    - standard instantiable classes via their __constructor
1185
+	 * Prior to instantiation, if the classname exists in the dependency_map,
1186
+	 * then the constructor for the requested class will be examined to determine
1187
+	 * if any dependencies exist, and if they can be injected.
1188
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1189
+	 *
1190
+	 * @param string $class_name
1191
+	 * @param array  $arguments
1192
+	 * @param string $type
1193
+	 * @param bool   $from_db
1194
+	 * @return null|object|bool
1195
+	 * @throws InvalidArgumentException
1196
+	 * @throws InvalidInterfaceException
1197
+	 * @throws EE_Error
1198
+	 * @throws ReflectionException
1199
+	 * @throws InvalidDataTypeException
1200
+	 */
1201
+	protected function _create_object(
1202
+		string $class_name,
1203
+		array $arguments = [],
1204
+		string $type = '',
1205
+		bool $from_db = false
1206
+	) {
1207
+		// create reflection
1208
+		$reflector = $this->mirror->getReflectionClass($class_name);
1209
+		// make sure arguments are an array
1210
+		$arguments = is_array($arguments)
1211
+			? $arguments
1212
+			: [$arguments];
1213
+		// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1214
+		// else wrap it in an additional array so that it doesn't get split into multiple parameters
1215
+		$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1216
+			? $arguments
1217
+			: [$arguments];
1218
+		// attempt to inject dependencies ?
1219
+		if ($this->_dependency_map->has($class_name)) {
1220
+			$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1221
+		}
1222
+		// instantiate the class if possible
1223
+		if ($reflector->isAbstract()) {
1224
+			// nothing to instantiate, loading file was enough
1225
+			// does not throw an exception so $instantiation_mode is unused
1226
+			// $instantiation_mode = "1) no constructor abstract class";
1227
+			return true;
1228
+		}
1229
+		if (
1230
+			empty($arguments)
1231
+			&& $this->mirror->getConstructorFromReflection($reflector) === null
1232
+			&& $reflector->isInstantiable()
1233
+		) {
1234
+			// no constructor = static methods only... nothing to instantiate, loading file was enough
1235
+			// $instantiation_mode = "2) no constructor but instantiable";
1236
+			return $reflector->newInstance();
1237
+		}
1238
+		if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1239
+			// $instantiation_mode = "3) new_instance_from_db()";
1240
+			return call_user_func_array([$class_name, 'new_instance_from_db'], $arguments);
1241
+		}
1242
+		if (method_exists($class_name, 'new_instance')) {
1243
+			// $instantiation_mode = "4) new_instance()";
1244
+			return call_user_func_array([$class_name, 'new_instance'], $arguments);
1245
+		}
1246
+		if (method_exists($class_name, 'instance')) {
1247
+			// $instantiation_mode = "5) instance()";
1248
+			return call_user_func_array([$class_name, 'instance'], $arguments);
1249
+		}
1250
+		if ($reflector->isInstantiable()) {
1251
+			$args_passed_count = count($arguments);
1252
+			$args_required_count = count($this->mirror->getRequiredParameters($class_name));
1253
+			if ($args_passed_count < $args_required_count) {
1254
+				throw new RuntimeException(
1255
+					sprintf(
1256
+						__(
1257
+							'Invalid arguments supplied for the %1$s class, %2$s were required but %3$s were passed.',
1258
+							'event_espresso'
1259
+						),
1260
+						$class_name,
1261
+						$args_required_count,
1262
+						$args_passed_count
1263
+					)
1264
+				);
1265
+			}
1266
+			// $instantiation_mode = "6) constructor";
1267
+			return $reflector->newInstanceArgs($arguments);
1268
+		}
1269
+		// heh ? something's not right !
1270
+		throw new EE_Error(
1271
+			sprintf(
1272
+				esc_html__('The %s file %s could not be instantiated.', 'event_espresso'),
1273
+				$type,
1274
+				$class_name
1275
+			)
1276
+		);
1277
+	}
1278
+
1279
+
1280
+	/**
1281
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1282
+	 * @param array $array
1283
+	 * @return bool
1284
+	 */
1285
+	protected function _array_is_numerically_and_sequentially_indexed(array $array): bool
1286
+	{
1287
+		return empty($array) || array_keys($array) === range(0, count($array) - 1);
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 * _resolve_dependencies
1293
+	 * examines the constructor for the requested class to determine
1294
+	 * if any dependencies exist, and if they can be injected.
1295
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1296
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
1297
+	 * For example:
1298
+	 *        if attempting to load a class "Foo" with the following constructor:
1299
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
1300
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
1301
+	 *        but only IF they are NOT already present in the incoming arguments array,
1302
+	 *        and the correct classes can be loaded
1303
+	 *
1304
+	 * @param ReflectionClass $reflector
1305
+	 * @param string          $class_name
1306
+	 * @param array           $arguments
1307
+	 * @return array
1308
+	 * @throws InvalidArgumentException
1309
+	 * @throws InvalidDataTypeException
1310
+	 * @throws InvalidInterfaceException
1311
+	 * @throws ReflectionException
1312
+	 */
1313
+	protected function _resolve_dependencies(
1314
+		ReflectionClass $reflector,
1315
+		string $class_name,
1316
+		array $arguments = []
1317
+	): array {
1318
+		// let's examine the constructor
1319
+		$constructor = $this->mirror->getConstructorFromReflection($reflector);
1320
+		// whu? huh? nothing?
1321
+		if (! $constructor) {
1322
+			return $arguments;
1323
+		}
1324
+		// get constructor parameters
1325
+		$params = $this->mirror->getParametersFromReflection($reflector);
1326
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1327
+		$argument_keys = array_keys($arguments);
1328
+		// now loop thru all the constructors' expected parameters
1329
+		foreach ($params as $index => $param) {
1330
+			try {
1331
+				// is this a dependency for a specific class ?
1332
+				$param_class = $this->mirror->getParameterClassName($param, $class_name, $index);
1333
+			} catch (ReflectionException $exception) {
1334
+				// uh-oh... most likely a legacy class that has not been autoloaded
1335
+				// let's try to derive the classname from what we have now
1336
+				// and hope that the property var name is close to the class name
1337
+				$param_class = $param->getName();
1338
+				$param_class = str_replace('_', ' ', $param_class);
1339
+				$param_class = ucwords($param_class);
1340
+				$param_class = str_replace(' ', '_', $param_class);
1341
+			}
1342
+			// BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1343
+			$param_class = $this->class_cache->isAlias($param_class, $class_name)
1344
+				? $this->class_cache->getFqnForAlias($param_class, $class_name)
1345
+				: $param_class;
1346
+			if (
1347
+				// param is not even a class
1348
+				($param_class === null || $this->parameterIsPrimitive($param_class))
1349
+				// and something already exists in the incoming arguments for this param
1350
+				&& array_key_exists($index, $argument_keys)
1351
+				&& isset($arguments[ $argument_keys[ $index ] ])
1352
+			) {
1353
+				// so let's skip this argument and move on to the next
1354
+				continue;
1355
+			}
1356
+			// parameter is type hinted as a class
1357
+			if ($param_class !== null) {
1358
+				// parameter exists as an incoming argument, AND it's the correct class
1359
+				if (
1360
+					array_key_exists($index, $argument_keys)
1361
+					&& isset($arguments[ $argument_keys[ $index ] ])
1362
+					&& $arguments[ $argument_keys[ $index ] ] instanceof $param_class
1363
+				) {
1364
+					// skip this argument and move on to the next
1365
+					continue;
1366
+				}
1367
+				// parameter should be injected
1368
+				if ($this->_dependency_map->has_dependency_for_class($class_name, $param_class)) {
1369
+					$arguments = $this->_resolve_dependency(
1370
+						$class_name,
1371
+						$param_class,
1372
+						$arguments,
1373
+						$index
1374
+					);
1375
+				}
1376
+			}
1377
+			if (empty($arguments[ $index ])) {
1378
+				$default_value = $this->mirror->getParameterDefaultValue(
1379
+					$param,
1380
+					$class_name,
1381
+					$index
1382
+				);
1383
+				// if there's no default value, and the incoming argument is an array (albeit empty), then use that
1384
+				$arguments[ $index ] = $default_value === null
1385
+									   && isset($arguments[ $index ])
1386
+									   && is_array($arguments[ $index ])
1387
+					? $arguments[ $index ]
1388
+					: $default_value;
1389
+			}
1390
+		}
1391
+		return $arguments;
1392
+	}
1393
+
1394
+
1395
+	/**
1396
+	 * @param string $class_name
1397
+	 * @param string $param_class
1398
+	 * @param array  $arguments
1399
+	 * @param mixed  $index
1400
+	 * @return array
1401
+	 * @throws InvalidArgumentException
1402
+	 * @throws InvalidInterfaceException
1403
+	 * @throws InvalidDataTypeException
1404
+	 */
1405
+	protected function _resolve_dependency(string $class_name, string $param_class, array $arguments, $index): array
1406
+	{
1407
+		$dependency = null;
1408
+		// should dependency be loaded from cache ?
1409
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1410
+			$class_name,
1411
+			$param_class
1412
+		);
1413
+		$cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1414
+		// we might have a dependency...
1415
+		// let's MAYBE try and find it in our cache if that's what's been requested
1416
+		$cached_class = $cache_on
1417
+			? $this->_get_cached_class($param_class)
1418
+			: null;
1419
+		// and grab it if it exists
1420
+		if ($cached_class instanceof $param_class) {
1421
+			$dependency = $cached_class;
1422
+		} elseif ($param_class !== $class_name) {
1423
+			// obtain the loader method from the dependency map
1424
+			$loader = $this->_dependency_map->class_loader($param_class);
1425
+			// is loader a custom closure ?
1426
+			if ($loader instanceof Closure) {
1427
+				$dependency = $loader($arguments);
1428
+			} else {
1429
+				// set the cache on property for the recursive loading call
1430
+				$this->_cache_on = $cache_on;
1431
+				// if not, then let's try and load it via the registry
1432
+				if ($loader && method_exists($this, $loader)) {
1433
+					$dependency = $this->{$loader}($param_class);
1434
+				} else {
1435
+					$dependency = LoaderFactory::getLoader()->load(
1436
+						$param_class,
1437
+						[],
1438
+						$cache_on
1439
+					);
1440
+				}
1441
+			}
1442
+		}
1443
+		// did we successfully find the correct dependency ?
1444
+		if ($dependency instanceof $param_class) {
1445
+			// then let's inject it into the incoming array of arguments at the correct location
1446
+			$arguments[ $index ] = $dependency;
1447
+		}
1448
+		return $arguments;
1449
+	}
1450
+
1451
+
1452
+	/**
1453
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1454
+	 *
1455
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1456
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1457
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1458
+	 * @param array  $arguments
1459
+	 * @return object
1460
+	 */
1461
+	public static function factory(string $classname, array $arguments = [])
1462
+	{
1463
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1464
+		if ($loader instanceof Closure) {
1465
+			return $loader($arguments);
1466
+		}
1467
+		if (method_exists(self::instance(), $loader)) {
1468
+			return self::instance()->{$loader}($classname, $arguments);
1469
+		}
1470
+		return null;
1471
+	}
1472
+
1473
+
1474
+	/**
1475
+	 * Gets the addon by its class name
1476
+	 *
1477
+	 * @param string $class_name
1478
+	 * @return EE_Addon
1479
+	 */
1480
+	public function getAddon(string $class_name): ?EE_Addon
1481
+	{
1482
+		$class_name = str_replace('\\', '_', $class_name);
1483
+		return $this->addons->{$class_name} ?? null;
1484
+	}
1485
+
1486
+
1487
+	/**
1488
+	 * removes the addon from the internal cache
1489
+	 *
1490
+	 * @param string $class_name
1491
+	 * @return void
1492
+	 */
1493
+	public function removeAddon(string $class_name)
1494
+	{
1495
+		$class_name = str_replace('\\', '_', $class_name);
1496
+		$this->addons->remove($class_name);
1497
+	}
1498
+
1499
+
1500
+	/**
1501
+	 * Gets the addon by its name/slug (not classname. For that, just
1502
+	 * use the get_addon() method above
1503
+	 *
1504
+	 * @param string $name
1505
+	 * @return EE_Addon
1506
+	 */
1507
+	public function get_addon_by_name(string $name): ?EE_Addon
1508
+	{
1509
+		foreach ($this->addons as $addon) {
1510
+			if ($addon->name() === $name) {
1511
+				return $addon;
1512
+			}
1513
+		}
1514
+		return null;
1515
+	}
1516
+
1517
+
1518
+	/**
1519
+	 * Gets an array of all the registered addons, where the keys are their names.
1520
+	 * (ie, what each returns for their name() function)
1521
+	 * They're already available on EE_Registry::instance()->addons as properties,
1522
+	 * where each property's name is the addon's classname,
1523
+	 * So if you just want to get the addon by classname,
1524
+	 * OR use the get_addon() method above.
1525
+	 * PLEASE  NOTE:
1526
+	 * addons with Fully Qualified Class Names
1527
+	 * have had the namespace separators converted to underscores,
1528
+	 * so a classname like Fully\Qualified\ClassName
1529
+	 * would have been converted to Fully_Qualified_ClassName
1530
+	 *
1531
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1532
+	 */
1533
+	public function get_addons_by_name(): array
1534
+	{
1535
+		$addons = [];
1536
+		foreach ($this->addons as $addon) {
1537
+			$addons[ $addon->name() ] = $addon;
1538
+		}
1539
+		return $addons;
1540
+	}
1541
+
1542
+
1543
+	/**
1544
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1545
+	 * a stale copy of it around
1546
+	 *
1547
+	 * @param string $model_name
1548
+	 * @return EEM_Base
1549
+	 * @throws EE_Error
1550
+	 * @throws ReflectionException
1551
+	 */
1552
+	public function reset_model(string $model_name): ?EEM_Base
1553
+	{
1554
+		$model_class_name = strpos($model_name, 'EEM_') !== 0
1555
+			? "EEM_$model_name"
1556
+			: $model_name;
1557
+		if (! $this->LIB->has($model_class_name)) {
1558
+			return null;
1559
+		}
1560
+		$model = $this->LIB->get($model_class_name);
1561
+		if (! $model instanceof EEM_Base) {
1562
+			return null;
1563
+		}
1564
+		// get that model reset it and make sure we nuke the old reference to it
1565
+		if ($model instanceof $model_class_name && is_callable([$model_class_name, 'reset'])) {
1566
+			$this->LIB->remove($model_class_name);
1567
+			$this->LIB->add($model_class_name, $model->reset());
1568
+		} else {
1569
+			throw new EE_Error(
1570
+				sprintf(
1571
+					esc_html__('Model %s does not have a method "reset"', 'event_espresso'),
1572
+					$model_name
1573
+				)
1574
+			);
1575
+		}
1576
+		return $model;
1577
+	}
1578
+
1579
+
1580
+	/**
1581
+	 * Resets the registry.
1582
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when
1583
+	 * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1584
+	 * - $_dependency_map
1585
+	 * - $_class_abbreviations
1586
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1587
+	 * - $REQ:  Still on the same request so no need to change.
1588
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1589
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1590
+	 * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1591
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1592
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1593
+	 *             switch or on the restore.
1594
+	 * - $modules
1595
+	 * - $shortcodes
1596
+	 * - $widgets
1597
+	 *
1598
+	 * @param boolean $hard             [deprecated]
1599
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1600
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1601
+	 *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1602
+	 * @param bool    $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1603
+	 *                                  client
1604
+	 *                                  code instead can just change the model context to a different blog id if
1605
+	 *                                  necessary
1606
+	 * @return EE_Registry
1607
+	 * @throws EE_Error
1608
+	 * @throws ReflectionException
1609
+	 */
1610
+	public static function reset(bool $hard = false, bool $reinstantiate = true, bool $reset_models = true): EE_Registry
1611
+	{
1612
+		$instance            = self::instance();
1613
+		$instance->_cache_on = true;
1614
+		// reset some "special" classes
1615
+		EEH_Activation::reset();
1616
+		$hard = apply_filters('FHEE__EE_Registry__reset__hard', $hard);
1617
+		$instance->CFG = EE_Config::reset($hard, $reinstantiate);
1618
+		$instance->CART = null;
1619
+		$instance->MRM = null;
1620
+		// messages reset
1621
+		EED_Messages::reset();
1622
+		// handle of objects cached on LIB
1623
+		foreach (['LIB', 'modules'] as $cache) {
1624
+			foreach ($instance->{$cache} as $class_name => $class) {
1625
+				if (self::_reset_and_unset_object($class, $reset_models)) {
1626
+					unset($instance->{$cache}->{$class_name});
1627
+				}
1628
+			}
1629
+		}
1630
+		return $instance;
1631
+	}
1632
+
1633
+
1634
+	/**
1635
+	 * if passed object implements ResettableInterface, then call it's reset() method
1636
+	 * if passed object implements InterminableInterface, then return false,
1637
+	 * to indicate that it should NOT be cleared from the Registry cache
1638
+	 *
1639
+	 * @param      $object
1640
+	 * @param bool $reset_models
1641
+	 * @return bool returns true if cached object should be unset
1642
+	 * @throws EE_Error
1643
+	 * @throws ReflectionException
1644
+	 */
1645
+	private static function _reset_and_unset_object($object, bool $reset_models): bool
1646
+	{
1647
+		if (! is_object($object)) {
1648
+			// don't unset anything that's not an object
1649
+			return false;
1650
+		}
1651
+		if ($object instanceof EED_Module) {
1652
+			$object::reset();
1653
+			// don't unset modules
1654
+			return false;
1655
+		}
1656
+		if ($object instanceof ResettableInterface) {
1657
+			if ($object instanceof EEM_Base) {
1658
+				if ($reset_models) {
1659
+					$object->reset();
1660
+					return true;
1661
+				}
1662
+				return false;
1663
+			}
1664
+			$object->reset();
1665
+			return true;
1666
+		}
1667
+		if (! $object instanceof InterminableInterface) {
1668
+			return true;
1669
+		}
1670
+		return false;
1671
+	}
1672
+
1673
+
1674
+	/**
1675
+	 * Gets all the custom post type models defined
1676
+	 *
1677
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1678
+	 */
1679
+	public function cpt_models(): array
1680
+	{
1681
+		$cpt_models = [];
1682
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1683
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1684
+				$cpt_models[ $short_name ] = $classname;
1685
+			}
1686
+		}
1687
+		return $cpt_models;
1688
+	}
1689
+
1690
+
1691
+	/**
1692
+	 * @return EE_Config
1693
+	 */
1694
+	public static function CFG(): EE_Config
1695
+	{
1696
+		return self::instance()->CFG;
1697
+	}
1698
+
1699
+
1700
+	/**
1701
+	 * @param string $class_name
1702
+	 * @return ReflectionClass
1703
+	 * @throws ReflectionException
1704
+	 * @throws InvalidDataTypeException
1705
+	 * @deprecated 4.9.62.p
1706
+	 */
1707
+	public function get_ReflectionClass(string $class_name): ReflectionClass
1708
+	{
1709
+		return $this->mirror->getReflectionClass($class_name);
1710
+	}
1711
+
1712
+	private function parameterIsPrimitive(?string $param_class): bool
1713
+	{
1714
+		return in_array(
1715
+			$param_class,
1716
+			[
1717
+				'array',
1718
+				'bool',
1719
+				'float',
1720
+				'int',
1721
+				'string',
1722
+			]
1723
+		);
1724
+	}
1725 1725
 }
Please login to merge, or discard this patch.
core/EE_Payment_Processor.core.php 1 patch
Indentation   +409 added lines, -409 removed lines patch added patch discarded remove patch
@@ -20,413 +20,413 @@
 block discarded – undo
20 20
  */
21 21
 class EE_Payment_Processor extends EE_Processor_Base implements ResettableInterface
22 22
 {
23
-    private static ?EE_Payment_Processor $_instance = null;
24
-
25
-    private IpnHandler $ipn_handler;
26
-
27
-    private PaymentProcessor $payment_processor;
28
-
29
-    private PostPaymentProcessor $post_payment_processor;
30
-
31
-    private RegistrationPayments $registration_payments;
32
-
33
-
34
-    /**
35
-     * @singleton method used to instantiate class object
36
-     * @param PaymentProcessor|null     $payment_processor
37
-     * @param PostPaymentProcessor|null $post_payment_processor
38
-     * @param RegistrationPayments|null $registration_payments
39
-     * @param IpnHandler|null           $ipn_handler
40
-     * @return EE_Payment_Processor instance
41
-     */
42
-    public static function instance(
43
-        ?PaymentProcessor $payment_processor = null,
44
-        ?PostPaymentProcessor $post_payment_processor = null,
45
-        ?RegistrationPayments $registration_payments = null,
46
-        ?IpnHandler $ipn_handler = null
47
-    ): EE_Payment_Processor {
48
-        // check if class object is instantiated
49
-        if (! EE_Payment_Processor::$_instance instanceof EE_Payment_Processor) {
50
-            EE_Payment_Processor::$_instance = new EE_Payment_Processor(
51
-                $payment_processor,
52
-                $post_payment_processor,
53
-                $registration_payments,
54
-                $ipn_handler
55
-            );
56
-        }
57
-        return EE_Payment_Processor::$_instance;
58
-    }
59
-
60
-
61
-    /**
62
-     * @return EE_Payment_Processor
63
-     */
64
-    public static function reset(): EE_Payment_Processor
65
-    {
66
-        EE_Payment_Processor::$_instance = null;
67
-        return EE_Payment_Processor::instance();
68
-    }
69
-
70
-
71
-    /**
72
-     * @param PaymentProcessor|null     $payment_processor
73
-     * @param PostPaymentProcessor|null $post_payment_processor
74
-     * @param RegistrationPayments|null $registration_payments
75
-     * @param IpnHandler|null           $ipn_handler
76
-     */
77
-    private function __construct(
78
-        ?PaymentProcessor $payment_processor,
79
-        ?PostPaymentProcessor $post_payment_processor,
80
-        ?RegistrationPayments $registration_payments,
81
-        ?IpnHandler $ipn_handler
82
-    ) {
83
-        $this->payment_processor      = $payment_processor instanceof PaymentProcessor
84
-            ? $payment_processor
85
-            : LoaderFactory::getShared(PaymentProcessor::class);
86
-        $this->post_payment_processor = $post_payment_processor instanceof PostPaymentProcessor
87
-            ? $post_payment_processor
88
-            : LoaderFactory::getShared(PostPaymentProcessor::class);
89
-        $this->registration_payments  = $registration_payments instanceof RegistrationPayments
90
-            ? $registration_payments
91
-            : LoaderFactory::getShared(RegistrationPayments::class);
92
-        $this->ipn_handler            = $ipn_handler instanceof IpnHandler
93
-            ? $ipn_handler
94
-            : LoaderFactory::getShared(IpnHandler::class);
95
-        do_action('AHEE__EE_Payment_Processor__construct');
96
-    }
97
-
98
-
99
-    /**
100
-     * Using the selected gateway, processes the payment for that transaction, and updates the transaction
101
-     * appropriately. Saves the payment that is generated
102
-     *
103
-     * @param EE_Payment_Method         $payment_method
104
-     * @param EE_Transaction            $transaction
105
-     * @param float|null                $amount       if only part of the transaction is to be paid for, how much.
106
-     *                                                Leave null if payment is for the full amount owing
107
-     * @param EE_Billing_Info_Form|null $billing_form (or probably null, if it's an offline or offsite payment method).
108
-     *                                                Receive_form_submission() should have
109
-     *                                                already been called on the billing form
110
-     *                                                (ie, its inputs should have their normalized values set).
111
-     * @param string|null               $return_url   string used mostly by offsite gateways to specify
112
-     *                                                where to go AFTER the offsite gateway
113
-     * @param string                    $method       like 'CART', indicates who the client who called this was
114
-     * @param bool                      $by_admin     TRUE if payment is being attempted from the admin
115
-     * @param bool                      $update_txn   whether to call
116
-     *                                                EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
117
-     * @param string                    $cancel_url   URL to return to if off-site payments are cancelled
118
-     * @return EE_Payment
119
-     * @throws EE_Error
120
-     * @throws ReflectionException
121
-     */
122
-    public function process_payment(
123
-        EE_Payment_Method $payment_method,
124
-        EE_Transaction $transaction,
125
-        ?float $amount = null,
126
-        ?EE_Billing_Info_Form $billing_form = null,
127
-        ?string $return_url = null,
128
-        string $method = 'CART',
129
-        bool $by_admin = false,
130
-        bool $update_txn = true,
131
-        string $cancel_url = ''
132
-    ): ?EE_Payment {
133
-        return $this->payment_processor->processPayment(
134
-            $payment_method,
135
-            $transaction,
136
-            $billing_form,
137
-            (float) $amount,
138
-            $by_admin,
139
-            $update_txn,
140
-            (string) $return_url,
141
-            $cancel_url,
142
-            $method
143
-        );
144
-    }
145
-
146
-
147
-    /**
148
-     * @param EE_Transaction|int $transaction
149
-     * @param EE_Payment_Method  $payment_method
150
-     * @return string
151
-     * @throws EE_Error
152
-     * @throws ReflectionException
153
-     */
154
-    public function get_ipn_url_for_payment_method($transaction, $payment_method): string
155
-    {
156
-        /** @type EE_Transaction $transaction */
157
-        $transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
158
-        return $this->ipn_handler->getIpnUrlForPaymentMethod($transaction, $payment_method);
159
-    }
160
-
161
-
162
-    /**
163
-     * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
164
-     * we can easily find what registration the IPN is for and what payment method.
165
-     * However, if not, we'll give all payment methods a chance to claim it and process it.
166
-     * If a payment is found for the IPN info, it is saved.
167
-     *
168
-     * @param array              $_req_data            form post data
169
-     * @param EE_Transaction|int $transaction          optional (or a transactions id)
170
-     * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
171
-     * @param boolean            $update_txn           whether to call
172
-     *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
173
-     * @param bool               $separate_IPN_request whether the IPN uses a separate request (true, like PayPal)
174
-     *                                                 or is processed manually (false, like Authorize.net)
175
-     * @return EE_Payment
176
-     * @throws EE_Error
177
-     * @throws Exception
178
-     * @throws ReflectionException
179
-     */
180
-    public function process_ipn(
181
-        $_req_data,
182
-        $transaction = null,
183
-        $payment_method = null,
184
-        $update_txn = true,
185
-        $separate_IPN_request = true
186
-    ) {
187
-        return $this->ipn_handler->processIPN(
188
-            (array) $_req_data,
189
-            $transaction,
190
-            $payment_method,
191
-            $update_txn,
192
-            $separate_IPN_request
193
-        );
194
-    }
195
-
196
-
197
-    /**
198
-     * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
199
-     *
200
-     * @param EE_Payment_Method|null $payment_method
201
-     * @param EE_Payment             $payment_to_refund
202
-     * @param array                  $refund_info
203
-     * @return EE_Payment
204
-     * @throws EE_Error
205
-     * @throws ReflectionException
206
-     */
207
-    public function process_refund(
208
-        ?EE_Payment_Method $payment_method,
209
-        EE_Payment $payment_to_refund,
210
-        array $refund_info = []
211
-    ): EE_Payment {
212
-        return $this->payment_processor->processRefund($payment_method, $payment_to_refund, $refund_info);
213
-    }
214
-
215
-
216
-    /**
217
-     * This should be called each time there may have been an update to a
218
-     * payment on a transaction (ie, we asked for a payment to process a
219
-     * payment for a transaction, or we told a payment method about an IPN, or
220
-     * we told a payment method to
221
-     * "finalize_payment_for" (a transaction), or we told a payment method to
222
-     * process a refund. This should handle firing the correct hooks to
223
-     * indicate
224
-     * what exactly happened and updating the transaction appropriately). This
225
-     * could be integrated directly into EE_Transaction upon save, but we want
226
-     * this logic to be separate from 'normal' plain-jane saving and updating
227
-     * of transactions and payments, and to be tied to payment processing.
228
-     * Note: this method DOES NOT save the payment passed into it. It is the responsibility
229
-     * of previous code to decide whether to save (because the payment passed into
230
-     * this method might be a temporary, never-to-be-saved payment from an offline gateway,
231
-     * in which case we only want that payment object for some temporary usage during this request,
232
-     * but we don't want it to be saved).
233
-     *
234
-     * @param EE_Transaction|int $transaction
235
-     * @param EE_Payment         $payment
236
-     * @param bool               $update_txn whether to call
237
-     *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
238
-     *                                       (you can save 1 DB query if you know you're going to save it later
239
-     *                                       instead)
240
-     * @param bool               $IPN        if processing IPNs or other similar payment related activities that occur
241
-     *                                       in alternate requests than the main one that is processing the TXN,
242
-     *                                       then set this to true to check whether the TXN is locked before updating
243
-     * @throws EE_Error
244
-     * @throws ReflectionException
245
-     */
246
-    public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
247
-    {
248
-        $this->payment_processor->updateTransactionBasedOnPayment(
249
-            $transaction,
250
-            $payment,
251
-            (bool) $update_txn,
252
-            (bool) $IPN
253
-        );
254
-    }
255
-
256
-
257
-    /**
258
-     * update registrations REG_paid field after successful payment and link registrations with payment
259
-     *
260
-     * @param EE_Transaction    $transaction
261
-     * @param EE_Payment        $payment
262
-     * @param EE_Registration[] $registrations
263
-     * @throws EE_Error
264
-     * @throws ReflectionException
265
-     */
266
-    public function process_registration_payments(
267
-        EE_Transaction $transaction,
268
-        EE_Payment $payment,
269
-        array $registrations = []
270
-    ) {
271
-        $this->registration_payments->processRegistrationPayments($transaction, $payment, $registrations);
272
-    }
273
-
274
-
275
-    /**
276
-     * update registration REG_paid field after successful payment and link registration with payment
277
-     *
278
-     * @param EE_Registration  $registration
279
-     * @param EE_Payment       $payment
280
-     * @param float|int|string $available_payment_amount
281
-     * @return float
282
-     * @throws EE_Error
283
-     * @throws ReflectionException
284
-     */
285
-    public function process_registration_payment(
286
-        EE_Registration $registration,
287
-        EE_Payment $payment,
288
-        $available_payment_amount = 0.00
289
-    ) {
290
-        return $this->registration_payments->processRegistrationPayment(
291
-            $registration,
292
-            $payment,
293
-            (float) $available_payment_amount
294
-        );
295
-    }
296
-
297
-
298
-    /**
299
-     * update registration REG_paid field after refund and link registration with payment
300
-     *
301
-     * @param EE_Registration $registration
302
-     * @param EE_Payment      $payment
303
-     * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
304
-     * @return float
305
-     * @throws EE_Error
306
-     * @throws ReflectionException
307
-     */
308
-    public function process_registration_refund(
309
-        EE_Registration $registration,
310
-        EE_Payment $payment,
311
-        float $available_refund_amount = 0.00
312
-    ): float {
313
-        return $this->registration_payments->processRegistrationRefund(
314
-            $registration,
315
-            $payment,
316
-            $available_refund_amount
317
-        );
318
-    }
319
-
320
-
321
-    /**
322
-     * Force posts to PayPal to use TLS v1.2. See:
323
-     * https://core.trac.wordpress.org/ticket/36320
324
-     * https://core.trac.wordpress.org/ticket/34924#comment:15
325
-     * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
326
-     * This will affect PayPal standard, pro, express, and Payflow.
327
-     *
328
-     * @param $handle
329
-     * @param $r
330
-     * @param $url
331
-     */
332
-    public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
333
-    {
334
-        if (strpos($url, 'https://') !== false && strpos($url, '.paypal.com') !== false) {
335
-            // Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
336
-            // instead of the constant because it might not be defined
337
-            curl_setopt($handle, CURLOPT_SSLVERSION, 6);
338
-        }
339
-    }
340
-
341
-
342
-    /**
343
-     * Process payments and transaction after payment process completed.
344
-     * ultimately this will send the TXN and payment details off so that notifications can be sent out.
345
-     * if this request happens to be processing an IPN,
346
-     * then we will also set the Payment Options Reg Step to completed,
347
-     * and attempt to completely finalize the TXN if all the other Reg Steps are completed as well.
348
-     *
349
-     * @param EE_Transaction $transaction
350
-     * @param EE_Payment     $payment
351
-     * @param bool           $IPN
352
-     * @throws EE_Error
353
-     * @throws ReflectionException
354
-     * @depecated 5.0.22.p
355
-     */
356
-    protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
357
-    {
358
-        $this->post_payment_processor->updateTransactionAndPayment($transaction, $payment, (bool) $IPN);
359
-    }
360
-
361
-
362
-    /**
363
-     * update registration REG_paid field after successful payment and link registration with payment
364
-     *
365
-     * @param EE_Registration $registration
366
-     * @param EE_Payment      $payment
367
-     * @param float           $payment_amount
368
-     * @return void
369
-     * @throws EE_Error
370
-     * @throws ReflectionException
371
-     * @depecated 5.0.22.p
372
-     */
373
-    protected function _apply_registration_payment(
374
-        EE_Registration $registration,
375
-        EE_Payment $payment,
376
-        $payment_amount = 0.00
377
-    ) {
378
-        // find any existing reg payment records for this registration and payment
379
-        $existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
380
-            [['REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()]]
381
-        );
382
-        // if existing registration payment exists
383
-        if ($existing_reg_payment instanceof EE_Registration_Payment) {
384
-            // then update that record
385
-            $existing_reg_payment->set_amount($payment_amount);
386
-            $existing_reg_payment->save();
387
-        } else {
388
-            // or add new relation between registration and payment and set amount
389
-            $registration->_add_relation_to(
390
-                $payment,
391
-                'Payment',
392
-                ['RPY_amount' => $payment_amount]
393
-            );
394
-            // make it stick
395
-            $registration->save();
396
-        }
397
-    }
398
-
399
-
400
-    /**
401
-     * Removes any non-printable illegal characters from the input,
402
-     * which might cause a raucous when trying to insert into the database
403
-     *
404
-     * @param array $request_data
405
-     * @return array
406
-     * @depecated 5.0.22.p
407
-     */
408
-    protected function _remove_unusable_characters_from_array(array $request_data)
409
-    {
410
-        $return_data = [];
411
-        foreach ($request_data as $key => $value) {
412
-            $return_data[ $this->_remove_unusable_characters($key) ] = $this->_remove_unusable_characters(
413
-                $value
414
-            );
415
-        }
416
-        return $return_data;
417
-    }
418
-
419
-
420
-    /**
421
-     * Removes any non-printable illegal characters from the input,
422
-     * which might cause a raucous when trying to insert into the database
423
-     *
424
-     * @param string $request_data
425
-     * @return string
426
-     * @depecated 5.0.22.p
427
-     */
428
-    protected function _remove_unusable_characters($request_data)
429
-    {
430
-        return preg_replace('/[^[:print:]]/', '', $request_data);
431
-    }
23
+	private static ?EE_Payment_Processor $_instance = null;
24
+
25
+	private IpnHandler $ipn_handler;
26
+
27
+	private PaymentProcessor $payment_processor;
28
+
29
+	private PostPaymentProcessor $post_payment_processor;
30
+
31
+	private RegistrationPayments $registration_payments;
32
+
33
+
34
+	/**
35
+	 * @singleton method used to instantiate class object
36
+	 * @param PaymentProcessor|null     $payment_processor
37
+	 * @param PostPaymentProcessor|null $post_payment_processor
38
+	 * @param RegistrationPayments|null $registration_payments
39
+	 * @param IpnHandler|null           $ipn_handler
40
+	 * @return EE_Payment_Processor instance
41
+	 */
42
+	public static function instance(
43
+		?PaymentProcessor $payment_processor = null,
44
+		?PostPaymentProcessor $post_payment_processor = null,
45
+		?RegistrationPayments $registration_payments = null,
46
+		?IpnHandler $ipn_handler = null
47
+	): EE_Payment_Processor {
48
+		// check if class object is instantiated
49
+		if (! EE_Payment_Processor::$_instance instanceof EE_Payment_Processor) {
50
+			EE_Payment_Processor::$_instance = new EE_Payment_Processor(
51
+				$payment_processor,
52
+				$post_payment_processor,
53
+				$registration_payments,
54
+				$ipn_handler
55
+			);
56
+		}
57
+		return EE_Payment_Processor::$_instance;
58
+	}
59
+
60
+
61
+	/**
62
+	 * @return EE_Payment_Processor
63
+	 */
64
+	public static function reset(): EE_Payment_Processor
65
+	{
66
+		EE_Payment_Processor::$_instance = null;
67
+		return EE_Payment_Processor::instance();
68
+	}
69
+
70
+
71
+	/**
72
+	 * @param PaymentProcessor|null     $payment_processor
73
+	 * @param PostPaymentProcessor|null $post_payment_processor
74
+	 * @param RegistrationPayments|null $registration_payments
75
+	 * @param IpnHandler|null           $ipn_handler
76
+	 */
77
+	private function __construct(
78
+		?PaymentProcessor $payment_processor,
79
+		?PostPaymentProcessor $post_payment_processor,
80
+		?RegistrationPayments $registration_payments,
81
+		?IpnHandler $ipn_handler
82
+	) {
83
+		$this->payment_processor      = $payment_processor instanceof PaymentProcessor
84
+			? $payment_processor
85
+			: LoaderFactory::getShared(PaymentProcessor::class);
86
+		$this->post_payment_processor = $post_payment_processor instanceof PostPaymentProcessor
87
+			? $post_payment_processor
88
+			: LoaderFactory::getShared(PostPaymentProcessor::class);
89
+		$this->registration_payments  = $registration_payments instanceof RegistrationPayments
90
+			? $registration_payments
91
+			: LoaderFactory::getShared(RegistrationPayments::class);
92
+		$this->ipn_handler            = $ipn_handler instanceof IpnHandler
93
+			? $ipn_handler
94
+			: LoaderFactory::getShared(IpnHandler::class);
95
+		do_action('AHEE__EE_Payment_Processor__construct');
96
+	}
97
+
98
+
99
+	/**
100
+	 * Using the selected gateway, processes the payment for that transaction, and updates the transaction
101
+	 * appropriately. Saves the payment that is generated
102
+	 *
103
+	 * @param EE_Payment_Method         $payment_method
104
+	 * @param EE_Transaction            $transaction
105
+	 * @param float|null                $amount       if only part of the transaction is to be paid for, how much.
106
+	 *                                                Leave null if payment is for the full amount owing
107
+	 * @param EE_Billing_Info_Form|null $billing_form (or probably null, if it's an offline or offsite payment method).
108
+	 *                                                Receive_form_submission() should have
109
+	 *                                                already been called on the billing form
110
+	 *                                                (ie, its inputs should have their normalized values set).
111
+	 * @param string|null               $return_url   string used mostly by offsite gateways to specify
112
+	 *                                                where to go AFTER the offsite gateway
113
+	 * @param string                    $method       like 'CART', indicates who the client who called this was
114
+	 * @param bool                      $by_admin     TRUE if payment is being attempted from the admin
115
+	 * @param bool                      $update_txn   whether to call
116
+	 *                                                EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
117
+	 * @param string                    $cancel_url   URL to return to if off-site payments are cancelled
118
+	 * @return EE_Payment
119
+	 * @throws EE_Error
120
+	 * @throws ReflectionException
121
+	 */
122
+	public function process_payment(
123
+		EE_Payment_Method $payment_method,
124
+		EE_Transaction $transaction,
125
+		?float $amount = null,
126
+		?EE_Billing_Info_Form $billing_form = null,
127
+		?string $return_url = null,
128
+		string $method = 'CART',
129
+		bool $by_admin = false,
130
+		bool $update_txn = true,
131
+		string $cancel_url = ''
132
+	): ?EE_Payment {
133
+		return $this->payment_processor->processPayment(
134
+			$payment_method,
135
+			$transaction,
136
+			$billing_form,
137
+			(float) $amount,
138
+			$by_admin,
139
+			$update_txn,
140
+			(string) $return_url,
141
+			$cancel_url,
142
+			$method
143
+		);
144
+	}
145
+
146
+
147
+	/**
148
+	 * @param EE_Transaction|int $transaction
149
+	 * @param EE_Payment_Method  $payment_method
150
+	 * @return string
151
+	 * @throws EE_Error
152
+	 * @throws ReflectionException
153
+	 */
154
+	public function get_ipn_url_for_payment_method($transaction, $payment_method): string
155
+	{
156
+		/** @type EE_Transaction $transaction */
157
+		$transaction = EEM_Transaction::instance()->ensure_is_obj($transaction);
158
+		return $this->ipn_handler->getIpnUrlForPaymentMethod($transaction, $payment_method);
159
+	}
160
+
161
+
162
+	/**
163
+	 * Process the IPN. Firstly, we'll hope we put the standard args into the IPN URL so
164
+	 * we can easily find what registration the IPN is for and what payment method.
165
+	 * However, if not, we'll give all payment methods a chance to claim it and process it.
166
+	 * If a payment is found for the IPN info, it is saved.
167
+	 *
168
+	 * @param array              $_req_data            form post data
169
+	 * @param EE_Transaction|int $transaction          optional (or a transactions id)
170
+	 * @param EE_Payment_Method  $payment_method       (or a slug or id of one)
171
+	 * @param boolean            $update_txn           whether to call
172
+	 *                                                 EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
173
+	 * @param bool               $separate_IPN_request whether the IPN uses a separate request (true, like PayPal)
174
+	 *                                                 or is processed manually (false, like Authorize.net)
175
+	 * @return EE_Payment
176
+	 * @throws EE_Error
177
+	 * @throws Exception
178
+	 * @throws ReflectionException
179
+	 */
180
+	public function process_ipn(
181
+		$_req_data,
182
+		$transaction = null,
183
+		$payment_method = null,
184
+		$update_txn = true,
185
+		$separate_IPN_request = true
186
+	) {
187
+		return $this->ipn_handler->processIPN(
188
+			(array) $_req_data,
189
+			$transaction,
190
+			$payment_method,
191
+			$update_txn,
192
+			$separate_IPN_request
193
+		);
194
+	}
195
+
196
+
197
+	/**
198
+	 * Processes a direct refund request, saves the payment, and updates the transaction appropriately.
199
+	 *
200
+	 * @param EE_Payment_Method|null $payment_method
201
+	 * @param EE_Payment             $payment_to_refund
202
+	 * @param array                  $refund_info
203
+	 * @return EE_Payment
204
+	 * @throws EE_Error
205
+	 * @throws ReflectionException
206
+	 */
207
+	public function process_refund(
208
+		?EE_Payment_Method $payment_method,
209
+		EE_Payment $payment_to_refund,
210
+		array $refund_info = []
211
+	): EE_Payment {
212
+		return $this->payment_processor->processRefund($payment_method, $payment_to_refund, $refund_info);
213
+	}
214
+
215
+
216
+	/**
217
+	 * This should be called each time there may have been an update to a
218
+	 * payment on a transaction (ie, we asked for a payment to process a
219
+	 * payment for a transaction, or we told a payment method about an IPN, or
220
+	 * we told a payment method to
221
+	 * "finalize_payment_for" (a transaction), or we told a payment method to
222
+	 * process a refund. This should handle firing the correct hooks to
223
+	 * indicate
224
+	 * what exactly happened and updating the transaction appropriately). This
225
+	 * could be integrated directly into EE_Transaction upon save, but we want
226
+	 * this logic to be separate from 'normal' plain-jane saving and updating
227
+	 * of transactions and payments, and to be tied to payment processing.
228
+	 * Note: this method DOES NOT save the payment passed into it. It is the responsibility
229
+	 * of previous code to decide whether to save (because the payment passed into
230
+	 * this method might be a temporary, never-to-be-saved payment from an offline gateway,
231
+	 * in which case we only want that payment object for some temporary usage during this request,
232
+	 * but we don't want it to be saved).
233
+	 *
234
+	 * @param EE_Transaction|int $transaction
235
+	 * @param EE_Payment         $payment
236
+	 * @param bool               $update_txn whether to call
237
+	 *                                       EE_Transaction_Processor::update_transaction_and_registrations_after_checkout_or_payment()
238
+	 *                                       (you can save 1 DB query if you know you're going to save it later
239
+	 *                                       instead)
240
+	 * @param bool               $IPN        if processing IPNs or other similar payment related activities that occur
241
+	 *                                       in alternate requests than the main one that is processing the TXN,
242
+	 *                                       then set this to true to check whether the TXN is locked before updating
243
+	 * @throws EE_Error
244
+	 * @throws ReflectionException
245
+	 */
246
+	public function update_txn_based_on_payment($transaction, $payment, $update_txn = true, $IPN = false)
247
+	{
248
+		$this->payment_processor->updateTransactionBasedOnPayment(
249
+			$transaction,
250
+			$payment,
251
+			(bool) $update_txn,
252
+			(bool) $IPN
253
+		);
254
+	}
255
+
256
+
257
+	/**
258
+	 * update registrations REG_paid field after successful payment and link registrations with payment
259
+	 *
260
+	 * @param EE_Transaction    $transaction
261
+	 * @param EE_Payment        $payment
262
+	 * @param EE_Registration[] $registrations
263
+	 * @throws EE_Error
264
+	 * @throws ReflectionException
265
+	 */
266
+	public function process_registration_payments(
267
+		EE_Transaction $transaction,
268
+		EE_Payment $payment,
269
+		array $registrations = []
270
+	) {
271
+		$this->registration_payments->processRegistrationPayments($transaction, $payment, $registrations);
272
+	}
273
+
274
+
275
+	/**
276
+	 * update registration REG_paid field after successful payment and link registration with payment
277
+	 *
278
+	 * @param EE_Registration  $registration
279
+	 * @param EE_Payment       $payment
280
+	 * @param float|int|string $available_payment_amount
281
+	 * @return float
282
+	 * @throws EE_Error
283
+	 * @throws ReflectionException
284
+	 */
285
+	public function process_registration_payment(
286
+		EE_Registration $registration,
287
+		EE_Payment $payment,
288
+		$available_payment_amount = 0.00
289
+	) {
290
+		return $this->registration_payments->processRegistrationPayment(
291
+			$registration,
292
+			$payment,
293
+			(float) $available_payment_amount
294
+		);
295
+	}
296
+
297
+
298
+	/**
299
+	 * update registration REG_paid field after refund and link registration with payment
300
+	 *
301
+	 * @param EE_Registration $registration
302
+	 * @param EE_Payment      $payment
303
+	 * @param float           $available_refund_amount - IMPORTANT !!! SEND AVAILABLE REFUND AMOUNT AS A POSITIVE NUMBER
304
+	 * @return float
305
+	 * @throws EE_Error
306
+	 * @throws ReflectionException
307
+	 */
308
+	public function process_registration_refund(
309
+		EE_Registration $registration,
310
+		EE_Payment $payment,
311
+		float $available_refund_amount = 0.00
312
+	): float {
313
+		return $this->registration_payments->processRegistrationRefund(
314
+			$registration,
315
+			$payment,
316
+			$available_refund_amount
317
+		);
318
+	}
319
+
320
+
321
+	/**
322
+	 * Force posts to PayPal to use TLS v1.2. See:
323
+	 * https://core.trac.wordpress.org/ticket/36320
324
+	 * https://core.trac.wordpress.org/ticket/34924#comment:15
325
+	 * https://www.paypal-knowledge.com/infocenter/index?page=content&widgetview=true&id=FAQ1914&viewlocale=en_US
326
+	 * This will affect PayPal standard, pro, express, and Payflow.
327
+	 *
328
+	 * @param $handle
329
+	 * @param $r
330
+	 * @param $url
331
+	 */
332
+	public static function _curl_requests_to_paypal_use_tls($handle, $r, $url)
333
+	{
334
+		if (strpos($url, 'https://') !== false && strpos($url, '.paypal.com') !== false) {
335
+			// Use the value of the constant CURL_SSLVERSION_TLSv1 = 1
336
+			// instead of the constant because it might not be defined
337
+			curl_setopt($handle, CURLOPT_SSLVERSION, 6);
338
+		}
339
+	}
340
+
341
+
342
+	/**
343
+	 * Process payments and transaction after payment process completed.
344
+	 * ultimately this will send the TXN and payment details off so that notifications can be sent out.
345
+	 * if this request happens to be processing an IPN,
346
+	 * then we will also set the Payment Options Reg Step to completed,
347
+	 * and attempt to completely finalize the TXN if all the other Reg Steps are completed as well.
348
+	 *
349
+	 * @param EE_Transaction $transaction
350
+	 * @param EE_Payment     $payment
351
+	 * @param bool           $IPN
352
+	 * @throws EE_Error
353
+	 * @throws ReflectionException
354
+	 * @depecated 5.0.22.p
355
+	 */
356
+	protected function _post_payment_processing(EE_Transaction $transaction, EE_Payment $payment, $IPN = false)
357
+	{
358
+		$this->post_payment_processor->updateTransactionAndPayment($transaction, $payment, (bool) $IPN);
359
+	}
360
+
361
+
362
+	/**
363
+	 * update registration REG_paid field after successful payment and link registration with payment
364
+	 *
365
+	 * @param EE_Registration $registration
366
+	 * @param EE_Payment      $payment
367
+	 * @param float           $payment_amount
368
+	 * @return void
369
+	 * @throws EE_Error
370
+	 * @throws ReflectionException
371
+	 * @depecated 5.0.22.p
372
+	 */
373
+	protected function _apply_registration_payment(
374
+		EE_Registration $registration,
375
+		EE_Payment $payment,
376
+		$payment_amount = 0.00
377
+	) {
378
+		// find any existing reg payment records for this registration and payment
379
+		$existing_reg_payment = EEM_Registration_Payment::instance()->get_one(
380
+			[['REG_ID' => $registration->ID(), 'PAY_ID' => $payment->ID()]]
381
+		);
382
+		// if existing registration payment exists
383
+		if ($existing_reg_payment instanceof EE_Registration_Payment) {
384
+			// then update that record
385
+			$existing_reg_payment->set_amount($payment_amount);
386
+			$existing_reg_payment->save();
387
+		} else {
388
+			// or add new relation between registration and payment and set amount
389
+			$registration->_add_relation_to(
390
+				$payment,
391
+				'Payment',
392
+				['RPY_amount' => $payment_amount]
393
+			);
394
+			// make it stick
395
+			$registration->save();
396
+		}
397
+	}
398
+
399
+
400
+	/**
401
+	 * Removes any non-printable illegal characters from the input,
402
+	 * which might cause a raucous when trying to insert into the database
403
+	 *
404
+	 * @param array $request_data
405
+	 * @return array
406
+	 * @depecated 5.0.22.p
407
+	 */
408
+	protected function _remove_unusable_characters_from_array(array $request_data)
409
+	{
410
+		$return_data = [];
411
+		foreach ($request_data as $key => $value) {
412
+			$return_data[ $this->_remove_unusable_characters($key) ] = $this->_remove_unusable_characters(
413
+				$value
414
+			);
415
+		}
416
+		return $return_data;
417
+	}
418
+
419
+
420
+	/**
421
+	 * Removes any non-printable illegal characters from the input,
422
+	 * which might cause a raucous when trying to insert into the database
423
+	 *
424
+	 * @param string $request_data
425
+	 * @return string
426
+	 * @depecated 5.0.22.p
427
+	 */
428
+	protected function _remove_unusable_characters($request_data)
429
+	{
430
+		return preg_replace('/[^[:print:]]/', '', $request_data);
431
+	}
432 432
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Event.class.php 1 patch
Indentation   +1634 added lines, -1634 removed lines patch added patch discarded remove patch
@@ -16,1641 +16,1641 @@
 block discarded – undo
16 16
  */
17 17
 class EE_Event extends EE_CPT_Base implements EEI_Line_Item_Object, EEI_Admin_Links, EEI_Has_Icon, EEI_Event
18 18
 {
19
-    /**
20
-     * cached value for the the logical active status for the event
21
-     *
22
-     * @see get_active_status()
23
-     * @var string
24
-     */
25
-    protected $_active_status = '';
26
-
27
-    /**
28
-     * This is just used for caching the Primary Datetime for the Event on initial retrieval
29
-     *
30
-     * @var EE_Datetime
31
-     */
32
-    protected $_Primary_Datetime;
33
-
34
-    /**
35
-     * @var EventSpacesCalculator $available_spaces_calculator
36
-     */
37
-    protected $available_spaces_calculator;
38
-
39
-
40
-    /**
41
-     * @param array  $props_n_values          incoming values
42
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
43
-     *                                        used.)
44
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
45
-     *                                        date_format and the second value is the time format
46
-     * @return EE_Event
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = []): EE_Event
51
-    {
52
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
53
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
54
-    }
55
-
56
-
57
-    /**
58
-     * @param array  $props_n_values  incoming values from the database
59
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
60
-     *                                the website will be used.
61
-     * @return EE_Event
62
-     * @throws EE_Error
63
-     * @throws ReflectionException
64
-     */
65
-    public static function new_instance_from_db($props_n_values = [], $timezone = ''): EE_Event
66
-    {
67
-        return new self($props_n_values, true, $timezone);
68
-    }
69
-
70
-
71
-    /**
72
-     * @return EventSpacesCalculator
73
-     * @throws EE_Error
74
-     * @throws ReflectionException
75
-     */
76
-    public function getAvailableSpacesCalculator(): EventSpacesCalculator
77
-    {
78
-        if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79
-            $this->available_spaces_calculator = new EventSpacesCalculator($this);
80
-        }
81
-        return $this->available_spaces_calculator;
82
-    }
83
-
84
-
85
-    /**
86
-     * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
87
-     *
88
-     * @param string $field_name
89
-     * @param mixed  $field_value
90
-     * @param bool   $use_default
91
-     * @throws EE_Error
92
-     * @throws ReflectionException
93
-     */
94
-    public function set($field_name, $field_value, $use_default = false)
95
-    {
96
-        switch ($field_name) {
97
-            case 'status':
98
-                $this->set_status($field_value, $use_default);
99
-                break;
100
-            default:
101
-                parent::set($field_name, $field_value, $use_default);
102
-        }
103
-    }
104
-
105
-
106
-    /**
107
-     *    set_status
108
-     * Checks if event status is being changed to SOLD OUT
109
-     * and updates event meta data with previous event status
110
-     * so that we can revert things if/when the event is no longer sold out
111
-     *
112
-     * @param string $status
113
-     * @param bool   $use_default
114
-     * @return void
115
-     * @throws EE_Error
116
-     * @throws ReflectionException
117
-     */
118
-    public function set_status($status = '', $use_default = false)
119
-    {
120
-        // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($status) && ! $use_default) {
122
-            return;
123
-        }
124
-        // get current Event status
125
-        $old_status = $this->status();
126
-        // if status has changed
127
-        if ($old_status !== $status) {
128
-            // TO sold_out
129
-            if ($status === EEM_Event::sold_out) {
130
-                // save the previous event status so that we can revert if the event is no longer sold out
131
-                $this->add_post_meta('_previous_event_status', $old_status);
132
-                do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $status);
133
-                // OR FROM  sold_out
134
-            } elseif ($old_status === EEM_Event::sold_out) {
135
-                $this->delete_post_meta('_previous_event_status');
136
-                do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $status);
137
-            }
138
-            // clear out the active status so that it gets reset the next time it is requested
139
-            $this->_active_status = null;
140
-            // update status
141
-            parent::set('status', $status, $use_default);
142
-            do_action('AHEE__EE_Event__set_status__after_update', $this);
143
-            return;
144
-        }
145
-        // even though the old value matches the new value, it's still good to
146
-        // allow the parent set method to have a say
147
-        parent::set('status', $status, $use_default);
148
-    }
149
-
150
-
151
-    /**
152
-     * Gets all the datetimes for this event
153
-     *
154
-     * @param array|null $query_params
155
-     * @return EE_Base_Class[]|EE_Datetime[]
156
-     * @throws EE_Error
157
-     * @throws ReflectionException
158
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
159
-     */
160
-    public function datetimes(?array $query_params = []): array
161
-    {
162
-        return $this->get_many_related('Datetime', $query_params);
163
-    }
164
-
165
-
166
-    /**
167
-     * Gets all the datetimes for this event that are currently ACTIVE,
168
-     * meaning the datetime has started and has not yet ended.
169
-     *
170
-     * @param int|null   $start_date   timestamp to use for event date start time, defaults to NOW unless set to 0
171
-     * @param array|null $query_params will recursively replace default values
172
-     * @throws EE_Error
173
-     * @throws ReflectionException
174
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
175
-     */
176
-    public function activeDatetimes(?int $start_date, ?array $query_params = []): array
177
-    {
178
-        // if start date is null, then use current time
179
-        $start_date = $start_date ?? time();
180
-        $where      = [];
181
-        if ($start_date) {
182
-            $where['DTT_EVT_start'] = ['<', $start_date];
183
-            $where['DTT_EVT_end']   = ['>', time()];
184
-        }
185
-        $query_params = array_replace_recursive(
186
-            [
187
-                $where,
188
-                'order_by' => ['DTT_EVT_start' => 'ASC'],
189
-            ],
190
-            $query_params
191
-        );
192
-        return $this->get_many_related('Datetime', $query_params);
193
-    }
194
-
195
-
196
-    /**
197
-     * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
198
-     *
199
-     * @return EE_Base_Class[]|EE_Datetime[]
200
-     * @throws EE_Error
201
-     * @throws ReflectionException
202
-     */
203
-    public function datetimes_in_chronological_order(): array
204
-    {
205
-        return $this->get_many_related('Datetime', ['order_by' => ['DTT_EVT_start' => 'ASC']]);
206
-    }
207
-
208
-
209
-    /**
210
-     * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
211
-     * @darren, we should probably UNSET timezone on the EEM_Datetime model
212
-     * after running our query, so that this timezone isn't set for EVERY query
213
-     * on EEM_Datetime for the rest of the request, no?
214
-     *
215
-     * @param bool     $show_expired whether or not to include expired events
216
-     * @param bool     $show_deleted whether or not to include deleted events
217
-     * @param int|null $limit
218
-     * @return EE_Datetime[]
219
-     * @throws EE_Error
220
-     * @throws ReflectionException
221
-     */
222
-    public function datetimes_ordered(bool $show_expired = true, bool $show_deleted = false, ?int $limit = null): array
223
-    {
224
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
225
-            $this->ID(),
226
-            $show_expired,
227
-            $show_deleted,
228
-            $limit
229
-        );
230
-    }
231
-
232
-
233
-    /**
234
-     * Returns one related datetime. Mostly only used by some legacy code.
235
-     *
236
-     * @return EE_Base_Class|EE_Datetime
237
-     * @throws EE_Error
238
-     * @throws ReflectionException
239
-     */
240
-    public function first_datetime(): EE_Datetime
241
-    {
242
-        return $this->get_first_related('Datetime');
243
-    }
244
-
245
-
246
-    /**
247
-     * Returns the 'primary' datetime for the event
248
-     *
249
-     * @param bool $try_to_exclude_expired
250
-     * @param bool $try_to_exclude_deleted
251
-     * @return EE_Datetime|null
252
-     * @throws EE_Error
253
-     * @throws ReflectionException
254
-     */
255
-    public function primary_datetime(
256
-        bool $try_to_exclude_expired = true,
257
-        bool $try_to_exclude_deleted = true
258
-    ): ?EE_Datetime {
259
-        if (! empty($this->_Primary_Datetime)) {
260
-            return $this->_Primary_Datetime;
261
-        }
262
-        $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
263
-            $this->ID(),
264
-            $try_to_exclude_expired,
265
-            $try_to_exclude_deleted
266
-        );
267
-        return $this->_Primary_Datetime;
268
-    }
269
-
270
-
271
-    /**
272
-     * Gets all the tickets available for purchase of this event
273
-     *
274
-     * @param array|null $query_params
275
-     * @return EE_Base_Class[]|EE_Ticket[]
276
-     * @throws EE_Error
277
-     * @throws ReflectionException
278
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
279
-     */
280
-    public function tickets(?array $query_params = []): array
281
-    {
282
-        // first get all datetimes
283
-        $datetimes = $this->datetimes_ordered();
284
-        if (! $datetimes) {
285
-            return [];
286
-        }
287
-        $datetime_ids = [];
288
-        foreach ($datetimes as $datetime) {
289
-            $datetime_ids[] = $datetime->ID();
290
-        }
291
-        $where_params = ['Datetime.DTT_ID' => ['IN', $datetime_ids]];
292
-        // if incoming $query_params has where conditions let's merge but not override existing.
293
-        if (is_array($query_params) && isset($query_params[0])) {
294
-            $where_params = array_merge($query_params[0], $where_params);
295
-            unset($query_params[0]);
296
-        }
297
-        // now add $where_params to $query_params
298
-        $query_params[0] = $where_params;
299
-        return EEM_Ticket::instance()->get_all($query_params);
300
-    }
301
-
302
-
303
-    /**
304
-     * get all unexpired not-trashed tickets
305
-     *
306
-     * @return EE_Ticket[]
307
-     * @throws EE_Error
308
-     * @throws ReflectionException
309
-     */
310
-    public function active_tickets(): array
311
-    {
312
-        return $this->tickets(
313
-            [
314
-                [
315
-                    'TKT_end_date' => ['>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')],
316
-                    'TKT_deleted'  => false,
317
-                ],
318
-            ]
319
-        );
320
-    }
321
-
322
-
323
-    /**
324
-     * @return int
325
-     * @throws EE_Error
326
-     * @throws ReflectionException
327
-     */
328
-    public function additional_limit(): int
329
-    {
330
-        return $this->get('EVT_additional_limit');
331
-    }
332
-
333
-
334
-    /**
335
-     * @return bool
336
-     * @throws EE_Error
337
-     * @throws ReflectionException
338
-     */
339
-    public function allow_overflow(): bool
340
-    {
341
-        return $this->get('EVT_allow_overflow');
342
-    }
343
-
344
-
345
-    /**
346
-     * @return string
347
-     * @throws EE_Error
348
-     * @throws ReflectionException
349
-     */
350
-    public function created(): string
351
-    {
352
-        return $this->get('EVT_created');
353
-    }
354
-
355
-
356
-    /**
357
-     * @return string
358
-     * @throws EE_Error
359
-     * @throws ReflectionException
360
-     */
361
-    public function description(): string
362
-    {
363
-        return $this->get('EVT_desc');
364
-    }
365
-
366
-
367
-    /**
368
-     * Runs do_shortcode and wpautop on the description
369
-     *
370
-     * @return string of html
371
-     * @throws EE_Error
372
-     * @throws ReflectionException
373
-     */
374
-    public function description_filtered(): string
375
-    {
376
-        return $this->get_pretty('EVT_desc');
377
-    }
378
-
379
-
380
-    /**
381
-     * @return bool
382
-     * @throws EE_Error
383
-     * @throws ReflectionException
384
-     */
385
-    public function display_description(): bool
386
-    {
387
-        return $this->get('EVT_display_desc');
388
-    }
389
-
390
-
391
-    /**
392
-     * @return bool
393
-     * @throws EE_Error
394
-     * @throws ReflectionException
395
-     */
396
-    public function display_ticket_selector(): bool
397
-    {
398
-        return (bool) $this->get('EVT_display_ticket_selector');
399
-    }
400
-
401
-
402
-    /**
403
-     * @return string
404
-     * @throws EE_Error
405
-     * @throws ReflectionException
406
-     */
407
-    public function external_url(): ?string
408
-    {
409
-        return $this->get('EVT_external_URL') ?? '';
410
-    }
411
-
412
-
413
-    /**
414
-     * @return bool
415
-     * @throws EE_Error
416
-     * @throws ReflectionException
417
-     */
418
-    public function member_only(): bool
419
-    {
420
-        return $this->get('EVT_member_only');
421
-    }
422
-
423
-
424
-    /**
425
-     * @return string
426
-     * @throws EE_Error
427
-     * @throws ReflectionException
428
-     */
429
-    public function phone(): string
430
-    {
431
-        return $this->get('EVT_phone');
432
-    }
433
-
434
-
435
-    /**
436
-     * @return string
437
-     * @throws EE_Error
438
-     * @throws ReflectionException
439
-     */
440
-    public function modified(): string
441
-    {
442
-        return $this->get('EVT_modified');
443
-    }
444
-
445
-
446
-    /**
447
-     * @return string
448
-     * @throws EE_Error
449
-     * @throws ReflectionException
450
-     */
451
-    public function name(): string
452
-    {
453
-        return $this->get('EVT_name');
454
-    }
455
-
456
-
457
-    /**
458
-     * @return int
459
-     * @throws EE_Error
460
-     * @throws ReflectionException
461
-     */
462
-    public function order(): int
463
-    {
464
-        return $this->get('EVT_order');
465
-    }
466
-
467
-
468
-    /**
469
-     * @return string
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     */
473
-    public function default_registration_status(): string
474
-    {
475
-        $event_default_registration_status = $this->get('EVT_default_registration_status');
476
-        return ! empty($event_default_registration_status)
477
-            ? $event_default_registration_status
478
-            : EE_Registry::instance()->CFG->registration->default_STS_ID;
479
-    }
480
-
481
-
482
-    /**
483
-     * @param int|null    $num_words
484
-     * @param string|null $more
485
-     * @param bool        $not_full_desc
486
-     * @return string
487
-     * @throws EE_Error
488
-     * @throws ReflectionException
489
-     */
490
-    public function short_description(?int $num_words = 55, string $more = null, bool $not_full_desc = false): string
491
-    {
492
-        $short_desc = $this->get('EVT_short_desc');
493
-        if (! empty($short_desc) || $not_full_desc) {
494
-            return $short_desc;
495
-        }
496
-        $full_desc = $this->get('EVT_desc');
497
-        return wp_trim_words($full_desc, $num_words, $more);
498
-    }
499
-
500
-
501
-    /**
502
-     * @return string
503
-     * @throws EE_Error
504
-     * @throws ReflectionException
505
-     */
506
-    public function slug(): string
507
-    {
508
-        return $this->get('EVT_slug');
509
-    }
510
-
511
-
512
-    /**
513
-     * @return string
514
-     * @throws EE_Error
515
-     * @throws ReflectionException
516
-     */
517
-    public function timezone_string(): string
518
-    {
519
-        return $this->get('EVT_timezone_string');
520
-    }
521
-
522
-
523
-    /**
524
-     * @return string
525
-     * @throws EE_Error
526
-     * @throws ReflectionException
527
-     * @deprecated
528
-     */
529
-    public function visible_on(): string
530
-    {
531
-        EE_Error::doing_it_wrong(
532
-            __METHOD__,
533
-            esc_html__(
534
-                'This method has been deprecated and there is no replacement for it.',
535
-                'event_espresso'
536
-            ),
537
-            '5.0.0.rc.002'
538
-        );
539
-        return $this->get('EVT_visible_on');
540
-    }
541
-
542
-
543
-    /**
544
-     * @return int
545
-     * @throws EE_Error
546
-     * @throws ReflectionException
547
-     */
548
-    public function wp_user(): int
549
-    {
550
-        return (int) $this->get('EVT_wp_user');
551
-    }
552
-
553
-
554
-    /**
555
-     * @return bool
556
-     * @throws EE_Error
557
-     * @throws ReflectionException
558
-     */
559
-    public function donations(): bool
560
-    {
561
-        return $this->get('EVT_donations');
562
-    }
563
-
564
-
565
-    /**
566
-     * @param int $limit
567
-     * @throws EE_Error
568
-     * @throws ReflectionException
569
-     */
570
-    public function set_additional_limit(int $limit)
571
-    {
572
-        $this->set('EVT_additional_limit', $limit);
573
-    }
574
-
575
-
576
-    /**
577
-     * @param $created
578
-     * @throws EE_Error
579
-     * @throws ReflectionException
580
-     */
581
-    public function set_created($created)
582
-    {
583
-        $this->set('EVT_created', $created);
584
-    }
585
-
586
-
587
-    /**
588
-     * @param $desc
589
-     * @throws EE_Error
590
-     * @throws ReflectionException
591
-     */
592
-    public function set_description($desc)
593
-    {
594
-        $this->set('EVT_desc', $desc);
595
-    }
596
-
597
-
598
-    /**
599
-     * @param $display_desc
600
-     * @throws EE_Error
601
-     * @throws ReflectionException
602
-     */
603
-    public function set_display_description($display_desc)
604
-    {
605
-        $this->set('EVT_display_desc', $display_desc);
606
-    }
607
-
608
-
609
-    /**
610
-     * @param $display_ticket_selector
611
-     * @throws EE_Error
612
-     * @throws ReflectionException
613
-     */
614
-    public function set_display_ticket_selector($display_ticket_selector)
615
-    {
616
-        $this->set('EVT_display_ticket_selector', $display_ticket_selector);
617
-    }
618
-
619
-
620
-    /**
621
-     * @param $external_url
622
-     * @throws EE_Error
623
-     * @throws ReflectionException
624
-     */
625
-    public function set_external_url($external_url)
626
-    {
627
-        $this->set('EVT_external_URL', $external_url);
628
-    }
629
-
630
-
631
-    /**
632
-     * @param $member_only
633
-     * @throws EE_Error
634
-     * @throws ReflectionException
635
-     */
636
-    public function set_member_only($member_only)
637
-    {
638
-        $this->set('EVT_member_only', $member_only);
639
-    }
640
-
641
-
642
-    /**
643
-     * @param $event_phone
644
-     * @throws EE_Error
645
-     * @throws ReflectionException
646
-     */
647
-    public function set_event_phone($event_phone)
648
-    {
649
-        $this->set('EVT_phone', $event_phone);
650
-    }
651
-
652
-
653
-    /**
654
-     * @param $modified
655
-     * @throws EE_Error
656
-     * @throws ReflectionException
657
-     */
658
-    public function set_modified($modified)
659
-    {
660
-        $this->set('EVT_modified', $modified);
661
-    }
662
-
663
-
664
-    /**
665
-     * @param $name
666
-     * @throws EE_Error
667
-     * @throws ReflectionException
668
-     */
669
-    public function set_name($name)
670
-    {
671
-        $this->set('EVT_name', $name);
672
-    }
673
-
674
-
675
-    /**
676
-     * @param $order
677
-     * @throws EE_Error
678
-     * @throws ReflectionException
679
-     */
680
-    public function set_order($order)
681
-    {
682
-        $this->set('EVT_order', $order);
683
-    }
684
-
685
-
686
-    /**
687
-     * @param $short_desc
688
-     * @throws EE_Error
689
-     * @throws ReflectionException
690
-     */
691
-    public function set_short_description($short_desc)
692
-    {
693
-        $this->set('EVT_short_desc', $short_desc);
694
-    }
695
-
696
-
697
-    /**
698
-     * @param $slug
699
-     * @throws EE_Error
700
-     * @throws ReflectionException
701
-     */
702
-    public function set_slug($slug)
703
-    {
704
-        $this->set('EVT_slug', $slug);
705
-    }
706
-
707
-
708
-    /**
709
-     * @param $timezone_string
710
-     * @throws EE_Error
711
-     * @throws ReflectionException
712
-     */
713
-    public function set_timezone_string($timezone_string)
714
-    {
715
-        $this->set('EVT_timezone_string', $timezone_string);
716
-    }
717
-
718
-
719
-    /**
720
-     * @param $visible_on
721
-     * @throws EE_Error
722
-     * @throws ReflectionException
723
-     * @deprecated
724
-     */
725
-    public function set_visible_on($visible_on)
726
-    {
727
-        EE_Error::doing_it_wrong(
728
-            __METHOD__,
729
-            esc_html__(
730
-                'This method has been deprecated and there is no replacement for it.',
731
-                'event_espresso'
732
-            ),
733
-            '5.0.0.rc.002'
734
-        );
735
-        $this->set('EVT_visible_on', $visible_on);
736
-    }
737
-
738
-
739
-    /**
740
-     * @param $wp_user
741
-     * @throws EE_Error
742
-     * @throws ReflectionException
743
-     */
744
-    public function set_wp_user($wp_user)
745
-    {
746
-        $this->set('EVT_wp_user', $wp_user);
747
-    }
748
-
749
-
750
-    /**
751
-     * @param $default_registration_status
752
-     * @throws EE_Error
753
-     * @throws ReflectionException
754
-     */
755
-    public function set_default_registration_status($default_registration_status)
756
-    {
757
-        $this->set('EVT_default_registration_status', $default_registration_status);
758
-    }
759
-
760
-
761
-    /**
762
-     * @param $donations
763
-     * @throws EE_Error
764
-     * @throws ReflectionException
765
-     */
766
-    public function set_donations($donations)
767
-    {
768
-        $this->set('EVT_donations', $donations);
769
-    }
770
-
771
-
772
-    /**
773
-     * Adds a venue to this event
774
-     *
775
-     * @param int|EE_Venue /int $venue_id_or_obj
776
-     * @return EE_Base_Class|EE_Venue
777
-     * @throws EE_Error
778
-     * @throws ReflectionException
779
-     */
780
-    public function add_venue($venue_id_or_obj): EE_Venue
781
-    {
782
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
783
-    }
784
-
785
-
786
-    /**
787
-     * Removes a venue from the event
788
-     *
789
-     * @param EE_Venue /int $venue_id_or_obj
790
-     * @return EE_Base_Class|EE_Venue
791
-     * @throws EE_Error
792
-     * @throws ReflectionException
793
-     */
794
-    public function remove_venue($venue_id_or_obj): EE_Venue
795
-    {
796
-        $venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
797
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
798
-    }
799
-
800
-
801
-    /**
802
-     * Gets the venue related to the event. May provide additional $query_params if desired
803
-     *
804
-     * @param array $query_params
805
-     * @return int
806
-     * @throws EE_Error
807
-     * @throws ReflectionException
808
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
809
-     */
810
-    public function venue_ID(array $query_params = []): int
811
-    {
812
-        $venue = $this->get_first_related('Venue', $query_params);
813
-        return $venue instanceof EE_Venue ? $venue->ID() : 0;
814
-    }
815
-
816
-
817
-    /**
818
-     * Gets the venue related to the event. May provide additional $query_params if desired
819
-     *
820
-     * @param array $query_params
821
-     * @return EE_Base_Class|EE_Venue|null
822
-     * @throws EE_Error
823
-     * @throws ReflectionException
824
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
825
-     */
826
-    public function venue(array $query_params = []): ?EE_Venue
827
-    {
828
-        return $this->get_first_related('Venue', $query_params);
829
-    }
830
-
831
-
832
-    /**
833
-     * @param array $query_params
834
-     * @return EE_Base_Class[]|EE_Venue[]
835
-     * @throws EE_Error
836
-     * @throws ReflectionException
837
-     * @deprecated 5.0.0.p
838
-     */
839
-    public function venues(array $query_params = []): array
840
-    {
841
-        $venue = $this->venue($query_params);
842
-        return $venue instanceof EE_Venue ? [$venue] : [];
843
-    }
844
-
845
-
846
-    /**
847
-     * check if event id is present and if event is published
848
-     *
849
-     * @return boolean true yes, false no
850
-     * @throws EE_Error
851
-     * @throws ReflectionException
852
-     */
853
-    private function _has_ID_and_is_published(): bool
854
-    {
855
-        // first check if event id is present and not NULL,
856
-        // then check if this event is published (or any of the equivalent "published" statuses)
857
-        return
858
-            $this->ID() && $this->ID() !== null
859
-            && (
860
-                $this->status() === 'publish'
861
-                || $this->status() === EEM_Event::sold_out
862
-                || $this->status() === EEM_Event::postponed
863
-                || $this->status() === EEM_Event::cancelled
864
-            );
865
-    }
866
-
867
-
868
-    /**
869
-     * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
870
-     *
871
-     * @return boolean true yes, false no
872
-     * @throws EE_Error
873
-     * @throws ReflectionException
874
-     */
875
-    public function is_upcoming(): bool
876
-    {
877
-        // check if event id is present and if this event is published
878
-        if ($this->is_inactive()) {
879
-            return false;
880
-        }
881
-        // set initial value
882
-        $upcoming = false;
883
-        // next let's get all datetimes and loop through them
884
-        $datetimes = $this->datetimes_in_chronological_order();
885
-        foreach ($datetimes as $datetime) {
886
-            if ($datetime instanceof EE_Datetime) {
887
-                // if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
888
-                if ($datetime->is_expired()) {
889
-                    continue;
890
-                }
891
-                // if this dtt is active then we return false.
892
-                if ($datetime->is_active()) {
893
-                    return false;
894
-                }
895
-                // otherwise let's check upcoming status
896
-                $upcoming = $datetime->is_upcoming();
897
-            }
898
-        }
899
-        return $upcoming;
900
-    }
901
-
902
-
903
-    /**
904
-     * @return bool
905
-     * @throws EE_Error
906
-     * @throws ReflectionException
907
-     */
908
-    public function is_active(): bool
909
-    {
910
-        // check if event id is present and if this event is published
911
-        if ($this->is_inactive()) {
912
-            return false;
913
-        }
914
-        // set initial value
915
-        $active = false;
916
-        // next let's get all datetimes and loop through them
917
-        $datetimes = $this->datetimes_in_chronological_order();
918
-        foreach ($datetimes as $datetime) {
919
-            if ($datetime instanceof EE_Datetime) {
920
-                // if this dtt is expired then we continue cause one of the other datetimes might be active.
921
-                if ($datetime->is_expired()) {
922
-                    continue;
923
-                }
924
-                // if this dtt is upcoming then we return false.
925
-                if ($datetime->is_upcoming()) {
926
-                    return false;
927
-                }
928
-                // otherwise let's check active status
929
-                $active = $datetime->is_active();
930
-            }
931
-        }
932
-        return $active;
933
-    }
934
-
935
-
936
-    /**
937
-     * @return bool
938
-     * @throws EE_Error
939
-     * @throws ReflectionException
940
-     */
941
-    public function is_expired(): bool
942
-    {
943
-        // check if event id is present and if this event is published
944
-        if ($this->is_inactive()) {
945
-            return false;
946
-        }
947
-        // set initial value
948
-        $expired = false;
949
-        // first let's get all datetimes and loop through them
950
-        $datetimes = $this->datetimes_in_chronological_order();
951
-        foreach ($datetimes as $datetime) {
952
-            if ($datetime instanceof EE_Datetime) {
953
-                // if this dtt is upcoming or active then we return false.
954
-                if ($datetime->is_upcoming() || $datetime->is_active()) {
955
-                    return false;
956
-                }
957
-                // otherwise let's check active status
958
-                $expired = $datetime->is_expired();
959
-            }
960
-        }
961
-        return $expired;
962
-    }
963
-
964
-
965
-    /**
966
-     * @return bool
967
-     * @throws EE_Error
968
-     * @throws ReflectionException
969
-     */
970
-    public function is_inactive(): bool
971
-    {
972
-        // check if event id is present and if this event is published
973
-        if ($this->_has_ID_and_is_published()) {
974
-            return false;
975
-        }
976
-        return true;
977
-    }
978
-
979
-
980
-    /**
981
-     * calculate spaces remaining based on "saleable" tickets
982
-     *
983
-     * @param array|null $tickets
984
-     * @param bool       $filtered
985
-     * @return int|float
986
-     * @throws EE_Error
987
-     * @throws DomainException
988
-     * @throws UnexpectedEntityException
989
-     * @throws ReflectionException
990
-     */
991
-    public function spaces_remaining(?array $tickets = [], ?bool $filtered = true)
992
-    {
993
-        $this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
994
-        $spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
995
-        return $filtered
996
-            ? apply_filters(
997
-                'FHEE_EE_Event__spaces_remaining',
998
-                $spaces_remaining,
999
-                $this,
1000
-                $tickets
1001
-            )
1002
-            : $spaces_remaining;
1003
-    }
1004
-
1005
-
1006
-    /**
1007
-     *    perform_sold_out_status_check
1008
-     *    checks all of this event's datetime  reg_limit - sold values to determine if ANY datetimes have spaces
1009
-     *    available... if NOT, then the event status will get toggled to 'sold_out'
1010
-     *
1011
-     * @return bool    return the ACTUAL sold out state.
1012
-     * @throws EE_Error
1013
-     * @throws DomainException
1014
-     * @throws UnexpectedEntityException
1015
-     * @throws ReflectionException
1016
-     */
1017
-    public function perform_sold_out_status_check(): bool
1018
-    {
1019
-        // get all tickets
1020
-        $tickets     = $this->tickets(
1021
-            [
1022
-                'default_where_conditions' => 'none',
1023
-                'order_by'                 => ['TKT_qty' => 'ASC'],
1024
-            ]
1025
-        );
1026
-        $all_expired = true;
1027
-        foreach ($tickets as $ticket) {
1028
-            if (! $ticket->is_expired()) {
1029
-                $all_expired = false;
1030
-                break;
1031
-            }
1032
-        }
1033
-        // if all the tickets are just expired, then don't update the event status to sold out
1034
-        if ($all_expired) {
1035
-            return true;
1036
-        }
1037
-        $spaces_remaining = $this->spaces_remaining($tickets);
1038
-        if ($spaces_remaining < 1) {
1039
-            if ($this->status() !== EEM_CPT_Base::post_status_private) {
1040
-                $this->set_status(EEM_Event::sold_out);
1041
-                $this->save();
1042
-            }
1043
-            $sold_out = true;
1044
-        } else {
1045
-            $sold_out = false;
1046
-            // was event previously marked as sold out ?
1047
-            if ($this->status() === EEM_Event::sold_out) {
1048
-                // revert status to previous value, if it was set
1049
-                $previous_event_status = $this->get_post_meta('_previous_event_status', true);
1050
-                if ($previous_event_status) {
1051
-                    $this->set_status($previous_event_status);
1052
-                    $this->save();
1053
-                }
1054
-            }
1055
-        }
1056
-        do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
1057
-        return $sold_out;
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     * This returns the total remaining spaces for sale on this event.
1063
-     *
1064
-     * @return int|float
1065
-     * @throws EE_Error
1066
-     * @throws DomainException
1067
-     * @throws UnexpectedEntityException
1068
-     * @throws ReflectionException
1069
-     * @uses EE_Event::total_available_spaces()
1070
-     */
1071
-    public function spaces_remaining_for_sale()
1072
-    {
1073
-        return $this->total_available_spaces(true);
1074
-    }
1075
-
1076
-
1077
-    /**
1078
-     * This returns the total spaces available for an event
1079
-     * while considering all the quantities on the tickets and the reg limits
1080
-     * on the datetimes attached to this event.
1081
-     *
1082
-     * @param bool $consider_sold   Whether to consider any tickets that have already sold in our calculation.
1083
-     *                              If this is false, then we return the most tickets that could ever be sold
1084
-     *                              for this event with the datetime and tickets setup on the event under optimal
1085
-     *                              selling conditions.  Otherwise we return a live calculation of spaces available
1086
-     *                              based on tickets sold.  Depending on setup and stage of sales, this
1087
-     *                              may appear to equal remaining tickets.  However, the more tickets are
1088
-     *                              sold out, the more accurate the "live" total is.
1089
-     * @return int|float
1090
-     * @throws EE_Error
1091
-     * @throws DomainException
1092
-     * @throws UnexpectedEntityException
1093
-     * @throws ReflectionException
1094
-     */
1095
-    public function total_available_spaces(bool $consider_sold = false)
1096
-    {
1097
-        $spaces_available = $consider_sold
1098
-            ? $this->getAvailableSpacesCalculator()->spacesRemaining()
1099
-            : $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
1100
-        return apply_filters(
1101
-            'FHEE_EE_Event__total_available_spaces__spaces_available',
1102
-            $spaces_available,
1103
-            $this,
1104
-            $this->getAvailableSpacesCalculator()->getDatetimes(),
1105
-            $this->getAvailableSpacesCalculator()->getActiveTickets()
1106
-        );
1107
-    }
1108
-
1109
-
1110
-    /**
1111
-     * Checks if the event is set to sold out
1112
-     *
1113
-     * @param bool $actual  whether or not to perform calculations to not only figure the
1114
-     *                      actual status but also to flip the status if necessary to sold
1115
-     *                      out If false, we just check the existing status of the event
1116
-     * @return boolean
1117
-     * @throws EE_Error
1118
-     * @throws ReflectionException
1119
-     */
1120
-    public function is_sold_out(bool $actual = false): bool
1121
-    {
1122
-        if (! $actual) {
1123
-            return $this->status() === EEM_Event::sold_out;
1124
-        }
1125
-        return $this->perform_sold_out_status_check();
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * Checks if the event is marked as postponed
1131
-     *
1132
-     * @return boolean
1133
-     */
1134
-    public function is_postponed(): bool
1135
-    {
1136
-        return $this->status() === EEM_Event::postponed;
1137
-    }
1138
-
1139
-
1140
-    /**
1141
-     * Checks if the event is marked as cancelled
1142
-     *
1143
-     * @return boolean
1144
-     */
1145
-    public function is_cancelled(): bool
1146
-    {
1147
-        return $this->status() === EEM_Event::cancelled;
1148
-    }
1149
-
1150
-
1151
-    /**
1152
-     * Get the logical active status in a hierarchical order for all the datetimes.  Note
1153
-     * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1154
-     * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1155
-     * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1156
-     * the event is considered expired.
1157
-     * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a
1158
-     * status set on the EVENT when it is not published and thus is done
1159
-     *
1160
-     * @param bool $reset
1161
-     * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1162
-     * @throws EE_Error
1163
-     * @throws ReflectionException
1164
-     */
1165
-    public function get_active_status(bool $reset = false)
1166
-    {
1167
-        // if the active status has already been set, then just use that value (unless we are resetting it)
1168
-        if (! empty($this->_active_status) && ! $reset) {
1169
-            return $this->_active_status;
1170
-        }
1171
-        // first check if event id is present on this object
1172
-        if (! $this->ID()) {
1173
-            return false;
1174
-        }
1175
-        $where_params_for_event = [['EVT_ID' => $this->ID()]];
1176
-        // if event is published:
1177
-        if (
1178
-            $this->status() === EEM_CPT_Base::post_status_publish
1179
-            || $this->status() === EEM_CPT_Base::post_status_private
1180
-        ) {
1181
-            // active?
1182
-            if (
1183
-                EEM_Datetime::instance()->get_datetime_count_for_status(
1184
-                    EE_Datetime::active,
1185
-                    $where_params_for_event
1186
-                ) > 0
1187
-            ) {
1188
-                $this->_active_status = EE_Datetime::active;
1189
-            } else {
1190
-                // upcoming?
1191
-                if (
1192
-                    EEM_Datetime::instance()->get_datetime_count_for_status(
1193
-                        EE_Datetime::upcoming,
1194
-                        $where_params_for_event
1195
-                    ) > 0
1196
-                ) {
1197
-                    $this->_active_status = EE_Datetime::upcoming;
1198
-                } else {
1199
-                    // expired?
1200
-                    if (
1201
-                        EEM_Datetime::instance()->get_datetime_count_for_status(
1202
-                            EE_Datetime::expired,
1203
-                            $where_params_for_event
1204
-                        ) > 0
1205
-                    ) {
1206
-                        $this->_active_status = EE_Datetime::expired;
1207
-                    } else {
1208
-                        // it would be odd if things make it this far
1209
-                        // because it basically means there are no datetimes attached to the event.
1210
-                        // So in this case it will just be considered inactive.
1211
-                        $this->_active_status = EE_Datetime::inactive;
1212
-                    }
1213
-                }
1214
-            }
1215
-        } else {
1216
-            // the event is not published, so let's just set it's active status according to its' post status
1217
-            switch ($this->status()) {
1218
-                case EEM_Event::sold_out:
1219
-                    $this->_active_status = EE_Datetime::sold_out;
1220
-                    break;
1221
-                case EEM_Event::cancelled:
1222
-                    $this->_active_status = EE_Datetime::cancelled;
1223
-                    break;
1224
-                case EEM_Event::postponed:
1225
-                    $this->_active_status = EE_Datetime::postponed;
1226
-                    break;
1227
-                default:
1228
-                    $this->_active_status = EE_Datetime::inactive;
1229
-            }
1230
-        }
1231
-        return $this->_active_status;
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     *    pretty_active_status
1237
-     *
1238
-     * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1239
-     * @return string
1240
-     * @throws EE_Error
1241
-     * @throws ReflectionException
1242
-     */
1243
-    public function pretty_active_status(bool $echo = true): string
1244
-    {
1245
-        $active_status = $this->get_active_status();
1246
-        $status        = "
19
+	/**
20
+	 * cached value for the the logical active status for the event
21
+	 *
22
+	 * @see get_active_status()
23
+	 * @var string
24
+	 */
25
+	protected $_active_status = '';
26
+
27
+	/**
28
+	 * This is just used for caching the Primary Datetime for the Event on initial retrieval
29
+	 *
30
+	 * @var EE_Datetime
31
+	 */
32
+	protected $_Primary_Datetime;
33
+
34
+	/**
35
+	 * @var EventSpacesCalculator $available_spaces_calculator
36
+	 */
37
+	protected $available_spaces_calculator;
38
+
39
+
40
+	/**
41
+	 * @param array  $props_n_values          incoming values
42
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
43
+	 *                                        used.)
44
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
45
+	 *                                        date_format and the second value is the time format
46
+	 * @return EE_Event
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = []): EE_Event
51
+	{
52
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
53
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
54
+	}
55
+
56
+
57
+	/**
58
+	 * @param array  $props_n_values  incoming values from the database
59
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
60
+	 *                                the website will be used.
61
+	 * @return EE_Event
62
+	 * @throws EE_Error
63
+	 * @throws ReflectionException
64
+	 */
65
+	public static function new_instance_from_db($props_n_values = [], $timezone = ''): EE_Event
66
+	{
67
+		return new self($props_n_values, true, $timezone);
68
+	}
69
+
70
+
71
+	/**
72
+	 * @return EventSpacesCalculator
73
+	 * @throws EE_Error
74
+	 * @throws ReflectionException
75
+	 */
76
+	public function getAvailableSpacesCalculator(): EventSpacesCalculator
77
+	{
78
+		if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79
+			$this->available_spaces_calculator = new EventSpacesCalculator($this);
80
+		}
81
+		return $this->available_spaces_calculator;
82
+	}
83
+
84
+
85
+	/**
86
+	 * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
87
+	 *
88
+	 * @param string $field_name
89
+	 * @param mixed  $field_value
90
+	 * @param bool   $use_default
91
+	 * @throws EE_Error
92
+	 * @throws ReflectionException
93
+	 */
94
+	public function set($field_name, $field_value, $use_default = false)
95
+	{
96
+		switch ($field_name) {
97
+			case 'status':
98
+				$this->set_status($field_value, $use_default);
99
+				break;
100
+			default:
101
+				parent::set($field_name, $field_value, $use_default);
102
+		}
103
+	}
104
+
105
+
106
+	/**
107
+	 *    set_status
108
+	 * Checks if event status is being changed to SOLD OUT
109
+	 * and updates event meta data with previous event status
110
+	 * so that we can revert things if/when the event is no longer sold out
111
+	 *
112
+	 * @param string $status
113
+	 * @param bool   $use_default
114
+	 * @return void
115
+	 * @throws EE_Error
116
+	 * @throws ReflectionException
117
+	 */
118
+	public function set_status($status = '', $use_default = false)
119
+	{
120
+		// if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
+		if (empty($status) && ! $use_default) {
122
+			return;
123
+		}
124
+		// get current Event status
125
+		$old_status = $this->status();
126
+		// if status has changed
127
+		if ($old_status !== $status) {
128
+			// TO sold_out
129
+			if ($status === EEM_Event::sold_out) {
130
+				// save the previous event status so that we can revert if the event is no longer sold out
131
+				$this->add_post_meta('_previous_event_status', $old_status);
132
+				do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $status);
133
+				// OR FROM  sold_out
134
+			} elseif ($old_status === EEM_Event::sold_out) {
135
+				$this->delete_post_meta('_previous_event_status');
136
+				do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $status);
137
+			}
138
+			// clear out the active status so that it gets reset the next time it is requested
139
+			$this->_active_status = null;
140
+			// update status
141
+			parent::set('status', $status, $use_default);
142
+			do_action('AHEE__EE_Event__set_status__after_update', $this);
143
+			return;
144
+		}
145
+		// even though the old value matches the new value, it's still good to
146
+		// allow the parent set method to have a say
147
+		parent::set('status', $status, $use_default);
148
+	}
149
+
150
+
151
+	/**
152
+	 * Gets all the datetimes for this event
153
+	 *
154
+	 * @param array|null $query_params
155
+	 * @return EE_Base_Class[]|EE_Datetime[]
156
+	 * @throws EE_Error
157
+	 * @throws ReflectionException
158
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
159
+	 */
160
+	public function datetimes(?array $query_params = []): array
161
+	{
162
+		return $this->get_many_related('Datetime', $query_params);
163
+	}
164
+
165
+
166
+	/**
167
+	 * Gets all the datetimes for this event that are currently ACTIVE,
168
+	 * meaning the datetime has started and has not yet ended.
169
+	 *
170
+	 * @param int|null   $start_date   timestamp to use for event date start time, defaults to NOW unless set to 0
171
+	 * @param array|null $query_params will recursively replace default values
172
+	 * @throws EE_Error
173
+	 * @throws ReflectionException
174
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
175
+	 */
176
+	public function activeDatetimes(?int $start_date, ?array $query_params = []): array
177
+	{
178
+		// if start date is null, then use current time
179
+		$start_date = $start_date ?? time();
180
+		$where      = [];
181
+		if ($start_date) {
182
+			$where['DTT_EVT_start'] = ['<', $start_date];
183
+			$where['DTT_EVT_end']   = ['>', time()];
184
+		}
185
+		$query_params = array_replace_recursive(
186
+			[
187
+				$where,
188
+				'order_by' => ['DTT_EVT_start' => 'ASC'],
189
+			],
190
+			$query_params
191
+		);
192
+		return $this->get_many_related('Datetime', $query_params);
193
+	}
194
+
195
+
196
+	/**
197
+	 * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
198
+	 *
199
+	 * @return EE_Base_Class[]|EE_Datetime[]
200
+	 * @throws EE_Error
201
+	 * @throws ReflectionException
202
+	 */
203
+	public function datetimes_in_chronological_order(): array
204
+	{
205
+		return $this->get_many_related('Datetime', ['order_by' => ['DTT_EVT_start' => 'ASC']]);
206
+	}
207
+
208
+
209
+	/**
210
+	 * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
211
+	 * @darren, we should probably UNSET timezone on the EEM_Datetime model
212
+	 * after running our query, so that this timezone isn't set for EVERY query
213
+	 * on EEM_Datetime for the rest of the request, no?
214
+	 *
215
+	 * @param bool     $show_expired whether or not to include expired events
216
+	 * @param bool     $show_deleted whether or not to include deleted events
217
+	 * @param int|null $limit
218
+	 * @return EE_Datetime[]
219
+	 * @throws EE_Error
220
+	 * @throws ReflectionException
221
+	 */
222
+	public function datetimes_ordered(bool $show_expired = true, bool $show_deleted = false, ?int $limit = null): array
223
+	{
224
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
225
+			$this->ID(),
226
+			$show_expired,
227
+			$show_deleted,
228
+			$limit
229
+		);
230
+	}
231
+
232
+
233
+	/**
234
+	 * Returns one related datetime. Mostly only used by some legacy code.
235
+	 *
236
+	 * @return EE_Base_Class|EE_Datetime
237
+	 * @throws EE_Error
238
+	 * @throws ReflectionException
239
+	 */
240
+	public function first_datetime(): EE_Datetime
241
+	{
242
+		return $this->get_first_related('Datetime');
243
+	}
244
+
245
+
246
+	/**
247
+	 * Returns the 'primary' datetime for the event
248
+	 *
249
+	 * @param bool $try_to_exclude_expired
250
+	 * @param bool $try_to_exclude_deleted
251
+	 * @return EE_Datetime|null
252
+	 * @throws EE_Error
253
+	 * @throws ReflectionException
254
+	 */
255
+	public function primary_datetime(
256
+		bool $try_to_exclude_expired = true,
257
+		bool $try_to_exclude_deleted = true
258
+	): ?EE_Datetime {
259
+		if (! empty($this->_Primary_Datetime)) {
260
+			return $this->_Primary_Datetime;
261
+		}
262
+		$this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
263
+			$this->ID(),
264
+			$try_to_exclude_expired,
265
+			$try_to_exclude_deleted
266
+		);
267
+		return $this->_Primary_Datetime;
268
+	}
269
+
270
+
271
+	/**
272
+	 * Gets all the tickets available for purchase of this event
273
+	 *
274
+	 * @param array|null $query_params
275
+	 * @return EE_Base_Class[]|EE_Ticket[]
276
+	 * @throws EE_Error
277
+	 * @throws ReflectionException
278
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
279
+	 */
280
+	public function tickets(?array $query_params = []): array
281
+	{
282
+		// first get all datetimes
283
+		$datetimes = $this->datetimes_ordered();
284
+		if (! $datetimes) {
285
+			return [];
286
+		}
287
+		$datetime_ids = [];
288
+		foreach ($datetimes as $datetime) {
289
+			$datetime_ids[] = $datetime->ID();
290
+		}
291
+		$where_params = ['Datetime.DTT_ID' => ['IN', $datetime_ids]];
292
+		// if incoming $query_params has where conditions let's merge but not override existing.
293
+		if (is_array($query_params) && isset($query_params[0])) {
294
+			$where_params = array_merge($query_params[0], $where_params);
295
+			unset($query_params[0]);
296
+		}
297
+		// now add $where_params to $query_params
298
+		$query_params[0] = $where_params;
299
+		return EEM_Ticket::instance()->get_all($query_params);
300
+	}
301
+
302
+
303
+	/**
304
+	 * get all unexpired not-trashed tickets
305
+	 *
306
+	 * @return EE_Ticket[]
307
+	 * @throws EE_Error
308
+	 * @throws ReflectionException
309
+	 */
310
+	public function active_tickets(): array
311
+	{
312
+		return $this->tickets(
313
+			[
314
+				[
315
+					'TKT_end_date' => ['>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')],
316
+					'TKT_deleted'  => false,
317
+				],
318
+			]
319
+		);
320
+	}
321
+
322
+
323
+	/**
324
+	 * @return int
325
+	 * @throws EE_Error
326
+	 * @throws ReflectionException
327
+	 */
328
+	public function additional_limit(): int
329
+	{
330
+		return $this->get('EVT_additional_limit');
331
+	}
332
+
333
+
334
+	/**
335
+	 * @return bool
336
+	 * @throws EE_Error
337
+	 * @throws ReflectionException
338
+	 */
339
+	public function allow_overflow(): bool
340
+	{
341
+		return $this->get('EVT_allow_overflow');
342
+	}
343
+
344
+
345
+	/**
346
+	 * @return string
347
+	 * @throws EE_Error
348
+	 * @throws ReflectionException
349
+	 */
350
+	public function created(): string
351
+	{
352
+		return $this->get('EVT_created');
353
+	}
354
+
355
+
356
+	/**
357
+	 * @return string
358
+	 * @throws EE_Error
359
+	 * @throws ReflectionException
360
+	 */
361
+	public function description(): string
362
+	{
363
+		return $this->get('EVT_desc');
364
+	}
365
+
366
+
367
+	/**
368
+	 * Runs do_shortcode and wpautop on the description
369
+	 *
370
+	 * @return string of html
371
+	 * @throws EE_Error
372
+	 * @throws ReflectionException
373
+	 */
374
+	public function description_filtered(): string
375
+	{
376
+		return $this->get_pretty('EVT_desc');
377
+	}
378
+
379
+
380
+	/**
381
+	 * @return bool
382
+	 * @throws EE_Error
383
+	 * @throws ReflectionException
384
+	 */
385
+	public function display_description(): bool
386
+	{
387
+		return $this->get('EVT_display_desc');
388
+	}
389
+
390
+
391
+	/**
392
+	 * @return bool
393
+	 * @throws EE_Error
394
+	 * @throws ReflectionException
395
+	 */
396
+	public function display_ticket_selector(): bool
397
+	{
398
+		return (bool) $this->get('EVT_display_ticket_selector');
399
+	}
400
+
401
+
402
+	/**
403
+	 * @return string
404
+	 * @throws EE_Error
405
+	 * @throws ReflectionException
406
+	 */
407
+	public function external_url(): ?string
408
+	{
409
+		return $this->get('EVT_external_URL') ?? '';
410
+	}
411
+
412
+
413
+	/**
414
+	 * @return bool
415
+	 * @throws EE_Error
416
+	 * @throws ReflectionException
417
+	 */
418
+	public function member_only(): bool
419
+	{
420
+		return $this->get('EVT_member_only');
421
+	}
422
+
423
+
424
+	/**
425
+	 * @return string
426
+	 * @throws EE_Error
427
+	 * @throws ReflectionException
428
+	 */
429
+	public function phone(): string
430
+	{
431
+		return $this->get('EVT_phone');
432
+	}
433
+
434
+
435
+	/**
436
+	 * @return string
437
+	 * @throws EE_Error
438
+	 * @throws ReflectionException
439
+	 */
440
+	public function modified(): string
441
+	{
442
+		return $this->get('EVT_modified');
443
+	}
444
+
445
+
446
+	/**
447
+	 * @return string
448
+	 * @throws EE_Error
449
+	 * @throws ReflectionException
450
+	 */
451
+	public function name(): string
452
+	{
453
+		return $this->get('EVT_name');
454
+	}
455
+
456
+
457
+	/**
458
+	 * @return int
459
+	 * @throws EE_Error
460
+	 * @throws ReflectionException
461
+	 */
462
+	public function order(): int
463
+	{
464
+		return $this->get('EVT_order');
465
+	}
466
+
467
+
468
+	/**
469
+	 * @return string
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 */
473
+	public function default_registration_status(): string
474
+	{
475
+		$event_default_registration_status = $this->get('EVT_default_registration_status');
476
+		return ! empty($event_default_registration_status)
477
+			? $event_default_registration_status
478
+			: EE_Registry::instance()->CFG->registration->default_STS_ID;
479
+	}
480
+
481
+
482
+	/**
483
+	 * @param int|null    $num_words
484
+	 * @param string|null $more
485
+	 * @param bool        $not_full_desc
486
+	 * @return string
487
+	 * @throws EE_Error
488
+	 * @throws ReflectionException
489
+	 */
490
+	public function short_description(?int $num_words = 55, string $more = null, bool $not_full_desc = false): string
491
+	{
492
+		$short_desc = $this->get('EVT_short_desc');
493
+		if (! empty($short_desc) || $not_full_desc) {
494
+			return $short_desc;
495
+		}
496
+		$full_desc = $this->get('EVT_desc');
497
+		return wp_trim_words($full_desc, $num_words, $more);
498
+	}
499
+
500
+
501
+	/**
502
+	 * @return string
503
+	 * @throws EE_Error
504
+	 * @throws ReflectionException
505
+	 */
506
+	public function slug(): string
507
+	{
508
+		return $this->get('EVT_slug');
509
+	}
510
+
511
+
512
+	/**
513
+	 * @return string
514
+	 * @throws EE_Error
515
+	 * @throws ReflectionException
516
+	 */
517
+	public function timezone_string(): string
518
+	{
519
+		return $this->get('EVT_timezone_string');
520
+	}
521
+
522
+
523
+	/**
524
+	 * @return string
525
+	 * @throws EE_Error
526
+	 * @throws ReflectionException
527
+	 * @deprecated
528
+	 */
529
+	public function visible_on(): string
530
+	{
531
+		EE_Error::doing_it_wrong(
532
+			__METHOD__,
533
+			esc_html__(
534
+				'This method has been deprecated and there is no replacement for it.',
535
+				'event_espresso'
536
+			),
537
+			'5.0.0.rc.002'
538
+		);
539
+		return $this->get('EVT_visible_on');
540
+	}
541
+
542
+
543
+	/**
544
+	 * @return int
545
+	 * @throws EE_Error
546
+	 * @throws ReflectionException
547
+	 */
548
+	public function wp_user(): int
549
+	{
550
+		return (int) $this->get('EVT_wp_user');
551
+	}
552
+
553
+
554
+	/**
555
+	 * @return bool
556
+	 * @throws EE_Error
557
+	 * @throws ReflectionException
558
+	 */
559
+	public function donations(): bool
560
+	{
561
+		return $this->get('EVT_donations');
562
+	}
563
+
564
+
565
+	/**
566
+	 * @param int $limit
567
+	 * @throws EE_Error
568
+	 * @throws ReflectionException
569
+	 */
570
+	public function set_additional_limit(int $limit)
571
+	{
572
+		$this->set('EVT_additional_limit', $limit);
573
+	}
574
+
575
+
576
+	/**
577
+	 * @param $created
578
+	 * @throws EE_Error
579
+	 * @throws ReflectionException
580
+	 */
581
+	public function set_created($created)
582
+	{
583
+		$this->set('EVT_created', $created);
584
+	}
585
+
586
+
587
+	/**
588
+	 * @param $desc
589
+	 * @throws EE_Error
590
+	 * @throws ReflectionException
591
+	 */
592
+	public function set_description($desc)
593
+	{
594
+		$this->set('EVT_desc', $desc);
595
+	}
596
+
597
+
598
+	/**
599
+	 * @param $display_desc
600
+	 * @throws EE_Error
601
+	 * @throws ReflectionException
602
+	 */
603
+	public function set_display_description($display_desc)
604
+	{
605
+		$this->set('EVT_display_desc', $display_desc);
606
+	}
607
+
608
+
609
+	/**
610
+	 * @param $display_ticket_selector
611
+	 * @throws EE_Error
612
+	 * @throws ReflectionException
613
+	 */
614
+	public function set_display_ticket_selector($display_ticket_selector)
615
+	{
616
+		$this->set('EVT_display_ticket_selector', $display_ticket_selector);
617
+	}
618
+
619
+
620
+	/**
621
+	 * @param $external_url
622
+	 * @throws EE_Error
623
+	 * @throws ReflectionException
624
+	 */
625
+	public function set_external_url($external_url)
626
+	{
627
+		$this->set('EVT_external_URL', $external_url);
628
+	}
629
+
630
+
631
+	/**
632
+	 * @param $member_only
633
+	 * @throws EE_Error
634
+	 * @throws ReflectionException
635
+	 */
636
+	public function set_member_only($member_only)
637
+	{
638
+		$this->set('EVT_member_only', $member_only);
639
+	}
640
+
641
+
642
+	/**
643
+	 * @param $event_phone
644
+	 * @throws EE_Error
645
+	 * @throws ReflectionException
646
+	 */
647
+	public function set_event_phone($event_phone)
648
+	{
649
+		$this->set('EVT_phone', $event_phone);
650
+	}
651
+
652
+
653
+	/**
654
+	 * @param $modified
655
+	 * @throws EE_Error
656
+	 * @throws ReflectionException
657
+	 */
658
+	public function set_modified($modified)
659
+	{
660
+		$this->set('EVT_modified', $modified);
661
+	}
662
+
663
+
664
+	/**
665
+	 * @param $name
666
+	 * @throws EE_Error
667
+	 * @throws ReflectionException
668
+	 */
669
+	public function set_name($name)
670
+	{
671
+		$this->set('EVT_name', $name);
672
+	}
673
+
674
+
675
+	/**
676
+	 * @param $order
677
+	 * @throws EE_Error
678
+	 * @throws ReflectionException
679
+	 */
680
+	public function set_order($order)
681
+	{
682
+		$this->set('EVT_order', $order);
683
+	}
684
+
685
+
686
+	/**
687
+	 * @param $short_desc
688
+	 * @throws EE_Error
689
+	 * @throws ReflectionException
690
+	 */
691
+	public function set_short_description($short_desc)
692
+	{
693
+		$this->set('EVT_short_desc', $short_desc);
694
+	}
695
+
696
+
697
+	/**
698
+	 * @param $slug
699
+	 * @throws EE_Error
700
+	 * @throws ReflectionException
701
+	 */
702
+	public function set_slug($slug)
703
+	{
704
+		$this->set('EVT_slug', $slug);
705
+	}
706
+
707
+
708
+	/**
709
+	 * @param $timezone_string
710
+	 * @throws EE_Error
711
+	 * @throws ReflectionException
712
+	 */
713
+	public function set_timezone_string($timezone_string)
714
+	{
715
+		$this->set('EVT_timezone_string', $timezone_string);
716
+	}
717
+
718
+
719
+	/**
720
+	 * @param $visible_on
721
+	 * @throws EE_Error
722
+	 * @throws ReflectionException
723
+	 * @deprecated
724
+	 */
725
+	public function set_visible_on($visible_on)
726
+	{
727
+		EE_Error::doing_it_wrong(
728
+			__METHOD__,
729
+			esc_html__(
730
+				'This method has been deprecated and there is no replacement for it.',
731
+				'event_espresso'
732
+			),
733
+			'5.0.0.rc.002'
734
+		);
735
+		$this->set('EVT_visible_on', $visible_on);
736
+	}
737
+
738
+
739
+	/**
740
+	 * @param $wp_user
741
+	 * @throws EE_Error
742
+	 * @throws ReflectionException
743
+	 */
744
+	public function set_wp_user($wp_user)
745
+	{
746
+		$this->set('EVT_wp_user', $wp_user);
747
+	}
748
+
749
+
750
+	/**
751
+	 * @param $default_registration_status
752
+	 * @throws EE_Error
753
+	 * @throws ReflectionException
754
+	 */
755
+	public function set_default_registration_status($default_registration_status)
756
+	{
757
+		$this->set('EVT_default_registration_status', $default_registration_status);
758
+	}
759
+
760
+
761
+	/**
762
+	 * @param $donations
763
+	 * @throws EE_Error
764
+	 * @throws ReflectionException
765
+	 */
766
+	public function set_donations($donations)
767
+	{
768
+		$this->set('EVT_donations', $donations);
769
+	}
770
+
771
+
772
+	/**
773
+	 * Adds a venue to this event
774
+	 *
775
+	 * @param int|EE_Venue /int $venue_id_or_obj
776
+	 * @return EE_Base_Class|EE_Venue
777
+	 * @throws EE_Error
778
+	 * @throws ReflectionException
779
+	 */
780
+	public function add_venue($venue_id_or_obj): EE_Venue
781
+	{
782
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
783
+	}
784
+
785
+
786
+	/**
787
+	 * Removes a venue from the event
788
+	 *
789
+	 * @param EE_Venue /int $venue_id_or_obj
790
+	 * @return EE_Base_Class|EE_Venue
791
+	 * @throws EE_Error
792
+	 * @throws ReflectionException
793
+	 */
794
+	public function remove_venue($venue_id_or_obj): EE_Venue
795
+	{
796
+		$venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
797
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
798
+	}
799
+
800
+
801
+	/**
802
+	 * Gets the venue related to the event. May provide additional $query_params if desired
803
+	 *
804
+	 * @param array $query_params
805
+	 * @return int
806
+	 * @throws EE_Error
807
+	 * @throws ReflectionException
808
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
809
+	 */
810
+	public function venue_ID(array $query_params = []): int
811
+	{
812
+		$venue = $this->get_first_related('Venue', $query_params);
813
+		return $venue instanceof EE_Venue ? $venue->ID() : 0;
814
+	}
815
+
816
+
817
+	/**
818
+	 * Gets the venue related to the event. May provide additional $query_params if desired
819
+	 *
820
+	 * @param array $query_params
821
+	 * @return EE_Base_Class|EE_Venue|null
822
+	 * @throws EE_Error
823
+	 * @throws ReflectionException
824
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
825
+	 */
826
+	public function venue(array $query_params = []): ?EE_Venue
827
+	{
828
+		return $this->get_first_related('Venue', $query_params);
829
+	}
830
+
831
+
832
+	/**
833
+	 * @param array $query_params
834
+	 * @return EE_Base_Class[]|EE_Venue[]
835
+	 * @throws EE_Error
836
+	 * @throws ReflectionException
837
+	 * @deprecated 5.0.0.p
838
+	 */
839
+	public function venues(array $query_params = []): array
840
+	{
841
+		$venue = $this->venue($query_params);
842
+		return $venue instanceof EE_Venue ? [$venue] : [];
843
+	}
844
+
845
+
846
+	/**
847
+	 * check if event id is present and if event is published
848
+	 *
849
+	 * @return boolean true yes, false no
850
+	 * @throws EE_Error
851
+	 * @throws ReflectionException
852
+	 */
853
+	private function _has_ID_and_is_published(): bool
854
+	{
855
+		// first check if event id is present and not NULL,
856
+		// then check if this event is published (or any of the equivalent "published" statuses)
857
+		return
858
+			$this->ID() && $this->ID() !== null
859
+			&& (
860
+				$this->status() === 'publish'
861
+				|| $this->status() === EEM_Event::sold_out
862
+				|| $this->status() === EEM_Event::postponed
863
+				|| $this->status() === EEM_Event::cancelled
864
+			);
865
+	}
866
+
867
+
868
+	/**
869
+	 * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
870
+	 *
871
+	 * @return boolean true yes, false no
872
+	 * @throws EE_Error
873
+	 * @throws ReflectionException
874
+	 */
875
+	public function is_upcoming(): bool
876
+	{
877
+		// check if event id is present and if this event is published
878
+		if ($this->is_inactive()) {
879
+			return false;
880
+		}
881
+		// set initial value
882
+		$upcoming = false;
883
+		// next let's get all datetimes and loop through them
884
+		$datetimes = $this->datetimes_in_chronological_order();
885
+		foreach ($datetimes as $datetime) {
886
+			if ($datetime instanceof EE_Datetime) {
887
+				// if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
888
+				if ($datetime->is_expired()) {
889
+					continue;
890
+				}
891
+				// if this dtt is active then we return false.
892
+				if ($datetime->is_active()) {
893
+					return false;
894
+				}
895
+				// otherwise let's check upcoming status
896
+				$upcoming = $datetime->is_upcoming();
897
+			}
898
+		}
899
+		return $upcoming;
900
+	}
901
+
902
+
903
+	/**
904
+	 * @return bool
905
+	 * @throws EE_Error
906
+	 * @throws ReflectionException
907
+	 */
908
+	public function is_active(): bool
909
+	{
910
+		// check if event id is present and if this event is published
911
+		if ($this->is_inactive()) {
912
+			return false;
913
+		}
914
+		// set initial value
915
+		$active = false;
916
+		// next let's get all datetimes and loop through them
917
+		$datetimes = $this->datetimes_in_chronological_order();
918
+		foreach ($datetimes as $datetime) {
919
+			if ($datetime instanceof EE_Datetime) {
920
+				// if this dtt is expired then we continue cause one of the other datetimes might be active.
921
+				if ($datetime->is_expired()) {
922
+					continue;
923
+				}
924
+				// if this dtt is upcoming then we return false.
925
+				if ($datetime->is_upcoming()) {
926
+					return false;
927
+				}
928
+				// otherwise let's check active status
929
+				$active = $datetime->is_active();
930
+			}
931
+		}
932
+		return $active;
933
+	}
934
+
935
+
936
+	/**
937
+	 * @return bool
938
+	 * @throws EE_Error
939
+	 * @throws ReflectionException
940
+	 */
941
+	public function is_expired(): bool
942
+	{
943
+		// check if event id is present and if this event is published
944
+		if ($this->is_inactive()) {
945
+			return false;
946
+		}
947
+		// set initial value
948
+		$expired = false;
949
+		// first let's get all datetimes and loop through them
950
+		$datetimes = $this->datetimes_in_chronological_order();
951
+		foreach ($datetimes as $datetime) {
952
+			if ($datetime instanceof EE_Datetime) {
953
+				// if this dtt is upcoming or active then we return false.
954
+				if ($datetime->is_upcoming() || $datetime->is_active()) {
955
+					return false;
956
+				}
957
+				// otherwise let's check active status
958
+				$expired = $datetime->is_expired();
959
+			}
960
+		}
961
+		return $expired;
962
+	}
963
+
964
+
965
+	/**
966
+	 * @return bool
967
+	 * @throws EE_Error
968
+	 * @throws ReflectionException
969
+	 */
970
+	public function is_inactive(): bool
971
+	{
972
+		// check if event id is present and if this event is published
973
+		if ($this->_has_ID_and_is_published()) {
974
+			return false;
975
+		}
976
+		return true;
977
+	}
978
+
979
+
980
+	/**
981
+	 * calculate spaces remaining based on "saleable" tickets
982
+	 *
983
+	 * @param array|null $tickets
984
+	 * @param bool       $filtered
985
+	 * @return int|float
986
+	 * @throws EE_Error
987
+	 * @throws DomainException
988
+	 * @throws UnexpectedEntityException
989
+	 * @throws ReflectionException
990
+	 */
991
+	public function spaces_remaining(?array $tickets = [], ?bool $filtered = true)
992
+	{
993
+		$this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
994
+		$spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
995
+		return $filtered
996
+			? apply_filters(
997
+				'FHEE_EE_Event__spaces_remaining',
998
+				$spaces_remaining,
999
+				$this,
1000
+				$tickets
1001
+			)
1002
+			: $spaces_remaining;
1003
+	}
1004
+
1005
+
1006
+	/**
1007
+	 *    perform_sold_out_status_check
1008
+	 *    checks all of this event's datetime  reg_limit - sold values to determine if ANY datetimes have spaces
1009
+	 *    available... if NOT, then the event status will get toggled to 'sold_out'
1010
+	 *
1011
+	 * @return bool    return the ACTUAL sold out state.
1012
+	 * @throws EE_Error
1013
+	 * @throws DomainException
1014
+	 * @throws UnexpectedEntityException
1015
+	 * @throws ReflectionException
1016
+	 */
1017
+	public function perform_sold_out_status_check(): bool
1018
+	{
1019
+		// get all tickets
1020
+		$tickets     = $this->tickets(
1021
+			[
1022
+				'default_where_conditions' => 'none',
1023
+				'order_by'                 => ['TKT_qty' => 'ASC'],
1024
+			]
1025
+		);
1026
+		$all_expired = true;
1027
+		foreach ($tickets as $ticket) {
1028
+			if (! $ticket->is_expired()) {
1029
+				$all_expired = false;
1030
+				break;
1031
+			}
1032
+		}
1033
+		// if all the tickets are just expired, then don't update the event status to sold out
1034
+		if ($all_expired) {
1035
+			return true;
1036
+		}
1037
+		$spaces_remaining = $this->spaces_remaining($tickets);
1038
+		if ($spaces_remaining < 1) {
1039
+			if ($this->status() !== EEM_CPT_Base::post_status_private) {
1040
+				$this->set_status(EEM_Event::sold_out);
1041
+				$this->save();
1042
+			}
1043
+			$sold_out = true;
1044
+		} else {
1045
+			$sold_out = false;
1046
+			// was event previously marked as sold out ?
1047
+			if ($this->status() === EEM_Event::sold_out) {
1048
+				// revert status to previous value, if it was set
1049
+				$previous_event_status = $this->get_post_meta('_previous_event_status', true);
1050
+				if ($previous_event_status) {
1051
+					$this->set_status($previous_event_status);
1052
+					$this->save();
1053
+				}
1054
+			}
1055
+		}
1056
+		do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
1057
+		return $sold_out;
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 * This returns the total remaining spaces for sale on this event.
1063
+	 *
1064
+	 * @return int|float
1065
+	 * @throws EE_Error
1066
+	 * @throws DomainException
1067
+	 * @throws UnexpectedEntityException
1068
+	 * @throws ReflectionException
1069
+	 * @uses EE_Event::total_available_spaces()
1070
+	 */
1071
+	public function spaces_remaining_for_sale()
1072
+	{
1073
+		return $this->total_available_spaces(true);
1074
+	}
1075
+
1076
+
1077
+	/**
1078
+	 * This returns the total spaces available for an event
1079
+	 * while considering all the quantities on the tickets and the reg limits
1080
+	 * on the datetimes attached to this event.
1081
+	 *
1082
+	 * @param bool $consider_sold   Whether to consider any tickets that have already sold in our calculation.
1083
+	 *                              If this is false, then we return the most tickets that could ever be sold
1084
+	 *                              for this event with the datetime and tickets setup on the event under optimal
1085
+	 *                              selling conditions.  Otherwise we return a live calculation of spaces available
1086
+	 *                              based on tickets sold.  Depending on setup and stage of sales, this
1087
+	 *                              may appear to equal remaining tickets.  However, the more tickets are
1088
+	 *                              sold out, the more accurate the "live" total is.
1089
+	 * @return int|float
1090
+	 * @throws EE_Error
1091
+	 * @throws DomainException
1092
+	 * @throws UnexpectedEntityException
1093
+	 * @throws ReflectionException
1094
+	 */
1095
+	public function total_available_spaces(bool $consider_sold = false)
1096
+	{
1097
+		$spaces_available = $consider_sold
1098
+			? $this->getAvailableSpacesCalculator()->spacesRemaining()
1099
+			: $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
1100
+		return apply_filters(
1101
+			'FHEE_EE_Event__total_available_spaces__spaces_available',
1102
+			$spaces_available,
1103
+			$this,
1104
+			$this->getAvailableSpacesCalculator()->getDatetimes(),
1105
+			$this->getAvailableSpacesCalculator()->getActiveTickets()
1106
+		);
1107
+	}
1108
+
1109
+
1110
+	/**
1111
+	 * Checks if the event is set to sold out
1112
+	 *
1113
+	 * @param bool $actual  whether or not to perform calculations to not only figure the
1114
+	 *                      actual status but also to flip the status if necessary to sold
1115
+	 *                      out If false, we just check the existing status of the event
1116
+	 * @return boolean
1117
+	 * @throws EE_Error
1118
+	 * @throws ReflectionException
1119
+	 */
1120
+	public function is_sold_out(bool $actual = false): bool
1121
+	{
1122
+		if (! $actual) {
1123
+			return $this->status() === EEM_Event::sold_out;
1124
+		}
1125
+		return $this->perform_sold_out_status_check();
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * Checks if the event is marked as postponed
1131
+	 *
1132
+	 * @return boolean
1133
+	 */
1134
+	public function is_postponed(): bool
1135
+	{
1136
+		return $this->status() === EEM_Event::postponed;
1137
+	}
1138
+
1139
+
1140
+	/**
1141
+	 * Checks if the event is marked as cancelled
1142
+	 *
1143
+	 * @return boolean
1144
+	 */
1145
+	public function is_cancelled(): bool
1146
+	{
1147
+		return $this->status() === EEM_Event::cancelled;
1148
+	}
1149
+
1150
+
1151
+	/**
1152
+	 * Get the logical active status in a hierarchical order for all the datetimes.  Note
1153
+	 * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1154
+	 * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1155
+	 * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1156
+	 * the event is considered expired.
1157
+	 * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a
1158
+	 * status set on the EVENT when it is not published and thus is done
1159
+	 *
1160
+	 * @param bool $reset
1161
+	 * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1162
+	 * @throws EE_Error
1163
+	 * @throws ReflectionException
1164
+	 */
1165
+	public function get_active_status(bool $reset = false)
1166
+	{
1167
+		// if the active status has already been set, then just use that value (unless we are resetting it)
1168
+		if (! empty($this->_active_status) && ! $reset) {
1169
+			return $this->_active_status;
1170
+		}
1171
+		// first check if event id is present on this object
1172
+		if (! $this->ID()) {
1173
+			return false;
1174
+		}
1175
+		$where_params_for_event = [['EVT_ID' => $this->ID()]];
1176
+		// if event is published:
1177
+		if (
1178
+			$this->status() === EEM_CPT_Base::post_status_publish
1179
+			|| $this->status() === EEM_CPT_Base::post_status_private
1180
+		) {
1181
+			// active?
1182
+			if (
1183
+				EEM_Datetime::instance()->get_datetime_count_for_status(
1184
+					EE_Datetime::active,
1185
+					$where_params_for_event
1186
+				) > 0
1187
+			) {
1188
+				$this->_active_status = EE_Datetime::active;
1189
+			} else {
1190
+				// upcoming?
1191
+				if (
1192
+					EEM_Datetime::instance()->get_datetime_count_for_status(
1193
+						EE_Datetime::upcoming,
1194
+						$where_params_for_event
1195
+					) > 0
1196
+				) {
1197
+					$this->_active_status = EE_Datetime::upcoming;
1198
+				} else {
1199
+					// expired?
1200
+					if (
1201
+						EEM_Datetime::instance()->get_datetime_count_for_status(
1202
+							EE_Datetime::expired,
1203
+							$where_params_for_event
1204
+						) > 0
1205
+					) {
1206
+						$this->_active_status = EE_Datetime::expired;
1207
+					} else {
1208
+						// it would be odd if things make it this far
1209
+						// because it basically means there are no datetimes attached to the event.
1210
+						// So in this case it will just be considered inactive.
1211
+						$this->_active_status = EE_Datetime::inactive;
1212
+					}
1213
+				}
1214
+			}
1215
+		} else {
1216
+			// the event is not published, so let's just set it's active status according to its' post status
1217
+			switch ($this->status()) {
1218
+				case EEM_Event::sold_out:
1219
+					$this->_active_status = EE_Datetime::sold_out;
1220
+					break;
1221
+				case EEM_Event::cancelled:
1222
+					$this->_active_status = EE_Datetime::cancelled;
1223
+					break;
1224
+				case EEM_Event::postponed:
1225
+					$this->_active_status = EE_Datetime::postponed;
1226
+					break;
1227
+				default:
1228
+					$this->_active_status = EE_Datetime::inactive;
1229
+			}
1230
+		}
1231
+		return $this->_active_status;
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 *    pretty_active_status
1237
+	 *
1238
+	 * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1239
+	 * @return string
1240
+	 * @throws EE_Error
1241
+	 * @throws ReflectionException
1242
+	 */
1243
+	public function pretty_active_status(bool $echo = true): string
1244
+	{
1245
+		$active_status = $this->get_active_status();
1246
+		$status        = "
1247 1247
         <span class='event-active-status event-active-status-$active_status ee-status ee-status-bg--$active_status'>
1248 1248
             " . EEH_Template::pretty_status($active_status, false, 'sentence') . "
1249 1249
         </span >";
1250
-        if ($echo) {
1251
-            echo wp_kses($status, AllowedTags::getAllowedTags());
1252
-            return '';
1253
-        }
1254
-        return $status;
1255
-    }
1256
-
1257
-
1258
-    /**
1259
-     * @return bool|int
1260
-     * @throws EE_Error
1261
-     * @throws ReflectionException
1262
-     */
1263
-    public function get_number_of_tickets_sold()
1264
-    {
1265
-        $tkt_sold = 0;
1266
-        if (! $this->ID()) {
1267
-            return 0;
1268
-        }
1269
-        $datetimes = $this->datetimes();
1270
-        foreach ($datetimes as $datetime) {
1271
-            if ($datetime instanceof EE_Datetime) {
1272
-                $tkt_sold += $datetime->sold();
1273
-            }
1274
-        }
1275
-        return $tkt_sold;
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * This just returns a count of all the registrations for this event
1281
-     *
1282
-     * @return int
1283
-     * @throws EE_Error
1284
-     * @throws ReflectionException
1285
-     */
1286
-    public function get_count_of_all_registrations(): int
1287
-    {
1288
-        return EEM_Event::instance()->count_related($this, 'Registration');
1289
-    }
1290
-
1291
-
1292
-    /**
1293
-     * This returns the ticket with the earliest start time that is
1294
-     * available for this event (across all datetimes attached to the event)
1295
-     *
1296
-     * @return EE_Base_Class|EE_Ticket|null
1297
-     * @throws EE_Error
1298
-     * @throws ReflectionException
1299
-     */
1300
-    public function get_ticket_with_earliest_start_time()
1301
-    {
1302
-        $where['Datetime.EVT_ID'] = $this->ID();
1303
-        $query_params             = [$where, 'order_by' => ['TKT_start_date' => 'ASC']];
1304
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1305
-    }
1306
-
1307
-
1308
-    /**
1309
-     * This returns the ticket with the latest end time that is available
1310
-     * for this event (across all datetimes attached to the event)
1311
-     *
1312
-     * @return EE_Base_Class|EE_Ticket|null
1313
-     * @throws EE_Error
1314
-     * @throws ReflectionException
1315
-     */
1316
-    public function get_ticket_with_latest_end_time()
1317
-    {
1318
-        $where['Datetime.EVT_ID'] = $this->ID();
1319
-        $query_params             = [$where, 'order_by' => ['TKT_end_date' => 'DESC']];
1320
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1321
-    }
1322
-
1323
-
1324
-    /**
1325
-     * This returns the number of different ticket types currently on sale for this event.
1326
-     *
1327
-     * @return int
1328
-     * @throws EE_Error
1329
-     * @throws ReflectionException
1330
-     */
1331
-    public function countTicketsOnSale(): int
1332
-    {
1333
-        $where = [
1334
-            'Datetime.EVT_ID' => $this->ID(),
1335
-            'TKT_start_date'  => ['<', time()],
1336
-            'TKT_end_date'    => ['>', time()],
1337
-        ];
1338
-        return EEM_Ticket::instance()->count([$where]);
1339
-    }
1340
-
1341
-
1342
-    /**
1343
-     * This returns whether there are any tickets on sale for this event.
1344
-     *
1345
-     * @return bool true = YES tickets on sale.
1346
-     * @throws EE_Error
1347
-     * @throws ReflectionException
1348
-     */
1349
-    public function tickets_on_sale(): bool
1350
-    {
1351
-        return $this->countTicketsOnSale() > 0;
1352
-    }
1353
-
1354
-
1355
-    /**
1356
-     * Gets the URL for viewing this event on the front-end. Overrides parent
1357
-     * to check for an external URL first
1358
-     *
1359
-     * @return string
1360
-     * @throws EE_Error
1361
-     * @throws ReflectionException
1362
-     */
1363
-    public function get_permalink(): string
1364
-    {
1365
-        if ($this->external_url()) {
1366
-            return $this->external_url();
1367
-        }
1368
-        return parent::get_permalink();
1369
-    }
1370
-
1371
-
1372
-    /**
1373
-     * Gets the first term for 'espresso_event_categories' we can find
1374
-     *
1375
-     * @param array $query_params
1376
-     * @return EE_Base_Class|EE_Term|null
1377
-     * @throws EE_Error
1378
-     * @throws ReflectionException
1379
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1380
-     */
1381
-    public function first_event_category(array $query_params = []): ?EE_Term
1382
-    {
1383
-        $query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1384
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1385
-        return EEM_Term::instance()->get_one($query_params);
1386
-    }
1387
-
1388
-
1389
-    /**
1390
-     * Gets all terms for 'espresso_event_categories' we can find
1391
-     *
1392
-     * @param array $query_params
1393
-     * @return EE_Base_Class[]|EE_Term[]
1394
-     * @throws EE_Error
1395
-     * @throws ReflectionException
1396
-     */
1397
-    public function get_all_event_categories(array $query_params = []): array
1398
-    {
1399
-        $query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1400
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1401
-        return EEM_Term::instance()->get_all($query_params);
1402
-    }
1403
-
1404
-
1405
-    /**
1406
-     * Adds a question group to this event
1407
-     *
1408
-     * @param EE_Question_Group|int $question_group_id_or_obj
1409
-     * @param bool                  $for_primary if true, the question group will be added for the primary
1410
-     *                                           registrant, if false will be added for others. default: false
1411
-     * @return EE_Base_Class|EE_Question_Group
1412
-     * @throws EE_Error
1413
-     * @throws InvalidArgumentException
1414
-     * @throws InvalidDataTypeException
1415
-     * @throws InvalidInterfaceException
1416
-     * @throws ReflectionException
1417
-     */
1418
-    public function add_question_group($question_group_id_or_obj, bool $for_primary = false): EE_Question_Group
1419
-    {
1420
-        // If the row already exists, it will be updated. If it doesn't, it will be inserted.
1421
-        // That's in EE_HABTM_Relation::add_relation_to().
1422
-        return $this->_add_relation_to(
1423
-            $question_group_id_or_obj,
1424
-            'Question_Group',
1425
-            [
1426
-                EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary) => true,
1427
-            ]
1428
-        );
1429
-    }
1430
-
1431
-
1432
-    /**
1433
-     * Removes a question group from the event
1434
-     *
1435
-     * @param EE_Question_Group|int $question_group_id_or_obj
1436
-     * @param bool                  $for_primary if true, the question group will be removed from the primary
1437
-     *                                           registrant, if false will be removed from others. default: false
1438
-     * @return EE_Base_Class|EE_Question_Group|int
1439
-     * @throws EE_Error
1440
-     * @throws InvalidArgumentException
1441
-     * @throws ReflectionException
1442
-     * @throws InvalidDataTypeException
1443
-     * @throws InvalidInterfaceException
1444
-     */
1445
-    public function remove_question_group($question_group_id_or_obj, bool $for_primary = false)
1446
-    {
1447
-        // If the question group is used for the other type (primary or additional)
1448
-        // then just update it. If not, delete it outright.
1449
-        $existing_relation = $this->get_first_related(
1450
-            'Event_Question_Group',
1451
-            [
1452
-                [
1453
-                    'QSG_ID' => EEM_Question_Group::instance()->ensure_is_ID($question_group_id_or_obj),
1454
-                ],
1455
-            ]
1456
-        );
1457
-        $field_to_update   = EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary);
1458
-        $other_field       = EEM_Event_Question_Group::instance()->fieldNameForContext(! $for_primary);
1459
-        if ($existing_relation->get($other_field) === false) {
1460
-            // Delete it. It's now no longer for primary or additional question groups.
1461
-            return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group');
1462
-        }
1463
-        // Just update it. They'll still use this question group for the other category
1464
-        $existing_relation->save(
1465
-            [
1466
-                $field_to_update => false,
1467
-            ]
1468
-        );
1469
-        return $question_group_id_or_obj;
1470
-    }
1471
-
1472
-
1473
-    /**
1474
-     * Gets all the question groups, ordering them by QSG_order ascending
1475
-     *
1476
-     * @param array $query_params
1477
-     * @return EE_Base_Class[]|EE_Question_Group[]
1478
-     * @throws EE_Error
1479
-     * @throws ReflectionException
1480
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1481
-     */
1482
-    public function question_groups(array $query_params = []): array
1483
-    {
1484
-        $query_params = ! empty($query_params) ? $query_params : ['order_by' => ['QSG_order' => 'ASC']];
1485
-        return $this->get_many_related('Question_Group', $query_params);
1486
-    }
1487
-
1488
-
1489
-    /**
1490
-     * Implementation for EEI_Has_Icon interface method.
1491
-     *
1492
-     * @return string
1493
-     * @see EEI_Visual_Representation for comments
1494
-     */
1495
-    public function get_icon(): string
1496
-    {
1497
-        return '<span class="dashicons dashicons-flag"></span>';
1498
-    }
1499
-
1500
-
1501
-    /**
1502
-     * Implementation for EEI_Admin_Links interface method.
1503
-     *
1504
-     * @return string
1505
-     * @throws EE_Error
1506
-     * @throws ReflectionException
1507
-     * @see EEI_Admin_Links for comments
1508
-     */
1509
-    public function get_admin_details_link(): string
1510
-    {
1511
-        return $this->get_admin_edit_link();
1512
-    }
1513
-
1514
-
1515
-    /**
1516
-     * Implementation for EEI_Admin_Links interface method.
1517
-     *
1518
-     * @return string
1519
-     * @throws EE_Error
1520
-     * @throws ReflectionException
1521
-     * @see EEI_Admin_Links for comments
1522
-     */
1523
-    public function get_admin_edit_link(): string
1524
-    {
1525
-        return EEH_URL::add_query_args_and_nonce(
1526
-            [
1527
-                'page'   => 'espresso_events',
1528
-                'action' => 'edit',
1529
-                'post'   => $this->ID(),
1530
-            ],
1531
-            admin_url('admin.php')
1532
-        );
1533
-    }
1534
-
1535
-
1536
-    /**
1537
-     * Implementation for EEI_Admin_Links interface method.
1538
-     *
1539
-     * @return string
1540
-     * @see EEI_Admin_Links for comments
1541
-     */
1542
-    public function get_admin_settings_link(): string
1543
-    {
1544
-        return EEH_URL::add_query_args_and_nonce(
1545
-            [
1546
-                'page'   => 'espresso_events',
1547
-                'action' => 'default_event_settings',
1548
-            ],
1549
-            admin_url('admin.php')
1550
-        );
1551
-    }
1552
-
1553
-
1554
-    /**
1555
-     * Implementation for EEI_Admin_Links interface method.
1556
-     *
1557
-     * @return string
1558
-     * @see EEI_Admin_Links for comments
1559
-     */
1560
-    public function get_admin_overview_link(): string
1561
-    {
1562
-        return EEH_URL::add_query_args_and_nonce(
1563
-            [
1564
-                'page'   => 'espresso_events',
1565
-                'action' => 'default',
1566
-            ],
1567
-            admin_url('admin.php')
1568
-        );
1569
-    }
1570
-
1571
-
1572
-    /**
1573
-     * @return string|null
1574
-     * @throws EE_Error
1575
-     * @throws ReflectionException
1576
-     */
1577
-    public function registrationFormUuid(): ?string
1578
-    {
1579
-        return $this->get('FSC_UUID') ?? '';
1580
-    }
1581
-
1582
-
1583
-    /**
1584
-     * Gets all the form sections for this event
1585
-     *
1586
-     * @return EE_Base_Class[]|EE_Form_Section[]
1587
-     * @throws EE_Error
1588
-     * @throws ReflectionException
1589
-     */
1590
-    public function registrationForm(): array
1591
-    {
1592
-        $FSC_UUID = $this->registrationFormUuid();
1593
-
1594
-        if (empty($FSC_UUID)) {
1595
-            return [];
1596
-        }
1597
-
1598
-        return EEM_Form_Section::instance()->get_all(
1599
-            [
1600
-                [
1601
-                    'OR' => [
1602
-                        'FSC_UUID'      => $FSC_UUID, // top level form
1603
-                        'FSC_belongsTo' => $FSC_UUID, // child form sections
1604
-                    ],
1605
-                ],
1606
-                'order_by' => ['FSC_order' => 'ASC'],
1607
-            ]
1608
-        );
1609
-    }
1610
-
1611
-
1612
-    /**
1613
-     * @param string $UUID
1614
-     * @throws EE_Error
1615
-     * @throws ReflectionException
1616
-     */
1617
-    public function setRegistrationFormUuid(string $UUID): void
1618
-    {
1619
-        if (! Cuid::isCuid($UUID)) {
1620
-            throw new InvalidArgumentException(
1621
-                sprintf(
1622
-                /* translators: 1: UUID value, 2: UUID generator function. */
1623
-                    esc_html__(
1624
-                        'The supplied UUID "%1$s" is invalid or missing. Please use %2$s to generate a valid one.',
1625
-                        'event_espresso'
1626
-                    ),
1627
-                    $UUID,
1628
-                    '`Cuid::cuid()`'
1629
-                )
1630
-            );
1631
-        }
1632
-        $this->set('FSC_UUID', $UUID);
1633
-    }
1634
-
1635
-
1636
-    /**
1637
-     * Get visibility status of event
1638
-     *
1639
-     * @param bool $hide_public
1640
-     * @return string
1641
-     */
1642
-    public function get_visibility_status(bool $hide_public = true): string
1643
-    {
1644
-        if ($this->status() === 'private') {
1645
-            return esc_html__('Private', 'event_espresso');
1646
-        }
1647
-        if (! empty($this->wp_post()->post_password)) {
1648
-            return esc_html__('Password Protected', 'event_espresso');
1649
-        }
1650
-        if (! $hide_public) {
1651
-            return esc_html__('Public', 'event_espresso');
1652
-        }
1653
-
1654
-        return '';
1655
-    }
1250
+		if ($echo) {
1251
+			echo wp_kses($status, AllowedTags::getAllowedTags());
1252
+			return '';
1253
+		}
1254
+		return $status;
1255
+	}
1256
+
1257
+
1258
+	/**
1259
+	 * @return bool|int
1260
+	 * @throws EE_Error
1261
+	 * @throws ReflectionException
1262
+	 */
1263
+	public function get_number_of_tickets_sold()
1264
+	{
1265
+		$tkt_sold = 0;
1266
+		if (! $this->ID()) {
1267
+			return 0;
1268
+		}
1269
+		$datetimes = $this->datetimes();
1270
+		foreach ($datetimes as $datetime) {
1271
+			if ($datetime instanceof EE_Datetime) {
1272
+				$tkt_sold += $datetime->sold();
1273
+			}
1274
+		}
1275
+		return $tkt_sold;
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * This just returns a count of all the registrations for this event
1281
+	 *
1282
+	 * @return int
1283
+	 * @throws EE_Error
1284
+	 * @throws ReflectionException
1285
+	 */
1286
+	public function get_count_of_all_registrations(): int
1287
+	{
1288
+		return EEM_Event::instance()->count_related($this, 'Registration');
1289
+	}
1290
+
1291
+
1292
+	/**
1293
+	 * This returns the ticket with the earliest start time that is
1294
+	 * available for this event (across all datetimes attached to the event)
1295
+	 *
1296
+	 * @return EE_Base_Class|EE_Ticket|null
1297
+	 * @throws EE_Error
1298
+	 * @throws ReflectionException
1299
+	 */
1300
+	public function get_ticket_with_earliest_start_time()
1301
+	{
1302
+		$where['Datetime.EVT_ID'] = $this->ID();
1303
+		$query_params             = [$where, 'order_by' => ['TKT_start_date' => 'ASC']];
1304
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1305
+	}
1306
+
1307
+
1308
+	/**
1309
+	 * This returns the ticket with the latest end time that is available
1310
+	 * for this event (across all datetimes attached to the event)
1311
+	 *
1312
+	 * @return EE_Base_Class|EE_Ticket|null
1313
+	 * @throws EE_Error
1314
+	 * @throws ReflectionException
1315
+	 */
1316
+	public function get_ticket_with_latest_end_time()
1317
+	{
1318
+		$where['Datetime.EVT_ID'] = $this->ID();
1319
+		$query_params             = [$where, 'order_by' => ['TKT_end_date' => 'DESC']];
1320
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1321
+	}
1322
+
1323
+
1324
+	/**
1325
+	 * This returns the number of different ticket types currently on sale for this event.
1326
+	 *
1327
+	 * @return int
1328
+	 * @throws EE_Error
1329
+	 * @throws ReflectionException
1330
+	 */
1331
+	public function countTicketsOnSale(): int
1332
+	{
1333
+		$where = [
1334
+			'Datetime.EVT_ID' => $this->ID(),
1335
+			'TKT_start_date'  => ['<', time()],
1336
+			'TKT_end_date'    => ['>', time()],
1337
+		];
1338
+		return EEM_Ticket::instance()->count([$where]);
1339
+	}
1340
+
1341
+
1342
+	/**
1343
+	 * This returns whether there are any tickets on sale for this event.
1344
+	 *
1345
+	 * @return bool true = YES tickets on sale.
1346
+	 * @throws EE_Error
1347
+	 * @throws ReflectionException
1348
+	 */
1349
+	public function tickets_on_sale(): bool
1350
+	{
1351
+		return $this->countTicketsOnSale() > 0;
1352
+	}
1353
+
1354
+
1355
+	/**
1356
+	 * Gets the URL for viewing this event on the front-end. Overrides parent
1357
+	 * to check for an external URL first
1358
+	 *
1359
+	 * @return string
1360
+	 * @throws EE_Error
1361
+	 * @throws ReflectionException
1362
+	 */
1363
+	public function get_permalink(): string
1364
+	{
1365
+		if ($this->external_url()) {
1366
+			return $this->external_url();
1367
+		}
1368
+		return parent::get_permalink();
1369
+	}
1370
+
1371
+
1372
+	/**
1373
+	 * Gets the first term for 'espresso_event_categories' we can find
1374
+	 *
1375
+	 * @param array $query_params
1376
+	 * @return EE_Base_Class|EE_Term|null
1377
+	 * @throws EE_Error
1378
+	 * @throws ReflectionException
1379
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1380
+	 */
1381
+	public function first_event_category(array $query_params = []): ?EE_Term
1382
+	{
1383
+		$query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1384
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1385
+		return EEM_Term::instance()->get_one($query_params);
1386
+	}
1387
+
1388
+
1389
+	/**
1390
+	 * Gets all terms for 'espresso_event_categories' we can find
1391
+	 *
1392
+	 * @param array $query_params
1393
+	 * @return EE_Base_Class[]|EE_Term[]
1394
+	 * @throws EE_Error
1395
+	 * @throws ReflectionException
1396
+	 */
1397
+	public function get_all_event_categories(array $query_params = []): array
1398
+	{
1399
+		$query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1400
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1401
+		return EEM_Term::instance()->get_all($query_params);
1402
+	}
1403
+
1404
+
1405
+	/**
1406
+	 * Adds a question group to this event
1407
+	 *
1408
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1409
+	 * @param bool                  $for_primary if true, the question group will be added for the primary
1410
+	 *                                           registrant, if false will be added for others. default: false
1411
+	 * @return EE_Base_Class|EE_Question_Group
1412
+	 * @throws EE_Error
1413
+	 * @throws InvalidArgumentException
1414
+	 * @throws InvalidDataTypeException
1415
+	 * @throws InvalidInterfaceException
1416
+	 * @throws ReflectionException
1417
+	 */
1418
+	public function add_question_group($question_group_id_or_obj, bool $for_primary = false): EE_Question_Group
1419
+	{
1420
+		// If the row already exists, it will be updated. If it doesn't, it will be inserted.
1421
+		// That's in EE_HABTM_Relation::add_relation_to().
1422
+		return $this->_add_relation_to(
1423
+			$question_group_id_or_obj,
1424
+			'Question_Group',
1425
+			[
1426
+				EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary) => true,
1427
+			]
1428
+		);
1429
+	}
1430
+
1431
+
1432
+	/**
1433
+	 * Removes a question group from the event
1434
+	 *
1435
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1436
+	 * @param bool                  $for_primary if true, the question group will be removed from the primary
1437
+	 *                                           registrant, if false will be removed from others. default: false
1438
+	 * @return EE_Base_Class|EE_Question_Group|int
1439
+	 * @throws EE_Error
1440
+	 * @throws InvalidArgumentException
1441
+	 * @throws ReflectionException
1442
+	 * @throws InvalidDataTypeException
1443
+	 * @throws InvalidInterfaceException
1444
+	 */
1445
+	public function remove_question_group($question_group_id_or_obj, bool $for_primary = false)
1446
+	{
1447
+		// If the question group is used for the other type (primary or additional)
1448
+		// then just update it. If not, delete it outright.
1449
+		$existing_relation = $this->get_first_related(
1450
+			'Event_Question_Group',
1451
+			[
1452
+				[
1453
+					'QSG_ID' => EEM_Question_Group::instance()->ensure_is_ID($question_group_id_or_obj),
1454
+				],
1455
+			]
1456
+		);
1457
+		$field_to_update   = EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary);
1458
+		$other_field       = EEM_Event_Question_Group::instance()->fieldNameForContext(! $for_primary);
1459
+		if ($existing_relation->get($other_field) === false) {
1460
+			// Delete it. It's now no longer for primary or additional question groups.
1461
+			return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group');
1462
+		}
1463
+		// Just update it. They'll still use this question group for the other category
1464
+		$existing_relation->save(
1465
+			[
1466
+				$field_to_update => false,
1467
+			]
1468
+		);
1469
+		return $question_group_id_or_obj;
1470
+	}
1471
+
1472
+
1473
+	/**
1474
+	 * Gets all the question groups, ordering them by QSG_order ascending
1475
+	 *
1476
+	 * @param array $query_params
1477
+	 * @return EE_Base_Class[]|EE_Question_Group[]
1478
+	 * @throws EE_Error
1479
+	 * @throws ReflectionException
1480
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1481
+	 */
1482
+	public function question_groups(array $query_params = []): array
1483
+	{
1484
+		$query_params = ! empty($query_params) ? $query_params : ['order_by' => ['QSG_order' => 'ASC']];
1485
+		return $this->get_many_related('Question_Group', $query_params);
1486
+	}
1487
+
1488
+
1489
+	/**
1490
+	 * Implementation for EEI_Has_Icon interface method.
1491
+	 *
1492
+	 * @return string
1493
+	 * @see EEI_Visual_Representation for comments
1494
+	 */
1495
+	public function get_icon(): string
1496
+	{
1497
+		return '<span class="dashicons dashicons-flag"></span>';
1498
+	}
1499
+
1500
+
1501
+	/**
1502
+	 * Implementation for EEI_Admin_Links interface method.
1503
+	 *
1504
+	 * @return string
1505
+	 * @throws EE_Error
1506
+	 * @throws ReflectionException
1507
+	 * @see EEI_Admin_Links for comments
1508
+	 */
1509
+	public function get_admin_details_link(): string
1510
+	{
1511
+		return $this->get_admin_edit_link();
1512
+	}
1513
+
1514
+
1515
+	/**
1516
+	 * Implementation for EEI_Admin_Links interface method.
1517
+	 *
1518
+	 * @return string
1519
+	 * @throws EE_Error
1520
+	 * @throws ReflectionException
1521
+	 * @see EEI_Admin_Links for comments
1522
+	 */
1523
+	public function get_admin_edit_link(): string
1524
+	{
1525
+		return EEH_URL::add_query_args_and_nonce(
1526
+			[
1527
+				'page'   => 'espresso_events',
1528
+				'action' => 'edit',
1529
+				'post'   => $this->ID(),
1530
+			],
1531
+			admin_url('admin.php')
1532
+		);
1533
+	}
1534
+
1535
+
1536
+	/**
1537
+	 * Implementation for EEI_Admin_Links interface method.
1538
+	 *
1539
+	 * @return string
1540
+	 * @see EEI_Admin_Links for comments
1541
+	 */
1542
+	public function get_admin_settings_link(): string
1543
+	{
1544
+		return EEH_URL::add_query_args_and_nonce(
1545
+			[
1546
+				'page'   => 'espresso_events',
1547
+				'action' => 'default_event_settings',
1548
+			],
1549
+			admin_url('admin.php')
1550
+		);
1551
+	}
1552
+
1553
+
1554
+	/**
1555
+	 * Implementation for EEI_Admin_Links interface method.
1556
+	 *
1557
+	 * @return string
1558
+	 * @see EEI_Admin_Links for comments
1559
+	 */
1560
+	public function get_admin_overview_link(): string
1561
+	{
1562
+		return EEH_URL::add_query_args_and_nonce(
1563
+			[
1564
+				'page'   => 'espresso_events',
1565
+				'action' => 'default',
1566
+			],
1567
+			admin_url('admin.php')
1568
+		);
1569
+	}
1570
+
1571
+
1572
+	/**
1573
+	 * @return string|null
1574
+	 * @throws EE_Error
1575
+	 * @throws ReflectionException
1576
+	 */
1577
+	public function registrationFormUuid(): ?string
1578
+	{
1579
+		return $this->get('FSC_UUID') ?? '';
1580
+	}
1581
+
1582
+
1583
+	/**
1584
+	 * Gets all the form sections for this event
1585
+	 *
1586
+	 * @return EE_Base_Class[]|EE_Form_Section[]
1587
+	 * @throws EE_Error
1588
+	 * @throws ReflectionException
1589
+	 */
1590
+	public function registrationForm(): array
1591
+	{
1592
+		$FSC_UUID = $this->registrationFormUuid();
1593
+
1594
+		if (empty($FSC_UUID)) {
1595
+			return [];
1596
+		}
1597
+
1598
+		return EEM_Form_Section::instance()->get_all(
1599
+			[
1600
+				[
1601
+					'OR' => [
1602
+						'FSC_UUID'      => $FSC_UUID, // top level form
1603
+						'FSC_belongsTo' => $FSC_UUID, // child form sections
1604
+					],
1605
+				],
1606
+				'order_by' => ['FSC_order' => 'ASC'],
1607
+			]
1608
+		);
1609
+	}
1610
+
1611
+
1612
+	/**
1613
+	 * @param string $UUID
1614
+	 * @throws EE_Error
1615
+	 * @throws ReflectionException
1616
+	 */
1617
+	public function setRegistrationFormUuid(string $UUID): void
1618
+	{
1619
+		if (! Cuid::isCuid($UUID)) {
1620
+			throw new InvalidArgumentException(
1621
+				sprintf(
1622
+				/* translators: 1: UUID value, 2: UUID generator function. */
1623
+					esc_html__(
1624
+						'The supplied UUID "%1$s" is invalid or missing. Please use %2$s to generate a valid one.',
1625
+						'event_espresso'
1626
+					),
1627
+					$UUID,
1628
+					'`Cuid::cuid()`'
1629
+				)
1630
+			);
1631
+		}
1632
+		$this->set('FSC_UUID', $UUID);
1633
+	}
1634
+
1635
+
1636
+	/**
1637
+	 * Get visibility status of event
1638
+	 *
1639
+	 * @param bool $hide_public
1640
+	 * @return string
1641
+	 */
1642
+	public function get_visibility_status(bool $hide_public = true): string
1643
+	{
1644
+		if ($this->status() === 'private') {
1645
+			return esc_html__('Private', 'event_espresso');
1646
+		}
1647
+		if (! empty($this->wp_post()->post_password)) {
1648
+			return esc_html__('Password Protected', 'event_espresso');
1649
+		}
1650
+		if (! $hide_public) {
1651
+			return esc_html__('Public', 'event_espresso');
1652
+		}
1653
+
1654
+		return '';
1655
+	}
1656 1656
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 2 patches
Indentation   +2592 added lines, -2592 removed lines patch added patch discarded remove patch
@@ -19,2596 +19,2596 @@
 block discarded – undo
19 19
  */
20 20
 class EE_Registration extends EE_Soft_Delete_Base_Class implements EEI_Registration, EEI_Admin_Links
21 21
 {
22
-    /**
23
-     * Used to reference when a registration has never been checked in.
24
-     *
25
-     * @deprecated use \EE_Checkin::status_checked_never instead
26
-     * @type int
27
-     */
28
-    const checkin_status_never = 2;
29
-
30
-    /**
31
-     * Used to reference when a registration has been checked in.
32
-     *
33
-     * @deprecated use \EE_Checkin::status_checked_in instead
34
-     * @type int
35
-     */
36
-    const checkin_status_in = 1;
37
-
38
-    /**
39
-     * Used to reference when a registration has been checked out.
40
-     *
41
-     * @deprecated use \EE_Checkin::status_checked_out instead
42
-     * @type int
43
-     */
44
-    const checkin_status_out = 0;
45
-
46
-    /**
47
-     * extra meta key for tracking reg status os trashed registrations
48
-     *
49
-     * @type string
50
-     */
51
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
-
53
-    /**
54
-     * extra meta key for tracking if registration has reserved ticket
55
-     *
56
-     * @type string
57
-     */
58
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
59
-
60
-
61
-    /**
62
-     * @param array  $props_n_values          incoming values
63
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
64
-     *                                        used.)
65
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
66
-     *                                        date_format and the second value is the time format
67
-     * @return EE_Registration
68
-     * @throws EE_Error
69
-     * @throws InvalidArgumentException
70
-     * @throws InvalidDataTypeException
71
-     * @throws InvalidInterfaceException
72
-     * @throws ReflectionException
73
-     */
74
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
75
-    {
76
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
77
-        return $has_object
78
-            ?: new self($props_n_values, false, $timezone, $date_formats);
79
-    }
80
-
81
-
82
-    /**
83
-     * @param array  $props_n_values  incoming values from the database
84
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
85
-     *                                the website will be used.
86
-     * @return EE_Registration
87
-     * @throws EE_Error
88
-     * @throws InvalidArgumentException
89
-     * @throws InvalidDataTypeException
90
-     * @throws InvalidInterfaceException
91
-     * @throws ReflectionException
92
-     */
93
-    public static function new_instance_from_db($props_n_values = [], $timezone = '')
94
-    {
95
-        return new self($props_n_values, true, $timezone);
96
-    }
97
-
98
-
99
-    /**
100
-     *        Set Event ID
101
-     *
102
-     * @param int $EVT_ID Event ID
103
-     * @throws DomainException
104
-     * @throws EE_Error
105
-     * @throws EntityNotFoundException
106
-     * @throws InvalidArgumentException
107
-     * @throws InvalidDataTypeException
108
-     * @throws InvalidInterfaceException
109
-     * @throws ReflectionException
110
-     * @throws RuntimeException
111
-     * @throws UnexpectedEntityException
112
-     */
113
-    public function set_event($EVT_ID = 0)
114
-    {
115
-        $this->set('EVT_ID', $EVT_ID);
116
-    }
117
-
118
-
119
-    /**
120
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
121
-     * be routed to internal methods
122
-     *
123
-     * @param string $field_name
124
-     * @param mixed  $field_value
125
-     * @param bool   $use_default
126
-     * @throws DomainException
127
-     * @throws EE_Error
128
-     * @throws EntityNotFoundException
129
-     * @throws InvalidArgumentException
130
-     * @throws InvalidDataTypeException
131
-     * @throws InvalidInterfaceException
132
-     * @throws ReflectionException
133
-     * @throws RuntimeException
134
-     * @throws UnexpectedEntityException
135
-     */
136
-    public function set($field_name, $field_value, $use_default = false)
137
-    {
138
-        switch ($field_name) {
139
-            case 'REG_code':
140
-                if (! empty($field_value) && ! $this->reg_code()) {
141
-                    $this->set_reg_code($field_value, $use_default);
142
-                }
143
-                break;
144
-            case 'STS_ID':
145
-                $this->set_status((string) $field_value, $use_default);
146
-                break;
147
-            default:
148
-                parent::set($field_name, $field_value, $use_default);
149
-        }
150
-    }
151
-
152
-
153
-    /**
154
-     * Set Status ID
155
-     * updates the registration status and ALSO...
156
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
157
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
158
-     *
159
-     * @param string                $new_STS_ID
160
-     * @param boolean               $use_default
161
-     * @param ContextInterface|null $context
162
-     * @return bool
163
-     * @throws DomainException
164
-     * @throws EE_Error
165
-     * @throws EntityNotFoundException
166
-     * @throws InvalidArgumentException
167
-     * @throws InvalidDataTypeException
168
-     * @throws InvalidInterfaceException
169
-     * @throws ReflectionException
170
-     * @throws RuntimeException
171
-     * @throws UnexpectedEntityException
172
-     */
173
-    public function set_status(
174
-        string $new_STS_ID = '',
175
-        bool $use_default = false,
176
-        ?ContextInterface $context = null
177
-    ): bool {
178
-        // get current REG_Status
179
-        $old_STS_ID = $this->status_ID();
180
-        $new_STS_ID = (string) apply_filters(
181
-            'AFEE__EE_Registration__set_status__new_STS_ID',
182
-            $new_STS_ID,
183
-            $context,
184
-            $this
185
-        );
186
-        // it's still good to allow the parent set method to have a say
187
-        parent::set('STS_ID', (! empty($new_STS_ID) ? $new_STS_ID : null), $use_default);
188
-        // if status has changed
189
-        if (
190
-            $old_STS_ID !== $new_STS_ID // and that status has actually changed
191
-            && ! empty($old_STS_ID) // and that old status is actually set
192
-            && ! empty($new_STS_ID) // as well as the new status
193
-            && $this->ID() // ensure registration is in the db
194
-        ) {
195
-            // THEN handle other changes that occur when reg status changes
196
-            // TO approved
197
-            if ($new_STS_ID === RegStatus::APPROVED) {
198
-                // reserve a space by incrementing ticket and datetime sold values
199
-                $this->reserveRegistrationSpace();
200
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
201
-                // OR FROM  approved
202
-            } elseif ($old_STS_ID === RegStatus::APPROVED) {
203
-                // release a space by decrementing ticket and datetime sold values
204
-                $this->releaseRegistrationSpace();
205
-                do_action(
206
-                    'AHEE__EE_Registration__set_status__from_approved',
207
-                    $this,
208
-                    $old_STS_ID,
209
-                    $new_STS_ID,
210
-                    $context
211
-                );
212
-            }
213
-            $this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
214
-            if ($this->statusChangeUpdatesTransaction($context)) {
215
-                $this->updateTransactionAfterStatusChange();
216
-            }
217
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
218
-        }
219
-        return ! empty($new_STS_ID);
220
-    }
221
-
222
-
223
-    /**
224
-     * update REGs and TXN when cancelled or declined registrations involved
225
-     *
226
-     * @param string                $new_STS_ID
227
-     * @param string                $old_STS_ID
228
-     * @param ContextInterface|null $context
229
-     * @throws EE_Error
230
-     * @throws InvalidArgumentException
231
-     * @throws InvalidDataTypeException
232
-     * @throws InvalidInterfaceException
233
-     * @throws ReflectionException
234
-     * @throws RuntimeException
235
-     */
236
-    private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ?ContextInterface $context = null)
237
-    {
238
-        // these reg statuses should not be considered in any calculations involving monies owing
239
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
240
-        // true if registration has been cancelled or declined
241
-        $this->updateIfCanceled(
242
-            $closed_reg_statuses,
243
-            $new_STS_ID,
244
-            $old_STS_ID,
245
-            $context
246
-        );
247
-        $this->updateIfReinstated(
248
-            $closed_reg_statuses,
249
-            $new_STS_ID,
250
-            $old_STS_ID,
251
-            $context
252
-        );
253
-    }
254
-
255
-
256
-    /**
257
-     * update REGs and TXN when cancelled or declined registrations involved
258
-     *
259
-     * @param array                 $closed_reg_statuses
260
-     * @param string                $new_STS_ID
261
-     * @param string                $old_STS_ID
262
-     * @param ContextInterface|null $context
263
-     * @throws EE_Error
264
-     * @throws InvalidArgumentException
265
-     * @throws InvalidDataTypeException
266
-     * @throws InvalidInterfaceException
267
-     * @throws ReflectionException
268
-     * @throws RuntimeException
269
-     */
270
-    private function updateIfCanceled(
271
-        array $closed_reg_statuses,
272
-        $new_STS_ID,
273
-        $old_STS_ID,
274
-        ?ContextInterface $context = null
275
-    ) {
276
-        // true if registration has been cancelled or declined
277
-        if (
278
-            in_array($new_STS_ID, $closed_reg_statuses, true)
279
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
280
-        ) {
281
-            /** @type EE_Registration_Processor $registration_processor */
282
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
283
-            /** @type EE_Transaction_Processor $transaction_processor */
284
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
285
-            // cancelled or declined registration
286
-            $registration_processor->update_registration_after_being_canceled_or_declined(
287
-                $this,
288
-                $closed_reg_statuses
289
-            );
290
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
291
-                $this,
292
-                $closed_reg_statuses,
293
-                false
294
-            );
295
-            do_action(
296
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
297
-                $this,
298
-                $old_STS_ID,
299
-                $new_STS_ID,
300
-                $context
301
-            );
302
-        }
303
-    }
304
-
305
-
306
-    /**
307
-     * update REGs and TXN when cancelled or declined registrations involved
308
-     *
309
-     * @param array                 $closed_reg_statuses
310
-     * @param string                $new_STS_ID
311
-     * @param string                $old_STS_ID
312
-     * @param ContextInterface|null $context
313
-     * @throws EE_Error
314
-     * @throws InvalidArgumentException
315
-     * @throws InvalidDataTypeException
316
-     * @throws InvalidInterfaceException
317
-     * @throws ReflectionException
318
-     * @throws RuntimeException
319
-     */
320
-    private function updateIfReinstated(
321
-        array $closed_reg_statuses,
322
-        $new_STS_ID,
323
-        $old_STS_ID,
324
-        ?ContextInterface $context = null
325
-    ) {
326
-        // true if reinstating cancelled or declined registration
327
-        if (
328
-            in_array($old_STS_ID, $closed_reg_statuses, true)
329
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
330
-        ) {
331
-            /** @type EE_Registration_Processor $registration_processor */
332
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
333
-            /** @type EE_Transaction_Processor $transaction_processor */
334
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
335
-            // reinstating cancelled or declined registration
336
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
337
-                $this,
338
-                $closed_reg_statuses
339
-            );
340
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
341
-                $this,
342
-                $closed_reg_statuses,
343
-                false
344
-            );
345
-            do_action(
346
-                'AHEE__EE_Registration__set_status__after_reinstated',
347
-                $this,
348
-                $old_STS_ID,
349
-                $new_STS_ID,
350
-                $context
351
-            );
352
-        }
353
-    }
354
-
355
-
356
-    /**
357
-     * @param ContextInterface|null $context
358
-     * @return bool
359
-     */
360
-    private function statusChangeUpdatesTransaction(?ContextInterface $context = null)
361
-    {
362
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
363
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
364
-            ['spco_reg_step_attendee_information_process_registrations'],
365
-            $context,
366
-            $this
367
-        );
368
-        return ! (
369
-            $context instanceof ContextInterface
370
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
371
-        );
372
-    }
373
-
374
-
375
-    /**
376
-     * @throws EE_Error
377
-     * @throws EntityNotFoundException
378
-     * @throws InvalidArgumentException
379
-     * @throws InvalidDataTypeException
380
-     * @throws InvalidInterfaceException
381
-     * @throws ReflectionException
382
-     * @throws RuntimeException
383
-     */
384
-    private function updateTransactionAfterStatusChange()
385
-    {
386
-        /** @type EE_Transaction_Payments $transaction_payments */
387
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
388
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
389
-        $this->transaction()->update_status_based_on_total_paid();
390
-    }
391
-
392
-
393
-    /**
394
-     * get Status ID
395
-     *
396
-     * @throws EE_Error
397
-     * @throws InvalidArgumentException
398
-     * @throws InvalidDataTypeException
399
-     * @throws InvalidInterfaceException
400
-     * @throws ReflectionException
401
-     */
402
-    public function status_ID()
403
-    {
404
-        return $this->get('STS_ID');
405
-    }
406
-
407
-
408
-    /**
409
-     * Gets the ticket this registration is for
410
-     *
411
-     * @param boolean $include_archived whether to include archived tickets or not.
412
-     * @return EE_Ticket|EE_Base_Class
413
-     * @throws EE_Error
414
-     * @throws InvalidArgumentException
415
-     * @throws InvalidDataTypeException
416
-     * @throws InvalidInterfaceException
417
-     * @throws ReflectionException
418
-     */
419
-    public function ticket($include_archived = true)
420
-    {
421
-        return EEM_Ticket::instance()->get_one_by_ID($this->ticket_ID());
422
-    }
423
-
424
-
425
-    /**
426
-     * Gets the event this registration is for
427
-     *
428
-     * @return EE_Event
429
-     * @throws EE_Error
430
-     * @throws EntityNotFoundException
431
-     * @throws InvalidArgumentException
432
-     * @throws InvalidDataTypeException
433
-     * @throws InvalidInterfaceException
434
-     * @throws ReflectionException
435
-     */
436
-    public function event(): EE_Event
437
-    {
438
-        $event = $this->event_obj();
439
-        if (! $event instanceof EE_Event) {
440
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
441
-        }
442
-        return $event;
443
-    }
444
-
445
-
446
-    /**
447
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
448
-     * with the author of the event this registration is for.
449
-     *
450
-     * @return int
451
-     * @throws EE_Error
452
-     * @throws EntityNotFoundException
453
-     * @throws InvalidArgumentException
454
-     * @throws InvalidDataTypeException
455
-     * @throws InvalidInterfaceException
456
-     * @throws ReflectionException
457
-     * @since 4.5.0
458
-     */
459
-    public function wp_user(): int
460
-    {
461
-        return $this->event()->wp_user();
462
-    }
463
-
464
-
465
-    /**
466
-     * increments this registration's related ticket sold and corresponding datetime sold values
467
-     *
468
-     * @return void
469
-     * @throws DomainException
470
-     * @throws EE_Error
471
-     * @throws EntityNotFoundException
472
-     * @throws InvalidArgumentException
473
-     * @throws InvalidDataTypeException
474
-     * @throws InvalidInterfaceException
475
-     * @throws ReflectionException
476
-     * @throws UnexpectedEntityException
477
-     */
478
-    private function reserveRegistrationSpace()
479
-    {
480
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
481
-        // so stop tracking that this reg has a ticket reserved
482
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
483
-        $ticket = $this->ticket();
484
-        $ticket->increaseSold();
485
-        // possibly set event status to sold out
486
-        $this->event()->perform_sold_out_status_check();
487
-    }
488
-
489
-
490
-    /**
491
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
492
-     *
493
-     * @return void
494
-     * @throws DomainException
495
-     * @throws EE_Error
496
-     * @throws EntityNotFoundException
497
-     * @throws InvalidArgumentException
498
-     * @throws InvalidDataTypeException
499
-     * @throws InvalidInterfaceException
500
-     * @throws ReflectionException
501
-     * @throws UnexpectedEntityException
502
-     */
503
-    private function releaseRegistrationSpace()
504
-    {
505
-        $ticket = $this->ticket();
506
-        $ticket->decreaseSold();
507
-        // possibly change event status from sold out back to previous status
508
-        $this->event()->perform_sold_out_status_check();
509
-    }
510
-
511
-
512
-    /**
513
-     * tracks this registration's ticket reservation in extra meta
514
-     * and can increment related ticket reserved and corresponding datetime reserved values
515
-     *
516
-     * @param bool   $update_ticket if true, will increment ticket and datetime reserved count
517
-     * @param string $source
518
-     * @return void
519
-     * @throws EE_Error
520
-     * @throws InvalidArgumentException
521
-     * @throws InvalidDataTypeException
522
-     * @throws InvalidInterfaceException
523
-     * @throws ReflectionException
524
-     */
525
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
526
-    {
527
-        // only reserve ticket if space is not currently reserved
528
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
529
-            $reserved = $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
530
-            if ($reserved && $update_ticket) {
531
-                $ticket = $this->ticket();
532
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
533
-                $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
534
-                $ticket->save();
535
-            }
536
-        }
537
-    }
538
-
539
-
540
-    /**
541
-     * stops tracking this registration's ticket reservation in extra meta
542
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
543
-     *
544
-     * @param bool   $update_ticket if true, will decrement ticket and datetime reserved count
545
-     * @param string $source
546
-     * @return void
547
-     * @throws EE_Error
548
-     * @throws InvalidArgumentException
549
-     * @throws InvalidDataTypeException
550
-     * @throws InvalidInterfaceException
551
-     * @throws ReflectionException
552
-     */
553
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
554
-    {
555
-        // only release ticket if space is currently reserved
556
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
557
-            $reserved = $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false);
558
-            if ($reserved && $update_ticket) {
559
-                $ticket = $this->ticket();
560
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
561
-                $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
562
-            }
563
-        }
564
-    }
565
-
566
-
567
-    /**
568
-     * Set Attendee ID
569
-     *
570
-     * @param int $ATT_ID Attendee ID
571
-     * @throws DomainException
572
-     * @throws EE_Error
573
-     * @throws EntityNotFoundException
574
-     * @throws InvalidArgumentException
575
-     * @throws InvalidDataTypeException
576
-     * @throws InvalidInterfaceException
577
-     * @throws ReflectionException
578
-     * @throws RuntimeException
579
-     * @throws UnexpectedEntityException
580
-     */
581
-    public function set_attendee_id($ATT_ID = 0)
582
-    {
583
-        $this->set('ATT_ID', $ATT_ID);
584
-    }
585
-
586
-
587
-    /**
588
-     *        Set Transaction ID
589
-     *
590
-     * @param int $TXN_ID Transaction ID
591
-     * @throws DomainException
592
-     * @throws EE_Error
593
-     * @throws EntityNotFoundException
594
-     * @throws InvalidArgumentException
595
-     * @throws InvalidDataTypeException
596
-     * @throws InvalidInterfaceException
597
-     * @throws ReflectionException
598
-     * @throws RuntimeException
599
-     * @throws UnexpectedEntityException
600
-     */
601
-    public function set_transaction_id($TXN_ID = 0)
602
-    {
603
-        $this->set('TXN_ID', $TXN_ID);
604
-    }
605
-
606
-
607
-    /**
608
-     *        Set Session
609
-     *
610
-     * @param string $REG_session PHP Session ID
611
-     * @throws DomainException
612
-     * @throws EE_Error
613
-     * @throws EntityNotFoundException
614
-     * @throws InvalidArgumentException
615
-     * @throws InvalidDataTypeException
616
-     * @throws InvalidInterfaceException
617
-     * @throws ReflectionException
618
-     * @throws RuntimeException
619
-     * @throws UnexpectedEntityException
620
-     */
621
-    public function set_session($REG_session = '')
622
-    {
623
-        $this->set('REG_session', $REG_session);
624
-    }
625
-
626
-
627
-    /**
628
-     *        Set Registration URL Link
629
-     *
630
-     * @param string $REG_url_link Registration URL Link
631
-     * @throws DomainException
632
-     * @throws EE_Error
633
-     * @throws EntityNotFoundException
634
-     * @throws InvalidArgumentException
635
-     * @throws InvalidDataTypeException
636
-     * @throws InvalidInterfaceException
637
-     * @throws ReflectionException
638
-     * @throws RuntimeException
639
-     * @throws UnexpectedEntityException
640
-     */
641
-    public function set_reg_url_link($REG_url_link = '')
642
-    {
643
-        $this->set('REG_url_link', $REG_url_link);
644
-    }
645
-
646
-
647
-    /**
648
-     *        Set Attendee Counter
649
-     *
650
-     * @param int $REG_count Primary Attendee
651
-     * @throws DomainException
652
-     * @throws EE_Error
653
-     * @throws EntityNotFoundException
654
-     * @throws InvalidArgumentException
655
-     * @throws InvalidDataTypeException
656
-     * @throws InvalidInterfaceException
657
-     * @throws ReflectionException
658
-     * @throws RuntimeException
659
-     * @throws UnexpectedEntityException
660
-     */
661
-    public function set_count($REG_count = 1)
662
-    {
663
-        $this->set('REG_count', $REG_count);
664
-    }
665
-
666
-
667
-    /**
668
-     *        Set Group Size
669
-     *
670
-     * @param boolean $REG_group_size Group Registration
671
-     * @throws DomainException
672
-     * @throws EE_Error
673
-     * @throws EntityNotFoundException
674
-     * @throws InvalidArgumentException
675
-     * @throws InvalidDataTypeException
676
-     * @throws InvalidInterfaceException
677
-     * @throws ReflectionException
678
-     * @throws RuntimeException
679
-     * @throws UnexpectedEntityException
680
-     */
681
-    public function set_group_size($REG_group_size = false)
682
-    {
683
-        $this->set('REG_group_size', $REG_group_size);
684
-    }
685
-
686
-
687
-    /**
688
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
689
-     *    RegStatus::AWAITING_REVIEW
690
-     *
691
-     * @return        boolean
692
-     * @throws EE_Error
693
-     * @throws InvalidArgumentException
694
-     * @throws InvalidDataTypeException
695
-     * @throws InvalidInterfaceException
696
-     * @throws ReflectionException
697
-     */
698
-    public function is_not_approved()
699
-    {
700
-        return $this->status_ID() === RegStatus::AWAITING_REVIEW;
701
-    }
702
-
703
-
704
-    /**
705
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
706
-     *    RegStatus::PENDING_PAYMENT
707
-     *
708
-     * @return        boolean
709
-     * @throws EE_Error
710
-     * @throws InvalidArgumentException
711
-     * @throws InvalidDataTypeException
712
-     * @throws InvalidInterfaceException
713
-     * @throws ReflectionException
714
-     */
715
-    public function is_pending_payment()
716
-    {
717
-        return $this->status_ID() === RegStatus::PENDING_PAYMENT;
718
-    }
719
-
720
-
721
-    /**
722
-     *    is_approved -  convenience method that returns TRUE if REG status ID == RegStatus::APPROVED
723
-     *
724
-     * @return        boolean
725
-     * @throws EE_Error
726
-     * @throws InvalidArgumentException
727
-     * @throws InvalidDataTypeException
728
-     * @throws InvalidInterfaceException
729
-     * @throws ReflectionException
730
-     */
731
-    public function is_approved()
732
-    {
733
-        return $this->status_ID() === RegStatus::APPROVED;
734
-    }
735
-
736
-
737
-    /**
738
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == RegStatus::CANCELLED
739
-     *
740
-     * @return        boolean
741
-     * @throws EE_Error
742
-     * @throws InvalidArgumentException
743
-     * @throws InvalidDataTypeException
744
-     * @throws InvalidInterfaceException
745
-     * @throws ReflectionException
746
-     */
747
-    public function is_cancelled()
748
-    {
749
-        return $this->status_ID() === RegStatus::CANCELLED;
750
-    }
751
-
752
-
753
-    /**
754
-     *    is_declined -  convenience method that returns TRUE if REG status ID == RegStatus::DECLINED
755
-     *
756
-     * @return        boolean
757
-     * @throws EE_Error
758
-     * @throws InvalidArgumentException
759
-     * @throws InvalidDataTypeException
760
-     * @throws InvalidInterfaceException
761
-     * @throws ReflectionException
762
-     */
763
-    public function is_declined()
764
-    {
765
-        return $this->status_ID() === RegStatus::DECLINED;
766
-    }
767
-
768
-
769
-    /**
770
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
771
-     *    RegStatus::INCOMPLETE
772
-     *
773
-     * @return        boolean
774
-     * @throws EE_Error
775
-     * @throws InvalidArgumentException
776
-     * @throws InvalidDataTypeException
777
-     * @throws InvalidInterfaceException
778
-     * @throws ReflectionException
779
-     */
780
-    public function is_incomplete()
781
-    {
782
-        return $this->status_ID() === RegStatus::INCOMPLETE;
783
-    }
784
-
785
-
786
-    /**
787
-     *        Set Registration Date
788
-     *
789
-     * @param mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
790
-     *                                                 Date
791
-     * @throws DomainException
792
-     * @throws EE_Error
793
-     * @throws EntityNotFoundException
794
-     * @throws InvalidArgumentException
795
-     * @throws InvalidDataTypeException
796
-     * @throws InvalidInterfaceException
797
-     * @throws ReflectionException
798
-     * @throws RuntimeException
799
-     * @throws UnexpectedEntityException
800
-     */
801
-    public function set_reg_date($REG_date = false)
802
-    {
803
-        $this->set('REG_date', $REG_date);
804
-    }
805
-
806
-
807
-    /**
808
-     *    Set final price owing for this registration after all ticket/price modifications
809
-     *
810
-     * @param float $REG_final_price
811
-     * @throws DomainException
812
-     * @throws EE_Error
813
-     * @throws EntityNotFoundException
814
-     * @throws InvalidArgumentException
815
-     * @throws InvalidDataTypeException
816
-     * @throws InvalidInterfaceException
817
-     * @throws ReflectionException
818
-     * @throws RuntimeException
819
-     * @throws UnexpectedEntityException
820
-     */
821
-    public function set_final_price($REG_final_price = 0.00)
822
-    {
823
-        $this->set('REG_final_price', $REG_final_price);
824
-    }
825
-
826
-
827
-    /**
828
-     *    Set amount paid towards this registration's final price
829
-     *
830
-     * @param float|int|string $REG_paid
831
-     * @throws DomainException
832
-     * @throws EE_Error
833
-     * @throws EntityNotFoundException
834
-     * @throws InvalidArgumentException
835
-     * @throws InvalidDataTypeException
836
-     * @throws InvalidInterfaceException
837
-     * @throws ReflectionException
838
-     * @throws RuntimeException
839
-     * @throws UnexpectedEntityException
840
-     */
841
-    public function set_paid($REG_paid = 0.00)
842
-    {
843
-        $this->set('REG_paid', (float) $REG_paid);
844
-    }
845
-
846
-
847
-    /**
848
-     *        Attendee Is Going
849
-     *
850
-     * @param boolean $REG_att_is_going Attendee Is Going
851
-     * @throws DomainException
852
-     * @throws EE_Error
853
-     * @throws EntityNotFoundException
854
-     * @throws InvalidArgumentException
855
-     * @throws InvalidDataTypeException
856
-     * @throws InvalidInterfaceException
857
-     * @throws ReflectionException
858
-     * @throws RuntimeException
859
-     * @throws UnexpectedEntityException
860
-     */
861
-    public function set_att_is_going($REG_att_is_going = false)
862
-    {
863
-        $this->set('REG_att_is_going', $REG_att_is_going);
864
-    }
865
-
866
-
867
-    /**
868
-     * Gets the related attendee
869
-     *
870
-     * @return EE_Attendee|EE_Base_Class
871
-     * @throws EE_Error
872
-     * @throws InvalidArgumentException
873
-     * @throws InvalidDataTypeException
874
-     * @throws InvalidInterfaceException
875
-     * @throws ReflectionException
876
-     */
877
-    public function attendee()
878
-    {
879
-        return EEM_Attendee::instance()->get_one_by_ID($this->attendee_ID());
880
-    }
881
-
882
-
883
-    /**
884
-     * Gets the name of the attendee.
885
-     *
886
-     * @param bool $apply_html_entities set to true if you want to use HTML entities.
887
-     * @return string
888
-     * @throws EE_Error
889
-     * @throws InvalidArgumentException
890
-     * @throws InvalidDataTypeException
891
-     * @throws InvalidInterfaceException
892
-     * @throws ReflectionException
893
-     * @since 4.10.12.p
894
-     */
895
-    public function attendeeName($apply_html_entities = false)
896
-    {
897
-        $attendee = $this->attendee();
898
-        if ($attendee instanceof EE_Attendee) {
899
-            $attendee_name = $attendee->full_name($apply_html_entities);
900
-        } else {
901
-            $attendee_name = esc_html__('Unknown', 'event_espresso');
902
-        }
903
-        return $attendee_name;
904
-    }
905
-
906
-
907
-    /**
908
-     *        get Event ID
909
-     */
910
-    public function event_ID()
911
-    {
912
-        return $this->get('EVT_ID');
913
-    }
914
-
915
-
916
-    /**
917
-     *        get Event ID
918
-     */
919
-    public function event_name()
920
-    {
921
-        $event = $this->event_obj();
922
-        if ($event) {
923
-            return $event->name();
924
-        } else {
925
-            return null;
926
-        }
927
-    }
928
-
929
-
930
-    /**
931
-     * Fetches the event this registration is for
932
-     *
933
-     * @return EE_Base_Class|EE_Event
934
-     * @throws EE_Error
935
-     * @throws InvalidArgumentException
936
-     * @throws InvalidDataTypeException
937
-     * @throws InvalidInterfaceException
938
-     * @throws ReflectionException
939
-     */
940
-    public function event_obj()
941
-    {
942
-        return EEM_Event::instance()->get_one_by_ID($this->event_ID());
943
-    }
944
-
945
-
946
-    /**
947
-     *        get Attendee ID
948
-     */
949
-    public function attendee_ID()
950
-    {
951
-        return $this->get('ATT_ID');
952
-    }
953
-
954
-
955
-    /**
956
-     *        get PHP Session ID
957
-     */
958
-    public function session_ID()
959
-    {
960
-        return $this->get('REG_session');
961
-    }
962
-
963
-
964
-    /**
965
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
966
-     *
967
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
968
-     * @return string
969
-     * @throws DomainException
970
-     * @throws InvalidArgumentException
971
-     * @throws InvalidDataTypeException
972
-     * @throws InvalidInterfaceException
973
-     */
974
-    public function receipt_url($messenger = 'html')
975
-    {
976
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
977
-    }
978
-
979
-
980
-    /**
981
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
982
-     *
983
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
984
-     * @return string
985
-     * @throws DomainException
986
-     * @throws InvalidArgumentException
987
-     * @throws InvalidDataTypeException
988
-     * @throws InvalidInterfaceException
989
-     */
990
-    public function invoice_url($messenger = 'html')
991
-    {
992
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
993
-    }
994
-
995
-
996
-    /**
997
-     * get Registration URL Link
998
-     *
999
-     * @return string
1000
-     * @throws EE_Error
1001
-     * @throws InvalidArgumentException
1002
-     * @throws InvalidDataTypeException
1003
-     * @throws InvalidInterfaceException
1004
-     * @throws ReflectionException
1005
-     */
1006
-    public function reg_url_link()
1007
-    {
1008
-        return (string) $this->get('REG_url_link');
1009
-    }
1010
-
1011
-
1012
-    /**
1013
-     * Echoes out invoice_url()
1014
-     *
1015
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
1016
-     * @return void
1017
-     * @throws DomainException
1018
-     * @throws EE_Error
1019
-     * @throws InvalidArgumentException
1020
-     * @throws InvalidDataTypeException
1021
-     * @throws InvalidInterfaceException
1022
-     * @throws ReflectionException
1023
-     */
1024
-    public function e_invoice_url($type = 'launch')
1025
-    {
1026
-        echo esc_url_raw($this->invoice_url($type));
1027
-    }
1028
-
1029
-
1030
-    /**
1031
-     * Echoes out payment_overview_url
1032
-     */
1033
-    public function e_payment_overview_url()
1034
-    {
1035
-        echo esc_url_raw($this->payment_overview_url());
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * Gets the URL for the checkout payment options reg step
1041
-     * with this registration's REG_url_link added as a query parameter
1042
-     *
1043
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
1044
-     *                            payment overview url.
1045
-     * @return string
1046
-     * @throws EE_Error
1047
-     * @throws InvalidArgumentException
1048
-     * @throws InvalidDataTypeException
1049
-     * @throws InvalidInterfaceException
1050
-     * @throws ReflectionException
1051
-     */
1052
-    public function payment_overview_url($clear_session = false)
1053
-    {
1054
-        return add_query_arg(
1055
-            (array) apply_filters(
1056
-                'FHEE__EE_Registration__payment_overview_url__query_args',
1057
-                [
1058
-                    'e_reg_url_link' => $this->reg_url_link(),
1059
-                    'step'           => 'payment_options',
1060
-                    'revisit'        => true,
1061
-                    'clear_session'  => (bool) $clear_session,
1062
-                ],
1063
-                $this
1064
-            ),
1065
-            EE_Registry::instance()->CFG->core->reg_page_url()
1066
-        );
1067
-    }
1068
-
1069
-
1070
-    /**
1071
-     * Gets the URL for the checkout attendee information reg step
1072
-     * with this registration's REG_url_link added as a query parameter
1073
-     *
1074
-     * @return string
1075
-     * @throws EE_Error
1076
-     * @throws InvalidArgumentException
1077
-     * @throws InvalidDataTypeException
1078
-     * @throws InvalidInterfaceException
1079
-     * @throws ReflectionException
1080
-     */
1081
-    public function edit_attendee_information_url()
1082
-    {
1083
-        return add_query_arg(
1084
-            (array) apply_filters(
1085
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
1086
-                [
1087
-                    'e_reg_url_link' => $this->reg_url_link(),
1088
-                    'step'           => 'attendee_information',
1089
-                    'revisit'        => true,
1090
-                ],
1091
-                $this
1092
-            ),
1093
-            EE_Registry::instance()->CFG->core->reg_page_url()
1094
-        );
1095
-    }
1096
-
1097
-
1098
-    /**
1099
-     * Simply generates and returns the appropriate admin_url link to edit this registration
1100
-     *
1101
-     * @return string
1102
-     * @throws EE_Error
1103
-     * @throws InvalidArgumentException
1104
-     * @throws InvalidDataTypeException
1105
-     * @throws InvalidInterfaceException
1106
-     * @throws ReflectionException
1107
-     */
1108
-    public function get_admin_edit_url()
1109
-    {
1110
-        return EEH_URL::add_query_args_and_nonce(
1111
-            [
1112
-                'page'    => 'espresso_registrations',
1113
-                'action'  => 'view_registration',
1114
-                '_REG_ID' => $this->ID(),
1115
-            ],
1116
-            admin_url('admin.php')
1117
-        );
1118
-    }
1119
-
1120
-
1121
-    /**
1122
-     * is_primary_registrant?
1123
-     *
1124
-     * @throws EE_Error
1125
-     * @throws InvalidArgumentException
1126
-     * @throws InvalidDataTypeException
1127
-     * @throws InvalidInterfaceException
1128
-     * @throws ReflectionException
1129
-     */
1130
-    public function is_primary_registrant()
1131
-    {
1132
-        return (int) $this->get('REG_count') === 1;
1133
-    }
1134
-
1135
-
1136
-    /**
1137
-     * This returns the primary registration object for this registration group (which may be this object).
1138
-     *
1139
-     * @return EE_Registration
1140
-     * @throws EE_Error
1141
-     * @throws InvalidArgumentException
1142
-     * @throws InvalidDataTypeException
1143
-     * @throws InvalidInterfaceException
1144
-     * @throws ReflectionException
1145
-     */
1146
-    public function get_primary_registration()
1147
-    {
1148
-        if ($this->is_primary_registrant()) {
1149
-            return $this;
1150
-        }
1151
-
1152
-        // k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1153
-        /** @var EE_Registration $primary_registrant */
1154
-        $primary_registrant = EEM_Registration::instance()->get_one(
1155
-            [
1156
-                [
1157
-                    'TXN_ID'    => $this->transaction_ID(),
1158
-                    'REG_count' => 1,
1159
-                ],
1160
-            ]
1161
-        );
1162
-        return $primary_registrant;
1163
-    }
1164
-
1165
-
1166
-    /**
1167
-     * get  Attendee Number
1168
-     *
1169
-     * @throws EE_Error
1170
-     * @throws InvalidArgumentException
1171
-     * @throws InvalidDataTypeException
1172
-     * @throws InvalidInterfaceException
1173
-     * @throws ReflectionException
1174
-     */
1175
-    public function count()
1176
-    {
1177
-        return $this->get('REG_count');
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * get Group Size
1183
-     *
1184
-     * @throws EE_Error
1185
-     * @throws InvalidArgumentException
1186
-     * @throws InvalidDataTypeException
1187
-     * @throws InvalidInterfaceException
1188
-     * @throws ReflectionException
1189
-     */
1190
-    public function group_size()
1191
-    {
1192
-        return $this->get('REG_group_size');
1193
-    }
1194
-
1195
-
1196
-    /**
1197
-     * get Registration Date
1198
-     *
1199
-     * @throws EE_Error
1200
-     * @throws InvalidArgumentException
1201
-     * @throws InvalidDataTypeException
1202
-     * @throws InvalidInterfaceException
1203
-     * @throws ReflectionException
1204
-     */
1205
-    public function date()
1206
-    {
1207
-        return $this->get('REG_date');
1208
-    }
1209
-
1210
-
1211
-    /**
1212
-     * gets a pretty date
1213
-     *
1214
-     * @param string $date_format
1215
-     * @param string $time_format
1216
-     * @return string
1217
-     * @throws EE_Error
1218
-     * @throws InvalidArgumentException
1219
-     * @throws InvalidDataTypeException
1220
-     * @throws InvalidInterfaceException
1221
-     * @throws ReflectionException
1222
-     */
1223
-    public function pretty_date($date_format = null, $time_format = null)
1224
-    {
1225
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * final_price
1231
-     * the registration's share of the transaction total, so that the
1232
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1233
-     *
1234
-     * @return float
1235
-     * @throws EE_Error
1236
-     * @throws InvalidArgumentException
1237
-     * @throws InvalidDataTypeException
1238
-     * @throws InvalidInterfaceException
1239
-     * @throws ReflectionException
1240
-     */
1241
-    public function final_price(): float
1242
-    {
1243
-        return (float) $this->get('REG_final_price');
1244
-    }
1245
-
1246
-
1247
-    /**
1248
-     * pretty_final_price
1249
-     *  final price as formatted string, with correct decimal places and currency symbol
1250
-     *
1251
-     * @param string|null $schema
1252
-     *      Schemas:
1253
-     *      'localized_float': "3,023.00"
1254
-     *      'no_currency_code': "$3,023.00"
1255
-     *      null: "$3,023.00<span>USD</span>"
1256
-     * @return string
1257
-     * @throws EE_Error
1258
-     * @throws InvalidArgumentException
1259
-     * @throws InvalidDataTypeException
1260
-     * @throws InvalidInterfaceException
1261
-     * @throws ReflectionException
1262
-     */
1263
-    public function pretty_final_price(?string $schema = null)
1264
-    {
1265
-        return $this->get_pretty('REG_final_price', $schema);
1266
-    }
1267
-
1268
-
1269
-    /**
1270
-     * get paid (yeah)
1271
-     *
1272
-     * @return float
1273
-     * @throws EE_Error
1274
-     * @throws InvalidArgumentException
1275
-     * @throws InvalidDataTypeException
1276
-     * @throws InvalidInterfaceException
1277
-     * @throws ReflectionException
1278
-     */
1279
-    public function paid(): float
1280
-    {
1281
-        return (float) $this->get('REG_paid');
1282
-    }
1283
-
1284
-
1285
-    /**
1286
-     * pretty_paid
1287
-     *
1288
-     * @param string|null $schema
1289
-     *      Schemas:
1290
-     *      'localized_float': "3,023.00"
1291
-     *      'no_currency_code': "$3,023.00"
1292
-     *      null: "$3,023.00<span>USD</span>"
1293
-     * @return float
1294
-     * @throws EE_Error
1295
-     * @throws InvalidArgumentException
1296
-     * @throws InvalidDataTypeException
1297
-     * @throws InvalidInterfaceException
1298
-     * @throws ReflectionException
1299
-     */
1300
-    public function pretty_paid(?string $schema = null)
1301
-    {
1302
-        return $this->get_pretty('REG_paid', $schema);
1303
-    }
1304
-
1305
-
1306
-    /**
1307
-     * owes_monies_and_can_pay
1308
-     * whether this registration has monies owing and it's' status allows payment
1309
-     *
1310
-     * @param array $requires_payment list of registration statuses that allow a registrant to make a payment
1311
-     * @return bool
1312
-     * @throws EE_Error
1313
-     * @throws InvalidArgumentException
1314
-     * @throws InvalidDataTypeException
1315
-     * @throws InvalidInterfaceException
1316
-     * @throws ReflectionException
1317
-     */
1318
-    public function owes_monies_and_can_pay(array $requires_payment = []): bool
1319
-    {
1320
-        // these reg statuses require payment (if event is not free)
1321
-        $requires_payment = ! empty($requires_payment)
1322
-            ? $requires_payment
1323
-            : EEM_Registration::reg_statuses_that_allow_payment();
1324
-        if (
1325
-            $this->final_price() !== 0.0 &&
1326
-            $this->final_price() !== $this->paid() &&
1327
-            in_array($this->status_ID(), $requires_payment)
1328
-        ) {
1329
-            return true;
1330
-        }
1331
-        return false;
1332
-    }
1333
-
1334
-
1335
-    /**
1336
-     * Prints out the return value of $this->pretty_status()
1337
-     *
1338
-     * @param bool $show_icons
1339
-     * @return void
1340
-     * @throws EE_Error
1341
-     * @throws InvalidArgumentException
1342
-     * @throws InvalidDataTypeException
1343
-     * @throws InvalidInterfaceException
1344
-     * @throws ReflectionException
1345
-     */
1346
-    public function e_pretty_status($show_icons = false)
1347
-    {
1348
-        echo wp_kses($this->pretty_status($show_icons), AllowedTags::getAllowedTags());
1349
-    }
1350
-
1351
-
1352
-    /**
1353
-     * Returns a nice version of the status for displaying to customers
1354
-     *
1355
-     * @param bool $show_icons
1356
-     * @return string
1357
-     * @throws EE_Error
1358
-     * @throws InvalidArgumentException
1359
-     * @throws InvalidDataTypeException
1360
-     * @throws InvalidInterfaceException
1361
-     * @throws ReflectionException
1362
-     */
1363
-    public function pretty_status($show_icons = false)
1364
-    {
1365
-        $status = EEM_Status::instance()->localized_status(
1366
-            [$this->status_ID() => esc_html__('unknown', 'event_espresso')],
1367
-            false,
1368
-            'sentence'
1369
-        );
1370
-        $icon   = '';
1371
-        switch ($this->status_ID()) {
1372
-            case RegStatus::APPROVED:
1373
-                $icon = $show_icons
1374
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1375
-                    : '';
1376
-                break;
1377
-            case RegStatus::PENDING_PAYMENT:
1378
-                $icon = $show_icons
1379
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1380
-                    : '';
1381
-                break;
1382
-            case RegStatus::AWAITING_REVIEW:
1383
-                $icon = $show_icons
1384
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1385
-                    : '';
1386
-                break;
1387
-            case RegStatus::CANCELLED:
1388
-                $icon = $show_icons
1389
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1390
-                    : '';
1391
-                break;
1392
-            case RegStatus::INCOMPLETE:
1393
-                $icon = $show_icons
1394
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1395
-                    : '';
1396
-                break;
1397
-            case RegStatus::DECLINED:
1398
-                $icon = $show_icons
1399
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1400
-                    : '';
1401
-                break;
1402
-            case RegStatus::WAIT_LIST:
1403
-                $icon = $show_icons
1404
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1405
-                    : '';
1406
-                break;
1407
-        }
1408
-        return $icon . $status[ $this->status_ID() ];
1409
-    }
1410
-
1411
-
1412
-    /**
1413
-     *        get Attendee Is Going
1414
-     */
1415
-    public function att_is_going()
1416
-    {
1417
-        return $this->get('REG_att_is_going');
1418
-    }
1419
-
1420
-
1421
-    /**
1422
-     * Gets related answers
1423
-     *
1424
-     * @param array $query_params @see
1425
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1426
-     * @return EE_Answer[]|EE_Base_Class[]
1427
-     * @throws EE_Error
1428
-     * @throws InvalidArgumentException
1429
-     * @throws InvalidDataTypeException
1430
-     * @throws InvalidInterfaceException
1431
-     * @throws ReflectionException
1432
-     */
1433
-    public function answers($query_params = [])
1434
-    {
1435
-        return $this->get_many_related('Answer', $query_params);
1436
-    }
1437
-
1438
-
1439
-    /**
1440
-     * Gets the registration's answer value to the specified question
1441
-     * (either the question's ID or a question object)
1442
-     *
1443
-     * @param EE_Question|int $question
1444
-     * @param bool            $pretty_value
1445
-     * @return array|string if pretty_value= true, the result will always be a string
1446
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1447
-     * will convert it into some kind of string)
1448
-     * @throws EE_Error
1449
-     * @throws InvalidArgumentException
1450
-     * @throws InvalidDataTypeException
1451
-     * @throws InvalidInterfaceException
1452
-     */
1453
-    public function answer_value_to_question($question, $pretty_value = true)
1454
-    {
1455
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1456
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1457
-    }
1458
-
1459
-
1460
-    /**
1461
-     * question_groups
1462
-     * returns an array of EE_Question_Group objects for this registration
1463
-     *
1464
-     * @return EE_Question_Group[]
1465
-     * @throws EE_Error
1466
-     * @throws InvalidArgumentException
1467
-     * @throws InvalidDataTypeException
1468
-     * @throws InvalidInterfaceException
1469
-     * @throws ReflectionException
1470
-     */
1471
-    public function question_groups()
1472
-    {
1473
-        return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1474
-    }
1475
-
1476
-
1477
-    /**
1478
-     * count_question_groups
1479
-     * returns a count of the number of EE_Question_Group objects for this registration
1480
-     *
1481
-     * @return int
1482
-     * @throws EE_Error
1483
-     * @throws EntityNotFoundException
1484
-     * @throws InvalidArgumentException
1485
-     * @throws InvalidDataTypeException
1486
-     * @throws InvalidInterfaceException
1487
-     * @throws ReflectionException
1488
-     */
1489
-    public function count_question_groups()
1490
-    {
1491
-        return EEM_Event::instance()->count_related(
1492
-            $this->event_ID(),
1493
-            'Question_Group',
1494
-            [
1495
-                [
1496
-                    'Event_Question_Group.'
1497
-                    . EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1498
-                ],
1499
-            ]
1500
-        );
1501
-    }
1502
-
1503
-
1504
-    /**
1505
-     * Returns the registration date in the 'standard' string format
1506
-     * (function may be improved in the future to allow for different formats and timezones)
1507
-     *
1508
-     * @return string
1509
-     * @throws EE_Error
1510
-     * @throws InvalidArgumentException
1511
-     * @throws InvalidDataTypeException
1512
-     * @throws InvalidInterfaceException
1513
-     * @throws ReflectionException
1514
-     */
1515
-    public function reg_date()
1516
-    {
1517
-        return $this->get_datetime('REG_date');
1518
-    }
1519
-
1520
-
1521
-    /**
1522
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1523
-     * the ticket this registration purchased, or the datetime they have registered
1524
-     * to attend)
1525
-     *
1526
-     * @return EE_Base_Class|EE_Datetime_Ticket
1527
-     * @throws EE_Error
1528
-     * @throws InvalidArgumentException
1529
-     * @throws InvalidDataTypeException
1530
-     * @throws InvalidInterfaceException
1531
-     * @throws ReflectionException
1532
-     */
1533
-    public function datetime_ticket()
1534
-    {
1535
-        return $this->get_first_related('Datetime_Ticket');
1536
-    }
1537
-
1538
-
1539
-    /**
1540
-     * Sets the registration's datetime_ticket.
1541
-     *
1542
-     * @param EE_Datetime_Ticket $datetime_ticket
1543
-     * @return EE_Base_Class|EE_Datetime_Ticket
1544
-     * @throws EE_Error
1545
-     * @throws InvalidArgumentException
1546
-     * @throws InvalidDataTypeException
1547
-     * @throws InvalidInterfaceException
1548
-     * @throws ReflectionException
1549
-     */
1550
-    public function set_datetime_ticket($datetime_ticket)
1551
-    {
1552
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1553
-    }
1554
-
1555
-
1556
-    /**
1557
-     * Gets deleted
1558
-     *
1559
-     * @return bool
1560
-     * @throws EE_Error
1561
-     * @throws InvalidArgumentException
1562
-     * @throws InvalidDataTypeException
1563
-     * @throws InvalidInterfaceException
1564
-     * @throws ReflectionException
1565
-     */
1566
-    public function deleted()
1567
-    {
1568
-        return $this->get('REG_deleted');
1569
-    }
1570
-
1571
-
1572
-    /**
1573
-     * Sets deleted
1574
-     *
1575
-     * @param boolean $deleted
1576
-     * @return void
1577
-     * @throws DomainException
1578
-     * @throws EE_Error
1579
-     * @throws EntityNotFoundException
1580
-     * @throws InvalidArgumentException
1581
-     * @throws InvalidDataTypeException
1582
-     * @throws InvalidInterfaceException
1583
-     * @throws ReflectionException
1584
-     * @throws RuntimeException
1585
-     * @throws UnexpectedEntityException
1586
-     */
1587
-    public function set_deleted($deleted)
1588
-    {
1589
-        if ($deleted) {
1590
-            $this->delete();
1591
-        } else {
1592
-            $this->restore();
1593
-        }
1594
-    }
1595
-
1596
-
1597
-    /**
1598
-     * Get the status object of this object
1599
-     *
1600
-     * @return EE_Base_Class|EE_Status
1601
-     * @throws EE_Error
1602
-     * @throws InvalidArgumentException
1603
-     * @throws InvalidDataTypeException
1604
-     * @throws InvalidInterfaceException
1605
-     * @throws ReflectionException
1606
-     */
1607
-    public function status_obj()
1608
-    {
1609
-        return $this->get_first_related('Status');
1610
-    }
1611
-
1612
-
1613
-    /**
1614
-     * Returns the number of times this registration has checked into any of the datetimes it's available for
1615
-     *
1616
-     * @return int
1617
-     * @throws EE_Error
1618
-     * @throws InvalidArgumentException
1619
-     * @throws InvalidDataTypeException
1620
-     * @throws InvalidInterfaceException
1621
-     * @throws ReflectionException
1622
-     */
1623
-    public function count_checkins()
1624
-    {
1625
-        return $this->get_model()->count_related($this, 'Checkin');
1626
-    }
1627
-
1628
-
1629
-    /**
1630
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1631
-     * registration is for.  Note, this is ONLY checked in (does not include checked out)
1632
-     *
1633
-     * @return int
1634
-     * @throws EE_Error
1635
-     * @throws InvalidArgumentException
1636
-     * @throws InvalidDataTypeException
1637
-     * @throws InvalidInterfaceException
1638
-     * @throws ReflectionException
1639
-     */
1640
-    public function count_checkins_not_checkedout()
1641
-    {
1642
-        return $this->get_model()->count_related($this, 'Checkin', [['CHK_in' => 1]]);
1643
-    }
1644
-
1645
-
1646
-    /**
1647
-     * The purpose of this method is simply to check whether this registration can check in to the given datetime.
1648
-     *
1649
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1650
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1651
-     *                                          consider registration status as well as datetime access.
1652
-     * @return bool
1653
-     * @throws EE_Error
1654
-     * @throws InvalidArgumentException
1655
-     * @throws InvalidDataTypeException
1656
-     * @throws InvalidInterfaceException
1657
-     * @throws ReflectionException
1658
-     */
1659
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1660
-    {
1661
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1662
-        // first check registration status
1663
-        if (! $DTT_ID || ($check_approved && ! $this->is_approved())) {
1664
-            return false;
1665
-        }
1666
-        // is there a datetime ticket that matches this dtt_ID?
1667
-        if (
1668
-            ! (EEM_Datetime_Ticket::instance()->exists(
1669
-                [
1670
-                    [
1671
-                        'TKT_ID' => $this->get('TKT_ID'),
1672
-                        'DTT_ID' => $DTT_ID,
1673
-                    ],
1674
-                ]
1675
-            ))
1676
-        ) {
1677
-            return false;
1678
-        }
1679
-
1680
-        // final check is against TKT_uses
1681
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1682
-    }
1683
-
1684
-
1685
-    /**
1686
-     * This method verifies whether the user can check in for the given datetime considering the max uses value set on
1687
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1688
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1689
-     * then return false.  Otherwise return true.
1690
-     *
1691
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1692
-     * @return bool true means can check in.  false means cannot check in.
1693
-     * @throws EE_Error
1694
-     * @throws InvalidArgumentException
1695
-     * @throws InvalidDataTypeException
1696
-     * @throws InvalidInterfaceException
1697
-     * @throws ReflectionException
1698
-     */
1699
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1700
-    {
1701
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1702
-
1703
-        if (! $DTT_ID) {
1704
-            return false;
1705
-        }
1706
-
1707
-        $max_uses = $this->ticket() instanceof EE_Ticket
1708
-            ? $this->ticket()->uses()
1709
-            : EE_INF;
1710
-
1711
-        // if max uses is not set or equals infinity then return true
1712
-        // because it's not a factor for whether user can check in or not.
1713
-        if (! $max_uses || $max_uses === EE_INF) {
1714
-            return true;
1715
-        }
1716
-
1717
-        // does this datetime have a check-in record?  If so, then the dtt count has already been verified so we can just
1718
-        // go ahead and toggle.
1719
-        if (EEM_Checkin::instance()->exists([['REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID]])) {
1720
-            return true;
1721
-        }
1722
-
1723
-        // made it here so the last check is whether the number of check-ins per unique datetime on this registration
1724
-        // disallows further check-ins.
1725
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1726
-            [
1727
-                [
1728
-                    'REG_ID' => $this->ID(),
1729
-                    'CHK_in' => true,
1730
-                ],
1731
-            ],
1732
-            'DTT_ID',
1733
-            true
1734
-        );
1735
-        // check-ins have already reached their max number of uses
1736
-        // so registrant can NOT check in
1737
-        if ($count_unique_dtt_checkins >= $max_uses) {
1738
-            EE_Error::add_error(
1739
-                esc_html__(
1740
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1741
-                    'event_espresso'
1742
-                ),
1743
-                __FILE__,
1744
-                __FUNCTION__,
1745
-                __LINE__
1746
-            );
1747
-            return false;
1748
-        }
1749
-        return true;
1750
-    }
1751
-
1752
-
1753
-    /**
1754
-     * toggle Check-in status for this registration
1755
-     * Check-ins are toggled in the following order:
1756
-     * never checked in -> checked in
1757
-     * checked in -> checked out
1758
-     * checked out -> checked in
1759
-     *
1760
-     * @param int  $DTT_ID  include specific datetime to toggle Check-in for.
1761
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1762
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1763
-     *                      can be checked in or not.  Otherwise this forces change in check-in status.
1764
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1765
-     * @throws EE_Error
1766
-     * @throws InvalidArgumentException
1767
-     * @throws InvalidDataTypeException
1768
-     * @throws InvalidInterfaceException
1769
-     * @throws ReflectionException
1770
-     */
1771
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1772
-    {
1773
-        if (empty($DTT_ID)) {
1774
-            $datetime = $this->get_latest_related_datetime();
1775
-            $DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1776
-            // verify the registration can check in for the given DTT_ID
1777
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1778
-            EE_Error::add_error(
1779
-                sprintf(
1780
-                    esc_html__(
1781
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1782
-                        'event_espresso'
1783
-                    ),
1784
-                    $this->ID(),
1785
-                    $DTT_ID
1786
-                ),
1787
-                __FILE__,
1788
-                __FUNCTION__,
1789
-                __LINE__
1790
-            );
1791
-            return false;
1792
-        }
1793
-        $status_paths = [
1794
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1795
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1796
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1797
-        ];
1798
-        // start by getting the current status so we know what status we'll be changing to.
1799
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1800
-        $status_to  = $status_paths[ $cur_status ];
1801
-        // database only records true for checked IN or false for checked OUT
1802
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1803
-        $new_status = $status_to === EE_Checkin::status_checked_in;
1804
-        // add relation - note Check-ins are always creating new rows
1805
-        // because we are keeping track of Check-ins over time.
1806
-        // Eventually we'll probably want to show a list table
1807
-        // for the individual Check-ins so that they can be managed.
1808
-        $checkin = EE_Checkin::new_instance(
1809
-            [
1810
-                'REG_ID' => $this->ID(),
1811
-                'DTT_ID' => $DTT_ID,
1812
-                'CHK_in' => $new_status,
1813
-            ]
1814
-        );
1815
-        // if the record could not be saved then return false
1816
-        if ($checkin->save() === 0) {
1817
-            if (WP_DEBUG) {
1818
-                global $wpdb;
1819
-                $error = sprintf(
1820
-                    esc_html__(
1821
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1822
-                        'event_espresso'
1823
-                    ),
1824
-                    '<br />',
1825
-                    $wpdb->last_error
1826
-                );
1827
-            } else {
1828
-                $error = esc_html__(
1829
-                    'Registration check in update failed because of an unknown database error',
1830
-                    'event_espresso'
1831
-                );
1832
-            }
1833
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1834
-            return false;
1835
-        }
1836
-        // Fire a checked_in and checkout_out action.
1837
-        $checked_status = $status_to === EE_Checkin::status_checked_in
1838
-            ? 'checked_in'
1839
-            : 'checked_out';
1840
-        do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1841
-        return $status_to;
1842
-    }
1843
-
1844
-
1845
-    /**
1846
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1847
-     * "Latest" is defined by the `DTT_EVT_start` column.
1848
-     *
1849
-     * @return EE_Datetime|null
1850
-     * @throws EE_Error
1851
-     * @throws InvalidArgumentException
1852
-     * @throws InvalidDataTypeException
1853
-     * @throws InvalidInterfaceException
1854
-     * @throws ReflectionException
1855
-     */
1856
-    public function get_latest_related_datetime(): ?EE_Datetime
1857
-    {
1858
-        return EEM_Datetime::instance()->get_one(
1859
-            [
1860
-                [
1861
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1862
-                ],
1863
-                'order_by' => ['DTT_EVT_start' => 'DESC'],
1864
-            ]
1865
-        );
1866
-    }
1867
-
1868
-
1869
-    /**
1870
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1871
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1872
-     *
1873
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1874
-     * @throws EE_Error
1875
-     * @throws InvalidArgumentException
1876
-     * @throws InvalidDataTypeException
1877
-     * @throws InvalidInterfaceException
1878
-     * @throws ReflectionException
1879
-     */
1880
-    public function get_earliest_related_datetime()
1881
-    {
1882
-        return EEM_Datetime::instance()->get_one(
1883
-            [
1884
-                [
1885
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1886
-                ],
1887
-                'order_by' => ['DTT_EVT_start' => 'ASC'],
1888
-            ]
1889
-        );
1890
-    }
1891
-
1892
-
1893
-    /**
1894
-     * This method simply returns the check-in status for this registration and the given datetime.
1895
-     * If neither the datetime nor the check-in values are provided as arguments,
1896
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1897
-     *
1898
-     * @param int|null        $DTT_ID  The ID of the datetime we're checking against
1899
-     *                                 (if empty we'll get the primary datetime for
1900
-     *                                 this registration (via event) and use its ID);
1901
-     * @param EE_Checkin|null $checkin If present, we use the given check-in object rather than the dtt_id.
1902
-     * @return int                     Integer representing Check-in status.
1903
-     * @throws EE_Error
1904
-     * @throws ReflectionException
1905
-     */
1906
-    public function check_in_status_for_datetime(?int $DTT_ID = 0, ?EE_Checkin $checkin = null): int
1907
-    {
1908
-        if ($checkin instanceof EE_Checkin) {
1909
-            return $checkin->status();
1910
-        }
1911
-
1912
-        if (! $DTT_ID) {
1913
-            return EE_Checkin::status_invalid;
1914
-        }
1915
-
1916
-        $checkin_query_params = [
1917
-            0          => ['DTT_ID' => $DTT_ID],
1918
-            'order_by' => ['CHK_timestamp' => 'DESC'],
1919
-        ];
1920
-
1921
-        $checkin = $this->get_first_related(
1922
-            'Checkin',
1923
-            $checkin_query_params
1924
-        );
1925
-        return $checkin instanceof EE_Checkin ? $checkin->status() : EE_Checkin::status_checked_never;
1926
-    }
1927
-
1928
-
1929
-    /**
1930
-     * This method returns a localized message for the toggled Check-in message.
1931
-     *
1932
-     * @param int|null $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1933
-     *                         then it is assumed Check-in for primary datetime was toggled.
1934
-     * @param bool     $error  This just flags that you want an error message returned. This is put in so that the error
1935
-     *                         message can be customized with the attendee name.
1936
-     * @return string internationalized message
1937
-     * @throws EE_Error
1938
-     * @throws ReflectionException
1939
-     */
1940
-    public function get_checkin_msg(?int $DTT_ID, bool $error = false): string
1941
-    {
1942
-        // let's get the attendee first so we can include the name of the attendee
1943
-        $attendee = $this->attendee();
1944
-        if ($attendee instanceof EE_Attendee) {
1945
-            if ($error) {
1946
-                return sprintf(
1947
-                    esc_html__("%s's check-in status was not changed.", "event_espresso"),
1948
-                    $attendee->full_name()
1949
-                );
1950
-            }
1951
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1952
-            // what is the status message going to be?
1953
-            switch ($cur_status) {
1954
-                case EE_Checkin::status_checked_never:
1955
-                    return sprintf(
1956
-                        esc_html__('%s has been removed from Check-in records', 'event_espresso'),
1957
-                        $attendee->full_name()
1958
-                    );
1959
-                case EE_Checkin::status_checked_in:
1960
-                    return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1961
-                case EE_Checkin::status_checked_out:
1962
-                    return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1963
-            }
1964
-        }
1965
-        return esc_html__('The check-in status could not be determined.', 'event_espresso');
1966
-    }
1967
-
1968
-
1969
-    /**
1970
-     * Returns the related EE_Transaction to this registration
1971
-     *
1972
-     * @return EE_Transaction
1973
-     * @throws EE_Error
1974
-     * @throws EntityNotFoundException
1975
-     * @throws ReflectionException
1976
-     */
1977
-    public function transaction(): EE_Transaction
1978
-    {
1979
-        $TXN_ID = $this->transaction_ID();
1980
-        $transaction = $TXN_ID
1981
-            ? EEM_Transaction::instance()->get_one_by_ID($TXN_ID)
1982
-            : $this->get_one_from_cache('Transaction');
1983
-        if (! $transaction instanceof \EE_Transaction) {
1984
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1985
-        }
1986
-        return $transaction;
1987
-    }
1988
-
1989
-
1990
-    /**
1991
-     * get Registration Code
1992
-     *
1993
-     * @return string
1994
-     * @throws EE_Error
1995
-     * @throws InvalidArgumentException
1996
-     * @throws InvalidDataTypeException
1997
-     * @throws InvalidInterfaceException
1998
-     * @throws ReflectionException
1999
-     */
2000
-    public function reg_code(): string
2001
-    {
2002
-        return $this->get('REG_code')
2003
-            ?: '';
2004
-    }
2005
-
2006
-
2007
-    /**
2008
-     * @return mixed
2009
-     * @throws EE_Error
2010
-     * @throws InvalidArgumentException
2011
-     * @throws InvalidDataTypeException
2012
-     * @throws InvalidInterfaceException
2013
-     * @throws ReflectionException
2014
-     */
2015
-    public function transaction_ID()
2016
-    {
2017
-        return $this->get('TXN_ID');
2018
-    }
2019
-
2020
-
2021
-    /**
2022
-     * @return int
2023
-     * @throws EE_Error
2024
-     * @throws InvalidArgumentException
2025
-     * @throws InvalidDataTypeException
2026
-     * @throws InvalidInterfaceException
2027
-     * @throws ReflectionException
2028
-     */
2029
-    public function ticket_ID()
2030
-    {
2031
-        return $this->get('TKT_ID');
2032
-    }
2033
-
2034
-
2035
-    /**
2036
-     * Set Registration Code
2037
-     *
2038
-     * @param RegCode|string $REG_code Registration Code
2039
-     * @param boolean        $use_default
2040
-     * @throws EE_Error
2041
-     * @throws InvalidArgumentException
2042
-     * @throws InvalidDataTypeException
2043
-     * @throws InvalidInterfaceException
2044
-     * @throws ReflectionException
2045
-     */
2046
-    public function set_reg_code($REG_code, bool $use_default = false)
2047
-    {
2048
-        if (! $this->reg_code()) {
2049
-            parent::set('REG_code', $REG_code, $use_default);
2050
-        } elseif (empty($REG_code)) {
2051
-            EE_Error::add_error(
2052
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
2053
-                __FILE__,
2054
-                __FUNCTION__,
2055
-                __LINE__
2056
-            );
2057
-        } else {
2058
-            EE_Error::doing_it_wrong(
2059
-                __CLASS__ . '::' . __FUNCTION__,
2060
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
2061
-                '4.6.0'
2062
-            );
2063
-        }
2064
-    }
2065
-
2066
-
2067
-    /**
2068
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
2069
-     * Note, if you want to just get all registrations in the same transaction (group), use:
2070
-     *    $registration->transaction()->registrations();
2071
-     *
2072
-     * @return EE_Registration[] or empty array if this isn't a group registration.
2073
-     * @throws EE_Error
2074
-     * @throws InvalidArgumentException
2075
-     * @throws InvalidDataTypeException
2076
-     * @throws InvalidInterfaceException
2077
-     * @throws ReflectionException
2078
-     * @since 4.5.0
2079
-     */
2080
-    public function get_all_other_registrations_in_group()
2081
-    {
2082
-        if ($this->group_size() < 2) {
2083
-            return [];
2084
-        }
2085
-
2086
-        $query[0] = [
2087
-            'TXN_ID' => $this->transaction_ID(),
2088
-            'REG_ID' => ['!=', $this->ID()],
2089
-            'TKT_ID' => $this->ticket_ID(),
2090
-        ];
2091
-        /** @var EE_Registration[] $registrations */
2092
-        $registrations = $this->get_model()->get_all($query);
2093
-        return $registrations;
2094
-    }
2095
-
2096
-
2097
-    /**
2098
-     * Return the link to the admin details for the object.
2099
-     *
2100
-     * @return string
2101
-     * @throws EE_Error
2102
-     * @throws InvalidArgumentException
2103
-     * @throws InvalidDataTypeException
2104
-     * @throws InvalidInterfaceException
2105
-     * @throws ReflectionException
2106
-     */
2107
-    public function get_admin_details_link()
2108
-    {
2109
-        EE_Registry::instance()->load_helper('URL');
2110
-        return EEH_URL::add_query_args_and_nonce(
2111
-            [
2112
-                'page'    => 'espresso_registrations',
2113
-                'action'  => 'view_registration',
2114
-                '_REG_ID' => $this->ID(),
2115
-            ],
2116
-            admin_url('admin.php')
2117
-        );
2118
-    }
2119
-
2120
-
2121
-    /**
2122
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
2123
-     *
2124
-     * @return string
2125
-     * @throws EE_Error
2126
-     * @throws InvalidArgumentException
2127
-     * @throws InvalidDataTypeException
2128
-     * @throws InvalidInterfaceException
2129
-     * @throws ReflectionException
2130
-     */
2131
-    public function get_admin_edit_link()
2132
-    {
2133
-        return $this->get_admin_details_link();
2134
-    }
2135
-
2136
-
2137
-    /**
2138
-     * Returns the link to a settings page for the object.
2139
-     *
2140
-     * @return string
2141
-     * @throws EE_Error
2142
-     * @throws InvalidArgumentException
2143
-     * @throws InvalidDataTypeException
2144
-     * @throws InvalidInterfaceException
2145
-     * @throws ReflectionException
2146
-     */
2147
-    public function get_admin_settings_link()
2148
-    {
2149
-        return $this->get_admin_details_link();
2150
-    }
2151
-
2152
-
2153
-    /**
2154
-     * Returns the link to the "overview" for the object (typically the "list table" view).
2155
-     *
2156
-     * @return string
2157
-     * @throws EE_Error
2158
-     * @throws InvalidArgumentException
2159
-     * @throws InvalidDataTypeException
2160
-     * @throws InvalidInterfaceException
2161
-     * @throws ReflectionException
2162
-     */
2163
-    public function get_admin_overview_link()
2164
-    {
2165
-        EE_Registry::instance()->load_helper('URL');
2166
-        return EEH_URL::add_query_args_and_nonce(
2167
-            [
2168
-                'page' => 'espresso_registrations',
2169
-            ],
2170
-            admin_url('admin.php')
2171
-        );
2172
-    }
2173
-
2174
-
2175
-    /**
2176
-     * @param array $query_params
2177
-     * @return EE_Base_Class[]|EE_Registration[]
2178
-     * @throws EE_Error
2179
-     * @throws InvalidArgumentException
2180
-     * @throws InvalidDataTypeException
2181
-     * @throws InvalidInterfaceException
2182
-     * @throws ReflectionException
2183
-     */
2184
-    public function payments($query_params = [])
2185
-    {
2186
-        return $this->get_many_related('Payment', $query_params);
2187
-    }
2188
-
2189
-
2190
-    /**
2191
-     * @param array $query_params
2192
-     * @return EE_Base_Class[]|EE_Registration_Payment[]
2193
-     * @throws EE_Error
2194
-     * @throws InvalidArgumentException
2195
-     * @throws InvalidDataTypeException
2196
-     * @throws InvalidInterfaceException
2197
-     * @throws ReflectionException
2198
-     */
2199
-    public function registration_payments($query_params = [])
2200
-    {
2201
-        return $this->get_many_related('Registration_Payment', $query_params);
2202
-    }
2203
-
2204
-
2205
-    /**
2206
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
2207
-     * Note: if there are no payments on the registration there will be no payment method returned.
2208
-     *
2209
-     * @return EE_Payment|EE_Payment_Method|null
2210
-     * @throws EE_Error
2211
-     * @throws InvalidArgumentException
2212
-     * @throws InvalidDataTypeException
2213
-     * @throws InvalidInterfaceException
2214
-     */
2215
-    public function payment_method()
2216
-    {
2217
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
2218
-    }
2219
-
2220
-
2221
-    /**
2222
-     * @return \EE_Line_Item
2223
-     * @throws EE_Error
2224
-     * @throws EntityNotFoundException
2225
-     * @throws InvalidArgumentException
2226
-     * @throws InvalidDataTypeException
2227
-     * @throws InvalidInterfaceException
2228
-     * @throws ReflectionException
2229
-     */
2230
-    public function ticket_line_item()
2231
-    {
2232
-        $ticket            = $this->ticket();
2233
-        $transaction       = $this->transaction();
2234
-        $line_item         = null;
2235
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
2236
-            $transaction->total_line_item(),
2237
-            'Ticket',
2238
-            [$ticket->ID()]
2239
-        );
2240
-        foreach ($ticket_line_items as $ticket_line_item) {
2241
-            if (
2242
-                $ticket_line_item instanceof \EE_Line_Item
2243
-                && $ticket_line_item->OBJ_type() === 'Ticket'
2244
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
2245
-            ) {
2246
-                $line_item = $ticket_line_item;
2247
-                break;
2248
-            }
2249
-        }
2250
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
2251
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
2252
-        }
2253
-        return $line_item;
2254
-    }
2255
-
2256
-
2257
-    /**
2258
-     * Soft Deletes this model object.
2259
-     *
2260
-     * @param string $source function name that called this method
2261
-     * @return boolean | int
2262
-     * @throws DomainException
2263
-     * @throws EE_Error
2264
-     * @throws EntityNotFoundException
2265
-     * @throws InvalidArgumentException
2266
-     * @throws InvalidDataTypeException
2267
-     * @throws InvalidInterfaceException
2268
-     * @throws ReflectionException
2269
-     * @throws RuntimeException
2270
-     * @throws UnexpectedEntityException
2271
-     */
2272
-    public function delete()
2273
-    {
2274
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
2275
-            $this->set_status(
2276
-                RegStatus::CANCELLED,
2277
-                false,
2278
-                new Context(
2279
-                    __METHOD__,
2280
-                    esc_html__('Executed when a registration is trashed.', 'event_espresso')
2281
-                )
2282
-            );
2283
-        }
2284
-        return parent::delete();
2285
-    }
2286
-
2287
-
2288
-    /**
2289
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
2290
-     *
2291
-     * @param string $source function name that called this method
2292
-     * @return bool|int
2293
-     * @throws DomainException
2294
-     * @throws EE_Error
2295
-     * @throws EntityNotFoundException
2296
-     * @throws InvalidArgumentException
2297
-     * @throws InvalidDataTypeException
2298
-     * @throws InvalidInterfaceException
2299
-     * @throws ReflectionException
2300
-     * @throws RuntimeException
2301
-     * @throws UnexpectedEntityException
2302
-     */
2303
-    public function restore()
2304
-    {
2305
-        $previous_status = $this->get_extra_meta(
2306
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
2307
-            true,
2308
-            RegStatus::CANCELLED
2309
-        );
2310
-        if ($previous_status) {
2311
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
2312
-            $this->set_status(
2313
-                $previous_status,
2314
-                false,
2315
-                new Context(
2316
-                    __METHOD__,
2317
-                    esc_html__('Executed when a trashed registration is restored.', 'event_espresso')
2318
-                )
2319
-            );
2320
-        }
2321
-        return parent::restore();
2322
-    }
2323
-
2324
-
2325
-    /**
2326
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
2327
-     *
2328
-     * @param boolean $trigger_set_status_logic  EE_Registration::set_status() can trigger additional logic
2329
-     *                                           depending on whether the reg status changes to or from "Approved"
2330
-     * @return boolean whether the Registration status was updated
2331
-     * @throws DomainException
2332
-     * @throws EE_Error
2333
-     * @throws EntityNotFoundException
2334
-     * @throws InvalidArgumentException
2335
-     * @throws InvalidDataTypeException
2336
-     * @throws InvalidInterfaceException
2337
-     * @throws ReflectionException
2338
-     * @throws RuntimeException
2339
-     * @throws UnexpectedEntityException
2340
-     */
2341
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2342
-    {
2343
-        $paid  = $this->paid();
2344
-        $price = $this->final_price();
2345
-        switch (true) {
2346
-            // overpaid or paid
2347
-            case EEH_Money::compare_floats($paid, $price, '>'):
2348
-            case EEH_Money::compare_floats($paid, $price):
2349
-                $new_status = RegStatus::APPROVED;
2350
-                break;
2351
-            //  underpaid
2352
-            case EEH_Money::compare_floats($paid, $price, '<'):
2353
-                $new_status = RegStatus::PENDING_PAYMENT;
2354
-                break;
2355
-            // uhhh Houston...
2356
-            default:
2357
-                throw new RuntimeException(
2358
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2359
-                );
2360
-        }
2361
-        if ($new_status !== $this->status_ID()) {
2362
-            if ($trigger_set_status_logic) {
2363
-                return $this->set_status(
2364
-                    $new_status,
2365
-                    false,
2366
-                    new Context(
2367
-                        __METHOD__,
2368
-                        esc_html__(
2369
-                            'Executed when the registration status is updated based on total paid.',
2370
-                            'event_espresso'
2371
-                        )
2372
-                    )
2373
-                );
2374
-            }
2375
-            parent::set('STS_ID', $new_status);
2376
-            return true;
2377
-        }
2378
-        return false;
2379
-    }
2380
-
2381
-
2382
-    /*************************** DEPRECATED ***************************/
2383
-
2384
-
2385
-    /**
2386
-     * @deprecated
2387
-     * @since     4.7.0
2388
-     */
2389
-    public function price_paid()
2390
-    {
2391
-        EE_Error::doing_it_wrong(
2392
-            'EE_Registration::price_paid()',
2393
-            esc_html__(
2394
-                'This method is deprecated, please use EE_Registration::final_price() instead.',
2395
-                'event_espresso'
2396
-            ),
2397
-            '4.7.0'
2398
-        );
2399
-        return $this->final_price();
2400
-    }
2401
-
2402
-
2403
-    /**
2404
-     * @param float $REG_final_price
2405
-     * @throws EE_Error
2406
-     * @throws EntityNotFoundException
2407
-     * @throws InvalidArgumentException
2408
-     * @throws InvalidDataTypeException
2409
-     * @throws InvalidInterfaceException
2410
-     * @throws ReflectionException
2411
-     * @throws RuntimeException
2412
-     * @throws DomainException
2413
-     * @deprecated
2414
-     * @since     4.7.0
2415
-     */
2416
-    public function set_price_paid($REG_final_price = 0.00)
2417
-    {
2418
-        EE_Error::doing_it_wrong(
2419
-            'EE_Registration::set_price_paid()',
2420
-            esc_html__(
2421
-                'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2422
-                'event_espresso'
2423
-            ),
2424
-            '4.7.0'
2425
-        );
2426
-        $this->set_final_price($REG_final_price);
2427
-    }
2428
-
2429
-
2430
-    /**
2431
-     * @return string
2432
-     * @throws EE_Error
2433
-     * @throws InvalidArgumentException
2434
-     * @throws InvalidDataTypeException
2435
-     * @throws InvalidInterfaceException
2436
-     * @throws ReflectionException
2437
-     * @deprecated
2438
-     * @since 4.7.0
2439
-     */
2440
-    public function pretty_price_paid()
2441
-    {
2442
-        EE_Error::doing_it_wrong(
2443
-            'EE_Registration::pretty_price_paid()',
2444
-            esc_html__(
2445
-                'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2446
-                'event_espresso'
2447
-            ),
2448
-            '4.7.0'
2449
-        );
2450
-        return $this->pretty_final_price();
2451
-    }
2452
-
2453
-
2454
-    /**
2455
-     * Gets the primary datetime related to this registration via the related Event to this registration
2456
-     *
2457
-     * @return EE_Datetime
2458
-     * @throws EE_Error
2459
-     * @throws EntityNotFoundException
2460
-     * @throws InvalidArgumentException
2461
-     * @throws InvalidDataTypeException
2462
-     * @throws InvalidInterfaceException
2463
-     * @throws ReflectionException
2464
-     * @deprecated 4.9.17
2465
-     */
2466
-    public function get_related_primary_datetime()
2467
-    {
2468
-        EE_Error::doing_it_wrong(
2469
-            __METHOD__,
2470
-            esc_html__(
2471
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2472
-                'event_espresso'
2473
-            ),
2474
-            '4.9.17',
2475
-            '5.0.0'
2476
-        );
2477
-        return $this->event()->primary_datetime();
2478
-    }
2479
-
2480
-
2481
-    /**
2482
-     * Returns the contact's name (or "Unknown" if there is no contact.)
2483
-     *
2484
-     * @return string
2485
-     * @throws EE_Error
2486
-     * @throws InvalidArgumentException
2487
-     * @throws InvalidDataTypeException
2488
-     * @throws InvalidInterfaceException
2489
-     * @throws ReflectionException
2490
-     * @since 4.10.12.p
2491
-     */
2492
-    public function name()
2493
-    {
2494
-        return $this->attendeeName();
2495
-    }
2496
-
2497
-
2498
-    /**
2499
-     * @return bool
2500
-     * @throws EE_Error
2501
-     * @throws ReflectionException
2502
-     */
2503
-    public function wasMoved(): bool
2504
-    {
2505
-        // only need to check 'registration-moved-to' because
2506
-        // the existence of a new REG ID means the registration was moved
2507
-        $reg_moved = $this->get_extra_meta('registration-moved-to', true, []);
2508
-        return isset($reg_moved['NEW_REG_ID']) && $reg_moved['NEW_REG_ID'];
2509
-    }
2510
-
2511
-
2512
-    /**
2513
-     * @param EE_Payment $payment
2514
-     * @param float|null $amount
2515
-     * @return float
2516
-     * @throws EE_Error
2517
-     * @throws ReflectionException
2518
-     * @since 5.0.8.p
2519
-     */
2520
-    public function applyPayment(EE_Payment $payment, ?float $amount = null): float
2521
-    {
2522
-        $payment_amount = $amount ?? $payment->amount();
2523
-        // ensure $payment_amount is NOT negative
2524
-        $payment_amount = (float) abs($payment_amount);
2525
-        $payment_amount = $payment->is_a_refund()
2526
-            ? $this->processRefund($payment_amount)
2527
-            : $this->processPayment($payment_amount);
2528
-        if ($payment_amount) {
2529
-            $reg_payment = EEM_Registration_Payment::instance()->get_one(
2530
-                [['REG_ID' => $this->ID(), 'PAY_ID' => $payment->ID()]]
2531
-            );
2532
-            // if existing registration payment exists
2533
-            if ($reg_payment instanceof EE_Registration_Payment) {
2534
-                // then update that record
2535
-                $reg_payment->set_amount($payment_amount);
2536
-            } else {
2537
-                // or add new relation between registration and payment and set amount
2538
-                $reg_payment = EE_Registration_Payment::new_instance(
2539
-                    [
2540
-                        'REG_ID'     => $this->ID(),
2541
-                        'PAY_ID'     => $payment->ID(),
2542
-                        'RPY_amount' => $payment_amount,
2543
-                    ]
2544
-                );
2545
-            }
2546
-            $reg_payment->save();
2547
-        }
2548
-        return $payment_amount;
2549
-    }
2550
-
2551
-
2552
-    /**
2553
-     * @throws EE_Error
2554
-     * @throws ReflectionException
2555
-     */
2556
-    private function processPayment(float $payment_amount): float
2557
-    {
2558
-        $paid  = $this->paid();
2559
-        $owing = $this->final_price() - $paid;
2560
-        if ($owing <= 0) {
2561
-            return 0.0;
2562
-        }
2563
-        // don't allow payment amount to exceed the incoming amount, OR the amount owing
2564
-        $payment_amount = min($payment_amount, $owing);
2565
-        $paid           = $paid + $payment_amount;
2566
-        // calculate and set new REG_paid
2567
-        $this->set_paid($paid);
2568
-        // make it stick
2569
-        $this->save();
2570
-        return (float) $payment_amount;
2571
-    }
2572
-
2573
-
2574
-    /**
2575
-     * @throws ReflectionException
2576
-     * @throws EE_Error
2577
-     */
2578
-    private function processRefund(float $payment_amount): float
2579
-    {
2580
-        $paid = $this->paid();
2581
-        if ($paid <= 0) {
2582
-            return 0.0;
2583
-        }
2584
-        // don't allow refund amount to exceed the incoming amount, OR the amount paid
2585
-        $payment_amount = min($payment_amount, $paid);
2586
-        // calculate and set new REG_paid
2587
-        $paid = $paid - $payment_amount;
2588
-        $this->set_paid($paid);
2589
-        // make it stick
2590
-        $this->save();
2591
-        // convert payment amount back to a negative value for storage in the db
2592
-        return (float) $payment_amount;
2593
-    }
2594
-
2595
-
2596
-    /**
2597
-     * @return string
2598
-     * @throws EE_Error
2599
-     * @throws ReflectionException
2600
-     * @since 5.0.20.p
2601
-     */
2602
-    public function defaultRegistrationStatus(): string
2603
-    {
2604
-        $default_event_reg_status = $this->event()->default_registration_status();
2605
-        $default_reg_status = (string) apply_filters(
2606
-            'AFEE__EE_Registration__defaultRegistrationStatus__default_reg_status',
2607
-            $default_event_reg_status,
2608
-            $this
2609
-        );
2610
-        return RegStatus::isValidStatus($default_reg_status, false)
2611
-            ? $default_reg_status
2612
-            : $default_event_reg_status;
2613
-    }
22
+	/**
23
+	 * Used to reference when a registration has never been checked in.
24
+	 *
25
+	 * @deprecated use \EE_Checkin::status_checked_never instead
26
+	 * @type int
27
+	 */
28
+	const checkin_status_never = 2;
29
+
30
+	/**
31
+	 * Used to reference when a registration has been checked in.
32
+	 *
33
+	 * @deprecated use \EE_Checkin::status_checked_in instead
34
+	 * @type int
35
+	 */
36
+	const checkin_status_in = 1;
37
+
38
+	/**
39
+	 * Used to reference when a registration has been checked out.
40
+	 *
41
+	 * @deprecated use \EE_Checkin::status_checked_out instead
42
+	 * @type int
43
+	 */
44
+	const checkin_status_out = 0;
45
+
46
+	/**
47
+	 * extra meta key for tracking reg status os trashed registrations
48
+	 *
49
+	 * @type string
50
+	 */
51
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
+
53
+	/**
54
+	 * extra meta key for tracking if registration has reserved ticket
55
+	 *
56
+	 * @type string
57
+	 */
58
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
59
+
60
+
61
+	/**
62
+	 * @param array  $props_n_values          incoming values
63
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
64
+	 *                                        used.)
65
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
66
+	 *                                        date_format and the second value is the time format
67
+	 * @return EE_Registration
68
+	 * @throws EE_Error
69
+	 * @throws InvalidArgumentException
70
+	 * @throws InvalidDataTypeException
71
+	 * @throws InvalidInterfaceException
72
+	 * @throws ReflectionException
73
+	 */
74
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
75
+	{
76
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
77
+		return $has_object
78
+			?: new self($props_n_values, false, $timezone, $date_formats);
79
+	}
80
+
81
+
82
+	/**
83
+	 * @param array  $props_n_values  incoming values from the database
84
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
85
+	 *                                the website will be used.
86
+	 * @return EE_Registration
87
+	 * @throws EE_Error
88
+	 * @throws InvalidArgumentException
89
+	 * @throws InvalidDataTypeException
90
+	 * @throws InvalidInterfaceException
91
+	 * @throws ReflectionException
92
+	 */
93
+	public static function new_instance_from_db($props_n_values = [], $timezone = '')
94
+	{
95
+		return new self($props_n_values, true, $timezone);
96
+	}
97
+
98
+
99
+	/**
100
+	 *        Set Event ID
101
+	 *
102
+	 * @param int $EVT_ID Event ID
103
+	 * @throws DomainException
104
+	 * @throws EE_Error
105
+	 * @throws EntityNotFoundException
106
+	 * @throws InvalidArgumentException
107
+	 * @throws InvalidDataTypeException
108
+	 * @throws InvalidInterfaceException
109
+	 * @throws ReflectionException
110
+	 * @throws RuntimeException
111
+	 * @throws UnexpectedEntityException
112
+	 */
113
+	public function set_event($EVT_ID = 0)
114
+	{
115
+		$this->set('EVT_ID', $EVT_ID);
116
+	}
117
+
118
+
119
+	/**
120
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
121
+	 * be routed to internal methods
122
+	 *
123
+	 * @param string $field_name
124
+	 * @param mixed  $field_value
125
+	 * @param bool   $use_default
126
+	 * @throws DomainException
127
+	 * @throws EE_Error
128
+	 * @throws EntityNotFoundException
129
+	 * @throws InvalidArgumentException
130
+	 * @throws InvalidDataTypeException
131
+	 * @throws InvalidInterfaceException
132
+	 * @throws ReflectionException
133
+	 * @throws RuntimeException
134
+	 * @throws UnexpectedEntityException
135
+	 */
136
+	public function set($field_name, $field_value, $use_default = false)
137
+	{
138
+		switch ($field_name) {
139
+			case 'REG_code':
140
+				if (! empty($field_value) && ! $this->reg_code()) {
141
+					$this->set_reg_code($field_value, $use_default);
142
+				}
143
+				break;
144
+			case 'STS_ID':
145
+				$this->set_status((string) $field_value, $use_default);
146
+				break;
147
+			default:
148
+				parent::set($field_name, $field_value, $use_default);
149
+		}
150
+	}
151
+
152
+
153
+	/**
154
+	 * Set Status ID
155
+	 * updates the registration status and ALSO...
156
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
157
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
158
+	 *
159
+	 * @param string                $new_STS_ID
160
+	 * @param boolean               $use_default
161
+	 * @param ContextInterface|null $context
162
+	 * @return bool
163
+	 * @throws DomainException
164
+	 * @throws EE_Error
165
+	 * @throws EntityNotFoundException
166
+	 * @throws InvalidArgumentException
167
+	 * @throws InvalidDataTypeException
168
+	 * @throws InvalidInterfaceException
169
+	 * @throws ReflectionException
170
+	 * @throws RuntimeException
171
+	 * @throws UnexpectedEntityException
172
+	 */
173
+	public function set_status(
174
+		string $new_STS_ID = '',
175
+		bool $use_default = false,
176
+		?ContextInterface $context = null
177
+	): bool {
178
+		// get current REG_Status
179
+		$old_STS_ID = $this->status_ID();
180
+		$new_STS_ID = (string) apply_filters(
181
+			'AFEE__EE_Registration__set_status__new_STS_ID',
182
+			$new_STS_ID,
183
+			$context,
184
+			$this
185
+		);
186
+		// it's still good to allow the parent set method to have a say
187
+		parent::set('STS_ID', (! empty($new_STS_ID) ? $new_STS_ID : null), $use_default);
188
+		// if status has changed
189
+		if (
190
+			$old_STS_ID !== $new_STS_ID // and that status has actually changed
191
+			&& ! empty($old_STS_ID) // and that old status is actually set
192
+			&& ! empty($new_STS_ID) // as well as the new status
193
+			&& $this->ID() // ensure registration is in the db
194
+		) {
195
+			// THEN handle other changes that occur when reg status changes
196
+			// TO approved
197
+			if ($new_STS_ID === RegStatus::APPROVED) {
198
+				// reserve a space by incrementing ticket and datetime sold values
199
+				$this->reserveRegistrationSpace();
200
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
201
+				// OR FROM  approved
202
+			} elseif ($old_STS_ID === RegStatus::APPROVED) {
203
+				// release a space by decrementing ticket and datetime sold values
204
+				$this->releaseRegistrationSpace();
205
+				do_action(
206
+					'AHEE__EE_Registration__set_status__from_approved',
207
+					$this,
208
+					$old_STS_ID,
209
+					$new_STS_ID,
210
+					$context
211
+				);
212
+			}
213
+			$this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
214
+			if ($this->statusChangeUpdatesTransaction($context)) {
215
+				$this->updateTransactionAfterStatusChange();
216
+			}
217
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
218
+		}
219
+		return ! empty($new_STS_ID);
220
+	}
221
+
222
+
223
+	/**
224
+	 * update REGs and TXN when cancelled or declined registrations involved
225
+	 *
226
+	 * @param string                $new_STS_ID
227
+	 * @param string                $old_STS_ID
228
+	 * @param ContextInterface|null $context
229
+	 * @throws EE_Error
230
+	 * @throws InvalidArgumentException
231
+	 * @throws InvalidDataTypeException
232
+	 * @throws InvalidInterfaceException
233
+	 * @throws ReflectionException
234
+	 * @throws RuntimeException
235
+	 */
236
+	private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ?ContextInterface $context = null)
237
+	{
238
+		// these reg statuses should not be considered in any calculations involving monies owing
239
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
240
+		// true if registration has been cancelled or declined
241
+		$this->updateIfCanceled(
242
+			$closed_reg_statuses,
243
+			$new_STS_ID,
244
+			$old_STS_ID,
245
+			$context
246
+		);
247
+		$this->updateIfReinstated(
248
+			$closed_reg_statuses,
249
+			$new_STS_ID,
250
+			$old_STS_ID,
251
+			$context
252
+		);
253
+	}
254
+
255
+
256
+	/**
257
+	 * update REGs and TXN when cancelled or declined registrations involved
258
+	 *
259
+	 * @param array                 $closed_reg_statuses
260
+	 * @param string                $new_STS_ID
261
+	 * @param string                $old_STS_ID
262
+	 * @param ContextInterface|null $context
263
+	 * @throws EE_Error
264
+	 * @throws InvalidArgumentException
265
+	 * @throws InvalidDataTypeException
266
+	 * @throws InvalidInterfaceException
267
+	 * @throws ReflectionException
268
+	 * @throws RuntimeException
269
+	 */
270
+	private function updateIfCanceled(
271
+		array $closed_reg_statuses,
272
+		$new_STS_ID,
273
+		$old_STS_ID,
274
+		?ContextInterface $context = null
275
+	) {
276
+		// true if registration has been cancelled or declined
277
+		if (
278
+			in_array($new_STS_ID, $closed_reg_statuses, true)
279
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
280
+		) {
281
+			/** @type EE_Registration_Processor $registration_processor */
282
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
283
+			/** @type EE_Transaction_Processor $transaction_processor */
284
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
285
+			// cancelled or declined registration
286
+			$registration_processor->update_registration_after_being_canceled_or_declined(
287
+				$this,
288
+				$closed_reg_statuses
289
+			);
290
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
291
+				$this,
292
+				$closed_reg_statuses,
293
+				false
294
+			);
295
+			do_action(
296
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
297
+				$this,
298
+				$old_STS_ID,
299
+				$new_STS_ID,
300
+				$context
301
+			);
302
+		}
303
+	}
304
+
305
+
306
+	/**
307
+	 * update REGs and TXN when cancelled or declined registrations involved
308
+	 *
309
+	 * @param array                 $closed_reg_statuses
310
+	 * @param string                $new_STS_ID
311
+	 * @param string                $old_STS_ID
312
+	 * @param ContextInterface|null $context
313
+	 * @throws EE_Error
314
+	 * @throws InvalidArgumentException
315
+	 * @throws InvalidDataTypeException
316
+	 * @throws InvalidInterfaceException
317
+	 * @throws ReflectionException
318
+	 * @throws RuntimeException
319
+	 */
320
+	private function updateIfReinstated(
321
+		array $closed_reg_statuses,
322
+		$new_STS_ID,
323
+		$old_STS_ID,
324
+		?ContextInterface $context = null
325
+	) {
326
+		// true if reinstating cancelled or declined registration
327
+		if (
328
+			in_array($old_STS_ID, $closed_reg_statuses, true)
329
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
330
+		) {
331
+			/** @type EE_Registration_Processor $registration_processor */
332
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
333
+			/** @type EE_Transaction_Processor $transaction_processor */
334
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
335
+			// reinstating cancelled or declined registration
336
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
337
+				$this,
338
+				$closed_reg_statuses
339
+			);
340
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
341
+				$this,
342
+				$closed_reg_statuses,
343
+				false
344
+			);
345
+			do_action(
346
+				'AHEE__EE_Registration__set_status__after_reinstated',
347
+				$this,
348
+				$old_STS_ID,
349
+				$new_STS_ID,
350
+				$context
351
+			);
352
+		}
353
+	}
354
+
355
+
356
+	/**
357
+	 * @param ContextInterface|null $context
358
+	 * @return bool
359
+	 */
360
+	private function statusChangeUpdatesTransaction(?ContextInterface $context = null)
361
+	{
362
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
363
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
364
+			['spco_reg_step_attendee_information_process_registrations'],
365
+			$context,
366
+			$this
367
+		);
368
+		return ! (
369
+			$context instanceof ContextInterface
370
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
371
+		);
372
+	}
373
+
374
+
375
+	/**
376
+	 * @throws EE_Error
377
+	 * @throws EntityNotFoundException
378
+	 * @throws InvalidArgumentException
379
+	 * @throws InvalidDataTypeException
380
+	 * @throws InvalidInterfaceException
381
+	 * @throws ReflectionException
382
+	 * @throws RuntimeException
383
+	 */
384
+	private function updateTransactionAfterStatusChange()
385
+	{
386
+		/** @type EE_Transaction_Payments $transaction_payments */
387
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
388
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
389
+		$this->transaction()->update_status_based_on_total_paid();
390
+	}
391
+
392
+
393
+	/**
394
+	 * get Status ID
395
+	 *
396
+	 * @throws EE_Error
397
+	 * @throws InvalidArgumentException
398
+	 * @throws InvalidDataTypeException
399
+	 * @throws InvalidInterfaceException
400
+	 * @throws ReflectionException
401
+	 */
402
+	public function status_ID()
403
+	{
404
+		return $this->get('STS_ID');
405
+	}
406
+
407
+
408
+	/**
409
+	 * Gets the ticket this registration is for
410
+	 *
411
+	 * @param boolean $include_archived whether to include archived tickets or not.
412
+	 * @return EE_Ticket|EE_Base_Class
413
+	 * @throws EE_Error
414
+	 * @throws InvalidArgumentException
415
+	 * @throws InvalidDataTypeException
416
+	 * @throws InvalidInterfaceException
417
+	 * @throws ReflectionException
418
+	 */
419
+	public function ticket($include_archived = true)
420
+	{
421
+		return EEM_Ticket::instance()->get_one_by_ID($this->ticket_ID());
422
+	}
423
+
424
+
425
+	/**
426
+	 * Gets the event this registration is for
427
+	 *
428
+	 * @return EE_Event
429
+	 * @throws EE_Error
430
+	 * @throws EntityNotFoundException
431
+	 * @throws InvalidArgumentException
432
+	 * @throws InvalidDataTypeException
433
+	 * @throws InvalidInterfaceException
434
+	 * @throws ReflectionException
435
+	 */
436
+	public function event(): EE_Event
437
+	{
438
+		$event = $this->event_obj();
439
+		if (! $event instanceof EE_Event) {
440
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
441
+		}
442
+		return $event;
443
+	}
444
+
445
+
446
+	/**
447
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
448
+	 * with the author of the event this registration is for.
449
+	 *
450
+	 * @return int
451
+	 * @throws EE_Error
452
+	 * @throws EntityNotFoundException
453
+	 * @throws InvalidArgumentException
454
+	 * @throws InvalidDataTypeException
455
+	 * @throws InvalidInterfaceException
456
+	 * @throws ReflectionException
457
+	 * @since 4.5.0
458
+	 */
459
+	public function wp_user(): int
460
+	{
461
+		return $this->event()->wp_user();
462
+	}
463
+
464
+
465
+	/**
466
+	 * increments this registration's related ticket sold and corresponding datetime sold values
467
+	 *
468
+	 * @return void
469
+	 * @throws DomainException
470
+	 * @throws EE_Error
471
+	 * @throws EntityNotFoundException
472
+	 * @throws InvalidArgumentException
473
+	 * @throws InvalidDataTypeException
474
+	 * @throws InvalidInterfaceException
475
+	 * @throws ReflectionException
476
+	 * @throws UnexpectedEntityException
477
+	 */
478
+	private function reserveRegistrationSpace()
479
+	{
480
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
481
+		// so stop tracking that this reg has a ticket reserved
482
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
483
+		$ticket = $this->ticket();
484
+		$ticket->increaseSold();
485
+		// possibly set event status to sold out
486
+		$this->event()->perform_sold_out_status_check();
487
+	}
488
+
489
+
490
+	/**
491
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
492
+	 *
493
+	 * @return void
494
+	 * @throws DomainException
495
+	 * @throws EE_Error
496
+	 * @throws EntityNotFoundException
497
+	 * @throws InvalidArgumentException
498
+	 * @throws InvalidDataTypeException
499
+	 * @throws InvalidInterfaceException
500
+	 * @throws ReflectionException
501
+	 * @throws UnexpectedEntityException
502
+	 */
503
+	private function releaseRegistrationSpace()
504
+	{
505
+		$ticket = $this->ticket();
506
+		$ticket->decreaseSold();
507
+		// possibly change event status from sold out back to previous status
508
+		$this->event()->perform_sold_out_status_check();
509
+	}
510
+
511
+
512
+	/**
513
+	 * tracks this registration's ticket reservation in extra meta
514
+	 * and can increment related ticket reserved and corresponding datetime reserved values
515
+	 *
516
+	 * @param bool   $update_ticket if true, will increment ticket and datetime reserved count
517
+	 * @param string $source
518
+	 * @return void
519
+	 * @throws EE_Error
520
+	 * @throws InvalidArgumentException
521
+	 * @throws InvalidDataTypeException
522
+	 * @throws InvalidInterfaceException
523
+	 * @throws ReflectionException
524
+	 */
525
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
526
+	{
527
+		// only reserve ticket if space is not currently reserved
528
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
529
+			$reserved = $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
530
+			if ($reserved && $update_ticket) {
531
+				$ticket = $this->ticket();
532
+				$ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
533
+				$this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
534
+				$ticket->save();
535
+			}
536
+		}
537
+	}
538
+
539
+
540
+	/**
541
+	 * stops tracking this registration's ticket reservation in extra meta
542
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
543
+	 *
544
+	 * @param bool   $update_ticket if true, will decrement ticket and datetime reserved count
545
+	 * @param string $source
546
+	 * @return void
547
+	 * @throws EE_Error
548
+	 * @throws InvalidArgumentException
549
+	 * @throws InvalidDataTypeException
550
+	 * @throws InvalidInterfaceException
551
+	 * @throws ReflectionException
552
+	 */
553
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
554
+	{
555
+		// only release ticket if space is currently reserved
556
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
557
+			$reserved = $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false);
558
+			if ($reserved && $update_ticket) {
559
+				$ticket = $this->ticket();
560
+				$ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
561
+				$this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
562
+			}
563
+		}
564
+	}
565
+
566
+
567
+	/**
568
+	 * Set Attendee ID
569
+	 *
570
+	 * @param int $ATT_ID Attendee ID
571
+	 * @throws DomainException
572
+	 * @throws EE_Error
573
+	 * @throws EntityNotFoundException
574
+	 * @throws InvalidArgumentException
575
+	 * @throws InvalidDataTypeException
576
+	 * @throws InvalidInterfaceException
577
+	 * @throws ReflectionException
578
+	 * @throws RuntimeException
579
+	 * @throws UnexpectedEntityException
580
+	 */
581
+	public function set_attendee_id($ATT_ID = 0)
582
+	{
583
+		$this->set('ATT_ID', $ATT_ID);
584
+	}
585
+
586
+
587
+	/**
588
+	 *        Set Transaction ID
589
+	 *
590
+	 * @param int $TXN_ID Transaction ID
591
+	 * @throws DomainException
592
+	 * @throws EE_Error
593
+	 * @throws EntityNotFoundException
594
+	 * @throws InvalidArgumentException
595
+	 * @throws InvalidDataTypeException
596
+	 * @throws InvalidInterfaceException
597
+	 * @throws ReflectionException
598
+	 * @throws RuntimeException
599
+	 * @throws UnexpectedEntityException
600
+	 */
601
+	public function set_transaction_id($TXN_ID = 0)
602
+	{
603
+		$this->set('TXN_ID', $TXN_ID);
604
+	}
605
+
606
+
607
+	/**
608
+	 *        Set Session
609
+	 *
610
+	 * @param string $REG_session PHP Session ID
611
+	 * @throws DomainException
612
+	 * @throws EE_Error
613
+	 * @throws EntityNotFoundException
614
+	 * @throws InvalidArgumentException
615
+	 * @throws InvalidDataTypeException
616
+	 * @throws InvalidInterfaceException
617
+	 * @throws ReflectionException
618
+	 * @throws RuntimeException
619
+	 * @throws UnexpectedEntityException
620
+	 */
621
+	public function set_session($REG_session = '')
622
+	{
623
+		$this->set('REG_session', $REG_session);
624
+	}
625
+
626
+
627
+	/**
628
+	 *        Set Registration URL Link
629
+	 *
630
+	 * @param string $REG_url_link Registration URL Link
631
+	 * @throws DomainException
632
+	 * @throws EE_Error
633
+	 * @throws EntityNotFoundException
634
+	 * @throws InvalidArgumentException
635
+	 * @throws InvalidDataTypeException
636
+	 * @throws InvalidInterfaceException
637
+	 * @throws ReflectionException
638
+	 * @throws RuntimeException
639
+	 * @throws UnexpectedEntityException
640
+	 */
641
+	public function set_reg_url_link($REG_url_link = '')
642
+	{
643
+		$this->set('REG_url_link', $REG_url_link);
644
+	}
645
+
646
+
647
+	/**
648
+	 *        Set Attendee Counter
649
+	 *
650
+	 * @param int $REG_count Primary Attendee
651
+	 * @throws DomainException
652
+	 * @throws EE_Error
653
+	 * @throws EntityNotFoundException
654
+	 * @throws InvalidArgumentException
655
+	 * @throws InvalidDataTypeException
656
+	 * @throws InvalidInterfaceException
657
+	 * @throws ReflectionException
658
+	 * @throws RuntimeException
659
+	 * @throws UnexpectedEntityException
660
+	 */
661
+	public function set_count($REG_count = 1)
662
+	{
663
+		$this->set('REG_count', $REG_count);
664
+	}
665
+
666
+
667
+	/**
668
+	 *        Set Group Size
669
+	 *
670
+	 * @param boolean $REG_group_size Group Registration
671
+	 * @throws DomainException
672
+	 * @throws EE_Error
673
+	 * @throws EntityNotFoundException
674
+	 * @throws InvalidArgumentException
675
+	 * @throws InvalidDataTypeException
676
+	 * @throws InvalidInterfaceException
677
+	 * @throws ReflectionException
678
+	 * @throws RuntimeException
679
+	 * @throws UnexpectedEntityException
680
+	 */
681
+	public function set_group_size($REG_group_size = false)
682
+	{
683
+		$this->set('REG_group_size', $REG_group_size);
684
+	}
685
+
686
+
687
+	/**
688
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
689
+	 *    RegStatus::AWAITING_REVIEW
690
+	 *
691
+	 * @return        boolean
692
+	 * @throws EE_Error
693
+	 * @throws InvalidArgumentException
694
+	 * @throws InvalidDataTypeException
695
+	 * @throws InvalidInterfaceException
696
+	 * @throws ReflectionException
697
+	 */
698
+	public function is_not_approved()
699
+	{
700
+		return $this->status_ID() === RegStatus::AWAITING_REVIEW;
701
+	}
702
+
703
+
704
+	/**
705
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
706
+	 *    RegStatus::PENDING_PAYMENT
707
+	 *
708
+	 * @return        boolean
709
+	 * @throws EE_Error
710
+	 * @throws InvalidArgumentException
711
+	 * @throws InvalidDataTypeException
712
+	 * @throws InvalidInterfaceException
713
+	 * @throws ReflectionException
714
+	 */
715
+	public function is_pending_payment()
716
+	{
717
+		return $this->status_ID() === RegStatus::PENDING_PAYMENT;
718
+	}
719
+
720
+
721
+	/**
722
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == RegStatus::APPROVED
723
+	 *
724
+	 * @return        boolean
725
+	 * @throws EE_Error
726
+	 * @throws InvalidArgumentException
727
+	 * @throws InvalidDataTypeException
728
+	 * @throws InvalidInterfaceException
729
+	 * @throws ReflectionException
730
+	 */
731
+	public function is_approved()
732
+	{
733
+		return $this->status_ID() === RegStatus::APPROVED;
734
+	}
735
+
736
+
737
+	/**
738
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == RegStatus::CANCELLED
739
+	 *
740
+	 * @return        boolean
741
+	 * @throws EE_Error
742
+	 * @throws InvalidArgumentException
743
+	 * @throws InvalidDataTypeException
744
+	 * @throws InvalidInterfaceException
745
+	 * @throws ReflectionException
746
+	 */
747
+	public function is_cancelled()
748
+	{
749
+		return $this->status_ID() === RegStatus::CANCELLED;
750
+	}
751
+
752
+
753
+	/**
754
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == RegStatus::DECLINED
755
+	 *
756
+	 * @return        boolean
757
+	 * @throws EE_Error
758
+	 * @throws InvalidArgumentException
759
+	 * @throws InvalidDataTypeException
760
+	 * @throws InvalidInterfaceException
761
+	 * @throws ReflectionException
762
+	 */
763
+	public function is_declined()
764
+	{
765
+		return $this->status_ID() === RegStatus::DECLINED;
766
+	}
767
+
768
+
769
+	/**
770
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
771
+	 *    RegStatus::INCOMPLETE
772
+	 *
773
+	 * @return        boolean
774
+	 * @throws EE_Error
775
+	 * @throws InvalidArgumentException
776
+	 * @throws InvalidDataTypeException
777
+	 * @throws InvalidInterfaceException
778
+	 * @throws ReflectionException
779
+	 */
780
+	public function is_incomplete()
781
+	{
782
+		return $this->status_ID() === RegStatus::INCOMPLETE;
783
+	}
784
+
785
+
786
+	/**
787
+	 *        Set Registration Date
788
+	 *
789
+	 * @param mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
790
+	 *                                                 Date
791
+	 * @throws DomainException
792
+	 * @throws EE_Error
793
+	 * @throws EntityNotFoundException
794
+	 * @throws InvalidArgumentException
795
+	 * @throws InvalidDataTypeException
796
+	 * @throws InvalidInterfaceException
797
+	 * @throws ReflectionException
798
+	 * @throws RuntimeException
799
+	 * @throws UnexpectedEntityException
800
+	 */
801
+	public function set_reg_date($REG_date = false)
802
+	{
803
+		$this->set('REG_date', $REG_date);
804
+	}
805
+
806
+
807
+	/**
808
+	 *    Set final price owing for this registration after all ticket/price modifications
809
+	 *
810
+	 * @param float $REG_final_price
811
+	 * @throws DomainException
812
+	 * @throws EE_Error
813
+	 * @throws EntityNotFoundException
814
+	 * @throws InvalidArgumentException
815
+	 * @throws InvalidDataTypeException
816
+	 * @throws InvalidInterfaceException
817
+	 * @throws ReflectionException
818
+	 * @throws RuntimeException
819
+	 * @throws UnexpectedEntityException
820
+	 */
821
+	public function set_final_price($REG_final_price = 0.00)
822
+	{
823
+		$this->set('REG_final_price', $REG_final_price);
824
+	}
825
+
826
+
827
+	/**
828
+	 *    Set amount paid towards this registration's final price
829
+	 *
830
+	 * @param float|int|string $REG_paid
831
+	 * @throws DomainException
832
+	 * @throws EE_Error
833
+	 * @throws EntityNotFoundException
834
+	 * @throws InvalidArgumentException
835
+	 * @throws InvalidDataTypeException
836
+	 * @throws InvalidInterfaceException
837
+	 * @throws ReflectionException
838
+	 * @throws RuntimeException
839
+	 * @throws UnexpectedEntityException
840
+	 */
841
+	public function set_paid($REG_paid = 0.00)
842
+	{
843
+		$this->set('REG_paid', (float) $REG_paid);
844
+	}
845
+
846
+
847
+	/**
848
+	 *        Attendee Is Going
849
+	 *
850
+	 * @param boolean $REG_att_is_going Attendee Is Going
851
+	 * @throws DomainException
852
+	 * @throws EE_Error
853
+	 * @throws EntityNotFoundException
854
+	 * @throws InvalidArgumentException
855
+	 * @throws InvalidDataTypeException
856
+	 * @throws InvalidInterfaceException
857
+	 * @throws ReflectionException
858
+	 * @throws RuntimeException
859
+	 * @throws UnexpectedEntityException
860
+	 */
861
+	public function set_att_is_going($REG_att_is_going = false)
862
+	{
863
+		$this->set('REG_att_is_going', $REG_att_is_going);
864
+	}
865
+
866
+
867
+	/**
868
+	 * Gets the related attendee
869
+	 *
870
+	 * @return EE_Attendee|EE_Base_Class
871
+	 * @throws EE_Error
872
+	 * @throws InvalidArgumentException
873
+	 * @throws InvalidDataTypeException
874
+	 * @throws InvalidInterfaceException
875
+	 * @throws ReflectionException
876
+	 */
877
+	public function attendee()
878
+	{
879
+		return EEM_Attendee::instance()->get_one_by_ID($this->attendee_ID());
880
+	}
881
+
882
+
883
+	/**
884
+	 * Gets the name of the attendee.
885
+	 *
886
+	 * @param bool $apply_html_entities set to true if you want to use HTML entities.
887
+	 * @return string
888
+	 * @throws EE_Error
889
+	 * @throws InvalidArgumentException
890
+	 * @throws InvalidDataTypeException
891
+	 * @throws InvalidInterfaceException
892
+	 * @throws ReflectionException
893
+	 * @since 4.10.12.p
894
+	 */
895
+	public function attendeeName($apply_html_entities = false)
896
+	{
897
+		$attendee = $this->attendee();
898
+		if ($attendee instanceof EE_Attendee) {
899
+			$attendee_name = $attendee->full_name($apply_html_entities);
900
+		} else {
901
+			$attendee_name = esc_html__('Unknown', 'event_espresso');
902
+		}
903
+		return $attendee_name;
904
+	}
905
+
906
+
907
+	/**
908
+	 *        get Event ID
909
+	 */
910
+	public function event_ID()
911
+	{
912
+		return $this->get('EVT_ID');
913
+	}
914
+
915
+
916
+	/**
917
+	 *        get Event ID
918
+	 */
919
+	public function event_name()
920
+	{
921
+		$event = $this->event_obj();
922
+		if ($event) {
923
+			return $event->name();
924
+		} else {
925
+			return null;
926
+		}
927
+	}
928
+
929
+
930
+	/**
931
+	 * Fetches the event this registration is for
932
+	 *
933
+	 * @return EE_Base_Class|EE_Event
934
+	 * @throws EE_Error
935
+	 * @throws InvalidArgumentException
936
+	 * @throws InvalidDataTypeException
937
+	 * @throws InvalidInterfaceException
938
+	 * @throws ReflectionException
939
+	 */
940
+	public function event_obj()
941
+	{
942
+		return EEM_Event::instance()->get_one_by_ID($this->event_ID());
943
+	}
944
+
945
+
946
+	/**
947
+	 *        get Attendee ID
948
+	 */
949
+	public function attendee_ID()
950
+	{
951
+		return $this->get('ATT_ID');
952
+	}
953
+
954
+
955
+	/**
956
+	 *        get PHP Session ID
957
+	 */
958
+	public function session_ID()
959
+	{
960
+		return $this->get('REG_session');
961
+	}
962
+
963
+
964
+	/**
965
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
966
+	 *
967
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
968
+	 * @return string
969
+	 * @throws DomainException
970
+	 * @throws InvalidArgumentException
971
+	 * @throws InvalidDataTypeException
972
+	 * @throws InvalidInterfaceException
973
+	 */
974
+	public function receipt_url($messenger = 'html')
975
+	{
976
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
977
+	}
978
+
979
+
980
+	/**
981
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
982
+	 *
983
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
984
+	 * @return string
985
+	 * @throws DomainException
986
+	 * @throws InvalidArgumentException
987
+	 * @throws InvalidDataTypeException
988
+	 * @throws InvalidInterfaceException
989
+	 */
990
+	public function invoice_url($messenger = 'html')
991
+	{
992
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
993
+	}
994
+
995
+
996
+	/**
997
+	 * get Registration URL Link
998
+	 *
999
+	 * @return string
1000
+	 * @throws EE_Error
1001
+	 * @throws InvalidArgumentException
1002
+	 * @throws InvalidDataTypeException
1003
+	 * @throws InvalidInterfaceException
1004
+	 * @throws ReflectionException
1005
+	 */
1006
+	public function reg_url_link()
1007
+	{
1008
+		return (string) $this->get('REG_url_link');
1009
+	}
1010
+
1011
+
1012
+	/**
1013
+	 * Echoes out invoice_url()
1014
+	 *
1015
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
1016
+	 * @return void
1017
+	 * @throws DomainException
1018
+	 * @throws EE_Error
1019
+	 * @throws InvalidArgumentException
1020
+	 * @throws InvalidDataTypeException
1021
+	 * @throws InvalidInterfaceException
1022
+	 * @throws ReflectionException
1023
+	 */
1024
+	public function e_invoice_url($type = 'launch')
1025
+	{
1026
+		echo esc_url_raw($this->invoice_url($type));
1027
+	}
1028
+
1029
+
1030
+	/**
1031
+	 * Echoes out payment_overview_url
1032
+	 */
1033
+	public function e_payment_overview_url()
1034
+	{
1035
+		echo esc_url_raw($this->payment_overview_url());
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * Gets the URL for the checkout payment options reg step
1041
+	 * with this registration's REG_url_link added as a query parameter
1042
+	 *
1043
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
1044
+	 *                            payment overview url.
1045
+	 * @return string
1046
+	 * @throws EE_Error
1047
+	 * @throws InvalidArgumentException
1048
+	 * @throws InvalidDataTypeException
1049
+	 * @throws InvalidInterfaceException
1050
+	 * @throws ReflectionException
1051
+	 */
1052
+	public function payment_overview_url($clear_session = false)
1053
+	{
1054
+		return add_query_arg(
1055
+			(array) apply_filters(
1056
+				'FHEE__EE_Registration__payment_overview_url__query_args',
1057
+				[
1058
+					'e_reg_url_link' => $this->reg_url_link(),
1059
+					'step'           => 'payment_options',
1060
+					'revisit'        => true,
1061
+					'clear_session'  => (bool) $clear_session,
1062
+				],
1063
+				$this
1064
+			),
1065
+			EE_Registry::instance()->CFG->core->reg_page_url()
1066
+		);
1067
+	}
1068
+
1069
+
1070
+	/**
1071
+	 * Gets the URL for the checkout attendee information reg step
1072
+	 * with this registration's REG_url_link added as a query parameter
1073
+	 *
1074
+	 * @return string
1075
+	 * @throws EE_Error
1076
+	 * @throws InvalidArgumentException
1077
+	 * @throws InvalidDataTypeException
1078
+	 * @throws InvalidInterfaceException
1079
+	 * @throws ReflectionException
1080
+	 */
1081
+	public function edit_attendee_information_url()
1082
+	{
1083
+		return add_query_arg(
1084
+			(array) apply_filters(
1085
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
1086
+				[
1087
+					'e_reg_url_link' => $this->reg_url_link(),
1088
+					'step'           => 'attendee_information',
1089
+					'revisit'        => true,
1090
+				],
1091
+				$this
1092
+			),
1093
+			EE_Registry::instance()->CFG->core->reg_page_url()
1094
+		);
1095
+	}
1096
+
1097
+
1098
+	/**
1099
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
1100
+	 *
1101
+	 * @return string
1102
+	 * @throws EE_Error
1103
+	 * @throws InvalidArgumentException
1104
+	 * @throws InvalidDataTypeException
1105
+	 * @throws InvalidInterfaceException
1106
+	 * @throws ReflectionException
1107
+	 */
1108
+	public function get_admin_edit_url()
1109
+	{
1110
+		return EEH_URL::add_query_args_and_nonce(
1111
+			[
1112
+				'page'    => 'espresso_registrations',
1113
+				'action'  => 'view_registration',
1114
+				'_REG_ID' => $this->ID(),
1115
+			],
1116
+			admin_url('admin.php')
1117
+		);
1118
+	}
1119
+
1120
+
1121
+	/**
1122
+	 * is_primary_registrant?
1123
+	 *
1124
+	 * @throws EE_Error
1125
+	 * @throws InvalidArgumentException
1126
+	 * @throws InvalidDataTypeException
1127
+	 * @throws InvalidInterfaceException
1128
+	 * @throws ReflectionException
1129
+	 */
1130
+	public function is_primary_registrant()
1131
+	{
1132
+		return (int) $this->get('REG_count') === 1;
1133
+	}
1134
+
1135
+
1136
+	/**
1137
+	 * This returns the primary registration object for this registration group (which may be this object).
1138
+	 *
1139
+	 * @return EE_Registration
1140
+	 * @throws EE_Error
1141
+	 * @throws InvalidArgumentException
1142
+	 * @throws InvalidDataTypeException
1143
+	 * @throws InvalidInterfaceException
1144
+	 * @throws ReflectionException
1145
+	 */
1146
+	public function get_primary_registration()
1147
+	{
1148
+		if ($this->is_primary_registrant()) {
1149
+			return $this;
1150
+		}
1151
+
1152
+		// k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1153
+		/** @var EE_Registration $primary_registrant */
1154
+		$primary_registrant = EEM_Registration::instance()->get_one(
1155
+			[
1156
+				[
1157
+					'TXN_ID'    => $this->transaction_ID(),
1158
+					'REG_count' => 1,
1159
+				],
1160
+			]
1161
+		);
1162
+		return $primary_registrant;
1163
+	}
1164
+
1165
+
1166
+	/**
1167
+	 * get  Attendee Number
1168
+	 *
1169
+	 * @throws EE_Error
1170
+	 * @throws InvalidArgumentException
1171
+	 * @throws InvalidDataTypeException
1172
+	 * @throws InvalidInterfaceException
1173
+	 * @throws ReflectionException
1174
+	 */
1175
+	public function count()
1176
+	{
1177
+		return $this->get('REG_count');
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * get Group Size
1183
+	 *
1184
+	 * @throws EE_Error
1185
+	 * @throws InvalidArgumentException
1186
+	 * @throws InvalidDataTypeException
1187
+	 * @throws InvalidInterfaceException
1188
+	 * @throws ReflectionException
1189
+	 */
1190
+	public function group_size()
1191
+	{
1192
+		return $this->get('REG_group_size');
1193
+	}
1194
+
1195
+
1196
+	/**
1197
+	 * get Registration Date
1198
+	 *
1199
+	 * @throws EE_Error
1200
+	 * @throws InvalidArgumentException
1201
+	 * @throws InvalidDataTypeException
1202
+	 * @throws InvalidInterfaceException
1203
+	 * @throws ReflectionException
1204
+	 */
1205
+	public function date()
1206
+	{
1207
+		return $this->get('REG_date');
1208
+	}
1209
+
1210
+
1211
+	/**
1212
+	 * gets a pretty date
1213
+	 *
1214
+	 * @param string $date_format
1215
+	 * @param string $time_format
1216
+	 * @return string
1217
+	 * @throws EE_Error
1218
+	 * @throws InvalidArgumentException
1219
+	 * @throws InvalidDataTypeException
1220
+	 * @throws InvalidInterfaceException
1221
+	 * @throws ReflectionException
1222
+	 */
1223
+	public function pretty_date($date_format = null, $time_format = null)
1224
+	{
1225
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * final_price
1231
+	 * the registration's share of the transaction total, so that the
1232
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1233
+	 *
1234
+	 * @return float
1235
+	 * @throws EE_Error
1236
+	 * @throws InvalidArgumentException
1237
+	 * @throws InvalidDataTypeException
1238
+	 * @throws InvalidInterfaceException
1239
+	 * @throws ReflectionException
1240
+	 */
1241
+	public function final_price(): float
1242
+	{
1243
+		return (float) $this->get('REG_final_price');
1244
+	}
1245
+
1246
+
1247
+	/**
1248
+	 * pretty_final_price
1249
+	 *  final price as formatted string, with correct decimal places and currency symbol
1250
+	 *
1251
+	 * @param string|null $schema
1252
+	 *      Schemas:
1253
+	 *      'localized_float': "3,023.00"
1254
+	 *      'no_currency_code': "$3,023.00"
1255
+	 *      null: "$3,023.00<span>USD</span>"
1256
+	 * @return string
1257
+	 * @throws EE_Error
1258
+	 * @throws InvalidArgumentException
1259
+	 * @throws InvalidDataTypeException
1260
+	 * @throws InvalidInterfaceException
1261
+	 * @throws ReflectionException
1262
+	 */
1263
+	public function pretty_final_price(?string $schema = null)
1264
+	{
1265
+		return $this->get_pretty('REG_final_price', $schema);
1266
+	}
1267
+
1268
+
1269
+	/**
1270
+	 * get paid (yeah)
1271
+	 *
1272
+	 * @return float
1273
+	 * @throws EE_Error
1274
+	 * @throws InvalidArgumentException
1275
+	 * @throws InvalidDataTypeException
1276
+	 * @throws InvalidInterfaceException
1277
+	 * @throws ReflectionException
1278
+	 */
1279
+	public function paid(): float
1280
+	{
1281
+		return (float) $this->get('REG_paid');
1282
+	}
1283
+
1284
+
1285
+	/**
1286
+	 * pretty_paid
1287
+	 *
1288
+	 * @param string|null $schema
1289
+	 *      Schemas:
1290
+	 *      'localized_float': "3,023.00"
1291
+	 *      'no_currency_code': "$3,023.00"
1292
+	 *      null: "$3,023.00<span>USD</span>"
1293
+	 * @return float
1294
+	 * @throws EE_Error
1295
+	 * @throws InvalidArgumentException
1296
+	 * @throws InvalidDataTypeException
1297
+	 * @throws InvalidInterfaceException
1298
+	 * @throws ReflectionException
1299
+	 */
1300
+	public function pretty_paid(?string $schema = null)
1301
+	{
1302
+		return $this->get_pretty('REG_paid', $schema);
1303
+	}
1304
+
1305
+
1306
+	/**
1307
+	 * owes_monies_and_can_pay
1308
+	 * whether this registration has monies owing and it's' status allows payment
1309
+	 *
1310
+	 * @param array $requires_payment list of registration statuses that allow a registrant to make a payment
1311
+	 * @return bool
1312
+	 * @throws EE_Error
1313
+	 * @throws InvalidArgumentException
1314
+	 * @throws InvalidDataTypeException
1315
+	 * @throws InvalidInterfaceException
1316
+	 * @throws ReflectionException
1317
+	 */
1318
+	public function owes_monies_and_can_pay(array $requires_payment = []): bool
1319
+	{
1320
+		// these reg statuses require payment (if event is not free)
1321
+		$requires_payment = ! empty($requires_payment)
1322
+			? $requires_payment
1323
+			: EEM_Registration::reg_statuses_that_allow_payment();
1324
+		if (
1325
+			$this->final_price() !== 0.0 &&
1326
+			$this->final_price() !== $this->paid() &&
1327
+			in_array($this->status_ID(), $requires_payment)
1328
+		) {
1329
+			return true;
1330
+		}
1331
+		return false;
1332
+	}
1333
+
1334
+
1335
+	/**
1336
+	 * Prints out the return value of $this->pretty_status()
1337
+	 *
1338
+	 * @param bool $show_icons
1339
+	 * @return void
1340
+	 * @throws EE_Error
1341
+	 * @throws InvalidArgumentException
1342
+	 * @throws InvalidDataTypeException
1343
+	 * @throws InvalidInterfaceException
1344
+	 * @throws ReflectionException
1345
+	 */
1346
+	public function e_pretty_status($show_icons = false)
1347
+	{
1348
+		echo wp_kses($this->pretty_status($show_icons), AllowedTags::getAllowedTags());
1349
+	}
1350
+
1351
+
1352
+	/**
1353
+	 * Returns a nice version of the status for displaying to customers
1354
+	 *
1355
+	 * @param bool $show_icons
1356
+	 * @return string
1357
+	 * @throws EE_Error
1358
+	 * @throws InvalidArgumentException
1359
+	 * @throws InvalidDataTypeException
1360
+	 * @throws InvalidInterfaceException
1361
+	 * @throws ReflectionException
1362
+	 */
1363
+	public function pretty_status($show_icons = false)
1364
+	{
1365
+		$status = EEM_Status::instance()->localized_status(
1366
+			[$this->status_ID() => esc_html__('unknown', 'event_espresso')],
1367
+			false,
1368
+			'sentence'
1369
+		);
1370
+		$icon   = '';
1371
+		switch ($this->status_ID()) {
1372
+			case RegStatus::APPROVED:
1373
+				$icon = $show_icons
1374
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1375
+					: '';
1376
+				break;
1377
+			case RegStatus::PENDING_PAYMENT:
1378
+				$icon = $show_icons
1379
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1380
+					: '';
1381
+				break;
1382
+			case RegStatus::AWAITING_REVIEW:
1383
+				$icon = $show_icons
1384
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1385
+					: '';
1386
+				break;
1387
+			case RegStatus::CANCELLED:
1388
+				$icon = $show_icons
1389
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1390
+					: '';
1391
+				break;
1392
+			case RegStatus::INCOMPLETE:
1393
+				$icon = $show_icons
1394
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1395
+					: '';
1396
+				break;
1397
+			case RegStatus::DECLINED:
1398
+				$icon = $show_icons
1399
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1400
+					: '';
1401
+				break;
1402
+			case RegStatus::WAIT_LIST:
1403
+				$icon = $show_icons
1404
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1405
+					: '';
1406
+				break;
1407
+		}
1408
+		return $icon . $status[ $this->status_ID() ];
1409
+	}
1410
+
1411
+
1412
+	/**
1413
+	 *        get Attendee Is Going
1414
+	 */
1415
+	public function att_is_going()
1416
+	{
1417
+		return $this->get('REG_att_is_going');
1418
+	}
1419
+
1420
+
1421
+	/**
1422
+	 * Gets related answers
1423
+	 *
1424
+	 * @param array $query_params @see
1425
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1426
+	 * @return EE_Answer[]|EE_Base_Class[]
1427
+	 * @throws EE_Error
1428
+	 * @throws InvalidArgumentException
1429
+	 * @throws InvalidDataTypeException
1430
+	 * @throws InvalidInterfaceException
1431
+	 * @throws ReflectionException
1432
+	 */
1433
+	public function answers($query_params = [])
1434
+	{
1435
+		return $this->get_many_related('Answer', $query_params);
1436
+	}
1437
+
1438
+
1439
+	/**
1440
+	 * Gets the registration's answer value to the specified question
1441
+	 * (either the question's ID or a question object)
1442
+	 *
1443
+	 * @param EE_Question|int $question
1444
+	 * @param bool            $pretty_value
1445
+	 * @return array|string if pretty_value= true, the result will always be a string
1446
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1447
+	 * will convert it into some kind of string)
1448
+	 * @throws EE_Error
1449
+	 * @throws InvalidArgumentException
1450
+	 * @throws InvalidDataTypeException
1451
+	 * @throws InvalidInterfaceException
1452
+	 */
1453
+	public function answer_value_to_question($question, $pretty_value = true)
1454
+	{
1455
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1456
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1457
+	}
1458
+
1459
+
1460
+	/**
1461
+	 * question_groups
1462
+	 * returns an array of EE_Question_Group objects for this registration
1463
+	 *
1464
+	 * @return EE_Question_Group[]
1465
+	 * @throws EE_Error
1466
+	 * @throws InvalidArgumentException
1467
+	 * @throws InvalidDataTypeException
1468
+	 * @throws InvalidInterfaceException
1469
+	 * @throws ReflectionException
1470
+	 */
1471
+	public function question_groups()
1472
+	{
1473
+		return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1474
+	}
1475
+
1476
+
1477
+	/**
1478
+	 * count_question_groups
1479
+	 * returns a count of the number of EE_Question_Group objects for this registration
1480
+	 *
1481
+	 * @return int
1482
+	 * @throws EE_Error
1483
+	 * @throws EntityNotFoundException
1484
+	 * @throws InvalidArgumentException
1485
+	 * @throws InvalidDataTypeException
1486
+	 * @throws InvalidInterfaceException
1487
+	 * @throws ReflectionException
1488
+	 */
1489
+	public function count_question_groups()
1490
+	{
1491
+		return EEM_Event::instance()->count_related(
1492
+			$this->event_ID(),
1493
+			'Question_Group',
1494
+			[
1495
+				[
1496
+					'Event_Question_Group.'
1497
+					. EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1498
+				],
1499
+			]
1500
+		);
1501
+	}
1502
+
1503
+
1504
+	/**
1505
+	 * Returns the registration date in the 'standard' string format
1506
+	 * (function may be improved in the future to allow for different formats and timezones)
1507
+	 *
1508
+	 * @return string
1509
+	 * @throws EE_Error
1510
+	 * @throws InvalidArgumentException
1511
+	 * @throws InvalidDataTypeException
1512
+	 * @throws InvalidInterfaceException
1513
+	 * @throws ReflectionException
1514
+	 */
1515
+	public function reg_date()
1516
+	{
1517
+		return $this->get_datetime('REG_date');
1518
+	}
1519
+
1520
+
1521
+	/**
1522
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1523
+	 * the ticket this registration purchased, or the datetime they have registered
1524
+	 * to attend)
1525
+	 *
1526
+	 * @return EE_Base_Class|EE_Datetime_Ticket
1527
+	 * @throws EE_Error
1528
+	 * @throws InvalidArgumentException
1529
+	 * @throws InvalidDataTypeException
1530
+	 * @throws InvalidInterfaceException
1531
+	 * @throws ReflectionException
1532
+	 */
1533
+	public function datetime_ticket()
1534
+	{
1535
+		return $this->get_first_related('Datetime_Ticket');
1536
+	}
1537
+
1538
+
1539
+	/**
1540
+	 * Sets the registration's datetime_ticket.
1541
+	 *
1542
+	 * @param EE_Datetime_Ticket $datetime_ticket
1543
+	 * @return EE_Base_Class|EE_Datetime_Ticket
1544
+	 * @throws EE_Error
1545
+	 * @throws InvalidArgumentException
1546
+	 * @throws InvalidDataTypeException
1547
+	 * @throws InvalidInterfaceException
1548
+	 * @throws ReflectionException
1549
+	 */
1550
+	public function set_datetime_ticket($datetime_ticket)
1551
+	{
1552
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1553
+	}
1554
+
1555
+
1556
+	/**
1557
+	 * Gets deleted
1558
+	 *
1559
+	 * @return bool
1560
+	 * @throws EE_Error
1561
+	 * @throws InvalidArgumentException
1562
+	 * @throws InvalidDataTypeException
1563
+	 * @throws InvalidInterfaceException
1564
+	 * @throws ReflectionException
1565
+	 */
1566
+	public function deleted()
1567
+	{
1568
+		return $this->get('REG_deleted');
1569
+	}
1570
+
1571
+
1572
+	/**
1573
+	 * Sets deleted
1574
+	 *
1575
+	 * @param boolean $deleted
1576
+	 * @return void
1577
+	 * @throws DomainException
1578
+	 * @throws EE_Error
1579
+	 * @throws EntityNotFoundException
1580
+	 * @throws InvalidArgumentException
1581
+	 * @throws InvalidDataTypeException
1582
+	 * @throws InvalidInterfaceException
1583
+	 * @throws ReflectionException
1584
+	 * @throws RuntimeException
1585
+	 * @throws UnexpectedEntityException
1586
+	 */
1587
+	public function set_deleted($deleted)
1588
+	{
1589
+		if ($deleted) {
1590
+			$this->delete();
1591
+		} else {
1592
+			$this->restore();
1593
+		}
1594
+	}
1595
+
1596
+
1597
+	/**
1598
+	 * Get the status object of this object
1599
+	 *
1600
+	 * @return EE_Base_Class|EE_Status
1601
+	 * @throws EE_Error
1602
+	 * @throws InvalidArgumentException
1603
+	 * @throws InvalidDataTypeException
1604
+	 * @throws InvalidInterfaceException
1605
+	 * @throws ReflectionException
1606
+	 */
1607
+	public function status_obj()
1608
+	{
1609
+		return $this->get_first_related('Status');
1610
+	}
1611
+
1612
+
1613
+	/**
1614
+	 * Returns the number of times this registration has checked into any of the datetimes it's available for
1615
+	 *
1616
+	 * @return int
1617
+	 * @throws EE_Error
1618
+	 * @throws InvalidArgumentException
1619
+	 * @throws InvalidDataTypeException
1620
+	 * @throws InvalidInterfaceException
1621
+	 * @throws ReflectionException
1622
+	 */
1623
+	public function count_checkins()
1624
+	{
1625
+		return $this->get_model()->count_related($this, 'Checkin');
1626
+	}
1627
+
1628
+
1629
+	/**
1630
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1631
+	 * registration is for.  Note, this is ONLY checked in (does not include checked out)
1632
+	 *
1633
+	 * @return int
1634
+	 * @throws EE_Error
1635
+	 * @throws InvalidArgumentException
1636
+	 * @throws InvalidDataTypeException
1637
+	 * @throws InvalidInterfaceException
1638
+	 * @throws ReflectionException
1639
+	 */
1640
+	public function count_checkins_not_checkedout()
1641
+	{
1642
+		return $this->get_model()->count_related($this, 'Checkin', [['CHK_in' => 1]]);
1643
+	}
1644
+
1645
+
1646
+	/**
1647
+	 * The purpose of this method is simply to check whether this registration can check in to the given datetime.
1648
+	 *
1649
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1650
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1651
+	 *                                          consider registration status as well as datetime access.
1652
+	 * @return bool
1653
+	 * @throws EE_Error
1654
+	 * @throws InvalidArgumentException
1655
+	 * @throws InvalidDataTypeException
1656
+	 * @throws InvalidInterfaceException
1657
+	 * @throws ReflectionException
1658
+	 */
1659
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1660
+	{
1661
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1662
+		// first check registration status
1663
+		if (! $DTT_ID || ($check_approved && ! $this->is_approved())) {
1664
+			return false;
1665
+		}
1666
+		// is there a datetime ticket that matches this dtt_ID?
1667
+		if (
1668
+			! (EEM_Datetime_Ticket::instance()->exists(
1669
+				[
1670
+					[
1671
+						'TKT_ID' => $this->get('TKT_ID'),
1672
+						'DTT_ID' => $DTT_ID,
1673
+					],
1674
+				]
1675
+			))
1676
+		) {
1677
+			return false;
1678
+		}
1679
+
1680
+		// final check is against TKT_uses
1681
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1682
+	}
1683
+
1684
+
1685
+	/**
1686
+	 * This method verifies whether the user can check in for the given datetime considering the max uses value set on
1687
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1688
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1689
+	 * then return false.  Otherwise return true.
1690
+	 *
1691
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1692
+	 * @return bool true means can check in.  false means cannot check in.
1693
+	 * @throws EE_Error
1694
+	 * @throws InvalidArgumentException
1695
+	 * @throws InvalidDataTypeException
1696
+	 * @throws InvalidInterfaceException
1697
+	 * @throws ReflectionException
1698
+	 */
1699
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1700
+	{
1701
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1702
+
1703
+		if (! $DTT_ID) {
1704
+			return false;
1705
+		}
1706
+
1707
+		$max_uses = $this->ticket() instanceof EE_Ticket
1708
+			? $this->ticket()->uses()
1709
+			: EE_INF;
1710
+
1711
+		// if max uses is not set or equals infinity then return true
1712
+		// because it's not a factor for whether user can check in or not.
1713
+		if (! $max_uses || $max_uses === EE_INF) {
1714
+			return true;
1715
+		}
1716
+
1717
+		// does this datetime have a check-in record?  If so, then the dtt count has already been verified so we can just
1718
+		// go ahead and toggle.
1719
+		if (EEM_Checkin::instance()->exists([['REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID]])) {
1720
+			return true;
1721
+		}
1722
+
1723
+		// made it here so the last check is whether the number of check-ins per unique datetime on this registration
1724
+		// disallows further check-ins.
1725
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1726
+			[
1727
+				[
1728
+					'REG_ID' => $this->ID(),
1729
+					'CHK_in' => true,
1730
+				],
1731
+			],
1732
+			'DTT_ID',
1733
+			true
1734
+		);
1735
+		// check-ins have already reached their max number of uses
1736
+		// so registrant can NOT check in
1737
+		if ($count_unique_dtt_checkins >= $max_uses) {
1738
+			EE_Error::add_error(
1739
+				esc_html__(
1740
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1741
+					'event_espresso'
1742
+				),
1743
+				__FILE__,
1744
+				__FUNCTION__,
1745
+				__LINE__
1746
+			);
1747
+			return false;
1748
+		}
1749
+		return true;
1750
+	}
1751
+
1752
+
1753
+	/**
1754
+	 * toggle Check-in status for this registration
1755
+	 * Check-ins are toggled in the following order:
1756
+	 * never checked in -> checked in
1757
+	 * checked in -> checked out
1758
+	 * checked out -> checked in
1759
+	 *
1760
+	 * @param int  $DTT_ID  include specific datetime to toggle Check-in for.
1761
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1762
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1763
+	 *                      can be checked in or not.  Otherwise this forces change in check-in status.
1764
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1765
+	 * @throws EE_Error
1766
+	 * @throws InvalidArgumentException
1767
+	 * @throws InvalidDataTypeException
1768
+	 * @throws InvalidInterfaceException
1769
+	 * @throws ReflectionException
1770
+	 */
1771
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1772
+	{
1773
+		if (empty($DTT_ID)) {
1774
+			$datetime = $this->get_latest_related_datetime();
1775
+			$DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1776
+			// verify the registration can check in for the given DTT_ID
1777
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1778
+			EE_Error::add_error(
1779
+				sprintf(
1780
+					esc_html__(
1781
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1782
+						'event_espresso'
1783
+					),
1784
+					$this->ID(),
1785
+					$DTT_ID
1786
+				),
1787
+				__FILE__,
1788
+				__FUNCTION__,
1789
+				__LINE__
1790
+			);
1791
+			return false;
1792
+		}
1793
+		$status_paths = [
1794
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1795
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1796
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1797
+		];
1798
+		// start by getting the current status so we know what status we'll be changing to.
1799
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1800
+		$status_to  = $status_paths[ $cur_status ];
1801
+		// database only records true for checked IN or false for checked OUT
1802
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1803
+		$new_status = $status_to === EE_Checkin::status_checked_in;
1804
+		// add relation - note Check-ins are always creating new rows
1805
+		// because we are keeping track of Check-ins over time.
1806
+		// Eventually we'll probably want to show a list table
1807
+		// for the individual Check-ins so that they can be managed.
1808
+		$checkin = EE_Checkin::new_instance(
1809
+			[
1810
+				'REG_ID' => $this->ID(),
1811
+				'DTT_ID' => $DTT_ID,
1812
+				'CHK_in' => $new_status,
1813
+			]
1814
+		);
1815
+		// if the record could not be saved then return false
1816
+		if ($checkin->save() === 0) {
1817
+			if (WP_DEBUG) {
1818
+				global $wpdb;
1819
+				$error = sprintf(
1820
+					esc_html__(
1821
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1822
+						'event_espresso'
1823
+					),
1824
+					'<br />',
1825
+					$wpdb->last_error
1826
+				);
1827
+			} else {
1828
+				$error = esc_html__(
1829
+					'Registration check in update failed because of an unknown database error',
1830
+					'event_espresso'
1831
+				);
1832
+			}
1833
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1834
+			return false;
1835
+		}
1836
+		// Fire a checked_in and checkout_out action.
1837
+		$checked_status = $status_to === EE_Checkin::status_checked_in
1838
+			? 'checked_in'
1839
+			: 'checked_out';
1840
+		do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1841
+		return $status_to;
1842
+	}
1843
+
1844
+
1845
+	/**
1846
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1847
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1848
+	 *
1849
+	 * @return EE_Datetime|null
1850
+	 * @throws EE_Error
1851
+	 * @throws InvalidArgumentException
1852
+	 * @throws InvalidDataTypeException
1853
+	 * @throws InvalidInterfaceException
1854
+	 * @throws ReflectionException
1855
+	 */
1856
+	public function get_latest_related_datetime(): ?EE_Datetime
1857
+	{
1858
+		return EEM_Datetime::instance()->get_one(
1859
+			[
1860
+				[
1861
+					'Ticket.Registration.REG_ID' => $this->ID(),
1862
+				],
1863
+				'order_by' => ['DTT_EVT_start' => 'DESC'],
1864
+			]
1865
+		);
1866
+	}
1867
+
1868
+
1869
+	/**
1870
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1871
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1872
+	 *
1873
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1874
+	 * @throws EE_Error
1875
+	 * @throws InvalidArgumentException
1876
+	 * @throws InvalidDataTypeException
1877
+	 * @throws InvalidInterfaceException
1878
+	 * @throws ReflectionException
1879
+	 */
1880
+	public function get_earliest_related_datetime()
1881
+	{
1882
+		return EEM_Datetime::instance()->get_one(
1883
+			[
1884
+				[
1885
+					'Ticket.Registration.REG_ID' => $this->ID(),
1886
+				],
1887
+				'order_by' => ['DTT_EVT_start' => 'ASC'],
1888
+			]
1889
+		);
1890
+	}
1891
+
1892
+
1893
+	/**
1894
+	 * This method simply returns the check-in status for this registration and the given datetime.
1895
+	 * If neither the datetime nor the check-in values are provided as arguments,
1896
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1897
+	 *
1898
+	 * @param int|null        $DTT_ID  The ID of the datetime we're checking against
1899
+	 *                                 (if empty we'll get the primary datetime for
1900
+	 *                                 this registration (via event) and use its ID);
1901
+	 * @param EE_Checkin|null $checkin If present, we use the given check-in object rather than the dtt_id.
1902
+	 * @return int                     Integer representing Check-in status.
1903
+	 * @throws EE_Error
1904
+	 * @throws ReflectionException
1905
+	 */
1906
+	public function check_in_status_for_datetime(?int $DTT_ID = 0, ?EE_Checkin $checkin = null): int
1907
+	{
1908
+		if ($checkin instanceof EE_Checkin) {
1909
+			return $checkin->status();
1910
+		}
1911
+
1912
+		if (! $DTT_ID) {
1913
+			return EE_Checkin::status_invalid;
1914
+		}
1915
+
1916
+		$checkin_query_params = [
1917
+			0          => ['DTT_ID' => $DTT_ID],
1918
+			'order_by' => ['CHK_timestamp' => 'DESC'],
1919
+		];
1920
+
1921
+		$checkin = $this->get_first_related(
1922
+			'Checkin',
1923
+			$checkin_query_params
1924
+		);
1925
+		return $checkin instanceof EE_Checkin ? $checkin->status() : EE_Checkin::status_checked_never;
1926
+	}
1927
+
1928
+
1929
+	/**
1930
+	 * This method returns a localized message for the toggled Check-in message.
1931
+	 *
1932
+	 * @param int|null $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1933
+	 *                         then it is assumed Check-in for primary datetime was toggled.
1934
+	 * @param bool     $error  This just flags that you want an error message returned. This is put in so that the error
1935
+	 *                         message can be customized with the attendee name.
1936
+	 * @return string internationalized message
1937
+	 * @throws EE_Error
1938
+	 * @throws ReflectionException
1939
+	 */
1940
+	public function get_checkin_msg(?int $DTT_ID, bool $error = false): string
1941
+	{
1942
+		// let's get the attendee first so we can include the name of the attendee
1943
+		$attendee = $this->attendee();
1944
+		if ($attendee instanceof EE_Attendee) {
1945
+			if ($error) {
1946
+				return sprintf(
1947
+					esc_html__("%s's check-in status was not changed.", "event_espresso"),
1948
+					$attendee->full_name()
1949
+				);
1950
+			}
1951
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1952
+			// what is the status message going to be?
1953
+			switch ($cur_status) {
1954
+				case EE_Checkin::status_checked_never:
1955
+					return sprintf(
1956
+						esc_html__('%s has been removed from Check-in records', 'event_espresso'),
1957
+						$attendee->full_name()
1958
+					);
1959
+				case EE_Checkin::status_checked_in:
1960
+					return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1961
+				case EE_Checkin::status_checked_out:
1962
+					return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1963
+			}
1964
+		}
1965
+		return esc_html__('The check-in status could not be determined.', 'event_espresso');
1966
+	}
1967
+
1968
+
1969
+	/**
1970
+	 * Returns the related EE_Transaction to this registration
1971
+	 *
1972
+	 * @return EE_Transaction
1973
+	 * @throws EE_Error
1974
+	 * @throws EntityNotFoundException
1975
+	 * @throws ReflectionException
1976
+	 */
1977
+	public function transaction(): EE_Transaction
1978
+	{
1979
+		$TXN_ID = $this->transaction_ID();
1980
+		$transaction = $TXN_ID
1981
+			? EEM_Transaction::instance()->get_one_by_ID($TXN_ID)
1982
+			: $this->get_one_from_cache('Transaction');
1983
+		if (! $transaction instanceof \EE_Transaction) {
1984
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1985
+		}
1986
+		return $transaction;
1987
+	}
1988
+
1989
+
1990
+	/**
1991
+	 * get Registration Code
1992
+	 *
1993
+	 * @return string
1994
+	 * @throws EE_Error
1995
+	 * @throws InvalidArgumentException
1996
+	 * @throws InvalidDataTypeException
1997
+	 * @throws InvalidInterfaceException
1998
+	 * @throws ReflectionException
1999
+	 */
2000
+	public function reg_code(): string
2001
+	{
2002
+		return $this->get('REG_code')
2003
+			?: '';
2004
+	}
2005
+
2006
+
2007
+	/**
2008
+	 * @return mixed
2009
+	 * @throws EE_Error
2010
+	 * @throws InvalidArgumentException
2011
+	 * @throws InvalidDataTypeException
2012
+	 * @throws InvalidInterfaceException
2013
+	 * @throws ReflectionException
2014
+	 */
2015
+	public function transaction_ID()
2016
+	{
2017
+		return $this->get('TXN_ID');
2018
+	}
2019
+
2020
+
2021
+	/**
2022
+	 * @return int
2023
+	 * @throws EE_Error
2024
+	 * @throws InvalidArgumentException
2025
+	 * @throws InvalidDataTypeException
2026
+	 * @throws InvalidInterfaceException
2027
+	 * @throws ReflectionException
2028
+	 */
2029
+	public function ticket_ID()
2030
+	{
2031
+		return $this->get('TKT_ID');
2032
+	}
2033
+
2034
+
2035
+	/**
2036
+	 * Set Registration Code
2037
+	 *
2038
+	 * @param RegCode|string $REG_code Registration Code
2039
+	 * @param boolean        $use_default
2040
+	 * @throws EE_Error
2041
+	 * @throws InvalidArgumentException
2042
+	 * @throws InvalidDataTypeException
2043
+	 * @throws InvalidInterfaceException
2044
+	 * @throws ReflectionException
2045
+	 */
2046
+	public function set_reg_code($REG_code, bool $use_default = false)
2047
+	{
2048
+		if (! $this->reg_code()) {
2049
+			parent::set('REG_code', $REG_code, $use_default);
2050
+		} elseif (empty($REG_code)) {
2051
+			EE_Error::add_error(
2052
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
2053
+				__FILE__,
2054
+				__FUNCTION__,
2055
+				__LINE__
2056
+			);
2057
+		} else {
2058
+			EE_Error::doing_it_wrong(
2059
+				__CLASS__ . '::' . __FUNCTION__,
2060
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
2061
+				'4.6.0'
2062
+			);
2063
+		}
2064
+	}
2065
+
2066
+
2067
+	/**
2068
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
2069
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
2070
+	 *    $registration->transaction()->registrations();
2071
+	 *
2072
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
2073
+	 * @throws EE_Error
2074
+	 * @throws InvalidArgumentException
2075
+	 * @throws InvalidDataTypeException
2076
+	 * @throws InvalidInterfaceException
2077
+	 * @throws ReflectionException
2078
+	 * @since 4.5.0
2079
+	 */
2080
+	public function get_all_other_registrations_in_group()
2081
+	{
2082
+		if ($this->group_size() < 2) {
2083
+			return [];
2084
+		}
2085
+
2086
+		$query[0] = [
2087
+			'TXN_ID' => $this->transaction_ID(),
2088
+			'REG_ID' => ['!=', $this->ID()],
2089
+			'TKT_ID' => $this->ticket_ID(),
2090
+		];
2091
+		/** @var EE_Registration[] $registrations */
2092
+		$registrations = $this->get_model()->get_all($query);
2093
+		return $registrations;
2094
+	}
2095
+
2096
+
2097
+	/**
2098
+	 * Return the link to the admin details for the object.
2099
+	 *
2100
+	 * @return string
2101
+	 * @throws EE_Error
2102
+	 * @throws InvalidArgumentException
2103
+	 * @throws InvalidDataTypeException
2104
+	 * @throws InvalidInterfaceException
2105
+	 * @throws ReflectionException
2106
+	 */
2107
+	public function get_admin_details_link()
2108
+	{
2109
+		EE_Registry::instance()->load_helper('URL');
2110
+		return EEH_URL::add_query_args_and_nonce(
2111
+			[
2112
+				'page'    => 'espresso_registrations',
2113
+				'action'  => 'view_registration',
2114
+				'_REG_ID' => $this->ID(),
2115
+			],
2116
+			admin_url('admin.php')
2117
+		);
2118
+	}
2119
+
2120
+
2121
+	/**
2122
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
2123
+	 *
2124
+	 * @return string
2125
+	 * @throws EE_Error
2126
+	 * @throws InvalidArgumentException
2127
+	 * @throws InvalidDataTypeException
2128
+	 * @throws InvalidInterfaceException
2129
+	 * @throws ReflectionException
2130
+	 */
2131
+	public function get_admin_edit_link()
2132
+	{
2133
+		return $this->get_admin_details_link();
2134
+	}
2135
+
2136
+
2137
+	/**
2138
+	 * Returns the link to a settings page for the object.
2139
+	 *
2140
+	 * @return string
2141
+	 * @throws EE_Error
2142
+	 * @throws InvalidArgumentException
2143
+	 * @throws InvalidDataTypeException
2144
+	 * @throws InvalidInterfaceException
2145
+	 * @throws ReflectionException
2146
+	 */
2147
+	public function get_admin_settings_link()
2148
+	{
2149
+		return $this->get_admin_details_link();
2150
+	}
2151
+
2152
+
2153
+	/**
2154
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
2155
+	 *
2156
+	 * @return string
2157
+	 * @throws EE_Error
2158
+	 * @throws InvalidArgumentException
2159
+	 * @throws InvalidDataTypeException
2160
+	 * @throws InvalidInterfaceException
2161
+	 * @throws ReflectionException
2162
+	 */
2163
+	public function get_admin_overview_link()
2164
+	{
2165
+		EE_Registry::instance()->load_helper('URL');
2166
+		return EEH_URL::add_query_args_and_nonce(
2167
+			[
2168
+				'page' => 'espresso_registrations',
2169
+			],
2170
+			admin_url('admin.php')
2171
+		);
2172
+	}
2173
+
2174
+
2175
+	/**
2176
+	 * @param array $query_params
2177
+	 * @return EE_Base_Class[]|EE_Registration[]
2178
+	 * @throws EE_Error
2179
+	 * @throws InvalidArgumentException
2180
+	 * @throws InvalidDataTypeException
2181
+	 * @throws InvalidInterfaceException
2182
+	 * @throws ReflectionException
2183
+	 */
2184
+	public function payments($query_params = [])
2185
+	{
2186
+		return $this->get_many_related('Payment', $query_params);
2187
+	}
2188
+
2189
+
2190
+	/**
2191
+	 * @param array $query_params
2192
+	 * @return EE_Base_Class[]|EE_Registration_Payment[]
2193
+	 * @throws EE_Error
2194
+	 * @throws InvalidArgumentException
2195
+	 * @throws InvalidDataTypeException
2196
+	 * @throws InvalidInterfaceException
2197
+	 * @throws ReflectionException
2198
+	 */
2199
+	public function registration_payments($query_params = [])
2200
+	{
2201
+		return $this->get_many_related('Registration_Payment', $query_params);
2202
+	}
2203
+
2204
+
2205
+	/**
2206
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
2207
+	 * Note: if there are no payments on the registration there will be no payment method returned.
2208
+	 *
2209
+	 * @return EE_Payment|EE_Payment_Method|null
2210
+	 * @throws EE_Error
2211
+	 * @throws InvalidArgumentException
2212
+	 * @throws InvalidDataTypeException
2213
+	 * @throws InvalidInterfaceException
2214
+	 */
2215
+	public function payment_method()
2216
+	{
2217
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
2218
+	}
2219
+
2220
+
2221
+	/**
2222
+	 * @return \EE_Line_Item
2223
+	 * @throws EE_Error
2224
+	 * @throws EntityNotFoundException
2225
+	 * @throws InvalidArgumentException
2226
+	 * @throws InvalidDataTypeException
2227
+	 * @throws InvalidInterfaceException
2228
+	 * @throws ReflectionException
2229
+	 */
2230
+	public function ticket_line_item()
2231
+	{
2232
+		$ticket            = $this->ticket();
2233
+		$transaction       = $this->transaction();
2234
+		$line_item         = null;
2235
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
2236
+			$transaction->total_line_item(),
2237
+			'Ticket',
2238
+			[$ticket->ID()]
2239
+		);
2240
+		foreach ($ticket_line_items as $ticket_line_item) {
2241
+			if (
2242
+				$ticket_line_item instanceof \EE_Line_Item
2243
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
2244
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
2245
+			) {
2246
+				$line_item = $ticket_line_item;
2247
+				break;
2248
+			}
2249
+		}
2250
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
2251
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
2252
+		}
2253
+		return $line_item;
2254
+	}
2255
+
2256
+
2257
+	/**
2258
+	 * Soft Deletes this model object.
2259
+	 *
2260
+	 * @param string $source function name that called this method
2261
+	 * @return boolean | int
2262
+	 * @throws DomainException
2263
+	 * @throws EE_Error
2264
+	 * @throws EntityNotFoundException
2265
+	 * @throws InvalidArgumentException
2266
+	 * @throws InvalidDataTypeException
2267
+	 * @throws InvalidInterfaceException
2268
+	 * @throws ReflectionException
2269
+	 * @throws RuntimeException
2270
+	 * @throws UnexpectedEntityException
2271
+	 */
2272
+	public function delete()
2273
+	{
2274
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
2275
+			$this->set_status(
2276
+				RegStatus::CANCELLED,
2277
+				false,
2278
+				new Context(
2279
+					__METHOD__,
2280
+					esc_html__('Executed when a registration is trashed.', 'event_espresso')
2281
+				)
2282
+			);
2283
+		}
2284
+		return parent::delete();
2285
+	}
2286
+
2287
+
2288
+	/**
2289
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
2290
+	 *
2291
+	 * @param string $source function name that called this method
2292
+	 * @return bool|int
2293
+	 * @throws DomainException
2294
+	 * @throws EE_Error
2295
+	 * @throws EntityNotFoundException
2296
+	 * @throws InvalidArgumentException
2297
+	 * @throws InvalidDataTypeException
2298
+	 * @throws InvalidInterfaceException
2299
+	 * @throws ReflectionException
2300
+	 * @throws RuntimeException
2301
+	 * @throws UnexpectedEntityException
2302
+	 */
2303
+	public function restore()
2304
+	{
2305
+		$previous_status = $this->get_extra_meta(
2306
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
2307
+			true,
2308
+			RegStatus::CANCELLED
2309
+		);
2310
+		if ($previous_status) {
2311
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
2312
+			$this->set_status(
2313
+				$previous_status,
2314
+				false,
2315
+				new Context(
2316
+					__METHOD__,
2317
+					esc_html__('Executed when a trashed registration is restored.', 'event_espresso')
2318
+				)
2319
+			);
2320
+		}
2321
+		return parent::restore();
2322
+	}
2323
+
2324
+
2325
+	/**
2326
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
2327
+	 *
2328
+	 * @param boolean $trigger_set_status_logic  EE_Registration::set_status() can trigger additional logic
2329
+	 *                                           depending on whether the reg status changes to or from "Approved"
2330
+	 * @return boolean whether the Registration status was updated
2331
+	 * @throws DomainException
2332
+	 * @throws EE_Error
2333
+	 * @throws EntityNotFoundException
2334
+	 * @throws InvalidArgumentException
2335
+	 * @throws InvalidDataTypeException
2336
+	 * @throws InvalidInterfaceException
2337
+	 * @throws ReflectionException
2338
+	 * @throws RuntimeException
2339
+	 * @throws UnexpectedEntityException
2340
+	 */
2341
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2342
+	{
2343
+		$paid  = $this->paid();
2344
+		$price = $this->final_price();
2345
+		switch (true) {
2346
+			// overpaid or paid
2347
+			case EEH_Money::compare_floats($paid, $price, '>'):
2348
+			case EEH_Money::compare_floats($paid, $price):
2349
+				$new_status = RegStatus::APPROVED;
2350
+				break;
2351
+			//  underpaid
2352
+			case EEH_Money::compare_floats($paid, $price, '<'):
2353
+				$new_status = RegStatus::PENDING_PAYMENT;
2354
+				break;
2355
+			// uhhh Houston...
2356
+			default:
2357
+				throw new RuntimeException(
2358
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2359
+				);
2360
+		}
2361
+		if ($new_status !== $this->status_ID()) {
2362
+			if ($trigger_set_status_logic) {
2363
+				return $this->set_status(
2364
+					$new_status,
2365
+					false,
2366
+					new Context(
2367
+						__METHOD__,
2368
+						esc_html__(
2369
+							'Executed when the registration status is updated based on total paid.',
2370
+							'event_espresso'
2371
+						)
2372
+					)
2373
+				);
2374
+			}
2375
+			parent::set('STS_ID', $new_status);
2376
+			return true;
2377
+		}
2378
+		return false;
2379
+	}
2380
+
2381
+
2382
+	/*************************** DEPRECATED ***************************/
2383
+
2384
+
2385
+	/**
2386
+	 * @deprecated
2387
+	 * @since     4.7.0
2388
+	 */
2389
+	public function price_paid()
2390
+	{
2391
+		EE_Error::doing_it_wrong(
2392
+			'EE_Registration::price_paid()',
2393
+			esc_html__(
2394
+				'This method is deprecated, please use EE_Registration::final_price() instead.',
2395
+				'event_espresso'
2396
+			),
2397
+			'4.7.0'
2398
+		);
2399
+		return $this->final_price();
2400
+	}
2401
+
2402
+
2403
+	/**
2404
+	 * @param float $REG_final_price
2405
+	 * @throws EE_Error
2406
+	 * @throws EntityNotFoundException
2407
+	 * @throws InvalidArgumentException
2408
+	 * @throws InvalidDataTypeException
2409
+	 * @throws InvalidInterfaceException
2410
+	 * @throws ReflectionException
2411
+	 * @throws RuntimeException
2412
+	 * @throws DomainException
2413
+	 * @deprecated
2414
+	 * @since     4.7.0
2415
+	 */
2416
+	public function set_price_paid($REG_final_price = 0.00)
2417
+	{
2418
+		EE_Error::doing_it_wrong(
2419
+			'EE_Registration::set_price_paid()',
2420
+			esc_html__(
2421
+				'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2422
+				'event_espresso'
2423
+			),
2424
+			'4.7.0'
2425
+		);
2426
+		$this->set_final_price($REG_final_price);
2427
+	}
2428
+
2429
+
2430
+	/**
2431
+	 * @return string
2432
+	 * @throws EE_Error
2433
+	 * @throws InvalidArgumentException
2434
+	 * @throws InvalidDataTypeException
2435
+	 * @throws InvalidInterfaceException
2436
+	 * @throws ReflectionException
2437
+	 * @deprecated
2438
+	 * @since 4.7.0
2439
+	 */
2440
+	public function pretty_price_paid()
2441
+	{
2442
+		EE_Error::doing_it_wrong(
2443
+			'EE_Registration::pretty_price_paid()',
2444
+			esc_html__(
2445
+				'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2446
+				'event_espresso'
2447
+			),
2448
+			'4.7.0'
2449
+		);
2450
+		return $this->pretty_final_price();
2451
+	}
2452
+
2453
+
2454
+	/**
2455
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2456
+	 *
2457
+	 * @return EE_Datetime
2458
+	 * @throws EE_Error
2459
+	 * @throws EntityNotFoundException
2460
+	 * @throws InvalidArgumentException
2461
+	 * @throws InvalidDataTypeException
2462
+	 * @throws InvalidInterfaceException
2463
+	 * @throws ReflectionException
2464
+	 * @deprecated 4.9.17
2465
+	 */
2466
+	public function get_related_primary_datetime()
2467
+	{
2468
+		EE_Error::doing_it_wrong(
2469
+			__METHOD__,
2470
+			esc_html__(
2471
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2472
+				'event_espresso'
2473
+			),
2474
+			'4.9.17',
2475
+			'5.0.0'
2476
+		);
2477
+		return $this->event()->primary_datetime();
2478
+	}
2479
+
2480
+
2481
+	/**
2482
+	 * Returns the contact's name (or "Unknown" if there is no contact.)
2483
+	 *
2484
+	 * @return string
2485
+	 * @throws EE_Error
2486
+	 * @throws InvalidArgumentException
2487
+	 * @throws InvalidDataTypeException
2488
+	 * @throws InvalidInterfaceException
2489
+	 * @throws ReflectionException
2490
+	 * @since 4.10.12.p
2491
+	 */
2492
+	public function name()
2493
+	{
2494
+		return $this->attendeeName();
2495
+	}
2496
+
2497
+
2498
+	/**
2499
+	 * @return bool
2500
+	 * @throws EE_Error
2501
+	 * @throws ReflectionException
2502
+	 */
2503
+	public function wasMoved(): bool
2504
+	{
2505
+		// only need to check 'registration-moved-to' because
2506
+		// the existence of a new REG ID means the registration was moved
2507
+		$reg_moved = $this->get_extra_meta('registration-moved-to', true, []);
2508
+		return isset($reg_moved['NEW_REG_ID']) && $reg_moved['NEW_REG_ID'];
2509
+	}
2510
+
2511
+
2512
+	/**
2513
+	 * @param EE_Payment $payment
2514
+	 * @param float|null $amount
2515
+	 * @return float
2516
+	 * @throws EE_Error
2517
+	 * @throws ReflectionException
2518
+	 * @since 5.0.8.p
2519
+	 */
2520
+	public function applyPayment(EE_Payment $payment, ?float $amount = null): float
2521
+	{
2522
+		$payment_amount = $amount ?? $payment->amount();
2523
+		// ensure $payment_amount is NOT negative
2524
+		$payment_amount = (float) abs($payment_amount);
2525
+		$payment_amount = $payment->is_a_refund()
2526
+			? $this->processRefund($payment_amount)
2527
+			: $this->processPayment($payment_amount);
2528
+		if ($payment_amount) {
2529
+			$reg_payment = EEM_Registration_Payment::instance()->get_one(
2530
+				[['REG_ID' => $this->ID(), 'PAY_ID' => $payment->ID()]]
2531
+			);
2532
+			// if existing registration payment exists
2533
+			if ($reg_payment instanceof EE_Registration_Payment) {
2534
+				// then update that record
2535
+				$reg_payment->set_amount($payment_amount);
2536
+			} else {
2537
+				// or add new relation between registration and payment and set amount
2538
+				$reg_payment = EE_Registration_Payment::new_instance(
2539
+					[
2540
+						'REG_ID'     => $this->ID(),
2541
+						'PAY_ID'     => $payment->ID(),
2542
+						'RPY_amount' => $payment_amount,
2543
+					]
2544
+				);
2545
+			}
2546
+			$reg_payment->save();
2547
+		}
2548
+		return $payment_amount;
2549
+	}
2550
+
2551
+
2552
+	/**
2553
+	 * @throws EE_Error
2554
+	 * @throws ReflectionException
2555
+	 */
2556
+	private function processPayment(float $payment_amount): float
2557
+	{
2558
+		$paid  = $this->paid();
2559
+		$owing = $this->final_price() - $paid;
2560
+		if ($owing <= 0) {
2561
+			return 0.0;
2562
+		}
2563
+		// don't allow payment amount to exceed the incoming amount, OR the amount owing
2564
+		$payment_amount = min($payment_amount, $owing);
2565
+		$paid           = $paid + $payment_amount;
2566
+		// calculate and set new REG_paid
2567
+		$this->set_paid($paid);
2568
+		// make it stick
2569
+		$this->save();
2570
+		return (float) $payment_amount;
2571
+	}
2572
+
2573
+
2574
+	/**
2575
+	 * @throws ReflectionException
2576
+	 * @throws EE_Error
2577
+	 */
2578
+	private function processRefund(float $payment_amount): float
2579
+	{
2580
+		$paid = $this->paid();
2581
+		if ($paid <= 0) {
2582
+			return 0.0;
2583
+		}
2584
+		// don't allow refund amount to exceed the incoming amount, OR the amount paid
2585
+		$payment_amount = min($payment_amount, $paid);
2586
+		// calculate and set new REG_paid
2587
+		$paid = $paid - $payment_amount;
2588
+		$this->set_paid($paid);
2589
+		// make it stick
2590
+		$this->save();
2591
+		// convert payment amount back to a negative value for storage in the db
2592
+		return (float) $payment_amount;
2593
+	}
2594
+
2595
+
2596
+	/**
2597
+	 * @return string
2598
+	 * @throws EE_Error
2599
+	 * @throws ReflectionException
2600
+	 * @since 5.0.20.p
2601
+	 */
2602
+	public function defaultRegistrationStatus(): string
2603
+	{
2604
+		$default_event_reg_status = $this->event()->default_registration_status();
2605
+		$default_reg_status = (string) apply_filters(
2606
+			'AFEE__EE_Registration__defaultRegistrationStatus__default_reg_status',
2607
+			$default_event_reg_status,
2608
+			$this
2609
+		);
2610
+		return RegStatus::isValidStatus($default_reg_status, false)
2611
+			? $default_reg_status
2612
+			: $default_event_reg_status;
2613
+	}
2614 2614
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
     {
138 138
         switch ($field_name) {
139 139
             case 'REG_code':
140
-                if (! empty($field_value) && ! $this->reg_code()) {
140
+                if ( ! empty($field_value) && ! $this->reg_code()) {
141 141
                     $this->set_reg_code($field_value, $use_default);
142 142
                 }
143 143
                 break;
@@ -184,7 +184,7 @@  discard block
 block discarded – undo
184 184
             $this
185 185
         );
186 186
         // it's still good to allow the parent set method to have a say
187
-        parent::set('STS_ID', (! empty($new_STS_ID) ? $new_STS_ID : null), $use_default);
187
+        parent::set('STS_ID', ( ! empty($new_STS_ID) ? $new_STS_ID : null), $use_default);
188 188
         // if status has changed
189 189
         if (
190 190
             $old_STS_ID !== $new_STS_ID // and that status has actually changed
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
     public function event(): EE_Event
437 437
     {
438 438
         $event = $this->event_obj();
439
-        if (! $event instanceof EE_Event) {
439
+        if ( ! $event instanceof EE_Event) {
440 440
             throw new EntityNotFoundException('Event ID', $this->event_ID());
441 441
         }
442 442
         return $event;
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
     {
480 480
         // reserved ticket and datetime counts will be decremented as sold counts are incremented
481 481
         // so stop tracking that this reg has a ticket reserved
482
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
482
+        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:".__LINE__.')');
483 483
         $ticket = $this->ticket();
484 484
         $ticket->increaseSold();
485 485
         // possibly set event status to sold out
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
             $reserved = $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
530 530
             if ($reserved && $update_ticket) {
531 531
                 $ticket = $this->ticket();
532
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
532
+                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:".__LINE__.')');
533 533
                 $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
534 534
                 $ticket->save();
535 535
             }
@@ -557,7 +557,7 @@  discard block
 block discarded – undo
557 557
             $reserved = $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false);
558 558
             if ($reserved && $update_ticket) {
559 559
                 $ticket = $this->ticket();
560
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
560
+                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:".__LINE__.')');
561 561
                 $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
562 562
             }
563 563
         }
@@ -1367,7 +1367,7 @@  discard block
 block discarded – undo
1367 1367
             false,
1368 1368
             'sentence'
1369 1369
         );
1370
-        $icon   = '';
1370
+        $icon = '';
1371 1371
         switch ($this->status_ID()) {
1372 1372
             case RegStatus::APPROVED:
1373 1373
                 $icon = $show_icons
@@ -1405,7 +1405,7 @@  discard block
 block discarded – undo
1405 1405
                     : '';
1406 1406
                 break;
1407 1407
         }
1408
-        return $icon . $status[ $this->status_ID() ];
1408
+        return $icon.$status[$this->status_ID()];
1409 1409
     }
1410 1410
 
1411 1411
 
@@ -1660,7 +1660,7 @@  discard block
 block discarded – undo
1660 1660
     {
1661 1661
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1662 1662
         // first check registration status
1663
-        if (! $DTT_ID || ($check_approved && ! $this->is_approved())) {
1663
+        if ( ! $DTT_ID || ($check_approved && ! $this->is_approved())) {
1664 1664
             return false;
1665 1665
         }
1666 1666
         // is there a datetime ticket that matches this dtt_ID?
@@ -1700,7 +1700,7 @@  discard block
 block discarded – undo
1700 1700
     {
1701 1701
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1702 1702
 
1703
-        if (! $DTT_ID) {
1703
+        if ( ! $DTT_ID) {
1704 1704
             return false;
1705 1705
         }
1706 1706
 
@@ -1710,7 +1710,7 @@  discard block
 block discarded – undo
1710 1710
 
1711 1711
         // if max uses is not set or equals infinity then return true
1712 1712
         // because it's not a factor for whether user can check in or not.
1713
-        if (! $max_uses || $max_uses === EE_INF) {
1713
+        if ( ! $max_uses || $max_uses === EE_INF) {
1714 1714
             return true;
1715 1715
         }
1716 1716
 
@@ -1774,7 +1774,7 @@  discard block
 block discarded – undo
1774 1774
             $datetime = $this->get_latest_related_datetime();
1775 1775
             $DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1776 1776
             // verify the registration can check in for the given DTT_ID
1777
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1777
+        } elseif ( ! $this->can_checkin($DTT_ID, $verify)) {
1778 1778
             EE_Error::add_error(
1779 1779
                 sprintf(
1780 1780
                     esc_html__(
@@ -1797,7 +1797,7 @@  discard block
 block discarded – undo
1797 1797
         ];
1798 1798
         // start by getting the current status so we know what status we'll be changing to.
1799 1799
         $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1800
-        $status_to  = $status_paths[ $cur_status ];
1800
+        $status_to  = $status_paths[$cur_status];
1801 1801
         // database only records true for checked IN or false for checked OUT
1802 1802
         // no record ( null ) means checked in NEVER, but we obviously don't save that
1803 1803
         $new_status = $status_to === EE_Checkin::status_checked_in;
@@ -1909,7 +1909,7 @@  discard block
 block discarded – undo
1909 1909
             return $checkin->status();
1910 1910
         }
1911 1911
 
1912
-        if (! $DTT_ID) {
1912
+        if ( ! $DTT_ID) {
1913 1913
             return EE_Checkin::status_invalid;
1914 1914
         }
1915 1915
 
@@ -1980,7 +1980,7 @@  discard block
 block discarded – undo
1980 1980
         $transaction = $TXN_ID
1981 1981
             ? EEM_Transaction::instance()->get_one_by_ID($TXN_ID)
1982 1982
             : $this->get_one_from_cache('Transaction');
1983
-        if (! $transaction instanceof \EE_Transaction) {
1983
+        if ( ! $transaction instanceof \EE_Transaction) {
1984 1984
             throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1985 1985
         }
1986 1986
         return $transaction;
@@ -2045,7 +2045,7 @@  discard block
 block discarded – undo
2045 2045
      */
2046 2046
     public function set_reg_code($REG_code, bool $use_default = false)
2047 2047
     {
2048
-        if (! $this->reg_code()) {
2048
+        if ( ! $this->reg_code()) {
2049 2049
             parent::set('REG_code', $REG_code, $use_default);
2050 2050
         } elseif (empty($REG_code)) {
2051 2051
             EE_Error::add_error(
@@ -2056,7 +2056,7 @@  discard block
 block discarded – undo
2056 2056
             );
2057 2057
         } else {
2058 2058
             EE_Error::doing_it_wrong(
2059
-                __CLASS__ . '::' . __FUNCTION__,
2059
+                __CLASS__.'::'.__FUNCTION__,
2060 2060
                 esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
2061 2061
                 '4.6.0'
2062 2062
             );
@@ -2247,7 +2247,7 @@  discard block
 block discarded – undo
2247 2247
                 break;
2248 2248
             }
2249 2249
         }
2250
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
2250
+        if ( ! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
2251 2251
             throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
2252 2252
         }
2253 2253
         return $line_item;
Please login to merge, or discard this patch.
core/db_classes/EE_Line_Item.class.php 2 patches
Indentation   +1737 added lines, -1737 removed lines patch added patch discarded remove patch
@@ -16,1741 +16,1741 @@
 block discarded – undo
16 16
  */
17 17
 class EE_Line_Item extends EE_Base_Class
18 18
 {
19
-    /**
20
-     * for children line items (currently not a normal relation)
21
-     *
22
-     * @var EE_Line_Item[]
23
-     */
24
-    protected array $_children = [];
25
-
26
-    /**
27
-     * query params used to obtain children line items above
28
-     *
29
-     * @var array
30
-     */
31
-    private array $children_query_params = [];
32
-
33
-    /**
34
-     * for the parent line item
35
-     *
36
-     * @var EE_Line_Item|null
37
-     */
38
-    protected ?EE_Line_Item $_parent = null;
39
-
40
-    /**
41
-     * @var LineItemCalculator
42
-     */
43
-    protected LineItemCalculator $calculator;
44
-
45
-
46
-    /**
47
-     * @param array       $props_n_values incoming values
48
-     * @param string|null $timezone       incoming timezone as set by the model.
49
-     *                                    If not set the timezone for the website will be used.
50
-     * @param array       $date_formats   incoming date_formats in an array where the first value is the
51
-     *                                    date_format and the second value is the time format
52
-     * @return EE_Line_Item
53
-     * @throws EE_Error
54
-     * @throws InvalidArgumentException
55
-     * @throws InvalidDataTypeException
56
-     * @throws InvalidInterfaceException
57
-     * @throws ReflectionException
58
-     */
59
-    public static function new_instance(
60
-        array $props_n_values = [],
61
-        ?string $timezone = '',
62
-        array $date_formats = []
63
-    ): EE_Line_Item {
64
-        $has_object = parent::_check_for_object(
65
-            $props_n_values,
66
-            __CLASS__,
67
-            $timezone,
68
-            $date_formats
69
-        );
70
-        return $has_object ?: new self($props_n_values, false, $timezone);
71
-    }
72
-
73
-
74
-    /**
75
-     * @param array       $props_n_values incoming values from the database
76
-     * @param string|null $timezone       incoming timezone as set by the model.
77
-     *                                    If not set the timezone for the website will be used.
78
-     * @return EE_Line_Item
79
-     * @throws EE_Error
80
-     * @throws InvalidArgumentException
81
-     * @throws InvalidDataTypeException
82
-     * @throws InvalidInterfaceException
83
-     * @throws ReflectionException
84
-     */
85
-    public static function new_instance_from_db(array $props_n_values = [], ?string $timezone = ''): EE_Line_Item
86
-    {
87
-        return new self($props_n_values, true, $timezone);
88
-    }
89
-
90
-
91
-    /**
92
-     * Adds some defaults if they're not specified
93
-     *
94
-     * @param array  $fieldValues
95
-     * @param bool   $bydb
96
-     * @param string $timezone
97
-     * @throws EE_Error
98
-     * @throws InvalidArgumentException
99
-     * @throws InvalidDataTypeException
100
-     * @throws InvalidInterfaceException
101
-     * @throws ReflectionException
102
-     */
103
-    protected function __construct($fieldValues = [], $bydb = false, $timezone = '')
104
-    {
105
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
106
-        parent::__construct($fieldValues, $bydb, $timezone);
107
-        if (! $this->get('LIN_code')) {
108
-            $this->set_code($this->generate_code());
109
-        }
110
-    }
111
-
112
-
113
-    public function __wakeup()
114
-    {
115
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
116
-        parent::__wakeup();
117
-    }
118
-
119
-
120
-    /**
121
-     * Gets ID
122
-     *
123
-     * @return int
124
-     * @throws EE_Error
125
-     * @throws InvalidArgumentException
126
-     * @throws InvalidDataTypeException
127
-     * @throws InvalidInterfaceException
128
-     * @throws ReflectionException
129
-     */
130
-    public function ID(): int
131
-    {
132
-        return (int) $this->get('LIN_ID');
133
-    }
134
-
135
-
136
-    /**
137
-     * Gets TXN_ID
138
-     *
139
-     * @return int
140
-     * @throws EE_Error
141
-     * @throws InvalidArgumentException
142
-     * @throws InvalidDataTypeException
143
-     * @throws InvalidInterfaceException
144
-     * @throws ReflectionException
145
-     */
146
-    public function TXN_ID(): int
147
-    {
148
-        return (int) $this->get('TXN_ID');
149
-    }
150
-
151
-
152
-    /**
153
-     * Sets TXN_ID
154
-     *
155
-     * @param int $TXN_ID
156
-     * @throws EE_Error
157
-     * @throws InvalidArgumentException
158
-     * @throws InvalidDataTypeException
159
-     * @throws InvalidInterfaceException
160
-     * @throws ReflectionException
161
-     */
162
-    public function set_TXN_ID(int $TXN_ID)
163
-    {
164
-        $this->set('TXN_ID', $TXN_ID);
165
-    }
166
-
167
-
168
-    /**
169
-     * Gets name
170
-     *
171
-     * @return string
172
-     * @throws EE_Error
173
-     * @throws InvalidArgumentException
174
-     * @throws InvalidDataTypeException
175
-     * @throws InvalidInterfaceException
176
-     * @throws ReflectionException
177
-     */
178
-    public function name(): string
179
-    {
180
-        $name = (string) $this->get('LIN_name');
181
-        if (! $name) {
182
-            $name = ucwords(str_replace('-', ' ', $this->type()));
183
-        }
184
-        return $name;
185
-    }
186
-
187
-
188
-    /**
189
-     * Sets name
190
-     *
191
-     * @param string $name
192
-     * @throws EE_Error
193
-     * @throws InvalidArgumentException
194
-     * @throws InvalidDataTypeException
195
-     * @throws InvalidInterfaceException
196
-     * @throws ReflectionException
197
-     */
198
-    public function set_name(string $name)
199
-    {
200
-        $this->set('LIN_name', $name);
201
-    }
202
-
203
-
204
-    /**
205
-     * Gets desc
206
-     *
207
-     * @return string
208
-     * @throws EE_Error
209
-     * @throws InvalidArgumentException
210
-     * @throws InvalidDataTypeException
211
-     * @throws InvalidInterfaceException
212
-     * @throws ReflectionException
213
-     */
214
-    public function desc(): string
215
-    {
216
-        return (string) $this->get('LIN_desc');
217
-    }
218
-
219
-
220
-    /**
221
-     * Sets desc
222
-     *
223
-     * @param string $desc
224
-     * @throws EE_Error
225
-     * @throws InvalidArgumentException
226
-     * @throws InvalidDataTypeException
227
-     * @throws InvalidInterfaceException
228
-     * @throws ReflectionException
229
-     */
230
-    public function set_desc(string $desc)
231
-    {
232
-        $this->set('LIN_desc', $desc);
233
-    }
234
-
235
-
236
-    /**
237
-     * Gets quantity
238
-     *
239
-     * @return int
240
-     * @throws EE_Error
241
-     * @throws InvalidArgumentException
242
-     * @throws InvalidDataTypeException
243
-     * @throws InvalidInterfaceException
244
-     * @throws ReflectionException
245
-     */
246
-    public function quantity(): int
247
-    {
248
-        return (int) $this->get('LIN_quantity');
249
-    }
250
-
251
-
252
-    /**
253
-     * Sets quantity
254
-     *
255
-     * @param int $quantity
256
-     * @throws EE_Error
257
-     * @throws InvalidArgumentException
258
-     * @throws InvalidDataTypeException
259
-     * @throws InvalidInterfaceException
260
-     * @throws ReflectionException
261
-     */
262
-    public function set_quantity(int $quantity)
263
-    {
264
-        $this->set('LIN_quantity', max($quantity, 0));
265
-    }
266
-
267
-
268
-    /**
269
-     * Gets item_id
270
-     *
271
-     * @return int
272
-     * @throws EE_Error
273
-     * @throws InvalidArgumentException
274
-     * @throws InvalidDataTypeException
275
-     * @throws InvalidInterfaceException
276
-     * @throws ReflectionException
277
-     */
278
-    public function OBJ_ID(): int
279
-    {
280
-        return (int) $this->get('OBJ_ID');
281
-    }
282
-
283
-
284
-    /**
285
-     * Sets item_id
286
-     *
287
-     * @param int $item_id
288
-     * @throws EE_Error
289
-     * @throws InvalidArgumentException
290
-     * @throws InvalidDataTypeException
291
-     * @throws InvalidInterfaceException
292
-     * @throws ReflectionException
293
-     */
294
-    public function set_OBJ_ID(int $item_id)
295
-    {
296
-        $this->set('OBJ_ID', $item_id);
297
-    }
298
-
299
-
300
-    /**
301
-     * Gets item_type
302
-     *
303
-     * @return string
304
-     * @throws EE_Error
305
-     * @throws InvalidArgumentException
306
-     * @throws InvalidDataTypeException
307
-     * @throws InvalidInterfaceException
308
-     * @throws ReflectionException
309
-     */
310
-    public function OBJ_type(): string
311
-    {
312
-        return (string) $this->get('OBJ_type');
313
-    }
314
-
315
-
316
-    /**
317
-     * Gets item_type
318
-     *
319
-     * @return string
320
-     * @throws EE_Error
321
-     * @throws InvalidArgumentException
322
-     * @throws InvalidDataTypeException
323
-     * @throws InvalidInterfaceException
324
-     * @throws ReflectionException
325
-     */
326
-    public function OBJ_type_i18n(): string
327
-    {
328
-        $obj_type = $this->OBJ_type();
329
-        switch ($obj_type) {
330
-            case EEM_Line_Item::OBJ_TYPE_EVENT:
331
-                $obj_type = esc_html__('Event', 'event_espresso');
332
-                break;
333
-            case EEM_Line_Item::OBJ_TYPE_PRICE:
334
-                $obj_type = esc_html__('Price', 'event_espresso');
335
-                break;
336
-            case EEM_Line_Item::OBJ_TYPE_PROMOTION:
337
-                $obj_type = esc_html__('Promotion', 'event_espresso');
338
-                break;
339
-            case EEM_Line_Item::OBJ_TYPE_TICKET:
340
-                $obj_type = esc_html__('Ticket', 'event_espresso');
341
-                break;
342
-            case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
343
-                $obj_type = esc_html__('Transaction', 'event_espresso');
344
-                break;
345
-        }
346
-        return (string) apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
347
-    }
348
-
349
-
350
-    /**
351
-     * Sets item_type
352
-     *
353
-     * @param string $OBJ_type
354
-     * @throws EE_Error
355
-     * @throws InvalidArgumentException
356
-     * @throws InvalidDataTypeException
357
-     * @throws InvalidInterfaceException
358
-     * @throws ReflectionException
359
-     */
360
-    public function set_OBJ_type(string $OBJ_type)
361
-    {
362
-        $this->set('OBJ_type', $OBJ_type);
363
-    }
364
-
365
-
366
-    /**
367
-     * Gets unit_price
368
-     *
369
-     * @return float
370
-     * @throws EE_Error
371
-     * @throws InvalidArgumentException
372
-     * @throws InvalidDataTypeException
373
-     * @throws InvalidInterfaceException
374
-     * @throws ReflectionException
375
-     */
376
-    public function unit_price(): float
377
-    {
378
-        return (float) $this->get('LIN_unit_price');
379
-    }
380
-
381
-
382
-    /**
383
-     * Sets unit_price
384
-     *
385
-     * @param int|float $unit_price
386
-     * @throws EE_Error
387
-     * @throws InvalidArgumentException
388
-     * @throws InvalidDataTypeException
389
-     * @throws InvalidInterfaceException
390
-     * @throws ReflectionException
391
-     */
392
-    public function set_unit_price($unit_price)
393
-    {
394
-        $this->set('LIN_unit_price', (float) $unit_price);
395
-    }
396
-
397
-
398
-    /**
399
-     * Checks if this item is a percentage modifier or not
400
-     *
401
-     * @return bool
402
-     * @throws EE_Error
403
-     * @throws InvalidArgumentException
404
-     * @throws InvalidDataTypeException
405
-     * @throws InvalidInterfaceException
406
-     * @throws ReflectionException
407
-     */
408
-    public function is_percent(): bool
409
-    {
410
-        if ($this->is_tax_sub_total()) {
411
-            // tax subtotals HAVE a percent on them, that percentage only applies
412
-            // to taxable items, so it's an exception. Treat it like a flat line item
413
-            return false;
414
-        }
415
-        $unit_price = abs($this->get('LIN_unit_price'));
416
-        $percent    = abs($this->get('LIN_percent'));
417
-        if ($unit_price < .001 && $percent) {
418
-            return true;
419
-        }
420
-        if ($unit_price >= .001 && ! $percent) {
421
-            return false;
422
-        }
423
-        if ($unit_price >= .001 && $percent) {
424
-            throw new EE_Error(
425
-                sprintf(
426
-                    esc_html__(
427
-                        'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
428
-                        'event_espresso'
429
-                    ),
430
-                    $unit_price,
431
-                    $percent
432
-                )
433
-            );
434
-        }
435
-        // if they're both 0, assume it's not a percent item
436
-        return false;
437
-    }
438
-
439
-
440
-    /**
441
-     * Gets percent (between 100-.001)
442
-     *
443
-     * @return float
444
-     * @throws EE_Error
445
-     * @throws InvalidArgumentException
446
-     * @throws InvalidDataTypeException
447
-     * @throws InvalidInterfaceException
448
-     * @throws ReflectionException
449
-     */
450
-    public function percent(): float
451
-    {
452
-        return (float) $this->get('LIN_percent');
453
-    }
454
-
455
-
456
-    /**
457
-     * @return string
458
-     * @throws EE_Error
459
-     * @throws ReflectionException
460
-     * @since 5.0.0.p
461
-     */
462
-    public function prettyPercent(): string
463
-    {
464
-        return (string) $this->get_pretty('LIN_percent');
465
-    }
466
-
467
-
468
-    /**
469
-     * Sets percent (between 100-0.01)
470
-     *
471
-     * @param int|float $percent
472
-     * @throws EE_Error
473
-     * @throws InvalidArgumentException
474
-     * @throws InvalidDataTypeException
475
-     * @throws InvalidInterfaceException
476
-     * @throws ReflectionException
477
-     */
478
-    public function set_percent($percent)
479
-    {
480
-        $this->set('LIN_percent', (float) $percent);
481
-    }
482
-
483
-
484
-    /**
485
-     * Gets total
486
-     *
487
-     * @return float
488
-     * @throws EE_Error
489
-     * @throws InvalidArgumentException
490
-     * @throws InvalidDataTypeException
491
-     * @throws InvalidInterfaceException
492
-     * @throws ReflectionException
493
-     */
494
-    public function pretaxTotal(): float
495
-    {
496
-        return (float) $this->get('LIN_pretax');
497
-    }
498
-
499
-
500
-    /**
501
-     * Sets total
502
-     *
503
-     * @param int|float $pretax_total
504
-     * @throws EE_Error
505
-     * @throws InvalidArgumentException
506
-     * @throws InvalidDataTypeException
507
-     * @throws InvalidInterfaceException
508
-     * @throws ReflectionException
509
-     */
510
-    public function setPretaxTotal($pretax_total)
511
-    {
512
-        $this->set('LIN_pretax', (float) $pretax_total);
513
-    }
514
-
515
-
516
-    /**
517
-     * @return float
518
-     * @throws EE_Error
519
-     * @throws ReflectionException
520
-     * @since  5.0.0.p
521
-     */
522
-    public function totalWithTax(): float
523
-    {
524
-        return (float) $this->get('LIN_total');
525
-    }
526
-
527
-
528
-    /**
529
-     * Sets total
530
-     *
531
-     * @param int|float $total
532
-     * @throws EE_Error
533
-     * @throws ReflectionException
534
-     * @since  5.0.0.p
535
-     */
536
-    public function setTotalWithTax($total)
537
-    {
538
-        $this->set('LIN_total', (float) $total);
539
-    }
540
-
541
-
542
-    /**
543
-     * Gets total
544
-     *
545
-     * @return float
546
-     * @throws EE_Error
547
-     * @throws ReflectionException
548
-     * @deprecatd 5.0.0.p
549
-     */
550
-    public function total(): float
551
-    {
552
-        return $this->totalWithTax();
553
-    }
554
-
555
-
556
-    /**
557
-     * Sets total
558
-     *
559
-     * @param int|float $total
560
-     * @throws EE_Error
561
-     * @throws ReflectionException
562
-     * @deprecatd 5.0.0.p
563
-     */
564
-    public function set_total($total)
565
-    {
566
-        $this->setTotalWithTax((float) $total);
567
-    }
568
-
569
-
570
-    /**
571
-     * Gets order
572
-     *
573
-     * @return int
574
-     * @throws EE_Error
575
-     * @throws InvalidArgumentException
576
-     * @throws InvalidDataTypeException
577
-     * @throws InvalidInterfaceException
578
-     * @throws ReflectionException
579
-     */
580
-    public function order(): int
581
-    {
582
-        return (int) $this->get('LIN_order');
583
-    }
584
-
585
-
586
-    /**
587
-     * Sets order
588
-     *
589
-     * @param int $order
590
-     * @throws EE_Error
591
-     * @throws InvalidArgumentException
592
-     * @throws InvalidDataTypeException
593
-     * @throws InvalidInterfaceException
594
-     * @throws ReflectionException
595
-     */
596
-    public function set_order(int $order)
597
-    {
598
-        $this->set('LIN_order', $order);
599
-    }
600
-
601
-
602
-    /**
603
-     * Gets parent
604
-     *
605
-     * @return int
606
-     * @throws EE_Error
607
-     * @throws InvalidArgumentException
608
-     * @throws InvalidDataTypeException
609
-     * @throws InvalidInterfaceException
610
-     * @throws ReflectionException
611
-     */
612
-    public function parent_ID(): int
613
-    {
614
-        return (int) $this->get('LIN_parent');
615
-    }
616
-
617
-
618
-    /**
619
-     * Sets parent
620
-     *
621
-     * @param int $parent
622
-     * @throws EE_Error
623
-     * @throws InvalidArgumentException
624
-     * @throws InvalidDataTypeException
625
-     * @throws InvalidInterfaceException
626
-     * @throws ReflectionException
627
-     */
628
-    public function set_parent_ID(int $parent)
629
-    {
630
-        $this->set('LIN_parent', $parent);
631
-    }
632
-
633
-
634
-    /**
635
-     * Gets type
636
-     *
637
-     * @return string
638
-     * @throws EE_Error
639
-     * @throws InvalidArgumentException
640
-     * @throws InvalidDataTypeException
641
-     * @throws InvalidInterfaceException
642
-     * @throws ReflectionException
643
-     */
644
-    public function type(): string
645
-    {
646
-        return (string) $this->get('LIN_type');
647
-    }
648
-
649
-
650
-    /**
651
-     * Sets type
652
-     *
653
-     * @param string $type
654
-     * @throws EE_Error
655
-     * @throws InvalidArgumentException
656
-     * @throws InvalidDataTypeException
657
-     * @throws InvalidInterfaceException
658
-     * @throws ReflectionException
659
-     */
660
-    public function set_type(string $type)
661
-    {
662
-        $this->set('LIN_type', $type);
663
-    }
664
-
665
-
666
-    /**
667
-     * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
668
-     * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
669
-     * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
670
-     * or indirectly by `EE_Line_item::add_child_line_item()`)
671
-     *
672
-     * @return EE_Line_Item|null
673
-     * @throws EE_Error
674
-     * @throws InvalidArgumentException
675
-     * @throws InvalidDataTypeException
676
-     * @throws InvalidInterfaceException
677
-     * @throws ReflectionException
678
-     */
679
-    public function parent(): ?EE_Line_Item
680
-    {
681
-        if (! $this->_parent instanceof EE_Line_Item) {
682
-            $this->_parent = $this->ID()
683
-                ? $this->get_model()->get_one_by_ID($this->parent_ID())
684
-                : $this->_parent;
685
-        }
686
-        return $this->_parent;
687
-    }
688
-
689
-
690
-    /**
691
-     * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
692
-     *
693
-     * @return EE_Line_Item[]
694
-     * @throws EE_Error
695
-     * @throws InvalidArgumentException
696
-     * @throws InvalidDataTypeException
697
-     * @throws InvalidInterfaceException
698
-     * @throws ReflectionException
699
-     */
700
-    public function children(array $query_params = []): array
701
-    {
702
-        // check if the query params have changed since the last time we ran this query
703
-        $new_params = ! empty(EEH_Array::array_diff_recursive($query_params, $this->children_query_params));
704
-        if (($new_params || empty($this->_children)) && $this->ID()) {
705
-            $this->children_query_params = $query_params;
706
-            // ensure where params are an array
707
-            $query_params[0] = isset($query_params[0]) && is_array($query_params[0]) ? $query_params[0] : [];
708
-            // add defaults for line item parent and orderby
709
-            $query_params[0] += ['LIN_parent' => $this->ID()];
710
-            $query_params    += ['order_by' => ['LIN_order' => 'ASC']];
711
-            $children = $this->get_model()->get_all($query_params);
712
-            foreach ($children as $child) {
713
-                if ($child instanceof EE_Line_Item) {
714
-                    $this->addLineItemToChildren($child);
715
-                }
716
-            }
717
-        }
718
-        return $this->_children;
719
-    }
720
-
721
-
722
-    private function addLineItemToChildren($child_line_item)
723
-    {
724
-        $this->_children[ $child_line_item->code() ] = $child_line_item;
725
-    }
726
-
727
-
728
-    private function getChildLineItemFromCache(string $code): ?EE_Line_Item
729
-    {
730
-        return $this->_children[ $code ] ?? null;
731
-    }
732
-
733
-
734
-    private function removeChildLineItemFromCache(string $code): int
735
-    {
736
-        if (isset($this->_children[ $code ])) {
737
-            unset($this->_children[ $code ]);
738
-            return 1;
739
-        }
740
-        return 0;
741
-    }
742
-
743
-
744
-    private function resetChildren()
745
-    {
746
-        $this->_children = [];
747
-    }
748
-
749
-
750
-    /**
751
-     * Gets code
752
-     *
753
-     * @return string
754
-     * @throws EE_Error
755
-     * @throws InvalidArgumentException
756
-     * @throws InvalidDataTypeException
757
-     * @throws InvalidInterfaceException
758
-     * @throws ReflectionException
759
-     */
760
-    public function code(): string
761
-    {
762
-        return (string) $this->get('LIN_code');
763
-    }
764
-
765
-
766
-    /**
767
-     * Sets code
768
-     *
769
-     * @param string $code
770
-     * @throws EE_Error
771
-     * @throws InvalidArgumentException
772
-     * @throws InvalidDataTypeException
773
-     * @throws InvalidInterfaceException
774
-     * @throws ReflectionException
775
-     */
776
-    public function set_code(string $code)
777
-    {
778
-        $this->set('LIN_code', $code);
779
-    }
780
-
781
-
782
-    /**
783
-     * Gets is_taxable
784
-     *
785
-     * @return bool
786
-     * @throws EE_Error
787
-     * @throws InvalidArgumentException
788
-     * @throws InvalidDataTypeException
789
-     * @throws InvalidInterfaceException
790
-     * @throws ReflectionException
791
-     */
792
-    public function is_taxable(): bool
793
-    {
794
-        return (bool) $this->get('LIN_is_taxable');
795
-    }
796
-
797
-
798
-    /**
799
-     * Sets is_taxable
800
-     *
801
-     * @param bool $is_taxable
802
-     * @throws EE_Error
803
-     * @throws InvalidArgumentException
804
-     * @throws InvalidDataTypeException
805
-     * @throws InvalidInterfaceException
806
-     * @throws ReflectionException
807
-     */
808
-    public function set_is_taxable(bool $is_taxable)
809
-    {
810
-        $this->set('LIN_is_taxable', $is_taxable);
811
-    }
812
-
813
-
814
-    /**
815
-     * @param int $timestamp
816
-     * @throws EE_Error
817
-     * @throws ReflectionException
818
-     * @since 5.0.0.p
819
-     */
820
-    public function setTimestamp(int $timestamp)
821
-    {
822
-        $this->set('LIN_timestamp', $timestamp);
823
-    }
824
-
825
-
826
-    /**
827
-     * Gets the object that this model-joins-to.
828
-     * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
829
-     * EEM_Promotion_Object
830
-     *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
831
-     *
832
-     * @return EE_Base_Class|null
833
-     * @throws EE_Error
834
-     * @throws InvalidArgumentException
835
-     * @throws InvalidDataTypeException
836
-     * @throws InvalidInterfaceException
837
-     * @throws ReflectionException
838
-     */
839
-    public function get_object(): ?EE_Base_Class
840
-    {
841
-        $model_name_of_related_obj = $this->OBJ_type();
842
-        return $this->get_model()->has_relation($model_name_of_related_obj)
843
-            ? $this->get_first_related($model_name_of_related_obj)
844
-            : null;
845
-    }
846
-
847
-
848
-    /**
849
-     * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
850
-     * (IE, if this line item is for a price or something else, will return NULL)
851
-     *
852
-     * @param array $query_params deprecated 5.0.12.p
853
-     * @return EE_Ticket|null
854
-     * @throws EE_Error
855
-     * @throws ReflectionException
856
-     */
857
-    public function ticket(array $query_params = []): ?EE_Ticket
858
-    {
859
-        // we're going to assume that when this method is called
860
-        // we always want to receive the attached ticket EVEN if that ticket is archived.
861
-        if(! $this->OBJ_ID() || $this->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
862
-            return null;
863
-        }
864
-        if(empty($query_args)) {
865
-            return EEM_Ticket::instance()->get_one_by_ID($this->OBJ_ID());
866
-        }
867
-        // legacy usage
868
-        $query_params += ['default_where_conditions' => 'none'];
869
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
870
-    }
871
-
872
-
873
-    /**
874
-     * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
875
-     *
876
-     * @return EE_Datetime|null
877
-     * @throws EE_Error
878
-     * @throws InvalidArgumentException
879
-     * @throws InvalidDataTypeException
880
-     * @throws InvalidInterfaceException
881
-     * @throws ReflectionException
882
-     */
883
-    public function get_ticket_datetime(): ?EE_Datetime
884
-    {
885
-        if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
886
-            $ticket = $this->ticket();
887
-            if ($ticket instanceof EE_Ticket) {
888
-                $datetime = $ticket->first_datetime();
889
-                if ($datetime instanceof EE_Datetime) {
890
-                    return $datetime;
891
-                }
892
-            }
893
-        }
894
-        return null;
895
-    }
896
-
897
-
898
-    /**
899
-     * Gets the event's name that's related to the ticket, if this is for
900
-     * a ticket
901
-     *
902
-     * @return string
903
-     * @throws EE_Error
904
-     * @throws InvalidArgumentException
905
-     * @throws InvalidDataTypeException
906
-     * @throws InvalidInterfaceException
907
-     * @throws ReflectionException
908
-     */
909
-    public function ticket_event_name(): string
910
-    {
911
-        $event_name = esc_html__('Unknown', 'event_espresso');
912
-        $event      = $this->ticket_event();
913
-        if ($event instanceof EE_Event) {
914
-            $event_name = $event->name();
915
-        }
916
-        return $event_name;
917
-    }
918
-
919
-
920
-    /**
921
-     * Gets the event that's related to the ticket, if this line item represents a ticket.
922
-     *
923
-     * @return EE_Event|null
924
-     * @throws EE_Error
925
-     * @throws InvalidArgumentException
926
-     * @throws InvalidDataTypeException
927
-     * @throws InvalidInterfaceException
928
-     * @throws ReflectionException
929
-     */
930
-    public function ticket_event(): ?EE_Event
931
-    {
932
-        $event  = null;
933
-        $ticket = $this->ticket();
934
-        if ($ticket instanceof EE_Ticket) {
935
-            $datetime = $ticket->first_datetime();
936
-            if ($datetime instanceof EE_Datetime) {
937
-                $event = $datetime->event();
938
-            }
939
-        }
940
-        return $event;
941
-    }
942
-
943
-
944
-    /**
945
-     * Gets the first datetime for this lien item, assuming it's for a ticket
946
-     *
947
-     * @param string $date_format
948
-     * @param string $time_format
949
-     * @return string
950
-     * @throws EE_Error
951
-     * @throws InvalidArgumentException
952
-     * @throws InvalidDataTypeException
953
-     * @throws InvalidInterfaceException
954
-     * @throws ReflectionException
955
-     */
956
-    public function ticket_datetime_start(string $date_format = '', string $time_format = ''): string
957
-    {
958
-        $first_datetime_string = esc_html__('Unknown', 'event_espresso');
959
-        $datetime              = $this->get_ticket_datetime();
960
-        if ($datetime) {
961
-            $first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
962
-        }
963
-        return $first_datetime_string;
964
-    }
965
-
966
-
967
-    /**
968
-     * Adds the line item as a child to this line item. If there is another child line
969
-     * item with the same LIN_code, it is overwritten by this new one
970
-     *
971
-     * @param EE_Line_Item $line_item
972
-     * @param bool         $set_order
973
-     * @return bool success
974
-     * @throws EE_Error
975
-     * @throws InvalidArgumentException
976
-     * @throws InvalidDataTypeException
977
-     * @throws InvalidInterfaceException
978
-     * @throws ReflectionException
979
-     */
980
-    public function add_child_line_item(EE_Line_Item $line_item, bool $set_order = true): bool
981
-    {
982
-        // should we calculate the LIN_order for this line item ?
983
-        if ($set_order || $line_item->order() === null) {
984
-            $line_item->set_order(count($this->children()));
985
-        }
986
-        if ($this->ID()) {
987
-            // check for any duplicate line items (with the same code), if so, this replaces it
988
-            $line_item_with_same_code = $this->get_child_line_item($line_item->code());
989
-            if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
990
-                $this->delete_child_line_item($line_item_with_same_code->code());
991
-            }
992
-            $line_item->set_parent_ID($this->ID());
993
-            if ($this->TXN_ID()) {
994
-                $line_item->set_TXN_ID($this->TXN_ID());
995
-            }
996
-            $this->addLineItemToChildren($line_item);
997
-            return (bool) $line_item->save();
998
-        }
999
-        $this->addLineItemToChildren($line_item);
1000
-        if ($line_item->parent() !== $this) {
1001
-            $line_item->set_parent($this);
1002
-        }
1003
-        return true;
1004
-    }
1005
-
1006
-
1007
-    /**
1008
-     * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
1009
-     * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
1010
-     * However, if this line item is NOT saved to the DB, this just caches the parent on
1011
-     * the EE_Line_Item::_parent property.
1012
-     *
1013
-     * @param EE_Line_Item $line_item
1014
-     * @throws EE_Error
1015
-     * @throws InvalidArgumentException
1016
-     * @throws InvalidDataTypeException
1017
-     * @throws InvalidInterfaceException
1018
-     * @throws ReflectionException
1019
-     */
1020
-    public function set_parent(EE_Line_Item $line_item)
1021
-    {
1022
-        if ($this->ID()) {
1023
-            if (! $line_item->ID()) {
1024
-                $line_item->save();
1025
-            }
1026
-            $this->set_parent_ID($line_item->ID());
1027
-            $this->save();
1028
-        } else {
1029
-            $this->_parent = $line_item;
1030
-            $this->set_parent_ID($line_item->ID());
1031
-        }
1032
-    }
1033
-
1034
-
1035
-    /**
1036
-     * Gets the child line item as specified by its code. Because this returns an object (by reference)
1037
-     * you can modify this child line item and the parent (this object) can know about them
1038
-     * because it also has a reference to that line item
1039
-     *
1040
-     * @param string $code
1041
-     * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
1042
-     * @throws EE_Error
1043
-     * @throws InvalidArgumentException
1044
-     * @throws InvalidDataTypeException
1045
-     * @throws InvalidInterfaceException
1046
-     * @throws ReflectionException
1047
-     */
1048
-    public function get_child_line_item(string $code)
1049
-    {
1050
-        $child = $this->getChildLineItemFromCache($code);
1051
-        if ($child instanceof EE_Line_Item) {
1052
-            return $child;
1053
-        }
1054
-        if ($this->ID()) {
1055
-            return $this->get_model()->get_one(
1056
-                [['LIN_parent' => $this->ID(), 'LIN_code' => $code]]
1057
-            );
1058
-        }
1059
-        return null;
1060
-    }
1061
-
1062
-
1063
-    /**
1064
-     * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1065
-     * cached on it)
1066
-     *
1067
-     * @return int
1068
-     * @throws EE_Error
1069
-     * @throws InvalidArgumentException
1070
-     * @throws InvalidDataTypeException
1071
-     * @throws InvalidInterfaceException
1072
-     * @throws ReflectionException
1073
-     */
1074
-    public function delete_children_line_items(): int
1075
-    {
1076
-        $count = count($this->_children);
1077
-        $this->resetChildren();
1078
-        return $this->ID() ? (int) $this->get_model()->delete([['LIN_parent' => $this->ID()]]) : $count;
1079
-    }
1080
-
1081
-
1082
-    /**
1083
-     * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1084
-     * HAS NOT been saved to the DB, removes the child line item with index $code.
1085
-     * Also searches through the child's children for a matching line item. However, once a line item has been found
1086
-     * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1087
-     * deleted)
1088
-     *
1089
-     * @param string $code
1090
-     * @param bool   $stop_search_once_found
1091
-     * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1092
-     *             the DB yet)
1093
-     * @throws EE_Error
1094
-     * @throws InvalidArgumentException
1095
-     * @throws InvalidDataTypeException
1096
-     * @throws InvalidInterfaceException
1097
-     * @throws ReflectionException
1098
-     */
1099
-    public function delete_child_line_item(string $code, bool $stop_search_once_found = true): int
1100
-    {
1101
-        $removed = $this->removeChildLineItemFromCache($code);
1102
-        if ($this->ID()) {
1103
-            $items_deleted = 0;
1104
-            if ($this->code() === $code) {
1105
-                $items_deleted += EEH_Line_Item::delete_all_child_items($this);
1106
-                $items_deleted += (int) $this->delete();
1107
-                if ($stop_search_once_found) {
1108
-                    return $items_deleted;
1109
-                }
1110
-            }
1111
-            foreach ($this->children() as $child_line_item) {
1112
-                $items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1113
-            }
1114
-            return $items_deleted;
1115
-        }
1116
-        return $removed;
1117
-    }
1118
-
1119
-
1120
-    /**
1121
-     * If this line item is in the database, is of the type subtotal, and
1122
-     * has no children, why do we have it? It should be deleted so this function
1123
-     * does that
1124
-     *
1125
-     * @return bool
1126
-     * @throws EE_Error
1127
-     * @throws InvalidArgumentException
1128
-     * @throws InvalidDataTypeException
1129
-     * @throws InvalidInterfaceException
1130
-     * @throws ReflectionException
1131
-     */
1132
-    public function delete_if_childless_subtotal(): bool
1133
-    {
1134
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1135
-            return $this->delete();
1136
-        }
1137
-        return false;
1138
-    }
1139
-
1140
-
1141
-    /**
1142
-     * Creates a code and returns a string. doesn't assign the code to this model object
1143
-     *
1144
-     * @return string
1145
-     * @throws EE_Error
1146
-     * @throws InvalidArgumentException
1147
-     * @throws InvalidDataTypeException
1148
-     * @throws InvalidInterfaceException
1149
-     * @throws ReflectionException
1150
-     */
1151
-    public function generate_code(): string
1152
-    {
1153
-        // each line item in the cart requires a unique identifier
1154
-        return $this->get('OBJ_type') . '-' . $this->get('OBJ_ID');
1155
-    }
1156
-
1157
-
1158
-    /**
1159
-     * @return bool
1160
-     * @throws EE_Error
1161
-     * @throws InvalidArgumentException
1162
-     * @throws InvalidDataTypeException
1163
-     * @throws InvalidInterfaceException
1164
-     * @throws ReflectionException
1165
-     */
1166
-    public function isTax(): bool
1167
-    {
1168
-        return $this->type() === EEM_Line_Item::type_tax || $this->type() === EEM_Line_Item::type_sub_tax;
1169
-    }
1170
-
1171
-
1172
-    /**
1173
-     * @return bool
1174
-     * @throws EE_Error
1175
-     * @throws InvalidArgumentException
1176
-     * @throws InvalidDataTypeException
1177
-     * @throws InvalidInterfaceException
1178
-     * @throws ReflectionException
1179
-     */
1180
-    public function isGlobalTax(): bool
1181
-    {
1182
-        return $this->type() === EEM_Line_Item::type_tax;
1183
-    }
1184
-
1185
-
1186
-    /**
1187
-     * @return bool
1188
-     * @throws EE_Error
1189
-     * @throws InvalidArgumentException
1190
-     * @throws InvalidDataTypeException
1191
-     * @throws InvalidInterfaceException
1192
-     * @throws ReflectionException
1193
-     */
1194
-    public function isSubTax(): bool
1195
-    {
1196
-        return $this->type() === EEM_Line_Item::type_sub_tax;
1197
-    }
1198
-
1199
-
1200
-    /**
1201
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1202
-     *
1203
-     * @return array
1204
-     * @throws EE_Error
1205
-     * @throws InvalidArgumentException
1206
-     * @throws InvalidDataTypeException
1207
-     * @throws InvalidInterfaceException
1208
-     * @throws ReflectionException
1209
-     */
1210
-    public function getSubTaxes(): array
1211
-    {
1212
-        if (! $this->is_line_item()) {
1213
-            return [];
1214
-        }
1215
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1216
-    }
1217
-
1218
-
1219
-    /**
1220
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1221
-     *
1222
-     * @return bool
1223
-     * @throws EE_Error
1224
-     * @throws InvalidArgumentException
1225
-     * @throws InvalidDataTypeException
1226
-     * @throws InvalidInterfaceException
1227
-     * @throws ReflectionException
1228
-     */
1229
-    public function hasSubTaxes(): bool
1230
-    {
1231
-        if (! $this->is_line_item()) {
1232
-            return false;
1233
-        }
1234
-        $sub_taxes = $this->getSubTaxes();
1235
-        return ! empty($sub_taxes);
1236
-    }
1237
-
1238
-
1239
-    /**
1240
-     * @return bool
1241
-     * @throws EE_Error
1242
-     * @throws ReflectionException
1243
-     * @deprecated   5.0.0.p
1244
-     */
1245
-    public function is_tax(): bool
1246
-    {
1247
-        return $this->isGlobalTax();
1248
-    }
1249
-
1250
-
1251
-    /**
1252
-     * @return bool
1253
-     * @throws EE_Error
1254
-     * @throws InvalidArgumentException
1255
-     * @throws InvalidDataTypeException
1256
-     * @throws InvalidInterfaceException
1257
-     * @throws ReflectionException
1258
-     */
1259
-    public function is_tax_sub_total(): bool
1260
-    {
1261
-        return $this->type() === EEM_Line_Item::type_tax_sub_total;
1262
-    }
1263
-
1264
-
1265
-    /**
1266
-     * @return bool
1267
-     * @throws EE_Error
1268
-     * @throws InvalidArgumentException
1269
-     * @throws InvalidDataTypeException
1270
-     * @throws InvalidInterfaceException
1271
-     * @throws ReflectionException
1272
-     */
1273
-    public function is_line_item(): bool
1274
-    {
1275
-        return $this->type() === EEM_Line_Item::type_line_item;
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * @return bool
1281
-     * @throws EE_Error
1282
-     * @throws InvalidArgumentException
1283
-     * @throws InvalidDataTypeException
1284
-     * @throws InvalidInterfaceException
1285
-     * @throws ReflectionException
1286
-     */
1287
-    public function is_sub_line_item(): bool
1288
-    {
1289
-        return $this->type() === EEM_Line_Item::type_sub_line_item;
1290
-    }
1291
-
1292
-
1293
-    /**
1294
-     * @return bool
1295
-     * @throws EE_Error
1296
-     * @throws InvalidArgumentException
1297
-     * @throws InvalidDataTypeException
1298
-     * @throws InvalidInterfaceException
1299
-     * @throws ReflectionException
1300
-     */
1301
-    public function is_sub_total(): bool
1302
-    {
1303
-        return $this->type() === EEM_Line_Item::type_sub_total;
1304
-    }
1305
-
1306
-
1307
-    /**
1308
-     * Whether this line item is a cancellation line item
1309
-     *
1310
-     * @return bool
1311
-     * @throws EE_Error
1312
-     * @throws InvalidArgumentException
1313
-     * @throws InvalidDataTypeException
1314
-     * @throws InvalidInterfaceException
1315
-     * @throws ReflectionException
1316
-     */
1317
-    public function is_cancellation(): bool
1318
-    {
1319
-        return EEM_Line_Item::type_cancellation === $this->type();
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * @return bool
1325
-     * @throws EE_Error
1326
-     * @throws InvalidArgumentException
1327
-     * @throws InvalidDataTypeException
1328
-     * @throws InvalidInterfaceException
1329
-     * @throws ReflectionException
1330
-     */
1331
-    public function is_total(): bool
1332
-    {
1333
-        return $this->type() === EEM_Line_Item::type_total;
1334
-    }
1335
-
1336
-
1337
-    /**
1338
-     * @return bool
1339
-     * @throws EE_Error
1340
-     * @throws InvalidArgumentException
1341
-     * @throws InvalidDataTypeException
1342
-     * @throws InvalidInterfaceException
1343
-     * @throws ReflectionException
1344
-     */
1345
-    public function is_cancelled(): bool
1346
-    {
1347
-        return $this->type() === EEM_Line_Item::type_cancellation;
1348
-    }
1349
-
1350
-
1351
-    /**
1352
-     * @return string like '2, 004.00', formatted according to the localized currency
1353
-     * @throws EE_Error
1354
-     * @throws ReflectionException
1355
-     */
1356
-    public function unit_price_no_code(): string
1357
-    {
1358
-        return $this->prettyUnitPrice();
1359
-    }
1360
-
1361
-
1362
-    /**
1363
-     * @return string like '2, 004.00', formatted according to the localized currency
1364
-     * @throws EE_Error
1365
-     * @throws ReflectionException
1366
-     * @since 5.0.0.p
1367
-     */
1368
-    public function prettyUnitPrice(): string
1369
-    {
1370
-        return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1371
-    }
1372
-
1373
-
1374
-    /**
1375
-     * @return string like '2, 004.00', formatted according to the localized currency
1376
-     * @throws EE_Error
1377
-     * @throws ReflectionException
1378
-     */
1379
-    public function total_no_code(): string
1380
-    {
1381
-        return $this->prettyTotal();
1382
-    }
1383
-
1384
-
1385
-    /**
1386
-     * @return string like '2, 004.00', formatted according to the localized currency
1387
-     * @throws EE_Error
1388
-     * @throws ReflectionException
1389
-     * @since 5.0.0.p
1390
-     */
1391
-    public function prettyTotal(): string
1392
-    {
1393
-        return $this->get_pretty('LIN_total', 'no_currency_code');
1394
-    }
1395
-
1396
-
1397
-    /**
1398
-     * Gets the final total on this item, taking taxes into account.
1399
-     * Has the side effect of setting the sub-total as it was just calculated.
1400
-     * If this is used on a grand-total line item, also updates the transaction's
1401
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
1402
-     * want to change a persistable transaction with info from a non-persistent line item)
1403
-     *
1404
-     * @param bool $update_txn_status
1405
-     * @return float
1406
-     * @throws EE_Error
1407
-     * @throws InvalidArgumentException
1408
-     * @throws InvalidDataTypeException
1409
-     * @throws InvalidInterfaceException
1410
-     * @throws ReflectionException
1411
-     * @throws RuntimeException
1412
-     */
1413
-    public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1414
-    {
1415
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1416
-        $grand_total_line_item->ensureLineItemsAreSaved();
1417
-        return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1418
-    }
1419
-
1420
-
1421
-    /**
1422
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1423
-     * tax-sub-totals (they're an odd beast). Updates the 'total' on each line item according to either its
1424
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1425
-     * when this is called on the grand total
1426
-     *
1427
-     * @return float
1428
-     * @throws EE_Error
1429
-     * @throws InvalidArgumentException
1430
-     * @throws InvalidDataTypeException
1431
-     * @throws InvalidInterfaceException
1432
-     * @throws ReflectionException
1433
-     */
1434
-    public function recalculate_pre_tax_total(): float
1435
-    {
1436
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1437
-        $grand_total_line_item->ensureLineItemsAreSaved();
1438
-        [$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1439
-        return (float) $total;
1440
-    }
1441
-
1442
-
1443
-    /**
1444
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1445
-     * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1446
-     * and tax sub-total if already in the DB
1447
-     *
1448
-     * @return float
1449
-     * @throws EE_Error
1450
-     * @throws InvalidArgumentException
1451
-     * @throws InvalidDataTypeException
1452
-     * @throws InvalidInterfaceException
1453
-     * @throws ReflectionException
1454
-     */
1455
-    public function recalculate_taxes_and_tax_total(): float
1456
-    {
1457
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1458
-        $grand_total_line_item->ensureLineItemsAreSaved();
1459
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1460
-    }
1461
-
1462
-
1463
-    /**
1464
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
1465
-     * recalculate_taxes_and_total
1466
-     *
1467
-     * @return float
1468
-     * @throws EE_Error
1469
-     * @throws InvalidArgumentException
1470
-     * @throws InvalidDataTypeException
1471
-     * @throws InvalidInterfaceException
1472
-     * @throws ReflectionException
1473
-     */
1474
-    public function get_total_tax(): float
1475
-    {
1476
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1477
-        $grand_total_line_item->ensureLineItemsAreSaved();
1478
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1479
-    }
1480
-
1481
-
1482
-    /**
1483
-     * Gets the total for all the items purchased only
1484
-     *
1485
-     * @return float
1486
-     * @throws EE_Error
1487
-     * @throws InvalidArgumentException
1488
-     * @throws InvalidDataTypeException
1489
-     * @throws InvalidInterfaceException
1490
-     * @throws ReflectionException
1491
-     */
1492
-    public function get_items_total()
1493
-    {
1494
-        // by default, let's make sure we're consistent with the existing line item
1495
-        if ($this->is_total()) {
1496
-            return $this->pretaxTotal();
1497
-        }
1498
-        $total = 0;
1499
-        foreach ($this->get_items() as $item) {
1500
-            if ($item instanceof EE_Line_Item) {
1501
-                $total += $item->pretaxTotal();
1502
-            }
1503
-        }
1504
-        return $total;
1505
-    }
1506
-
1507
-
1508
-    /**
1509
-     * Gets all the descendants (ie, children or children of children etc.) that
1510
-     * are of the type 'tax'
1511
-     *
1512
-     * @return EE_Line_Item[]
1513
-     * @throws EE_Error
1514
-     * @throws ReflectionException
1515
-     */
1516
-    public function tax_descendants(): array
1517
-    {
1518
-        return EEH_Line_Item::get_tax_descendants($this);
1519
-    }
1520
-
1521
-
1522
-    /**
1523
-     * Gets all the real items purchased which are children of this item
1524
-     *
1525
-     * @return EE_Line_Item[]
1526
-     * @throws EE_Error
1527
-     * @throws ReflectionException
1528
-     */
1529
-    public function get_items(): array
1530
-    {
1531
-        return EEH_Line_Item::get_line_item_descendants($this);
1532
-    }
1533
-
1534
-
1535
-    /**
1536
-     * Returns the amount taxable among this line item's children (or if it has no children,
1537
-     * how much of it is taxable). Does not recalculate totals or subtotals.
1538
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
1539
-     * but there is a "Taxable" discount), returns 0.
1540
-     *
1541
-     * @return float
1542
-     * @throws EE_Error
1543
-     * @throws InvalidArgumentException
1544
-     * @throws InvalidDataTypeException
1545
-     * @throws InvalidInterfaceException
1546
-     * @throws ReflectionException
1547
-     */
1548
-    public function taxable_total(): float
1549
-    {
1550
-        $this->ensureLineItemsAreSaved();
1551
-        return $this->calculator->taxableAmountForGlobalTaxes($this);
1552
-    }
1553
-
1554
-
1555
-    /**
1556
-     * Gets the transaction for this line item
1557
-     *
1558
-     * @return EE_Transaction|null
1559
-     * @throws EE_Error
1560
-     * @throws InvalidArgumentException
1561
-     * @throws InvalidDataTypeException
1562
-     * @throws InvalidInterfaceException
1563
-     * @throws ReflectionException
1564
-     */
1565
-    public function transaction(): ?EE_Transaction
1566
-    {
1567
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1568
-    }
1569
-
1570
-
1571
-    /**
1572
-     * Saves this line item to the DB, and recursively saves its descendants.
1573
-     * Because there currently is no proper parent-child relation on the model,
1574
-     * save_this_and_cached() will NOT save the descendants.
1575
-     * Also sets the transaction on this line item and all its descendants before saving
1576
-     *
1577
-     * @param int|null $txn_id if none is provided, assumes $this->TXN_ID()
1578
-     * @return int count of items saved
1579
-     * @throws EE_Error
1580
-     * @throws InvalidArgumentException
1581
-     * @throws InvalidDataTypeException
1582
-     * @throws InvalidInterfaceException
1583
-     * @throws ReflectionException
1584
-     */
1585
-    public function save_this_and_descendants_to_txn(int $txn_id = 0): int
1586
-    {
1587
-        $count = 0;
1588
-        if ($txn_id) {
1589
-            $this->set_TXN_ID($txn_id);
1590
-        }
1591
-        $children = $this->children();
1592
-        $count    += $this->save() ? 1 : 0;
1593
-        foreach ($children as $child_line_item) {
1594
-            if ($child_line_item instanceof EE_Line_Item) {
1595
-                $child_line_item->set_parent_ID($this->ID());
1596
-                $count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1597
-            }
1598
-        }
1599
-        return $count;
1600
-    }
1601
-
1602
-
1603
-    /**
1604
-     * Saves this line item to the DB, and recursively saves its descendants.
1605
-     *
1606
-     * @return int count of items saved
1607
-     * @throws EE_Error
1608
-     * @throws InvalidArgumentException
1609
-     * @throws InvalidDataTypeException
1610
-     * @throws InvalidInterfaceException
1611
-     * @throws ReflectionException
1612
-     */
1613
-    public function save_this_and_descendants(): int
1614
-    {
1615
-        $count    = 0;
1616
-        $children = $this->children();
1617
-        $count    += $this->save() ? 1 : 0;
1618
-        foreach ($children as $child_line_item) {
1619
-            if ($child_line_item instanceof EE_Line_Item) {
1620
-                $child_line_item->set_parent_ID($this->ID());
1621
-                $count += $child_line_item->save_this_and_descendants();
1622
-            }
1623
-        }
1624
-        return $count;
1625
-    }
1626
-
1627
-
1628
-    /**
1629
-     * returns the cancellation line item if this item was cancelled
1630
-     *
1631
-     * @return EE_Line_Item[]
1632
-     * @throws InvalidArgumentException
1633
-     * @throws InvalidInterfaceException
1634
-     * @throws InvalidDataTypeException
1635
-     * @throws ReflectionException
1636
-     * @throws EE_Error
1637
-     */
1638
-    public function get_cancellations(): array
1639
-    {
1640
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1641
-    }
1642
-
1643
-
1644
-    /**
1645
-     * If this item has an ID, then this saves it again to update the db
1646
-     *
1647
-     * @return bool|int count of items saved or false on error
1648
-     * @throws EE_Error
1649
-     * @throws InvalidArgumentException
1650
-     * @throws InvalidDataTypeException
1651
-     * @throws InvalidInterfaceException
1652
-     * @throws ReflectionException
1653
-     */
1654
-    public function maybe_save()
1655
-    {
1656
-        if ($this->ID()) {
1657
-            return $this->save();
1658
-        }
1659
-        return false;
1660
-    }
1661
-
1662
-
1663
-    /**
1664
-     * clears the cached children and parent from the line item
1665
-     *
1666
-     * @return void
1667
-     */
1668
-    public function clear_related_line_item_cache()
1669
-    {
1670
-        $this->resetChildren();
1671
-        $this->_parent   = null;
1672
-    }
1673
-
1674
-
1675
-    /**
1676
-     * @param bool $raw
1677
-     * @return int|string
1678
-     * @throws EE_Error
1679
-     * @throws InvalidArgumentException
1680
-     * @throws InvalidDataTypeException
1681
-     * @throws InvalidInterfaceException
1682
-     * @throws ReflectionException
1683
-     */
1684
-    public function timestamp(bool $raw = false)
1685
-    {
1686
-        return $raw
1687
-            ? (int) $this->get_raw('LIN_timestamp')
1688
-            : (string) $this->get('LIN_timestamp');
1689
-    }
1690
-
1691
-
1692
-    /**
1693
-     * @return void
1694
-     * @throws EE_Error
1695
-     * @throws ReflectionException
1696
-     * @since 5.0.25.p
1697
-     */
1698
-    private function ensureLineItemsAreSaved()
1699
-    {
1700
-        if (! $this->ID()) {
1701
-            $this->save();
1702
-        }
1703
-        $children = $this->children();
1704
-        foreach ($children as $child_line_item) {
1705
-            $child_line_item->ensureLineItemsAreSaved();
1706
-        }
1707
-    }
1708
-
1709
-
1710
-
1711
-
1712
-    /************************* DEPRECATED *************************/
1713
-    /**
1714
-     * @param string $type one of the constants on EEM_Line_Item
1715
-     * @return EE_Line_Item[]
1716
-     * @throws EE_Error
1717
-     * @throws ReflectionException
1718
-     * @deprecated 4.6.0
1719
-     */
1720
-    protected function _get_descendants_of_type(string $type): array
1721
-    {
1722
-        EE_Error::doing_it_wrong(
1723
-            'EE_Line_Item::_get_descendants_of_type()',
1724
-            sprintf(
1725
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1726
-                'EEH_Line_Item::get_descendants_of_type()'
1727
-            ),
1728
-            '4.6.0'
1729
-        );
1730
-        return EEH_Line_Item::get_descendants_of_type($this, $type);
1731
-    }
1732
-
1733
-
1734
-    /**
1735
-     * @param string $type like one of the EEM_Line_Item::type_*
1736
-     * @return EE_Line_Item
1737
-     * @throws EE_Error
1738
-     * @throws InvalidArgumentException
1739
-     * @throws InvalidDataTypeException
1740
-     * @throws InvalidInterfaceException
1741
-     * @throws ReflectionException
1742
-     * @deprecated 4.6.0
1743
-     */
1744
-    public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1745
-    {
1746
-        EE_Error::doing_it_wrong(
1747
-            'EE_Line_Item::get_nearest_descendant_of_type()',
1748
-            sprintf(
1749
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1750
-                'EEH_Line_Item::get_nearest_descendant_of_type()'
1751
-            ),
1752
-            '4.6.0'
1753
-        );
1754
-        return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1755
-    }
19
+	/**
20
+	 * for children line items (currently not a normal relation)
21
+	 *
22
+	 * @var EE_Line_Item[]
23
+	 */
24
+	protected array $_children = [];
25
+
26
+	/**
27
+	 * query params used to obtain children line items above
28
+	 *
29
+	 * @var array
30
+	 */
31
+	private array $children_query_params = [];
32
+
33
+	/**
34
+	 * for the parent line item
35
+	 *
36
+	 * @var EE_Line_Item|null
37
+	 */
38
+	protected ?EE_Line_Item $_parent = null;
39
+
40
+	/**
41
+	 * @var LineItemCalculator
42
+	 */
43
+	protected LineItemCalculator $calculator;
44
+
45
+
46
+	/**
47
+	 * @param array       $props_n_values incoming values
48
+	 * @param string|null $timezone       incoming timezone as set by the model.
49
+	 *                                    If not set the timezone for the website will be used.
50
+	 * @param array       $date_formats   incoming date_formats in an array where the first value is the
51
+	 *                                    date_format and the second value is the time format
52
+	 * @return EE_Line_Item
53
+	 * @throws EE_Error
54
+	 * @throws InvalidArgumentException
55
+	 * @throws InvalidDataTypeException
56
+	 * @throws InvalidInterfaceException
57
+	 * @throws ReflectionException
58
+	 */
59
+	public static function new_instance(
60
+		array $props_n_values = [],
61
+		?string $timezone = '',
62
+		array $date_formats = []
63
+	): EE_Line_Item {
64
+		$has_object = parent::_check_for_object(
65
+			$props_n_values,
66
+			__CLASS__,
67
+			$timezone,
68
+			$date_formats
69
+		);
70
+		return $has_object ?: new self($props_n_values, false, $timezone);
71
+	}
72
+
73
+
74
+	/**
75
+	 * @param array       $props_n_values incoming values from the database
76
+	 * @param string|null $timezone       incoming timezone as set by the model.
77
+	 *                                    If not set the timezone for the website will be used.
78
+	 * @return EE_Line_Item
79
+	 * @throws EE_Error
80
+	 * @throws InvalidArgumentException
81
+	 * @throws InvalidDataTypeException
82
+	 * @throws InvalidInterfaceException
83
+	 * @throws ReflectionException
84
+	 */
85
+	public static function new_instance_from_db(array $props_n_values = [], ?string $timezone = ''): EE_Line_Item
86
+	{
87
+		return new self($props_n_values, true, $timezone);
88
+	}
89
+
90
+
91
+	/**
92
+	 * Adds some defaults if they're not specified
93
+	 *
94
+	 * @param array  $fieldValues
95
+	 * @param bool   $bydb
96
+	 * @param string $timezone
97
+	 * @throws EE_Error
98
+	 * @throws InvalidArgumentException
99
+	 * @throws InvalidDataTypeException
100
+	 * @throws InvalidInterfaceException
101
+	 * @throws ReflectionException
102
+	 */
103
+	protected function __construct($fieldValues = [], $bydb = false, $timezone = '')
104
+	{
105
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
106
+		parent::__construct($fieldValues, $bydb, $timezone);
107
+		if (! $this->get('LIN_code')) {
108
+			$this->set_code($this->generate_code());
109
+		}
110
+	}
111
+
112
+
113
+	public function __wakeup()
114
+	{
115
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
116
+		parent::__wakeup();
117
+	}
118
+
119
+
120
+	/**
121
+	 * Gets ID
122
+	 *
123
+	 * @return int
124
+	 * @throws EE_Error
125
+	 * @throws InvalidArgumentException
126
+	 * @throws InvalidDataTypeException
127
+	 * @throws InvalidInterfaceException
128
+	 * @throws ReflectionException
129
+	 */
130
+	public function ID(): int
131
+	{
132
+		return (int) $this->get('LIN_ID');
133
+	}
134
+
135
+
136
+	/**
137
+	 * Gets TXN_ID
138
+	 *
139
+	 * @return int
140
+	 * @throws EE_Error
141
+	 * @throws InvalidArgumentException
142
+	 * @throws InvalidDataTypeException
143
+	 * @throws InvalidInterfaceException
144
+	 * @throws ReflectionException
145
+	 */
146
+	public function TXN_ID(): int
147
+	{
148
+		return (int) $this->get('TXN_ID');
149
+	}
150
+
151
+
152
+	/**
153
+	 * Sets TXN_ID
154
+	 *
155
+	 * @param int $TXN_ID
156
+	 * @throws EE_Error
157
+	 * @throws InvalidArgumentException
158
+	 * @throws InvalidDataTypeException
159
+	 * @throws InvalidInterfaceException
160
+	 * @throws ReflectionException
161
+	 */
162
+	public function set_TXN_ID(int $TXN_ID)
163
+	{
164
+		$this->set('TXN_ID', $TXN_ID);
165
+	}
166
+
167
+
168
+	/**
169
+	 * Gets name
170
+	 *
171
+	 * @return string
172
+	 * @throws EE_Error
173
+	 * @throws InvalidArgumentException
174
+	 * @throws InvalidDataTypeException
175
+	 * @throws InvalidInterfaceException
176
+	 * @throws ReflectionException
177
+	 */
178
+	public function name(): string
179
+	{
180
+		$name = (string) $this->get('LIN_name');
181
+		if (! $name) {
182
+			$name = ucwords(str_replace('-', ' ', $this->type()));
183
+		}
184
+		return $name;
185
+	}
186
+
187
+
188
+	/**
189
+	 * Sets name
190
+	 *
191
+	 * @param string $name
192
+	 * @throws EE_Error
193
+	 * @throws InvalidArgumentException
194
+	 * @throws InvalidDataTypeException
195
+	 * @throws InvalidInterfaceException
196
+	 * @throws ReflectionException
197
+	 */
198
+	public function set_name(string $name)
199
+	{
200
+		$this->set('LIN_name', $name);
201
+	}
202
+
203
+
204
+	/**
205
+	 * Gets desc
206
+	 *
207
+	 * @return string
208
+	 * @throws EE_Error
209
+	 * @throws InvalidArgumentException
210
+	 * @throws InvalidDataTypeException
211
+	 * @throws InvalidInterfaceException
212
+	 * @throws ReflectionException
213
+	 */
214
+	public function desc(): string
215
+	{
216
+		return (string) $this->get('LIN_desc');
217
+	}
218
+
219
+
220
+	/**
221
+	 * Sets desc
222
+	 *
223
+	 * @param string $desc
224
+	 * @throws EE_Error
225
+	 * @throws InvalidArgumentException
226
+	 * @throws InvalidDataTypeException
227
+	 * @throws InvalidInterfaceException
228
+	 * @throws ReflectionException
229
+	 */
230
+	public function set_desc(string $desc)
231
+	{
232
+		$this->set('LIN_desc', $desc);
233
+	}
234
+
235
+
236
+	/**
237
+	 * Gets quantity
238
+	 *
239
+	 * @return int
240
+	 * @throws EE_Error
241
+	 * @throws InvalidArgumentException
242
+	 * @throws InvalidDataTypeException
243
+	 * @throws InvalidInterfaceException
244
+	 * @throws ReflectionException
245
+	 */
246
+	public function quantity(): int
247
+	{
248
+		return (int) $this->get('LIN_quantity');
249
+	}
250
+
251
+
252
+	/**
253
+	 * Sets quantity
254
+	 *
255
+	 * @param int $quantity
256
+	 * @throws EE_Error
257
+	 * @throws InvalidArgumentException
258
+	 * @throws InvalidDataTypeException
259
+	 * @throws InvalidInterfaceException
260
+	 * @throws ReflectionException
261
+	 */
262
+	public function set_quantity(int $quantity)
263
+	{
264
+		$this->set('LIN_quantity', max($quantity, 0));
265
+	}
266
+
267
+
268
+	/**
269
+	 * Gets item_id
270
+	 *
271
+	 * @return int
272
+	 * @throws EE_Error
273
+	 * @throws InvalidArgumentException
274
+	 * @throws InvalidDataTypeException
275
+	 * @throws InvalidInterfaceException
276
+	 * @throws ReflectionException
277
+	 */
278
+	public function OBJ_ID(): int
279
+	{
280
+		return (int) $this->get('OBJ_ID');
281
+	}
282
+
283
+
284
+	/**
285
+	 * Sets item_id
286
+	 *
287
+	 * @param int $item_id
288
+	 * @throws EE_Error
289
+	 * @throws InvalidArgumentException
290
+	 * @throws InvalidDataTypeException
291
+	 * @throws InvalidInterfaceException
292
+	 * @throws ReflectionException
293
+	 */
294
+	public function set_OBJ_ID(int $item_id)
295
+	{
296
+		$this->set('OBJ_ID', $item_id);
297
+	}
298
+
299
+
300
+	/**
301
+	 * Gets item_type
302
+	 *
303
+	 * @return string
304
+	 * @throws EE_Error
305
+	 * @throws InvalidArgumentException
306
+	 * @throws InvalidDataTypeException
307
+	 * @throws InvalidInterfaceException
308
+	 * @throws ReflectionException
309
+	 */
310
+	public function OBJ_type(): string
311
+	{
312
+		return (string) $this->get('OBJ_type');
313
+	}
314
+
315
+
316
+	/**
317
+	 * Gets item_type
318
+	 *
319
+	 * @return string
320
+	 * @throws EE_Error
321
+	 * @throws InvalidArgumentException
322
+	 * @throws InvalidDataTypeException
323
+	 * @throws InvalidInterfaceException
324
+	 * @throws ReflectionException
325
+	 */
326
+	public function OBJ_type_i18n(): string
327
+	{
328
+		$obj_type = $this->OBJ_type();
329
+		switch ($obj_type) {
330
+			case EEM_Line_Item::OBJ_TYPE_EVENT:
331
+				$obj_type = esc_html__('Event', 'event_espresso');
332
+				break;
333
+			case EEM_Line_Item::OBJ_TYPE_PRICE:
334
+				$obj_type = esc_html__('Price', 'event_espresso');
335
+				break;
336
+			case EEM_Line_Item::OBJ_TYPE_PROMOTION:
337
+				$obj_type = esc_html__('Promotion', 'event_espresso');
338
+				break;
339
+			case EEM_Line_Item::OBJ_TYPE_TICKET:
340
+				$obj_type = esc_html__('Ticket', 'event_espresso');
341
+				break;
342
+			case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
343
+				$obj_type = esc_html__('Transaction', 'event_espresso');
344
+				break;
345
+		}
346
+		return (string) apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
347
+	}
348
+
349
+
350
+	/**
351
+	 * Sets item_type
352
+	 *
353
+	 * @param string $OBJ_type
354
+	 * @throws EE_Error
355
+	 * @throws InvalidArgumentException
356
+	 * @throws InvalidDataTypeException
357
+	 * @throws InvalidInterfaceException
358
+	 * @throws ReflectionException
359
+	 */
360
+	public function set_OBJ_type(string $OBJ_type)
361
+	{
362
+		$this->set('OBJ_type', $OBJ_type);
363
+	}
364
+
365
+
366
+	/**
367
+	 * Gets unit_price
368
+	 *
369
+	 * @return float
370
+	 * @throws EE_Error
371
+	 * @throws InvalidArgumentException
372
+	 * @throws InvalidDataTypeException
373
+	 * @throws InvalidInterfaceException
374
+	 * @throws ReflectionException
375
+	 */
376
+	public function unit_price(): float
377
+	{
378
+		return (float) $this->get('LIN_unit_price');
379
+	}
380
+
381
+
382
+	/**
383
+	 * Sets unit_price
384
+	 *
385
+	 * @param int|float $unit_price
386
+	 * @throws EE_Error
387
+	 * @throws InvalidArgumentException
388
+	 * @throws InvalidDataTypeException
389
+	 * @throws InvalidInterfaceException
390
+	 * @throws ReflectionException
391
+	 */
392
+	public function set_unit_price($unit_price)
393
+	{
394
+		$this->set('LIN_unit_price', (float) $unit_price);
395
+	}
396
+
397
+
398
+	/**
399
+	 * Checks if this item is a percentage modifier or not
400
+	 *
401
+	 * @return bool
402
+	 * @throws EE_Error
403
+	 * @throws InvalidArgumentException
404
+	 * @throws InvalidDataTypeException
405
+	 * @throws InvalidInterfaceException
406
+	 * @throws ReflectionException
407
+	 */
408
+	public function is_percent(): bool
409
+	{
410
+		if ($this->is_tax_sub_total()) {
411
+			// tax subtotals HAVE a percent on them, that percentage only applies
412
+			// to taxable items, so it's an exception. Treat it like a flat line item
413
+			return false;
414
+		}
415
+		$unit_price = abs($this->get('LIN_unit_price'));
416
+		$percent    = abs($this->get('LIN_percent'));
417
+		if ($unit_price < .001 && $percent) {
418
+			return true;
419
+		}
420
+		if ($unit_price >= .001 && ! $percent) {
421
+			return false;
422
+		}
423
+		if ($unit_price >= .001 && $percent) {
424
+			throw new EE_Error(
425
+				sprintf(
426
+					esc_html__(
427
+						'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
428
+						'event_espresso'
429
+					),
430
+					$unit_price,
431
+					$percent
432
+				)
433
+			);
434
+		}
435
+		// if they're both 0, assume it's not a percent item
436
+		return false;
437
+	}
438
+
439
+
440
+	/**
441
+	 * Gets percent (between 100-.001)
442
+	 *
443
+	 * @return float
444
+	 * @throws EE_Error
445
+	 * @throws InvalidArgumentException
446
+	 * @throws InvalidDataTypeException
447
+	 * @throws InvalidInterfaceException
448
+	 * @throws ReflectionException
449
+	 */
450
+	public function percent(): float
451
+	{
452
+		return (float) $this->get('LIN_percent');
453
+	}
454
+
455
+
456
+	/**
457
+	 * @return string
458
+	 * @throws EE_Error
459
+	 * @throws ReflectionException
460
+	 * @since 5.0.0.p
461
+	 */
462
+	public function prettyPercent(): string
463
+	{
464
+		return (string) $this->get_pretty('LIN_percent');
465
+	}
466
+
467
+
468
+	/**
469
+	 * Sets percent (between 100-0.01)
470
+	 *
471
+	 * @param int|float $percent
472
+	 * @throws EE_Error
473
+	 * @throws InvalidArgumentException
474
+	 * @throws InvalidDataTypeException
475
+	 * @throws InvalidInterfaceException
476
+	 * @throws ReflectionException
477
+	 */
478
+	public function set_percent($percent)
479
+	{
480
+		$this->set('LIN_percent', (float) $percent);
481
+	}
482
+
483
+
484
+	/**
485
+	 * Gets total
486
+	 *
487
+	 * @return float
488
+	 * @throws EE_Error
489
+	 * @throws InvalidArgumentException
490
+	 * @throws InvalidDataTypeException
491
+	 * @throws InvalidInterfaceException
492
+	 * @throws ReflectionException
493
+	 */
494
+	public function pretaxTotal(): float
495
+	{
496
+		return (float) $this->get('LIN_pretax');
497
+	}
498
+
499
+
500
+	/**
501
+	 * Sets total
502
+	 *
503
+	 * @param int|float $pretax_total
504
+	 * @throws EE_Error
505
+	 * @throws InvalidArgumentException
506
+	 * @throws InvalidDataTypeException
507
+	 * @throws InvalidInterfaceException
508
+	 * @throws ReflectionException
509
+	 */
510
+	public function setPretaxTotal($pretax_total)
511
+	{
512
+		$this->set('LIN_pretax', (float) $pretax_total);
513
+	}
514
+
515
+
516
+	/**
517
+	 * @return float
518
+	 * @throws EE_Error
519
+	 * @throws ReflectionException
520
+	 * @since  5.0.0.p
521
+	 */
522
+	public function totalWithTax(): float
523
+	{
524
+		return (float) $this->get('LIN_total');
525
+	}
526
+
527
+
528
+	/**
529
+	 * Sets total
530
+	 *
531
+	 * @param int|float $total
532
+	 * @throws EE_Error
533
+	 * @throws ReflectionException
534
+	 * @since  5.0.0.p
535
+	 */
536
+	public function setTotalWithTax($total)
537
+	{
538
+		$this->set('LIN_total', (float) $total);
539
+	}
540
+
541
+
542
+	/**
543
+	 * Gets total
544
+	 *
545
+	 * @return float
546
+	 * @throws EE_Error
547
+	 * @throws ReflectionException
548
+	 * @deprecatd 5.0.0.p
549
+	 */
550
+	public function total(): float
551
+	{
552
+		return $this->totalWithTax();
553
+	}
554
+
555
+
556
+	/**
557
+	 * Sets total
558
+	 *
559
+	 * @param int|float $total
560
+	 * @throws EE_Error
561
+	 * @throws ReflectionException
562
+	 * @deprecatd 5.0.0.p
563
+	 */
564
+	public function set_total($total)
565
+	{
566
+		$this->setTotalWithTax((float) $total);
567
+	}
568
+
569
+
570
+	/**
571
+	 * Gets order
572
+	 *
573
+	 * @return int
574
+	 * @throws EE_Error
575
+	 * @throws InvalidArgumentException
576
+	 * @throws InvalidDataTypeException
577
+	 * @throws InvalidInterfaceException
578
+	 * @throws ReflectionException
579
+	 */
580
+	public function order(): int
581
+	{
582
+		return (int) $this->get('LIN_order');
583
+	}
584
+
585
+
586
+	/**
587
+	 * Sets order
588
+	 *
589
+	 * @param int $order
590
+	 * @throws EE_Error
591
+	 * @throws InvalidArgumentException
592
+	 * @throws InvalidDataTypeException
593
+	 * @throws InvalidInterfaceException
594
+	 * @throws ReflectionException
595
+	 */
596
+	public function set_order(int $order)
597
+	{
598
+		$this->set('LIN_order', $order);
599
+	}
600
+
601
+
602
+	/**
603
+	 * Gets parent
604
+	 *
605
+	 * @return int
606
+	 * @throws EE_Error
607
+	 * @throws InvalidArgumentException
608
+	 * @throws InvalidDataTypeException
609
+	 * @throws InvalidInterfaceException
610
+	 * @throws ReflectionException
611
+	 */
612
+	public function parent_ID(): int
613
+	{
614
+		return (int) $this->get('LIN_parent');
615
+	}
616
+
617
+
618
+	/**
619
+	 * Sets parent
620
+	 *
621
+	 * @param int $parent
622
+	 * @throws EE_Error
623
+	 * @throws InvalidArgumentException
624
+	 * @throws InvalidDataTypeException
625
+	 * @throws InvalidInterfaceException
626
+	 * @throws ReflectionException
627
+	 */
628
+	public function set_parent_ID(int $parent)
629
+	{
630
+		$this->set('LIN_parent', $parent);
631
+	}
632
+
633
+
634
+	/**
635
+	 * Gets type
636
+	 *
637
+	 * @return string
638
+	 * @throws EE_Error
639
+	 * @throws InvalidArgumentException
640
+	 * @throws InvalidDataTypeException
641
+	 * @throws InvalidInterfaceException
642
+	 * @throws ReflectionException
643
+	 */
644
+	public function type(): string
645
+	{
646
+		return (string) $this->get('LIN_type');
647
+	}
648
+
649
+
650
+	/**
651
+	 * Sets type
652
+	 *
653
+	 * @param string $type
654
+	 * @throws EE_Error
655
+	 * @throws InvalidArgumentException
656
+	 * @throws InvalidDataTypeException
657
+	 * @throws InvalidInterfaceException
658
+	 * @throws ReflectionException
659
+	 */
660
+	public function set_type(string $type)
661
+	{
662
+		$this->set('LIN_type', $type);
663
+	}
664
+
665
+
666
+	/**
667
+	 * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
668
+	 * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
669
+	 * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
670
+	 * or indirectly by `EE_Line_item::add_child_line_item()`)
671
+	 *
672
+	 * @return EE_Line_Item|null
673
+	 * @throws EE_Error
674
+	 * @throws InvalidArgumentException
675
+	 * @throws InvalidDataTypeException
676
+	 * @throws InvalidInterfaceException
677
+	 * @throws ReflectionException
678
+	 */
679
+	public function parent(): ?EE_Line_Item
680
+	{
681
+		if (! $this->_parent instanceof EE_Line_Item) {
682
+			$this->_parent = $this->ID()
683
+				? $this->get_model()->get_one_by_ID($this->parent_ID())
684
+				: $this->_parent;
685
+		}
686
+		return $this->_parent;
687
+	}
688
+
689
+
690
+	/**
691
+	 * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
692
+	 *
693
+	 * @return EE_Line_Item[]
694
+	 * @throws EE_Error
695
+	 * @throws InvalidArgumentException
696
+	 * @throws InvalidDataTypeException
697
+	 * @throws InvalidInterfaceException
698
+	 * @throws ReflectionException
699
+	 */
700
+	public function children(array $query_params = []): array
701
+	{
702
+		// check if the query params have changed since the last time we ran this query
703
+		$new_params = ! empty(EEH_Array::array_diff_recursive($query_params, $this->children_query_params));
704
+		if (($new_params || empty($this->_children)) && $this->ID()) {
705
+			$this->children_query_params = $query_params;
706
+			// ensure where params are an array
707
+			$query_params[0] = isset($query_params[0]) && is_array($query_params[0]) ? $query_params[0] : [];
708
+			// add defaults for line item parent and orderby
709
+			$query_params[0] += ['LIN_parent' => $this->ID()];
710
+			$query_params    += ['order_by' => ['LIN_order' => 'ASC']];
711
+			$children = $this->get_model()->get_all($query_params);
712
+			foreach ($children as $child) {
713
+				if ($child instanceof EE_Line_Item) {
714
+					$this->addLineItemToChildren($child);
715
+				}
716
+			}
717
+		}
718
+		return $this->_children;
719
+	}
720
+
721
+
722
+	private function addLineItemToChildren($child_line_item)
723
+	{
724
+		$this->_children[ $child_line_item->code() ] = $child_line_item;
725
+	}
726
+
727
+
728
+	private function getChildLineItemFromCache(string $code): ?EE_Line_Item
729
+	{
730
+		return $this->_children[ $code ] ?? null;
731
+	}
732
+
733
+
734
+	private function removeChildLineItemFromCache(string $code): int
735
+	{
736
+		if (isset($this->_children[ $code ])) {
737
+			unset($this->_children[ $code ]);
738
+			return 1;
739
+		}
740
+		return 0;
741
+	}
742
+
743
+
744
+	private function resetChildren()
745
+	{
746
+		$this->_children = [];
747
+	}
748
+
749
+
750
+	/**
751
+	 * Gets code
752
+	 *
753
+	 * @return string
754
+	 * @throws EE_Error
755
+	 * @throws InvalidArgumentException
756
+	 * @throws InvalidDataTypeException
757
+	 * @throws InvalidInterfaceException
758
+	 * @throws ReflectionException
759
+	 */
760
+	public function code(): string
761
+	{
762
+		return (string) $this->get('LIN_code');
763
+	}
764
+
765
+
766
+	/**
767
+	 * Sets code
768
+	 *
769
+	 * @param string $code
770
+	 * @throws EE_Error
771
+	 * @throws InvalidArgumentException
772
+	 * @throws InvalidDataTypeException
773
+	 * @throws InvalidInterfaceException
774
+	 * @throws ReflectionException
775
+	 */
776
+	public function set_code(string $code)
777
+	{
778
+		$this->set('LIN_code', $code);
779
+	}
780
+
781
+
782
+	/**
783
+	 * Gets is_taxable
784
+	 *
785
+	 * @return bool
786
+	 * @throws EE_Error
787
+	 * @throws InvalidArgumentException
788
+	 * @throws InvalidDataTypeException
789
+	 * @throws InvalidInterfaceException
790
+	 * @throws ReflectionException
791
+	 */
792
+	public function is_taxable(): bool
793
+	{
794
+		return (bool) $this->get('LIN_is_taxable');
795
+	}
796
+
797
+
798
+	/**
799
+	 * Sets is_taxable
800
+	 *
801
+	 * @param bool $is_taxable
802
+	 * @throws EE_Error
803
+	 * @throws InvalidArgumentException
804
+	 * @throws InvalidDataTypeException
805
+	 * @throws InvalidInterfaceException
806
+	 * @throws ReflectionException
807
+	 */
808
+	public function set_is_taxable(bool $is_taxable)
809
+	{
810
+		$this->set('LIN_is_taxable', $is_taxable);
811
+	}
812
+
813
+
814
+	/**
815
+	 * @param int $timestamp
816
+	 * @throws EE_Error
817
+	 * @throws ReflectionException
818
+	 * @since 5.0.0.p
819
+	 */
820
+	public function setTimestamp(int $timestamp)
821
+	{
822
+		$this->set('LIN_timestamp', $timestamp);
823
+	}
824
+
825
+
826
+	/**
827
+	 * Gets the object that this model-joins-to.
828
+	 * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
829
+	 * EEM_Promotion_Object
830
+	 *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
831
+	 *
832
+	 * @return EE_Base_Class|null
833
+	 * @throws EE_Error
834
+	 * @throws InvalidArgumentException
835
+	 * @throws InvalidDataTypeException
836
+	 * @throws InvalidInterfaceException
837
+	 * @throws ReflectionException
838
+	 */
839
+	public function get_object(): ?EE_Base_Class
840
+	{
841
+		$model_name_of_related_obj = $this->OBJ_type();
842
+		return $this->get_model()->has_relation($model_name_of_related_obj)
843
+			? $this->get_first_related($model_name_of_related_obj)
844
+			: null;
845
+	}
846
+
847
+
848
+	/**
849
+	 * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
850
+	 * (IE, if this line item is for a price or something else, will return NULL)
851
+	 *
852
+	 * @param array $query_params deprecated 5.0.12.p
853
+	 * @return EE_Ticket|null
854
+	 * @throws EE_Error
855
+	 * @throws ReflectionException
856
+	 */
857
+	public function ticket(array $query_params = []): ?EE_Ticket
858
+	{
859
+		// we're going to assume that when this method is called
860
+		// we always want to receive the attached ticket EVEN if that ticket is archived.
861
+		if(! $this->OBJ_ID() || $this->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
862
+			return null;
863
+		}
864
+		if(empty($query_args)) {
865
+			return EEM_Ticket::instance()->get_one_by_ID($this->OBJ_ID());
866
+		}
867
+		// legacy usage
868
+		$query_params += ['default_where_conditions' => 'none'];
869
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
870
+	}
871
+
872
+
873
+	/**
874
+	 * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
875
+	 *
876
+	 * @return EE_Datetime|null
877
+	 * @throws EE_Error
878
+	 * @throws InvalidArgumentException
879
+	 * @throws InvalidDataTypeException
880
+	 * @throws InvalidInterfaceException
881
+	 * @throws ReflectionException
882
+	 */
883
+	public function get_ticket_datetime(): ?EE_Datetime
884
+	{
885
+		if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
886
+			$ticket = $this->ticket();
887
+			if ($ticket instanceof EE_Ticket) {
888
+				$datetime = $ticket->first_datetime();
889
+				if ($datetime instanceof EE_Datetime) {
890
+					return $datetime;
891
+				}
892
+			}
893
+		}
894
+		return null;
895
+	}
896
+
897
+
898
+	/**
899
+	 * Gets the event's name that's related to the ticket, if this is for
900
+	 * a ticket
901
+	 *
902
+	 * @return string
903
+	 * @throws EE_Error
904
+	 * @throws InvalidArgumentException
905
+	 * @throws InvalidDataTypeException
906
+	 * @throws InvalidInterfaceException
907
+	 * @throws ReflectionException
908
+	 */
909
+	public function ticket_event_name(): string
910
+	{
911
+		$event_name = esc_html__('Unknown', 'event_espresso');
912
+		$event      = $this->ticket_event();
913
+		if ($event instanceof EE_Event) {
914
+			$event_name = $event->name();
915
+		}
916
+		return $event_name;
917
+	}
918
+
919
+
920
+	/**
921
+	 * Gets the event that's related to the ticket, if this line item represents a ticket.
922
+	 *
923
+	 * @return EE_Event|null
924
+	 * @throws EE_Error
925
+	 * @throws InvalidArgumentException
926
+	 * @throws InvalidDataTypeException
927
+	 * @throws InvalidInterfaceException
928
+	 * @throws ReflectionException
929
+	 */
930
+	public function ticket_event(): ?EE_Event
931
+	{
932
+		$event  = null;
933
+		$ticket = $this->ticket();
934
+		if ($ticket instanceof EE_Ticket) {
935
+			$datetime = $ticket->first_datetime();
936
+			if ($datetime instanceof EE_Datetime) {
937
+				$event = $datetime->event();
938
+			}
939
+		}
940
+		return $event;
941
+	}
942
+
943
+
944
+	/**
945
+	 * Gets the first datetime for this lien item, assuming it's for a ticket
946
+	 *
947
+	 * @param string $date_format
948
+	 * @param string $time_format
949
+	 * @return string
950
+	 * @throws EE_Error
951
+	 * @throws InvalidArgumentException
952
+	 * @throws InvalidDataTypeException
953
+	 * @throws InvalidInterfaceException
954
+	 * @throws ReflectionException
955
+	 */
956
+	public function ticket_datetime_start(string $date_format = '', string $time_format = ''): string
957
+	{
958
+		$first_datetime_string = esc_html__('Unknown', 'event_espresso');
959
+		$datetime              = $this->get_ticket_datetime();
960
+		if ($datetime) {
961
+			$first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
962
+		}
963
+		return $first_datetime_string;
964
+	}
965
+
966
+
967
+	/**
968
+	 * Adds the line item as a child to this line item. If there is another child line
969
+	 * item with the same LIN_code, it is overwritten by this new one
970
+	 *
971
+	 * @param EE_Line_Item $line_item
972
+	 * @param bool         $set_order
973
+	 * @return bool success
974
+	 * @throws EE_Error
975
+	 * @throws InvalidArgumentException
976
+	 * @throws InvalidDataTypeException
977
+	 * @throws InvalidInterfaceException
978
+	 * @throws ReflectionException
979
+	 */
980
+	public function add_child_line_item(EE_Line_Item $line_item, bool $set_order = true): bool
981
+	{
982
+		// should we calculate the LIN_order for this line item ?
983
+		if ($set_order || $line_item->order() === null) {
984
+			$line_item->set_order(count($this->children()));
985
+		}
986
+		if ($this->ID()) {
987
+			// check for any duplicate line items (with the same code), if so, this replaces it
988
+			$line_item_with_same_code = $this->get_child_line_item($line_item->code());
989
+			if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
990
+				$this->delete_child_line_item($line_item_with_same_code->code());
991
+			}
992
+			$line_item->set_parent_ID($this->ID());
993
+			if ($this->TXN_ID()) {
994
+				$line_item->set_TXN_ID($this->TXN_ID());
995
+			}
996
+			$this->addLineItemToChildren($line_item);
997
+			return (bool) $line_item->save();
998
+		}
999
+		$this->addLineItemToChildren($line_item);
1000
+		if ($line_item->parent() !== $this) {
1001
+			$line_item->set_parent($this);
1002
+		}
1003
+		return true;
1004
+	}
1005
+
1006
+
1007
+	/**
1008
+	 * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
1009
+	 * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
1010
+	 * However, if this line item is NOT saved to the DB, this just caches the parent on
1011
+	 * the EE_Line_Item::_parent property.
1012
+	 *
1013
+	 * @param EE_Line_Item $line_item
1014
+	 * @throws EE_Error
1015
+	 * @throws InvalidArgumentException
1016
+	 * @throws InvalidDataTypeException
1017
+	 * @throws InvalidInterfaceException
1018
+	 * @throws ReflectionException
1019
+	 */
1020
+	public function set_parent(EE_Line_Item $line_item)
1021
+	{
1022
+		if ($this->ID()) {
1023
+			if (! $line_item->ID()) {
1024
+				$line_item->save();
1025
+			}
1026
+			$this->set_parent_ID($line_item->ID());
1027
+			$this->save();
1028
+		} else {
1029
+			$this->_parent = $line_item;
1030
+			$this->set_parent_ID($line_item->ID());
1031
+		}
1032
+	}
1033
+
1034
+
1035
+	/**
1036
+	 * Gets the child line item as specified by its code. Because this returns an object (by reference)
1037
+	 * you can modify this child line item and the parent (this object) can know about them
1038
+	 * because it also has a reference to that line item
1039
+	 *
1040
+	 * @param string $code
1041
+	 * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
1042
+	 * @throws EE_Error
1043
+	 * @throws InvalidArgumentException
1044
+	 * @throws InvalidDataTypeException
1045
+	 * @throws InvalidInterfaceException
1046
+	 * @throws ReflectionException
1047
+	 */
1048
+	public function get_child_line_item(string $code)
1049
+	{
1050
+		$child = $this->getChildLineItemFromCache($code);
1051
+		if ($child instanceof EE_Line_Item) {
1052
+			return $child;
1053
+		}
1054
+		if ($this->ID()) {
1055
+			return $this->get_model()->get_one(
1056
+				[['LIN_parent' => $this->ID(), 'LIN_code' => $code]]
1057
+			);
1058
+		}
1059
+		return null;
1060
+	}
1061
+
1062
+
1063
+	/**
1064
+	 * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1065
+	 * cached on it)
1066
+	 *
1067
+	 * @return int
1068
+	 * @throws EE_Error
1069
+	 * @throws InvalidArgumentException
1070
+	 * @throws InvalidDataTypeException
1071
+	 * @throws InvalidInterfaceException
1072
+	 * @throws ReflectionException
1073
+	 */
1074
+	public function delete_children_line_items(): int
1075
+	{
1076
+		$count = count($this->_children);
1077
+		$this->resetChildren();
1078
+		return $this->ID() ? (int) $this->get_model()->delete([['LIN_parent' => $this->ID()]]) : $count;
1079
+	}
1080
+
1081
+
1082
+	/**
1083
+	 * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1084
+	 * HAS NOT been saved to the DB, removes the child line item with index $code.
1085
+	 * Also searches through the child's children for a matching line item. However, once a line item has been found
1086
+	 * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1087
+	 * deleted)
1088
+	 *
1089
+	 * @param string $code
1090
+	 * @param bool   $stop_search_once_found
1091
+	 * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1092
+	 *             the DB yet)
1093
+	 * @throws EE_Error
1094
+	 * @throws InvalidArgumentException
1095
+	 * @throws InvalidDataTypeException
1096
+	 * @throws InvalidInterfaceException
1097
+	 * @throws ReflectionException
1098
+	 */
1099
+	public function delete_child_line_item(string $code, bool $stop_search_once_found = true): int
1100
+	{
1101
+		$removed = $this->removeChildLineItemFromCache($code);
1102
+		if ($this->ID()) {
1103
+			$items_deleted = 0;
1104
+			if ($this->code() === $code) {
1105
+				$items_deleted += EEH_Line_Item::delete_all_child_items($this);
1106
+				$items_deleted += (int) $this->delete();
1107
+				if ($stop_search_once_found) {
1108
+					return $items_deleted;
1109
+				}
1110
+			}
1111
+			foreach ($this->children() as $child_line_item) {
1112
+				$items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1113
+			}
1114
+			return $items_deleted;
1115
+		}
1116
+		return $removed;
1117
+	}
1118
+
1119
+
1120
+	/**
1121
+	 * If this line item is in the database, is of the type subtotal, and
1122
+	 * has no children, why do we have it? It should be deleted so this function
1123
+	 * does that
1124
+	 *
1125
+	 * @return bool
1126
+	 * @throws EE_Error
1127
+	 * @throws InvalidArgumentException
1128
+	 * @throws InvalidDataTypeException
1129
+	 * @throws InvalidInterfaceException
1130
+	 * @throws ReflectionException
1131
+	 */
1132
+	public function delete_if_childless_subtotal(): bool
1133
+	{
1134
+		if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1135
+			return $this->delete();
1136
+		}
1137
+		return false;
1138
+	}
1139
+
1140
+
1141
+	/**
1142
+	 * Creates a code and returns a string. doesn't assign the code to this model object
1143
+	 *
1144
+	 * @return string
1145
+	 * @throws EE_Error
1146
+	 * @throws InvalidArgumentException
1147
+	 * @throws InvalidDataTypeException
1148
+	 * @throws InvalidInterfaceException
1149
+	 * @throws ReflectionException
1150
+	 */
1151
+	public function generate_code(): string
1152
+	{
1153
+		// each line item in the cart requires a unique identifier
1154
+		return $this->get('OBJ_type') . '-' . $this->get('OBJ_ID');
1155
+	}
1156
+
1157
+
1158
+	/**
1159
+	 * @return bool
1160
+	 * @throws EE_Error
1161
+	 * @throws InvalidArgumentException
1162
+	 * @throws InvalidDataTypeException
1163
+	 * @throws InvalidInterfaceException
1164
+	 * @throws ReflectionException
1165
+	 */
1166
+	public function isTax(): bool
1167
+	{
1168
+		return $this->type() === EEM_Line_Item::type_tax || $this->type() === EEM_Line_Item::type_sub_tax;
1169
+	}
1170
+
1171
+
1172
+	/**
1173
+	 * @return bool
1174
+	 * @throws EE_Error
1175
+	 * @throws InvalidArgumentException
1176
+	 * @throws InvalidDataTypeException
1177
+	 * @throws InvalidInterfaceException
1178
+	 * @throws ReflectionException
1179
+	 */
1180
+	public function isGlobalTax(): bool
1181
+	{
1182
+		return $this->type() === EEM_Line_Item::type_tax;
1183
+	}
1184
+
1185
+
1186
+	/**
1187
+	 * @return bool
1188
+	 * @throws EE_Error
1189
+	 * @throws InvalidArgumentException
1190
+	 * @throws InvalidDataTypeException
1191
+	 * @throws InvalidInterfaceException
1192
+	 * @throws ReflectionException
1193
+	 */
1194
+	public function isSubTax(): bool
1195
+	{
1196
+		return $this->type() === EEM_Line_Item::type_sub_tax;
1197
+	}
1198
+
1199
+
1200
+	/**
1201
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1202
+	 *
1203
+	 * @return array
1204
+	 * @throws EE_Error
1205
+	 * @throws InvalidArgumentException
1206
+	 * @throws InvalidDataTypeException
1207
+	 * @throws InvalidInterfaceException
1208
+	 * @throws ReflectionException
1209
+	 */
1210
+	public function getSubTaxes(): array
1211
+	{
1212
+		if (! $this->is_line_item()) {
1213
+			return [];
1214
+		}
1215
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1216
+	}
1217
+
1218
+
1219
+	/**
1220
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1221
+	 *
1222
+	 * @return bool
1223
+	 * @throws EE_Error
1224
+	 * @throws InvalidArgumentException
1225
+	 * @throws InvalidDataTypeException
1226
+	 * @throws InvalidInterfaceException
1227
+	 * @throws ReflectionException
1228
+	 */
1229
+	public function hasSubTaxes(): bool
1230
+	{
1231
+		if (! $this->is_line_item()) {
1232
+			return false;
1233
+		}
1234
+		$sub_taxes = $this->getSubTaxes();
1235
+		return ! empty($sub_taxes);
1236
+	}
1237
+
1238
+
1239
+	/**
1240
+	 * @return bool
1241
+	 * @throws EE_Error
1242
+	 * @throws ReflectionException
1243
+	 * @deprecated   5.0.0.p
1244
+	 */
1245
+	public function is_tax(): bool
1246
+	{
1247
+		return $this->isGlobalTax();
1248
+	}
1249
+
1250
+
1251
+	/**
1252
+	 * @return bool
1253
+	 * @throws EE_Error
1254
+	 * @throws InvalidArgumentException
1255
+	 * @throws InvalidDataTypeException
1256
+	 * @throws InvalidInterfaceException
1257
+	 * @throws ReflectionException
1258
+	 */
1259
+	public function is_tax_sub_total(): bool
1260
+	{
1261
+		return $this->type() === EEM_Line_Item::type_tax_sub_total;
1262
+	}
1263
+
1264
+
1265
+	/**
1266
+	 * @return bool
1267
+	 * @throws EE_Error
1268
+	 * @throws InvalidArgumentException
1269
+	 * @throws InvalidDataTypeException
1270
+	 * @throws InvalidInterfaceException
1271
+	 * @throws ReflectionException
1272
+	 */
1273
+	public function is_line_item(): bool
1274
+	{
1275
+		return $this->type() === EEM_Line_Item::type_line_item;
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * @return bool
1281
+	 * @throws EE_Error
1282
+	 * @throws InvalidArgumentException
1283
+	 * @throws InvalidDataTypeException
1284
+	 * @throws InvalidInterfaceException
1285
+	 * @throws ReflectionException
1286
+	 */
1287
+	public function is_sub_line_item(): bool
1288
+	{
1289
+		return $this->type() === EEM_Line_Item::type_sub_line_item;
1290
+	}
1291
+
1292
+
1293
+	/**
1294
+	 * @return bool
1295
+	 * @throws EE_Error
1296
+	 * @throws InvalidArgumentException
1297
+	 * @throws InvalidDataTypeException
1298
+	 * @throws InvalidInterfaceException
1299
+	 * @throws ReflectionException
1300
+	 */
1301
+	public function is_sub_total(): bool
1302
+	{
1303
+		return $this->type() === EEM_Line_Item::type_sub_total;
1304
+	}
1305
+
1306
+
1307
+	/**
1308
+	 * Whether this line item is a cancellation line item
1309
+	 *
1310
+	 * @return bool
1311
+	 * @throws EE_Error
1312
+	 * @throws InvalidArgumentException
1313
+	 * @throws InvalidDataTypeException
1314
+	 * @throws InvalidInterfaceException
1315
+	 * @throws ReflectionException
1316
+	 */
1317
+	public function is_cancellation(): bool
1318
+	{
1319
+		return EEM_Line_Item::type_cancellation === $this->type();
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * @return bool
1325
+	 * @throws EE_Error
1326
+	 * @throws InvalidArgumentException
1327
+	 * @throws InvalidDataTypeException
1328
+	 * @throws InvalidInterfaceException
1329
+	 * @throws ReflectionException
1330
+	 */
1331
+	public function is_total(): bool
1332
+	{
1333
+		return $this->type() === EEM_Line_Item::type_total;
1334
+	}
1335
+
1336
+
1337
+	/**
1338
+	 * @return bool
1339
+	 * @throws EE_Error
1340
+	 * @throws InvalidArgumentException
1341
+	 * @throws InvalidDataTypeException
1342
+	 * @throws InvalidInterfaceException
1343
+	 * @throws ReflectionException
1344
+	 */
1345
+	public function is_cancelled(): bool
1346
+	{
1347
+		return $this->type() === EEM_Line_Item::type_cancellation;
1348
+	}
1349
+
1350
+
1351
+	/**
1352
+	 * @return string like '2, 004.00', formatted according to the localized currency
1353
+	 * @throws EE_Error
1354
+	 * @throws ReflectionException
1355
+	 */
1356
+	public function unit_price_no_code(): string
1357
+	{
1358
+		return $this->prettyUnitPrice();
1359
+	}
1360
+
1361
+
1362
+	/**
1363
+	 * @return string like '2, 004.00', formatted according to the localized currency
1364
+	 * @throws EE_Error
1365
+	 * @throws ReflectionException
1366
+	 * @since 5.0.0.p
1367
+	 */
1368
+	public function prettyUnitPrice(): string
1369
+	{
1370
+		return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1371
+	}
1372
+
1373
+
1374
+	/**
1375
+	 * @return string like '2, 004.00', formatted according to the localized currency
1376
+	 * @throws EE_Error
1377
+	 * @throws ReflectionException
1378
+	 */
1379
+	public function total_no_code(): string
1380
+	{
1381
+		return $this->prettyTotal();
1382
+	}
1383
+
1384
+
1385
+	/**
1386
+	 * @return string like '2, 004.00', formatted according to the localized currency
1387
+	 * @throws EE_Error
1388
+	 * @throws ReflectionException
1389
+	 * @since 5.0.0.p
1390
+	 */
1391
+	public function prettyTotal(): string
1392
+	{
1393
+		return $this->get_pretty('LIN_total', 'no_currency_code');
1394
+	}
1395
+
1396
+
1397
+	/**
1398
+	 * Gets the final total on this item, taking taxes into account.
1399
+	 * Has the side effect of setting the sub-total as it was just calculated.
1400
+	 * If this is used on a grand-total line item, also updates the transaction's
1401
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
1402
+	 * want to change a persistable transaction with info from a non-persistent line item)
1403
+	 *
1404
+	 * @param bool $update_txn_status
1405
+	 * @return float
1406
+	 * @throws EE_Error
1407
+	 * @throws InvalidArgumentException
1408
+	 * @throws InvalidDataTypeException
1409
+	 * @throws InvalidInterfaceException
1410
+	 * @throws ReflectionException
1411
+	 * @throws RuntimeException
1412
+	 */
1413
+	public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1414
+	{
1415
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1416
+		$grand_total_line_item->ensureLineItemsAreSaved();
1417
+		return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1418
+	}
1419
+
1420
+
1421
+	/**
1422
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1423
+	 * tax-sub-totals (they're an odd beast). Updates the 'total' on each line item according to either its
1424
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1425
+	 * when this is called on the grand total
1426
+	 *
1427
+	 * @return float
1428
+	 * @throws EE_Error
1429
+	 * @throws InvalidArgumentException
1430
+	 * @throws InvalidDataTypeException
1431
+	 * @throws InvalidInterfaceException
1432
+	 * @throws ReflectionException
1433
+	 */
1434
+	public function recalculate_pre_tax_total(): float
1435
+	{
1436
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1437
+		$grand_total_line_item->ensureLineItemsAreSaved();
1438
+		[$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1439
+		return (float) $total;
1440
+	}
1441
+
1442
+
1443
+	/**
1444
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1445
+	 * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1446
+	 * and tax sub-total if already in the DB
1447
+	 *
1448
+	 * @return float
1449
+	 * @throws EE_Error
1450
+	 * @throws InvalidArgumentException
1451
+	 * @throws InvalidDataTypeException
1452
+	 * @throws InvalidInterfaceException
1453
+	 * @throws ReflectionException
1454
+	 */
1455
+	public function recalculate_taxes_and_tax_total(): float
1456
+	{
1457
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1458
+		$grand_total_line_item->ensureLineItemsAreSaved();
1459
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1460
+	}
1461
+
1462
+
1463
+	/**
1464
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
1465
+	 * recalculate_taxes_and_total
1466
+	 *
1467
+	 * @return float
1468
+	 * @throws EE_Error
1469
+	 * @throws InvalidArgumentException
1470
+	 * @throws InvalidDataTypeException
1471
+	 * @throws InvalidInterfaceException
1472
+	 * @throws ReflectionException
1473
+	 */
1474
+	public function get_total_tax(): float
1475
+	{
1476
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1477
+		$grand_total_line_item->ensureLineItemsAreSaved();
1478
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1479
+	}
1480
+
1481
+
1482
+	/**
1483
+	 * Gets the total for all the items purchased only
1484
+	 *
1485
+	 * @return float
1486
+	 * @throws EE_Error
1487
+	 * @throws InvalidArgumentException
1488
+	 * @throws InvalidDataTypeException
1489
+	 * @throws InvalidInterfaceException
1490
+	 * @throws ReflectionException
1491
+	 */
1492
+	public function get_items_total()
1493
+	{
1494
+		// by default, let's make sure we're consistent with the existing line item
1495
+		if ($this->is_total()) {
1496
+			return $this->pretaxTotal();
1497
+		}
1498
+		$total = 0;
1499
+		foreach ($this->get_items() as $item) {
1500
+			if ($item instanceof EE_Line_Item) {
1501
+				$total += $item->pretaxTotal();
1502
+			}
1503
+		}
1504
+		return $total;
1505
+	}
1506
+
1507
+
1508
+	/**
1509
+	 * Gets all the descendants (ie, children or children of children etc.) that
1510
+	 * are of the type 'tax'
1511
+	 *
1512
+	 * @return EE_Line_Item[]
1513
+	 * @throws EE_Error
1514
+	 * @throws ReflectionException
1515
+	 */
1516
+	public function tax_descendants(): array
1517
+	{
1518
+		return EEH_Line_Item::get_tax_descendants($this);
1519
+	}
1520
+
1521
+
1522
+	/**
1523
+	 * Gets all the real items purchased which are children of this item
1524
+	 *
1525
+	 * @return EE_Line_Item[]
1526
+	 * @throws EE_Error
1527
+	 * @throws ReflectionException
1528
+	 */
1529
+	public function get_items(): array
1530
+	{
1531
+		return EEH_Line_Item::get_line_item_descendants($this);
1532
+	}
1533
+
1534
+
1535
+	/**
1536
+	 * Returns the amount taxable among this line item's children (or if it has no children,
1537
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
1538
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
1539
+	 * but there is a "Taxable" discount), returns 0.
1540
+	 *
1541
+	 * @return float
1542
+	 * @throws EE_Error
1543
+	 * @throws InvalidArgumentException
1544
+	 * @throws InvalidDataTypeException
1545
+	 * @throws InvalidInterfaceException
1546
+	 * @throws ReflectionException
1547
+	 */
1548
+	public function taxable_total(): float
1549
+	{
1550
+		$this->ensureLineItemsAreSaved();
1551
+		return $this->calculator->taxableAmountForGlobalTaxes($this);
1552
+	}
1553
+
1554
+
1555
+	/**
1556
+	 * Gets the transaction for this line item
1557
+	 *
1558
+	 * @return EE_Transaction|null
1559
+	 * @throws EE_Error
1560
+	 * @throws InvalidArgumentException
1561
+	 * @throws InvalidDataTypeException
1562
+	 * @throws InvalidInterfaceException
1563
+	 * @throws ReflectionException
1564
+	 */
1565
+	public function transaction(): ?EE_Transaction
1566
+	{
1567
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1568
+	}
1569
+
1570
+
1571
+	/**
1572
+	 * Saves this line item to the DB, and recursively saves its descendants.
1573
+	 * Because there currently is no proper parent-child relation on the model,
1574
+	 * save_this_and_cached() will NOT save the descendants.
1575
+	 * Also sets the transaction on this line item and all its descendants before saving
1576
+	 *
1577
+	 * @param int|null $txn_id if none is provided, assumes $this->TXN_ID()
1578
+	 * @return int count of items saved
1579
+	 * @throws EE_Error
1580
+	 * @throws InvalidArgumentException
1581
+	 * @throws InvalidDataTypeException
1582
+	 * @throws InvalidInterfaceException
1583
+	 * @throws ReflectionException
1584
+	 */
1585
+	public function save_this_and_descendants_to_txn(int $txn_id = 0): int
1586
+	{
1587
+		$count = 0;
1588
+		if ($txn_id) {
1589
+			$this->set_TXN_ID($txn_id);
1590
+		}
1591
+		$children = $this->children();
1592
+		$count    += $this->save() ? 1 : 0;
1593
+		foreach ($children as $child_line_item) {
1594
+			if ($child_line_item instanceof EE_Line_Item) {
1595
+				$child_line_item->set_parent_ID($this->ID());
1596
+				$count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1597
+			}
1598
+		}
1599
+		return $count;
1600
+	}
1601
+
1602
+
1603
+	/**
1604
+	 * Saves this line item to the DB, and recursively saves its descendants.
1605
+	 *
1606
+	 * @return int count of items saved
1607
+	 * @throws EE_Error
1608
+	 * @throws InvalidArgumentException
1609
+	 * @throws InvalidDataTypeException
1610
+	 * @throws InvalidInterfaceException
1611
+	 * @throws ReflectionException
1612
+	 */
1613
+	public function save_this_and_descendants(): int
1614
+	{
1615
+		$count    = 0;
1616
+		$children = $this->children();
1617
+		$count    += $this->save() ? 1 : 0;
1618
+		foreach ($children as $child_line_item) {
1619
+			if ($child_line_item instanceof EE_Line_Item) {
1620
+				$child_line_item->set_parent_ID($this->ID());
1621
+				$count += $child_line_item->save_this_and_descendants();
1622
+			}
1623
+		}
1624
+		return $count;
1625
+	}
1626
+
1627
+
1628
+	/**
1629
+	 * returns the cancellation line item if this item was cancelled
1630
+	 *
1631
+	 * @return EE_Line_Item[]
1632
+	 * @throws InvalidArgumentException
1633
+	 * @throws InvalidInterfaceException
1634
+	 * @throws InvalidDataTypeException
1635
+	 * @throws ReflectionException
1636
+	 * @throws EE_Error
1637
+	 */
1638
+	public function get_cancellations(): array
1639
+	{
1640
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1641
+	}
1642
+
1643
+
1644
+	/**
1645
+	 * If this item has an ID, then this saves it again to update the db
1646
+	 *
1647
+	 * @return bool|int count of items saved or false on error
1648
+	 * @throws EE_Error
1649
+	 * @throws InvalidArgumentException
1650
+	 * @throws InvalidDataTypeException
1651
+	 * @throws InvalidInterfaceException
1652
+	 * @throws ReflectionException
1653
+	 */
1654
+	public function maybe_save()
1655
+	{
1656
+		if ($this->ID()) {
1657
+			return $this->save();
1658
+		}
1659
+		return false;
1660
+	}
1661
+
1662
+
1663
+	/**
1664
+	 * clears the cached children and parent from the line item
1665
+	 *
1666
+	 * @return void
1667
+	 */
1668
+	public function clear_related_line_item_cache()
1669
+	{
1670
+		$this->resetChildren();
1671
+		$this->_parent   = null;
1672
+	}
1673
+
1674
+
1675
+	/**
1676
+	 * @param bool $raw
1677
+	 * @return int|string
1678
+	 * @throws EE_Error
1679
+	 * @throws InvalidArgumentException
1680
+	 * @throws InvalidDataTypeException
1681
+	 * @throws InvalidInterfaceException
1682
+	 * @throws ReflectionException
1683
+	 */
1684
+	public function timestamp(bool $raw = false)
1685
+	{
1686
+		return $raw
1687
+			? (int) $this->get_raw('LIN_timestamp')
1688
+			: (string) $this->get('LIN_timestamp');
1689
+	}
1690
+
1691
+
1692
+	/**
1693
+	 * @return void
1694
+	 * @throws EE_Error
1695
+	 * @throws ReflectionException
1696
+	 * @since 5.0.25.p
1697
+	 */
1698
+	private function ensureLineItemsAreSaved()
1699
+	{
1700
+		if (! $this->ID()) {
1701
+			$this->save();
1702
+		}
1703
+		$children = $this->children();
1704
+		foreach ($children as $child_line_item) {
1705
+			$child_line_item->ensureLineItemsAreSaved();
1706
+		}
1707
+	}
1708
+
1709
+
1710
+
1711
+
1712
+	/************************* DEPRECATED *************************/
1713
+	/**
1714
+	 * @param string $type one of the constants on EEM_Line_Item
1715
+	 * @return EE_Line_Item[]
1716
+	 * @throws EE_Error
1717
+	 * @throws ReflectionException
1718
+	 * @deprecated 4.6.0
1719
+	 */
1720
+	protected function _get_descendants_of_type(string $type): array
1721
+	{
1722
+		EE_Error::doing_it_wrong(
1723
+			'EE_Line_Item::_get_descendants_of_type()',
1724
+			sprintf(
1725
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1726
+				'EEH_Line_Item::get_descendants_of_type()'
1727
+			),
1728
+			'4.6.0'
1729
+		);
1730
+		return EEH_Line_Item::get_descendants_of_type($this, $type);
1731
+	}
1732
+
1733
+
1734
+	/**
1735
+	 * @param string $type like one of the EEM_Line_Item::type_*
1736
+	 * @return EE_Line_Item
1737
+	 * @throws EE_Error
1738
+	 * @throws InvalidArgumentException
1739
+	 * @throws InvalidDataTypeException
1740
+	 * @throws InvalidInterfaceException
1741
+	 * @throws ReflectionException
1742
+	 * @deprecated 4.6.0
1743
+	 */
1744
+	public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1745
+	{
1746
+		EE_Error::doing_it_wrong(
1747
+			'EE_Line_Item::get_nearest_descendant_of_type()',
1748
+			sprintf(
1749
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1750
+				'EEH_Line_Item::get_nearest_descendant_of_type()'
1751
+			),
1752
+			'4.6.0'
1753
+		);
1754
+		return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1755
+	}
1756 1756
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
     {
105 105
         $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
106 106
         parent::__construct($fieldValues, $bydb, $timezone);
107
-        if (! $this->get('LIN_code')) {
107
+        if ( ! $this->get('LIN_code')) {
108 108
             $this->set_code($this->generate_code());
109 109
         }
110 110
     }
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
     public function name(): string
179 179
     {
180 180
         $name = (string) $this->get('LIN_name');
181
-        if (! $name) {
181
+        if ( ! $name) {
182 182
             $name = ucwords(str_replace('-', ' ', $this->type()));
183 183
         }
184 184
         return $name;
@@ -678,7 +678,7 @@  discard block
 block discarded – undo
678 678
      */
679 679
     public function parent(): ?EE_Line_Item
680 680
     {
681
-        if (! $this->_parent instanceof EE_Line_Item) {
681
+        if ( ! $this->_parent instanceof EE_Line_Item) {
682 682
             $this->_parent = $this->ID()
683 683
                 ? $this->get_model()->get_one_by_ID($this->parent_ID())
684 684
                 : $this->_parent;
@@ -721,20 +721,20 @@  discard block
 block discarded – undo
721 721
 
722 722
     private function addLineItemToChildren($child_line_item)
723 723
     {
724
-        $this->_children[ $child_line_item->code() ] = $child_line_item;
724
+        $this->_children[$child_line_item->code()] = $child_line_item;
725 725
     }
726 726
 
727 727
 
728 728
     private function getChildLineItemFromCache(string $code): ?EE_Line_Item
729 729
     {
730
-        return $this->_children[ $code ] ?? null;
730
+        return $this->_children[$code] ?? null;
731 731
     }
732 732
 
733 733
 
734 734
     private function removeChildLineItemFromCache(string $code): int
735 735
     {
736
-        if (isset($this->_children[ $code ])) {
737
-            unset($this->_children[ $code ]);
736
+        if (isset($this->_children[$code])) {
737
+            unset($this->_children[$code]);
738 738
             return 1;
739 739
         }
740 740
         return 0;
@@ -858,10 +858,10 @@  discard block
 block discarded – undo
858 858
     {
859 859
         // we're going to assume that when this method is called
860 860
         // we always want to receive the attached ticket EVEN if that ticket is archived.
861
-        if(! $this->OBJ_ID() || $this->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
861
+        if ( ! $this->OBJ_ID() || $this->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
862 862
             return null;
863 863
         }
864
-        if(empty($query_args)) {
864
+        if (empty($query_args)) {
865 865
             return EEM_Ticket::instance()->get_one_by_ID($this->OBJ_ID());
866 866
         }
867 867
         // legacy usage
@@ -1020,7 +1020,7 @@  discard block
 block discarded – undo
1020 1020
     public function set_parent(EE_Line_Item $line_item)
1021 1021
     {
1022 1022
         if ($this->ID()) {
1023
-            if (! $line_item->ID()) {
1023
+            if ( ! $line_item->ID()) {
1024 1024
                 $line_item->save();
1025 1025
             }
1026 1026
             $this->set_parent_ID($line_item->ID());
@@ -1151,7 +1151,7 @@  discard block
 block discarded – undo
1151 1151
     public function generate_code(): string
1152 1152
     {
1153 1153
         // each line item in the cart requires a unique identifier
1154
-        return $this->get('OBJ_type') . '-' . $this->get('OBJ_ID');
1154
+        return $this->get('OBJ_type').'-'.$this->get('OBJ_ID');
1155 1155
     }
1156 1156
 
1157 1157
 
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
      */
1210 1210
     public function getSubTaxes(): array
1211 1211
     {
1212
-        if (! $this->is_line_item()) {
1212
+        if ( ! $this->is_line_item()) {
1213 1213
             return [];
1214 1214
         }
1215 1215
         return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
@@ -1228,7 +1228,7 @@  discard block
 block discarded – undo
1228 1228
      */
1229 1229
     public function hasSubTaxes(): bool
1230 1230
     {
1231
-        if (! $this->is_line_item()) {
1231
+        if ( ! $this->is_line_item()) {
1232 1232
             return false;
1233 1233
         }
1234 1234
         $sub_taxes = $this->getSubTaxes();
@@ -1589,7 +1589,7 @@  discard block
 block discarded – undo
1589 1589
             $this->set_TXN_ID($txn_id);
1590 1590
         }
1591 1591
         $children = $this->children();
1592
-        $count    += $this->save() ? 1 : 0;
1592
+        $count += $this->save() ? 1 : 0;
1593 1593
         foreach ($children as $child_line_item) {
1594 1594
             if ($child_line_item instanceof EE_Line_Item) {
1595 1595
                 $child_line_item->set_parent_ID($this->ID());
@@ -1614,7 +1614,7 @@  discard block
 block discarded – undo
1614 1614
     {
1615 1615
         $count    = 0;
1616 1616
         $children = $this->children();
1617
-        $count    += $this->save() ? 1 : 0;
1617
+        $count += $this->save() ? 1 : 0;
1618 1618
         foreach ($children as $child_line_item) {
1619 1619
             if ($child_line_item instanceof EE_Line_Item) {
1620 1620
                 $child_line_item->set_parent_ID($this->ID());
@@ -1668,7 +1668,7 @@  discard block
 block discarded – undo
1668 1668
     public function clear_related_line_item_cache()
1669 1669
     {
1670 1670
         $this->resetChildren();
1671
-        $this->_parent   = null;
1671
+        $this->_parent = null;
1672 1672
     }
1673 1673
 
1674 1674
 
@@ -1697,7 +1697,7 @@  discard block
 block discarded – undo
1697 1697
      */
1698 1698
     private function ensureLineItemsAreSaved()
1699 1699
     {
1700
-        if (! $this->ID()) {
1700
+        if ( ! $this->ID()) {
1701 1701
             $this->save();
1702 1702
         }
1703 1703
         $children = $this->children();
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +3359 added lines, -3359 removed lines patch added patch discarded remove patch
@@ -16,3374 +16,3374 @@
 block discarded – undo
16 16
 abstract class EE_Base_Class
17 17
 {
18 18
 
19
-    /**
20
-     * @var EEM_Base|null
21
-     */
22
-    protected $_model = null;
23
-
24
-    /**
25
-     * This is an array of the original properties and values provided during construction
26
-     * of this model object. (keys are model field names, values are their values).
27
-     * This list is important to remember so that when we are merging data from the db, we know
28
-     * which values to override and which to not override.
29
-     */
30
-    protected ?array $_props_n_values_provided_in_constructor = null;
31
-
32
-    /**
33
-     * Timezone
34
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
35
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
36
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
37
-     * access to it.
38
-     */
39
-    protected string $_timezone = '';
40
-
41
-    /**
42
-     * date format
43
-     * pattern or format for displaying dates
44
-     */
45
-    protected string $_dt_frmt = '';
46
-
47
-    /**
48
-     * time format
49
-     * pattern or format for displaying time
50
-     */
51
-    protected string $_tm_frmt = '';
52
-
53
-    /**
54
-     * This property is for holding a cached array of object properties indexed by property name as the key.
55
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
56
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
-     */
59
-    protected array $_cached_properties = [];
60
-
61
-    /**
62
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
63
-     * single
64
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
65
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
66
-     * all others have an array)
67
-     */
68
-    protected array $_model_relations = [];
69
-
70
-    /**
71
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
72
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
73
-     */
74
-    protected array $_fields = [];
75
-
76
-    /**
77
-     * indicating whether or not this model object is intended to ever be saved
78
-     * For example, we might create model objects intended to only be used for the duration
79
-     * of this request and to be thrown away, and if they were accidentally saved
80
-     * it would be a bug.
81
-     */
82
-    protected bool $_allow_persist = true;
83
-
84
-    /**
85
-     * indicating whether or not this model object's properties have changed since construction
86
-     */
87
-    protected bool $_has_changes = false;
88
-
89
-    /**
90
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
91
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
92
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
93
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
94
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
95
-     * array as:
96
-     * array(
97
-     *  'Registration_Count' => 24
98
-     * );
99
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
100
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
101
-     * info)
102
-     */
103
-    protected array $custom_selection_results = [];
104
-
105
-
106
-    /**
107
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
108
-     * play nice
109
-     *
110
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
111
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
112
-     *                                                         TXN_amount, QST_name, etc) and values are their values
113
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
114
-     *                                                         corresponding db model or not.
115
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
116
-     *                                                         be in when instantiating a EE_Base_Class object.
117
-     * @param array   $date_formats                            An array of date formats to set on construct where first
118
-     *                                                         value is the date_format and second value is the time
119
-     *                                                         format.
120
-     * @throws InvalidArgumentException
121
-     * @throws InvalidInterfaceException
122
-     * @throws InvalidDataTypeException
123
-     * @throws EE_Error
124
-     * @throws ReflectionException
125
-     */
126
-    protected function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
127
-    {
128
-        $className = get_class($this);
129
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
130
-        $model        = $this->get_model();
131
-        $model_fields = $model->field_settings();
132
-        // ensure $fieldValues is an array
133
-        $fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
134
-        // verify client code has not passed any invalid field names
135
-        foreach ($fieldValues as $field_name => $field_value) {
136
-            if (! isset($model_fields[ $field_name ])) {
137
-                throw new EE_Error(
138
-                    sprintf(
139
-                        esc_html__(
140
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
141
-                            'event_espresso'
142
-                        ),
143
-                        $field_name,
144
-                        get_class($this),
145
-                        implode(', ', array_keys($model_fields))
146
-                    )
147
-                );
148
-            }
149
-        }
150
-
151
-        $date_format     = null;
152
-        $time_format     = null;
153
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
154
-        if (! empty($date_formats) && is_array($date_formats)) {
155
-            [$date_format, $time_format] = $date_formats;
156
-        }
157
-        $this->set_date_format($date_format);
158
-        $this->set_time_format($time_format);
159
-        // if db model is instantiating
160
-        foreach ($model_fields as $fieldName => $field) {
161
-            if ($bydb) {
162
-                // client code has indicated these field values are from the database
163
-                $this->set_from_db(
164
-                    $fieldName,
165
-                    $fieldValues[ $fieldName ] ?? null
166
-                );
167
-            } else {
168
-                // we're constructing a brand new instance of the model object.
169
-                // Generally, this means we'll need to do more field validation
170
-                $this->set(
171
-                    $fieldName,
172
-                    $fieldValues[ $fieldName ] ?? null,
173
-                    true
174
-                );
175
-            }
176
-        }
177
-        // remember what values were passed to this constructor
178
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
179
-        // remember in entity mapper
180
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
181
-            $model->add_to_entity_map($this);
182
-        }
183
-        // setup all the relations
184
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
185
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
186
-                $this->_model_relations[ $relation_name ] = null;
187
-            } else {
188
-                $this->_model_relations[ $relation_name ] = [];
189
-            }
190
-        }
191
-        /**
192
-         * Action done at the end of each model object construction
193
-         *
194
-         * @param EE_Base_Class $this the model object just created
195
-         */
196
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
197
-    }
198
-
199
-
200
-    /**
201
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
202
-     *
203
-     * @return boolean
204
-     */
205
-    public function allow_persist()
206
-    {
207
-        return $this->_allow_persist;
208
-    }
209
-
210
-
211
-    /**
212
-     * Sets whether or not this model object should be allowed to be saved to the DB.
213
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
214
-     * you got new information that somehow made you change your mind.
215
-     *
216
-     * @param boolean $allow_persist
217
-     * @return boolean
218
-     */
219
-    public function set_allow_persist($allow_persist)
220
-    {
221
-        return $this->_allow_persist = $allow_persist;
222
-    }
223
-
224
-
225
-    /**
226
-     * Gets the field's original value when this object was constructed during this request.
227
-     * This can be helpful when determining if a model object has changed or not
228
-     *
229
-     * @param string $field_name
230
-     * @return mixed|null
231
-     * @throws ReflectionException
232
-     * @throws InvalidArgumentException
233
-     * @throws InvalidInterfaceException
234
-     * @throws InvalidDataTypeException
235
-     * @throws EE_Error
236
-     */
237
-    public function get_original($field_name)
238
-    {
239
-        if (
240
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
241
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
242
-        ) {
243
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
244
-        }
245
-        return null;
246
-    }
247
-
248
-
249
-    /**
250
-     * @param EE_Base_Class $obj
251
-     * @return string
252
-     */
253
-    public function get_class($obj)
254
-    {
255
-        return get_class($obj);
256
-    }
257
-
258
-
259
-    /**
260
-     * Overrides parent because parent expects old models.
261
-     * This also doesn't do any validation, and won't work for serialized arrays
262
-     *
263
-     * @param string $field_name
264
-     * @param mixed  $field_value
265
-     * @param bool   $use_default
266
-     * @throws InvalidArgumentException
267
-     * @throws InvalidInterfaceException
268
-     * @throws InvalidDataTypeException
269
-     * @throws EE_Error
270
-     * @throws ReflectionException
271
-     * @throws Exception
272
-     */
273
-    public function set(string $field_name, $field_value, bool $use_default = false)
274
-    {
275
-        // if not using default and nothing has changed, and object has already been setup (has ID),
276
-        // then don't do anything
277
-        if (
278
-            ! $use_default
279
-            && $this->_fields[ $field_name ] === $field_value
280
-            && $this->ID()
281
-        ) {
282
-            return;
283
-        }
284
-        $model              = $this->get_model();
285
-        $this->_has_changes = true;
286
-        $field_obj          = $model->field_settings_for($field_name);
287
-        if (! $field_obj instanceof EE_Model_Field_Base) {
288
-            throw new EE_Error(
289
-                sprintf(
290
-                    esc_html__(
291
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
292
-                        'event_espresso'
293
-                    ),
294
-                    $field_name
295
-                )
296
-            );
297
-        }
298
-        // if ( method_exists( $field_obj, 'set_timezone' )) {
299
-        if ($field_obj instanceof EE_Datetime_Field) {
300
-            $field_obj->set_timezone($this->_timezone);
301
-            $field_obj->set_date_format($this->_dt_frmt);
302
-            $field_obj->set_time_format($this->_tm_frmt);
303
-        }
304
-
305
-        // should the value be null?
306
-        $value = $field_value === null && ($use_default || ! $field_obj->is_nullable())
307
-            ? $field_obj->get_default_value()
308
-            : $field_value;
309
-
310
-        $this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
311
-
312
-        // if we're not in the constructor...
313
-        // now check if what we set was a primary key
314
-        if (
315
-            // note: props_n_values_provided_in_constructor is only set at the END of the constructor
316
-            $this->_props_n_values_provided_in_constructor
317
-            && $field_value
318
-            && $field_name === $model->primary_key_name()
319
-        ) {
320
-            // if so, we want all this object's fields to be filled either with
321
-            // what we've explicitly set on this model
322
-            // or what we have in the db
323
-            // echo "setting primary key!";
324
-            $fields_on_model = self::_get_model(get_class($this))->field_settings();
325
-            $obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
326
-            foreach ($fields_on_model as $field_obj) {
327
-                if (
328
-                    ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
329
-                    && $field_obj->get_name() !== $field_name
330
-                ) {
331
-                    $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
332
-                }
333
-            }
334
-            // oh this model object has an ID? well make sure its in the entity mapper
335
-            $model->add_to_entity_map($this);
336
-        }
337
-        // let's unset any cache for this field_name from the $_cached_properties property.
338
-        $this->_clear_cached_property($field_name);
339
-    }
340
-
341
-
342
-    /**
343
-     * Overrides parent because parent expects old models.
344
-     * This also doesn't do any validation, and won't work for serialized arrays
345
-     *
346
-     * @param string $field_name
347
-     * @param mixed  $field_value_from_db
348
-     * @throws ReflectionException
349
-     * @throws InvalidArgumentException
350
-     * @throws InvalidInterfaceException
351
-     * @throws InvalidDataTypeException
352
-     * @throws EE_Error
353
-     */
354
-    public function set_from_db(string $field_name, $field_value_from_db)
355
-    {
356
-        $field_obj = $this->get_model()->field_settings_for($field_name);
357
-        if ($field_obj instanceof EE_Model_Field_Base) {
358
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
359
-            // eg, a CPT model object could have an entry in the posts table, but no
360
-            // entry in the meta table. Meaning that all its columns in the meta table
361
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
362
-            if ($field_value_from_db === null) {
363
-                if ($field_obj->is_nullable()) {
364
-                    // if the field allows nulls, then let it be null
365
-                    $field_value = null;
366
-                } else {
367
-                    $field_value = $field_obj->get_default_value();
368
-                }
369
-            } else {
370
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
371
-            }
372
-            $this->_fields[ $field_name ] = $field_value;
373
-            $this->_clear_cached_property($field_name);
374
-        }
375
-    }
376
-
377
-
378
-    /**
379
-     * Set custom select values for model.
380
-     *
381
-     * @param array $custom_select_values
382
-     */
383
-    public function setCustomSelectsValues(array $custom_select_values)
384
-    {
385
-        $this->custom_selection_results = $custom_select_values;
386
-    }
387
-
388
-
389
-    /**
390
-     * Returns the custom select value for the provided alias if its set.
391
-     * If not set, returns null.
392
-     *
393
-     * @param string $alias
394
-     * @return string|int|float|null
395
-     */
396
-    public function getCustomSelect($alias)
397
-    {
398
-        return $this->custom_selection_results[ $alias ] ?? null;
399
-    }
400
-
401
-
402
-    /**
403
-     * This sets the field value on the db column if it exists for the given $column_name or
404
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
405
-     *
406
-     * @param string $field_name  Must be the exact column name.
407
-     * @param mixed  $field_value The value to set.
408
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
409
-     * @throws InvalidArgumentException
410
-     * @throws InvalidInterfaceException
411
-     * @throws InvalidDataTypeException
412
-     * @throws EE_Error
413
-     * @throws ReflectionException
414
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
415
-     */
416
-    public function set_field_or_extra_meta($field_name, $field_value)
417
-    {
418
-        if ($this->get_model()->has_field($field_name)) {
419
-            $this->set($field_name, $field_value);
420
-            return true;
421
-        }
422
-        // ensure this object is saved first so that extra meta can be properly related.
423
-        $this->save();
424
-        return $this->update_extra_meta($field_name, $field_value);
425
-    }
426
-
427
-
428
-    /**
429
-     * This retrieves the value of the db column set on this class or if that's not present
430
-     * it will attempt to retrieve from extra_meta if found.
431
-     * Example Usage:
432
-     * Via EE_Message child class:
433
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
434
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
435
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
436
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
437
-     * value for those extra fields dynamically via the EE_message object.
438
-     *
439
-     * @param string $field_name expecting the fully qualified field name.
440
-     * @return mixed|null  value for the field if found.  null if not found.
441
-     * @throws ReflectionException
442
-     * @throws InvalidArgumentException
443
-     * @throws InvalidInterfaceException
444
-     * @throws InvalidDataTypeException
445
-     * @throws EE_Error
446
-     */
447
-    public function get_field_or_extra_meta($field_name)
448
-    {
449
-        if ($this->get_model()->has_field($field_name)) {
450
-            $column_value = $this->get($field_name);
451
-        } else {
452
-            // This isn't a column in the main table, let's see if it is in the extra meta.
453
-            $column_value = $this->get_extra_meta($field_name, true, null);
454
-        }
455
-        return $column_value;
456
-    }
457
-
458
-
459
-    /**
460
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
461
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
462
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
463
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
464
-     *
465
-     * @access public
466
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
467
-     * @return void
468
-     * @throws InvalidArgumentException
469
-     * @throws InvalidInterfaceException
470
-     * @throws InvalidDataTypeException
471
-     * @throws EE_Error
472
-     * @throws ReflectionException
473
-     * @throws Exception
474
-     */
475
-    public function set_timezone($timezone = '')
476
-    {
477
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
478
-        // make sure we clear all cached properties because they won't be relevant now
479
-        $this->_clear_cached_properties();
480
-        // make sure we update field settings and the date for all EE_Datetime_Fields
481
-        $model_fields = $this->get_model()->field_settings(false);
482
-        foreach ($model_fields as $field_name => $field_obj) {
483
-            if ($field_obj instanceof EE_Datetime_Field) {
484
-                $field_obj->set_timezone($this->_timezone);
485
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
486
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
487
-                }
488
-            }
489
-        }
490
-    }
491
-
492
-
493
-    /**
494
-     * This just returns whatever is set for the current timezone.
495
-     *
496
-     * @access public
497
-     * @return string timezone string
498
-     */
499
-    public function get_timezone()
500
-    {
501
-        return $this->_timezone;
502
-    }
503
-
504
-
505
-    /**
506
-     * This sets the internal date format to what is sent in to be used as the new default for the class
507
-     * internally instead of wp set date format options
508
-     *
509
-     * @param string|null $format should be a format recognizable by PHP date() functions.
510
-     * @since 4.6
511
-     */
512
-    public function set_date_format(?string $format)
513
-    {
514
-        $this->_dt_frmt = new DateFormat($format);
515
-        // clear cached_properties because they won't be relevant now.
516
-        $this->_clear_cached_properties();
517
-    }
518
-
519
-
520
-    /**
521
-     * This sets the internal time format string to what is sent in to be used as the new default for the
522
-     * class internally instead of wp set time format options.
523
-     *
524
-     * @param string|null $format should be a format recognizable by PHP date() functions.
525
-     * @since 4.6
526
-     */
527
-    public function set_time_format(?string $format)
528
-    {
529
-        $this->_tm_frmt = new TimeFormat($format);
530
-        // clear cached_properties because they won't be relevant now.
531
-        $this->_clear_cached_properties();
532
-    }
533
-
534
-
535
-    /**
536
-     * This returns the current internal set format for the date and time formats.
537
-     *
538
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
539
-     *                             where the first value is the date format and the second value is the time format.
540
-     * @return string|array
541
-     */
542
-    public function get_format($full = true)
543
-    {
544
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
545
-    }
546
-
547
-
548
-    /**
549
-     * cache
550
-     * stores the passed model object on the current model object.
551
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
552
-     *
553
-     * @param string        $relation_name   one of the keys in the _model_relations array on the model. Eg
554
-     *                                       'Registration' associated with this model object
555
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
556
-     *                                       that could be a payment or a registration)
557
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
558
-     *                                       items which will be stored in an array on this object
559
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
560
-     *                                       related thing, no array)
561
-     * @throws InvalidArgumentException
562
-     * @throws InvalidInterfaceException
563
-     * @throws InvalidDataTypeException
564
-     * @throws EE_Error
565
-     * @throws ReflectionException
566
-     */
567
-    public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
568
-    {
569
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
570
-        if (! $object_to_cache instanceof EE_Base_Class) {
571
-            return false;
572
-        }
573
-        // also get "how" the object is related, or throw an error
574
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
575
-            throw new EE_Error(
576
-                sprintf(
577
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
578
-                    $relation_name,
579
-                    get_class($this)
580
-                )
581
-            );
582
-        }
583
-        // how many things are related ?
584
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
585
-            // if it's a "belongs to" relationship, then there's only one related model object
586
-            // eg, if this is a registration, there's only 1 attendee for it
587
-            // so for these model objects just set it to be cached
588
-            $this->_model_relations[ $relation_name ] = $object_to_cache;
589
-            $return                                   = true;
590
-        } else {
591
-            // otherwise, this is the "many" side of a one to many relationship,
592
-            // so we'll add the object to the array of related objects for that type.
593
-            // eg: if this is an event, there are many registrations for that event,
594
-            // so we cache the registrations in an array
595
-            if (! is_array($this->_model_relations[ $relation_name ])) {
596
-                // if for some reason, the cached item is a model object,
597
-                // then stick that in the array, otherwise start with an empty array
598
-                $this->_model_relations[ $relation_name ] =
599
-                    $this->_model_relations[ $relation_name ] instanceof EE_Base_Class
600
-                        ? [$this->_model_relations[ $relation_name ]]
601
-                        : [];
602
-            }
603
-            // first check for a cache_id which is normally empty
604
-            if (! empty($cache_id)) {
605
-                // if the cache_id exists, then it means we are purposely trying to cache this
606
-                // with a known key that can then be used to retrieve the object later on
607
-                $this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
608
-                $return                                                = $cache_id;
609
-            } elseif ($object_to_cache->ID()) {
610
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
611
-                $this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
612
-                $return                                                             = $object_to_cache->ID();
613
-            } else {
614
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
615
-                $this->_model_relations[ $relation_name ][] = $object_to_cache;
616
-                // move the internal pointer to the end of the array
617
-                end($this->_model_relations[ $relation_name ]);
618
-                // and grab the key so that we can return it
619
-                $return = key($this->_model_relations[ $relation_name ]);
620
-            }
621
-        }
622
-        return $return;
623
-    }
624
-
625
-
626
-    /**
627
-     * For adding an item to the cached_properties property.
628
-     *
629
-     * @access protected
630
-     * @param string      $fieldname the property item the corresponding value is for.
631
-     * @param mixed       $value     The value we are caching.
632
-     * @param string|null $cache_type
633
-     * @return void
634
-     * @throws ReflectionException
635
-     * @throws InvalidArgumentException
636
-     * @throws InvalidInterfaceException
637
-     * @throws InvalidDataTypeException
638
-     * @throws EE_Error
639
-     */
640
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
641
-    {
642
-        // first make sure this property exists
643
-        $this->get_model()->field_settings_for($fieldname);
644
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
645
-
646
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
647
-    }
648
-
649
-
650
-    /**
651
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
652
-     * This also SETS the cache if we return the actual property!
653
-     *
654
-     * @param string $fieldname        the name of the property we're trying to retrieve
655
-     * @param bool   $pretty
656
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
657
-     *                                 (in cases where the same property may be used for different outputs
658
-     *                                 - i.e. datetime, money etc.)
659
-     *                                 It can also accept certain pre-defined "schema" strings
660
-     *                                 to define how to output the property.
661
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
662
-     * @return mixed                   whatever the value for the property is we're retrieving
663
-     * @throws ReflectionException
664
-     * @throws InvalidArgumentException
665
-     * @throws InvalidInterfaceException
666
-     * @throws InvalidDataTypeException
667
-     * @throws EE_Error
668
-     */
669
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
670
-    {
671
-        // verify the field exists
672
-        $model = $this->get_model();
673
-        $model->field_settings_for($fieldname);
674
-        $cache_type = $pretty ? 'pretty' : 'standard';
675
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
676
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
677
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
678
-        }
679
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
680
-        $this->_set_cached_property($fieldname, $value, $cache_type);
681
-        return $value;
682
-    }
683
-
684
-
685
-    /**
686
-     * If the cache didn't fetch the needed item, this fetches it.
687
-     *
688
-     * @param string $fieldname
689
-     * @param bool   $pretty
690
-     * @param string $extra_cache_ref
691
-     * @return mixed
692
-     * @throws InvalidArgumentException
693
-     * @throws InvalidInterfaceException
694
-     * @throws InvalidDataTypeException
695
-     * @throws EE_Error
696
-     * @throws ReflectionException
697
-     */
698
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
699
-    {
700
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
701
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
702
-        if ($field_obj instanceof EE_Datetime_Field) {
703
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
704
-        }
705
-        if (! isset($this->_fields[ $fieldname ])) {
706
-            $this->_fields[ $fieldname ] = null;
707
-        }
708
-        return $pretty
709
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
710
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
711
-    }
712
-
713
-
714
-    /**
715
-     * set timezone, formats, and output for EE_Datetime_Field objects
716
-     *
717
-     * @param EE_Datetime_Field $datetime_field
718
-     * @param bool              $pretty
719
-     * @param null              $date_or_time
720
-     * @return void
721
-     * @throws InvalidArgumentException
722
-     * @throws InvalidInterfaceException
723
-     * @throws InvalidDataTypeException
724
-     */
725
-    protected function _prepare_datetime_field(
726
-        EE_Datetime_Field $datetime_field,
727
-        $pretty = false,
728
-        $date_or_time = null
729
-    ) {
730
-        $datetime_field->set_timezone($this->_timezone);
731
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
732
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
733
-        // set the output returned
734
-        switch ($date_or_time) {
735
-            case 'D':
736
-                $datetime_field->set_date_time_output('date');
737
-                break;
738
-            case 'T':
739
-                $datetime_field->set_date_time_output('time');
740
-                break;
741
-            default:
742
-                $datetime_field->set_date_time_output();
743
-        }
744
-    }
745
-
746
-
747
-    /**
748
-     * This just takes care of clearing out the cached_properties
749
-     *
750
-     * @return void
751
-     */
752
-    protected function _clear_cached_properties()
753
-    {
754
-        $this->_cached_properties = [];
755
-    }
756
-
757
-
758
-    /**
759
-     * This just clears out ONE property if it exists in the cache
760
-     *
761
-     * @param string $property_name the property to remove if it exists (from the _cached_properties array)
762
-     * @return void
763
-     */
764
-    protected function _clear_cached_property($property_name)
765
-    {
766
-        if (isset($this->_cached_properties[ $property_name ])) {
767
-            unset($this->_cached_properties[ $property_name ]);
768
-        }
769
-    }
770
-
771
-
772
-    /**
773
-     * Ensures that this related thing is a model object.
774
-     *
775
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
776
-     * @param string $model_name   name of the related thing, eg 'Attendee',
777
-     * @return EE_Base_Class
778
-     * @throws ReflectionException
779
-     * @throws InvalidArgumentException
780
-     * @throws InvalidInterfaceException
781
-     * @throws InvalidDataTypeException
782
-     * @throws EE_Error
783
-     */
784
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
785
-    {
786
-        $other_model_instance = self::_get_model_instance_with_name(
787
-            self::_get_model_classname($model_name),
788
-            $this->_timezone
789
-        );
790
-        return $other_model_instance->ensure_is_obj($object_or_id);
791
-    }
792
-
793
-
794
-    /**
795
-     * Forgets the cached model of the given relation Name. So the next time we request it,
796
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
797
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
798
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
799
-     *
800
-     * @param string $relation_name                        one of the keys in the _model_relations array on the model.
801
-     *                                                     Eg 'Registration'
802
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
803
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
804
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
805
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
806
-     *                                                     this is HasMany or HABTM.
807
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
808
-     *                                                     relation from all
809
-     * @throws InvalidArgumentException
810
-     * @throws InvalidInterfaceException
811
-     * @throws InvalidDataTypeException
812
-     * @throws EE_Error
813
-     * @throws ReflectionException
814
-     */
815
-    public function clear_cache($relation_name, $object_to_remove_or_index_into_array = null, $clear_all = false)
816
-    {
817
-        $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
818
-        $index_in_cache        = '';
819
-        if (! $relationship_to_model) {
820
-            throw new EE_Error(
821
-                sprintf(
822
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
823
-                    $relation_name,
824
-                    get_class($this)
825
-                )
826
-            );
827
-        }
828
-        if ($clear_all) {
829
-            $obj_removed                              = true;
830
-            $this->_model_relations[ $relation_name ] = null;
831
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
-            $obj_removed                              = $this->_model_relations[ $relation_name ];
833
-            $this->_model_relations[ $relation_name ] = null;
834
-        } else {
835
-            if (
836
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
837
-                && $object_to_remove_or_index_into_array->ID()
838
-            ) {
839
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
840
-                if (
841
-                    is_array($this->_model_relations[ $relation_name ])
842
-                    && ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
843
-                ) {
844
-                    $index_found_at = null;
845
-                    // find this object in the array even though it has a different key
846
-                    foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
847
-                        /** @noinspection TypeUnsafeComparisonInspection */
848
-                        if (
849
-                            $obj instanceof EE_Base_Class
850
-                            && (
851
-                                $obj == $object_to_remove_or_index_into_array
852
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
853
-                            )
854
-                        ) {
855
-                            $index_found_at = $index;
856
-                            break;
857
-                        }
858
-                    }
859
-                    if ($index_found_at) {
860
-                        $index_in_cache = $index_found_at;
861
-                    } else {
862
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
863
-                        // if it wasn't in it to begin with. So we're done
864
-                        return $object_to_remove_or_index_into_array;
865
-                    }
866
-                }
867
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
868
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
869
-                foreach ($this->get_all_from_cache($relation_name) as $index => $potentially_obj_we_want) {
870
-                    /** @noinspection TypeUnsafeComparisonInspection */
871
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
872
-                        $index_in_cache = $index;
873
-                    }
874
-                }
875
-            } else {
876
-                $index_in_cache = $object_to_remove_or_index_into_array;
877
-            }
878
-            // supposedly we've found it. But it could just be that the client code
879
-            // provided a bad index/object
880
-            if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
881
-                $obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
882
-                unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
883
-            } else {
884
-                // that thing was never cached anyways.
885
-                $obj_removed = null;
886
-            }
887
-        }
888
-        return $obj_removed;
889
-    }
890
-
891
-
892
-    /**
893
-     * update_cache_after_object_save
894
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
895
-     * obtained after being saved to the db
896
-     *
897
-     * @param string        $relation_name      - the type of object that is cached
898
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
899
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
900
-     * @return boolean TRUE on success, FALSE on fail
901
-     * @throws ReflectionException
902
-     * @throws InvalidArgumentException
903
-     * @throws InvalidInterfaceException
904
-     * @throws InvalidDataTypeException
905
-     * @throws EE_Error
906
-     */
907
-    public function update_cache_after_object_save(
908
-        $relation_name,
909
-        EE_Base_Class $newly_saved_object,
910
-        $current_cache_id = ''
911
-    ) {
912
-        // verify that incoming object is of the correct type
913
-        $obj_class = 'EE_' . $relation_name;
914
-        if ($newly_saved_object instanceof $obj_class) {
915
-            /* @type EE_Base_Class $newly_saved_object */
916
-            // now get the type of relation
917
-            $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
918
-            // if this is a 1:1 relationship
919
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
920
-                // then just replace the cached object with the newly saved object
921
-                $this->_model_relations[ $relation_name ] = $newly_saved_object;
922
-                return true;
923
-                // or if it's some kind of sordid feral polyamorous relationship...
924
-            }
925
-            if (
926
-                is_array($this->_model_relations[ $relation_name ])
927
-                && isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
928
-            ) {
929
-                // then remove the current cached item
930
-                unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
931
-                // and cache the newly saved object using it's new ID
932
-                $this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
933
-                return true;
934
-            }
935
-        }
936
-        return false;
937
-    }
938
-
939
-
940
-    /**
941
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
942
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
943
-     *
944
-     * @param string $relation_name
945
-     * @return EE_Base_Class
946
-     */
947
-    public function get_one_from_cache($relation_name)
948
-    {
949
-        $cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
950
-        if (is_array($cached_array_or_object)) {
951
-            return array_shift($cached_array_or_object);
952
-        }
953
-        return $cached_array_or_object;
954
-    }
955
-
956
-
957
-    /**
958
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
959
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
960
-     *
961
-     * @param string $relation_name
962
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
963
-     * @throws InvalidArgumentException
964
-     * @throws InvalidInterfaceException
965
-     * @throws InvalidDataTypeException
966
-     * @throws EE_Error
967
-     * @throws ReflectionException
968
-     */
969
-    public function get_all_from_cache($relation_name)
970
-    {
971
-        $objects = $this->_model_relations[ $relation_name ] ?? [];
972
-        // if the result is not an array, but exists, make it an array
973
-        $objects = is_array($objects)
974
-            ? $objects
975
-            : [$objects];
976
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
977
-        // basically, if this model object was stored in the session, and these cached model objects
978
-        // already have IDs, let's make sure they're in their model's entity mapper
979
-        // otherwise we will have duplicates next time we call
980
-        // EE_Registry::instance()->load_model( $relation_name )->get_one_by_ID( $result->ID() );
981
-        $model = EE_Registry::instance()->load_model($relation_name);
982
-        foreach ($objects as $model_object) {
983
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
984
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
985
-                if ($model_object->ID()) {
986
-                    $model->add_to_entity_map($model_object);
987
-                }
988
-            } else {
989
-                throw new EE_Error(
990
-                    sprintf(
991
-                        esc_html__(
992
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
993
-                            'event_espresso'
994
-                        ),
995
-                        $relation_name,
996
-                        gettype($model_object)
997
-                    )
998
-                );
999
-            }
1000
-        }
1001
-        return $objects;
1002
-    }
1003
-
1004
-
1005
-    /**
1006
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1007
-     * matching the given query conditions.
1008
-     *
1009
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1010
-     * @param int   $limit              How many objects to return.
1011
-     * @param array $query_params       Any additional conditions on the query.
1012
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1013
-     *                                  you can indicate just the columns you want returned
1014
-     * @return array|EE_Base_Class[]
1015
-     * @throws ReflectionException
1016
-     * @throws InvalidArgumentException
1017
-     * @throws InvalidInterfaceException
1018
-     * @throws InvalidDataTypeException
1019
-     * @throws EE_Error
1020
-     */
1021
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = [], $columns_to_select = null)
1022
-    {
1023
-        $model         = $this->get_model();
1024
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1025
-            ? $model->get_primary_key_field()->get_name()
1026
-            : $field_to_order_by;
1027
-        $current_value = ! empty($field)
1028
-            ? $this->get($field)
1029
-            : null;
1030
-        if (empty($field) || empty($current_value)) {
1031
-            return [];
1032
-        }
1033
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1039
-     * matching the given query conditions.
1040
-     *
1041
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1042
-     * @param int   $limit              How many objects to return.
1043
-     * @param array $query_params       Any additional conditions on the query.
1044
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1045
-     *                                  you can indicate just the columns you want returned
1046
-     * @return array|EE_Base_Class[]
1047
-     * @throws ReflectionException
1048
-     * @throws InvalidArgumentException
1049
-     * @throws InvalidInterfaceException
1050
-     * @throws InvalidDataTypeException
1051
-     * @throws EE_Error
1052
-     */
1053
-    public function previous_x(
1054
-        $field_to_order_by = null,
1055
-        $limit = 1,
1056
-        $query_params = [],
1057
-        $columns_to_select = null
1058
-    ) {
1059
-        $model         = $this->get_model();
1060
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1061
-            ? $model->get_primary_key_field()->get_name()
1062
-            : $field_to_order_by;
1063
-        $current_value = ! empty($field) ? $this->get($field) : null;
1064
-        if (empty($field) || empty($current_value)) {
1065
-            return [];
1066
-        }
1067
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1068
-    }
1069
-
1070
-
1071
-    /**
1072
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1073
-     * matching the given query conditions.
1074
-     *
1075
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1076
-     * @param array $query_params       Any additional conditions on the query.
1077
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1078
-     *                                  you can indicate just the columns you want returned
1079
-     * @return array|EE_Base_Class
1080
-     * @throws ReflectionException
1081
-     * @throws InvalidArgumentException
1082
-     * @throws InvalidInterfaceException
1083
-     * @throws InvalidDataTypeException
1084
-     * @throws EE_Error
1085
-     */
1086
-    public function next($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1087
-    {
1088
-        $model         = $this->get_model();
1089
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1090
-            ? $model->get_primary_key_field()->get_name()
1091
-            : $field_to_order_by;
1092
-        $current_value = ! empty($field) ? $this->get($field) : null;
1093
-        if (empty($field) || empty($current_value)) {
1094
-            return [];
1095
-        }
1096
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1097
-    }
1098
-
1099
-
1100
-    /**
1101
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1102
-     * matching the given query conditions.
1103
-     *
1104
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1105
-     * @param array $query_params       Any additional conditions on the query.
1106
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1107
-     *                                  you can indicate just the column you want returned
1108
-     * @return array|EE_Base_Class
1109
-     * @throws ReflectionException
1110
-     * @throws InvalidArgumentException
1111
-     * @throws InvalidInterfaceException
1112
-     * @throws InvalidDataTypeException
1113
-     * @throws EE_Error
1114
-     */
1115
-    public function previous($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1116
-    {
1117
-        $model         = $this->get_model();
1118
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1119
-            ? $model->get_primary_key_field()->get_name()
1120
-            : $field_to_order_by;
1121
-        $current_value = ! empty($field) ? $this->get($field) : null;
1122
-        if (empty($field) || empty($current_value)) {
1123
-            return [];
1124
-        }
1125
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * verifies that the specified field is of the correct type
1131
-     *
1132
-     * @param string $field_name
1133
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1134
-     *                                (in cases where the same property may be used for different outputs
1135
-     *                                - i.e. datetime, money etc.)
1136
-     * @return mixed
1137
-     * @throws ReflectionException
1138
-     * @throws InvalidArgumentException
1139
-     * @throws InvalidInterfaceException
1140
-     * @throws InvalidDataTypeException
1141
-     * @throws EE_Error
1142
-     */
1143
-    public function get($field_name, $extra_cache_ref = null)
1144
-    {
1145
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1146
-    }
1147
-
1148
-
1149
-    /**
1150
-     * This method simply returns the RAW unprocessed value for the given property in this class
1151
-     *
1152
-     * @param string $field_name A valid fieldname
1153
-     * @return mixed              Whatever the raw value stored on the property is.
1154
-     * @throws ReflectionException
1155
-     * @throws InvalidArgumentException
1156
-     * @throws InvalidInterfaceException
1157
-     * @throws InvalidDataTypeException
1158
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1159
-     */
1160
-    public function get_raw($field_name)
1161
-    {
1162
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1163
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1164
-            ? $this->_fields[ $field_name ]->format('U')
1165
-            : $this->_fields[ $field_name ];
1166
-    }
1167
-
1168
-
1169
-    /**
1170
-     * This is used to return the internal DateTime object used for a field that is a
1171
-     * EE_Datetime_Field.
1172
-     *
1173
-     * @param string $field_name               The field name retrieving the DateTime object.
1174
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1175
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1176
-     *                                         EE_Datetime_Field and but the field value is null, then
1177
-     *                                         just null is returned (because that indicates that likely
1178
-     *                                         this field is nullable).
1179
-     * @throws InvalidArgumentException
1180
-     * @throws InvalidDataTypeException
1181
-     * @throws InvalidInterfaceException
1182
-     * @throws ReflectionException
1183
-     */
1184
-    public function get_DateTime_object($field_name)
1185
-    {
1186
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1187
-        if (! $field_settings instanceof EE_Datetime_Field) {
1188
-            EE_Error::add_error(
1189
-                sprintf(
1190
-                    esc_html__(
1191
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1192
-                        'event_espresso'
1193
-                    ),
1194
-                    $field_name
1195
-                ),
1196
-                __FILE__,
1197
-                __FUNCTION__,
1198
-                __LINE__
1199
-            );
1200
-            return false;
1201
-        }
1202
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1203
-            ? clone $this->_fields[ $field_name ]
1204
-            : null;
1205
-    }
1206
-
1207
-
1208
-    /**
1209
-     * To be used in template to immediately echo out the value, and format it for output.
1210
-     * Eg, should call stripslashes and whatnot before echoing
1211
-     *
1212
-     * @param string $field_name      the name of the field as it appears in the DB
1213
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1214
-     *                                (in cases where the same property may be used for different outputs
1215
-     *                                - i.e. datetime, money etc.)
1216
-     * @return void
1217
-     * @throws ReflectionException
1218
-     * @throws InvalidArgumentException
1219
-     * @throws InvalidInterfaceException
1220
-     * @throws InvalidDataTypeException
1221
-     * @throws EE_Error
1222
-     */
1223
-    public function e($field_name, $extra_cache_ref = null)
1224
-    {
1225
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1231
-     * can be easily used as the value of form input.
1232
-     *
1233
-     * @param string $field_name
1234
-     * @return void
1235
-     * @throws ReflectionException
1236
-     * @throws InvalidArgumentException
1237
-     * @throws InvalidInterfaceException
1238
-     * @throws InvalidDataTypeException
1239
-     * @throws EE_Error
1240
-     */
1241
-    public function f($field_name)
1242
-    {
1243
-        $this->e($field_name, 'form_input');
1244
-    }
1245
-
1246
-
1247
-    /**
1248
-     * Same as `f()` but just returns the value instead of echoing it
1249
-     *
1250
-     * @param string $field_name
1251
-     * @return string
1252
-     * @throws ReflectionException
1253
-     * @throws InvalidArgumentException
1254
-     * @throws InvalidInterfaceException
1255
-     * @throws InvalidDataTypeException
1256
-     * @throws EE_Error
1257
-     */
1258
-    public function get_f($field_name)
1259
-    {
1260
-        return (string) $this->get_pretty($field_name, 'form_input');
1261
-    }
1262
-
1263
-
1264
-    /**
1265
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1266
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1267
-     * to see what options are available.
1268
-     *
1269
-     * @param string $field_name
1270
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1271
-     *                                (in cases where the same property may be used for different outputs
1272
-     *                                - i.e. datetime, money etc.)
1273
-     * @return mixed
1274
-     * @throws ReflectionException
1275
-     * @throws InvalidArgumentException
1276
-     * @throws InvalidInterfaceException
1277
-     * @throws InvalidDataTypeException
1278
-     * @throws EE_Error
1279
-     */
1280
-    public function get_pretty($field_name, $extra_cache_ref = null)
1281
-    {
1282
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1283
-    }
1284
-
1285
-
1286
-    /**
1287
-     * This simply returns the datetime for the given field name
1288
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1289
-     * (and the equivalent e_date, e_time, e_datetime).
1290
-     *
1291
-     * @access   protected
1292
-     * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1293
-     * @param string|null $date_format  valid datetime format used for date
1294
-     *                                  (if '' then we just use the default on the field,
1295
-     *                                  if NULL we use the last-used format)
1296
-     * @param string|null $time_format  Same as above except this is for time format
1297
-     * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1298
-     * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1299
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1300
-     *                                  if field is not a valid dtt field, or void if echoing
1301
-     * @throws EE_Error
1302
-     * @throws ReflectionException
1303
-     */
1304
-    protected function _get_datetime(
1305
-        string $field_name,
1306
-        ?string $date_format = '',
1307
-        ?string $time_format = '',
1308
-        ?string $date_or_time = '',
1309
-        ?bool $echo = false
1310
-    ) {
1311
-        // clear cached property
1312
-        $this->_clear_cached_property($field_name);
1313
-        // reset format properties because they are used in get()
1314
-        $this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1315
-        $this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1316
-        if ($echo) {
1317
-            $this->e($field_name, $date_or_time);
1318
-            return '';
1319
-        }
1320
-        return $this->get($field_name, $date_or_time);
1321
-    }
1322
-
1323
-
1324
-    /**
1325
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1326
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1327
-     * other echoes the pretty value for dtt)
1328
-     *
1329
-     * @param string $field_name name of model object datetime field holding the value
1330
-     * @param string $format     format for the date returned (if NULL we use default in dt_frmt property)
1331
-     * @return string            datetime value formatted
1332
-     * @throws ReflectionException
1333
-     * @throws InvalidArgumentException
1334
-     * @throws InvalidInterfaceException
1335
-     * @throws InvalidDataTypeException
1336
-     * @throws EE_Error
1337
-     */
1338
-    public function get_date($field_name, $format = '')
1339
-    {
1340
-        return $this->_get_datetime($field_name, $format, null, 'D');
1341
-    }
1342
-
1343
-
1344
-    /**
1345
-     * @param        $field_name
1346
-     * @param string $format
1347
-     * @throws ReflectionException
1348
-     * @throws InvalidArgumentException
1349
-     * @throws InvalidInterfaceException
1350
-     * @throws InvalidDataTypeException
1351
-     * @throws EE_Error
1352
-     */
1353
-    public function e_date($field_name, $format = '')
1354
-    {
1355
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1356
-    }
1357
-
1358
-
1359
-    /**
1360
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1361
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1362
-     * other echoes the pretty value for dtt)
1363
-     *
1364
-     * @param string $field_name name of model object datetime field holding the value
1365
-     * @param string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1366
-     * @return string             datetime value formatted
1367
-     * @throws ReflectionException
1368
-     * @throws InvalidArgumentException
1369
-     * @throws InvalidInterfaceException
1370
-     * @throws InvalidDataTypeException
1371
-     * @throws EE_Error
1372
-     */
1373
-    public function get_time($field_name, $format = '')
1374
-    {
1375
-        return $this->_get_datetime($field_name, null, $format, 'T');
1376
-    }
1377
-
1378
-
1379
-    /**
1380
-     * @param        $field_name
1381
-     * @param string $format
1382
-     * @throws ReflectionException
1383
-     * @throws InvalidArgumentException
1384
-     * @throws InvalidInterfaceException
1385
-     * @throws InvalidDataTypeException
1386
-     * @throws EE_Error
1387
-     */
1388
-    public function e_time($field_name, $format = '')
1389
-    {
1390
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1391
-    }
1392
-
1393
-
1394
-    /**
1395
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1396
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1397
-     * other echoes the pretty value for dtt)
1398
-     *
1399
-     * @param string $field_name  name of model object datetime field holding the value
1400
-     * @param string $date_format format for the date returned (if NULL we use default in dt_frmt property)
1401
-     * @param string $time_format format for the time returned (if NULL we use default in tm_frmt property)
1402
-     * @return string             datetime value formatted
1403
-     * @throws ReflectionException
1404
-     * @throws InvalidArgumentException
1405
-     * @throws InvalidInterfaceException
1406
-     * @throws InvalidDataTypeException
1407
-     * @throws EE_Error
1408
-     */
1409
-    public function get_datetime($field_name, $date_format = '', $time_format = '')
1410
-    {
1411
-        return $this->_get_datetime($field_name, $date_format, $time_format);
1412
-    }
1413
-
1414
-
1415
-    /**
1416
-     * @param string $field_name
1417
-     * @param string $date_format
1418
-     * @param string $time_format
1419
-     * @throws ReflectionException
1420
-     * @throws InvalidArgumentException
1421
-     * @throws InvalidInterfaceException
1422
-     * @throws InvalidDataTypeException
1423
-     * @throws EE_Error
1424
-     */
1425
-    public function e_datetime($field_name, $date_format = '', $time_format = '')
1426
-    {
1427
-        $this->_get_datetime($field_name, $date_format, $time_format, null, true);
1428
-    }
1429
-
1430
-
1431
-    /**
1432
-     * Get the i8ln value for a date using the WordPress @param string $field_name The EE_Datetime_Field reference for
1433
-     *                           the date being retrieved.
1434
-     *
1435
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1436
-     *                           on the object will be used.
1437
-     * @return string Date and time string in set locale or false if no field exists for the given
1438
-     * @throws ReflectionException
1439
-     * @throws InvalidArgumentException
1440
-     * @throws InvalidInterfaceException
1441
-     * @throws InvalidDataTypeException
1442
-     * @throws EE_Error
1443
-     *                           field name.
1444
-     * @see date_i18n function.
1445
-     */
1446
-    public function get_i18n_datetime(string $field_name, string $format = ''): string
1447
-    {
1448
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1449
-        return date_i18n(
1450
-            $format,
1451
-            EEH_DTT_Helper::get_timestamp_with_offset(
1452
-                $this->get_raw($field_name),
1453
-                $this->_timezone
1454
-            )
1455
-        );
1456
-    }
1457
-
1458
-
1459
-    /**
1460
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1461
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1462
-     * thrown.
1463
-     *
1464
-     * @param string $field_name The field name being checked
1465
-     * @return EE_Datetime_Field
1466
-     * @throws InvalidArgumentException
1467
-     * @throws InvalidInterfaceException
1468
-     * @throws InvalidDataTypeException
1469
-     * @throws EE_Error
1470
-     * @throws ReflectionException
1471
-     */
1472
-    protected function _get_dtt_field_settings($field_name)
1473
-    {
1474
-        $field = $this->get_model()->field_settings_for($field_name);
1475
-        // check if field is dtt
1476
-        if ($field instanceof EE_Datetime_Field) {
1477
-            return $field;
1478
-        }
1479
-        throw new EE_Error(
1480
-            sprintf(
1481
-                esc_html__(
1482
-                    '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',
1483
-                    'event_espresso'
1484
-                ),
1485
-                $field_name,
1486
-                self::_get_model_classname(get_class($this))
1487
-            )
1488
-        );
1489
-    }
1490
-
1491
-
1492
-
1493
-
1494
-    /**
1495
-     * NOTE ABOUT BELOW:
1496
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1497
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1498
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1499
-     * method and make sure you send the entire datetime value for setting.
1500
-     */
1501
-    /**
1502
-     * sets the time on a datetime property
1503
-     *
1504
-     * @access protected
1505
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1506
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1507
-     * @throws ReflectionException
1508
-     * @throws InvalidArgumentException
1509
-     * @throws InvalidInterfaceException
1510
-     * @throws InvalidDataTypeException
1511
-     * @throws EE_Error
1512
-     */
1513
-    protected function _set_time_for($time, $fieldname)
1514
-    {
1515
-        $this->_set_date_time('T', $time, $fieldname);
1516
-    }
1517
-
1518
-
1519
-    /**
1520
-     * sets the date on a datetime property
1521
-     *
1522
-     * @access protected
1523
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1524
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1525
-     * @throws ReflectionException
1526
-     * @throws InvalidArgumentException
1527
-     * @throws InvalidInterfaceException
1528
-     * @throws InvalidDataTypeException
1529
-     * @throws EE_Error
1530
-     */
1531
-    protected function _set_date_for($date, $fieldname)
1532
-    {
1533
-        $this->_set_date_time('D', $date, $fieldname);
1534
-    }
1535
-
1536
-
1537
-    /**
1538
-     * This takes care of setting a date or time independently on a given model object property. This method also
1539
-     * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1540
-     *
1541
-     * @access protected
1542
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1543
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1544
-     * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1545
-     *                                        EE_Datetime_Field property)
1546
-     * @throws ReflectionException
1547
-     * @throws InvalidArgumentException
1548
-     * @throws InvalidInterfaceException
1549
-     * @throws InvalidDataTypeException
1550
-     * @throws EE_Error
1551
-     */
1552
-    protected function _set_date_time(string $what, $datetime_value, string $field_name)
1553
-    {
1554
-        $field = $this->_get_dtt_field_settings($field_name);
1555
-        $field->set_timezone($this->_timezone);
1556
-        $field->set_date_format($this->_dt_frmt);
1557
-        $field->set_time_format($this->_tm_frmt);
1558
-        switch ($what) {
1559
-            case 'T':
1560
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1561
-                    $datetime_value,
1562
-                    $this->_fields[ $field_name ]
1563
-                );
1564
-                $this->_has_changes           = true;
1565
-                break;
1566
-            case 'D':
1567
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1568
-                    $datetime_value,
1569
-                    $this->_fields[ $field_name ]
1570
-                );
1571
-                $this->_has_changes           = true;
1572
-                break;
1573
-            case 'B':
1574
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1575
-                $this->_has_changes           = true;
1576
-                break;
1577
-        }
1578
-        $this->_clear_cached_property($field_name);
1579
-    }
1580
-
1581
-
1582
-    /**
1583
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1584
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1585
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1586
-     * that could lead to some unexpected results!
1587
-     *
1588
-     * @access public
1589
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1590
-     *                                         value being returned.
1591
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1592
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1593
-     * @param string $prepend                  You can include something to prepend on the timestamp
1594
-     * @param string $append                   You can include something to append on the timestamp
1595
-     * @return string timestamp
1596
-     * @throws ReflectionException
1597
-     * @throws InvalidArgumentException
1598
-     * @throws InvalidInterfaceException
1599
-     * @throws InvalidDataTypeException
1600
-     * @throws EE_Error
1601
-     */
1602
-    public function display_in_my_timezone(
1603
-        $field_name,
1604
-        $callback = 'get_datetime',
1605
-        $args = null,
1606
-        $prepend = '',
1607
-        $append = ''
1608
-    ) {
1609
-        $timezone = EEH_DTT_Helper::get_timezone();
1610
-        if ($timezone === $this->_timezone) {
1611
-            return '';
1612
-        }
1613
-        $original_timezone = $this->_timezone;
1614
-        $this->set_timezone($timezone);
1615
-        $fn   = (array) $field_name;
1616
-        $args = array_merge($fn, (array) $args);
1617
-        if (! method_exists($this, $callback)) {
1618
-            throw new EE_Error(
1619
-                sprintf(
1620
-                    esc_html__(
1621
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1622
-                        'event_espresso'
1623
-                    ),
1624
-                    $callback
1625
-                )
1626
-            );
1627
-        }
1628
-        $args   = (array) $args;
1629
-        $return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1630
-        $this->set_timezone($original_timezone);
1631
-        return $return;
1632
-    }
1633
-
1634
-
1635
-    /**
1636
-     * Deletes this model object.
1637
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1638
-     * override
1639
-     * `EE_Base_Class::_delete` NOT this class.
1640
-     *
1641
-     * @return boolean | int
1642
-     * @throws ReflectionException
1643
-     * @throws InvalidArgumentException
1644
-     * @throws InvalidInterfaceException
1645
-     * @throws InvalidDataTypeException
1646
-     * @throws EE_Error
1647
-     */
1648
-    public function delete()
1649
-    {
1650
-        /**
1651
-         * Called just before the `EE_Base_Class::_delete` method call.
1652
-         * Note:
1653
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1654
-         * should be aware that `_delete` may not always result in a permanent delete.
1655
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1656
-         * soft deletes (trash) the object and does not permanently delete it.
1657
-         *
1658
-         * @param EE_Base_Class $model_object about to be 'deleted'
1659
-         */
1660
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1661
-        $result = $this->_delete();
1662
-        /**
1663
-         * Called just after the `EE_Base_Class::_delete` method call.
1664
-         * Note:
1665
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1666
-         * should be aware that `_delete` may not always result in a permanent delete.
1667
-         * For example `EE_Soft_Base_Class::_delete`
1668
-         * soft deletes (trash) the object and does not permanently delete it.
1669
-         *
1670
-         * @param EE_Base_Class $model_object that was just 'deleted'
1671
-         * @param boolean       $result
1672
-         */
1673
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1674
-        return $result;
1675
-    }
1676
-
1677
-
1678
-    /**
1679
-     * Calls the specific delete method for the instantiated class.
1680
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1681
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1682
-     * `EE_Base_Class::delete`
1683
-     *
1684
-     * @return bool|int
1685
-     * @throws ReflectionException
1686
-     * @throws InvalidArgumentException
1687
-     * @throws InvalidInterfaceException
1688
-     * @throws InvalidDataTypeException
1689
-     * @throws EE_Error
1690
-     */
1691
-    protected function _delete()
1692
-    {
1693
-        return $this->delete_permanently();
1694
-    }
1695
-
1696
-
1697
-    /**
1698
-     * Deletes this model object permanently from db
1699
-     * (but keep in mind related models may block the delete and return an error)
1700
-     *
1701
-     * @return bool | int
1702
-     * @throws ReflectionException
1703
-     * @throws InvalidArgumentException
1704
-     * @throws InvalidInterfaceException
1705
-     * @throws InvalidDataTypeException
1706
-     * @throws EE_Error
1707
-     */
1708
-    public function delete_permanently()
1709
-    {
1710
-        /**
1711
-         * Called just before HARD deleting a model object
1712
-         *
1713
-         * @param EE_Base_Class $model_object about to be 'deleted'
1714
-         */
1715
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1716
-        $model  = $this->get_model();
1717
-        $result = $model->delete_permanently_by_ID($this->ID());
1718
-        $this->refresh_cache_of_related_objects();
1719
-        /**
1720
-         * Called just after HARD deleting a model object
1721
-         *
1722
-         * @param EE_Base_Class $model_object that was just 'deleted'
1723
-         * @param boolean       $result
1724
-         */
1725
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1726
-        return $result;
1727
-    }
1728
-
1729
-
1730
-    /**
1731
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1732
-     * related model objects
1733
-     *
1734
-     * @throws ReflectionException
1735
-     * @throws InvalidArgumentException
1736
-     * @throws InvalidInterfaceException
1737
-     * @throws InvalidDataTypeException
1738
-     * @throws EE_Error
1739
-     */
1740
-    public function refresh_cache_of_related_objects()
1741
-    {
1742
-        $model = $this->get_model();
1743
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1744
-            if (! empty($this->_model_relations[ $relation_name ])) {
1745
-                $related_objects = $this->_model_relations[ $relation_name ];
1746
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1747
-                    // this relation only stores a single model object, not an array
1748
-                    // but let's make it consistent
1749
-                    $related_objects = [$related_objects];
1750
-                }
1751
-                foreach ($related_objects as $related_object) {
1752
-                    // only refresh their cache if they're in memory
1753
-                    if ($related_object instanceof EE_Base_Class) {
1754
-                        $related_object->clear_cache(
1755
-                            $model->get_this_model_name(),
1756
-                            $this
1757
-                        );
1758
-                    }
1759
-                }
1760
-            }
1761
-        }
1762
-    }
1763
-
1764
-
1765
-    /**
1766
-     *        Saves this object to the database. An array may be supplied to set some values on this
1767
-     * object just before saving.
1768
-     *
1769
-     * @access public
1770
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1771
-     *                                 if provided during the save() method (often client code will change the fields'
1772
-     *                                 values before calling save)
1773
-     * @return bool|int|string         1 on a successful update
1774
-     *                                 the ID of the new entry on insert
1775
-     *                                 0 on failure or if the model object isn't allowed to persist
1776
-     *                                 (as determined by EE_Base_Class::allow_persist())
1777
-     * @throws InvalidInterfaceException
1778
-     * @throws InvalidDataTypeException
1779
-     * @throws EE_Error
1780
-     * @throws InvalidArgumentException
1781
-     * @throws ReflectionException
1782
-     */
1783
-    public function save($set_cols_n_values = [])
1784
-    {
1785
-        $model = $this->get_model();
1786
-        /**
1787
-         * Filters the fields we're about to save on the model object
1788
-         *
1789
-         * @param array         $set_cols_n_values
1790
-         * @param EE_Base_Class $model_object
1791
-         */
1792
-        $set_cols_n_values = (array) apply_filters(
1793
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1794
-            $set_cols_n_values,
1795
-            $this
1796
-        );
1797
-        // set attributes as provided in $set_cols_n_values
1798
-        foreach ($set_cols_n_values as $column => $value) {
1799
-            $this->set($column, $value);
1800
-        }
1801
-        // no changes ? then don't do anything
1802
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1803
-            return 0;
1804
-        }
1805
-        /**
1806
-         * Saving a model object.
1807
-         * Before we perform a save, this action is fired.
1808
-         *
1809
-         * @param EE_Base_Class $model_object the model object about to be saved.
1810
-         */
1811
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1812
-        if (! $this->allow_persist()) {
1813
-            return 0;
1814
-        }
1815
-        // now get current attribute values
1816
-        $save_cols_n_values = $this->_fields;
1817
-        // if the object already has an ID, update it. Otherwise, insert it
1818
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1819
-        // They have been
1820
-        $old_assumption_concerning_value_preparation = $model
1821
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1822
-        $model->assume_values_already_prepared_by_model_object(true);
1823
-        // does this model have an autoincrement PK?
1824
-        if ($model->has_primary_key_field()) {
1825
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1826
-                // ok check if it's set, if so: update; if not, insert
1827
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1828
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1829
-                } else {
1830
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1831
-                    $results = $model->insert($save_cols_n_values);
1832
-                    if ($results) {
1833
-                        // if successful, set the primary key
1834
-                        // but don't use the normal SET method, because it will check if
1835
-                        // an item with the same ID exists in the mapper & db, then
1836
-                        // will find it in the db (because we just added it) and THAT object
1837
-                        // will get added to the mapper before we can add this one!
1838
-                        // but if we just avoid using the SET method, all that headache can be avoided
1839
-                        $pk_field_name                   = $model->primary_key_name();
1840
-                        $this->_fields[ $pk_field_name ] = $results;
1841
-                        $this->_clear_cached_property($pk_field_name);
1842
-                        $model->add_to_entity_map($this);
1843
-                        $this->_update_cached_related_model_objs_fks();
1844
-                    }
1845
-                }
1846
-            } else {// PK is NOT auto-increment
1847
-                // so check if one like it already exists in the db
1848
-                if ($model->exists_by_ID($this->ID())) {
1849
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1850
-                        throw new EE_Error(
1851
-                            sprintf(
1852
-                                esc_html__(
1853
-                                    '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',
1854
-                                    'event_espresso'
1855
-                                ),
1856
-                                get_class($this),
1857
-                                get_class($model) . '::instance()->add_to_entity_map()',
1858
-                                get_class($model) . '::instance()->get_one_by_ID()',
1859
-                                '<br />'
1860
-                            )
1861
-                        );
1862
-                    }
1863
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1864
-                } else {
1865
-                    $results = $model->insert($save_cols_n_values);
1866
-                    $this->_update_cached_related_model_objs_fks();
1867
-                }
1868
-            }
1869
-        } else {// there is NO primary key
1870
-            $already_in_db = false;
1871
-            foreach ($model->unique_indexes() as $index) {
1872
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1873
-                if ($model->exists([$uniqueness_where_params])) {
1874
-                    $already_in_db = true;
1875
-                }
1876
-            }
1877
-            if ($already_in_db) {
1878
-                $combined_pk_fields_n_values = array_intersect_key(
1879
-                    $save_cols_n_values,
1880
-                    $model->get_combined_primary_key_fields()
1881
-                );
1882
-                $results                     = $model->update(
1883
-                    $save_cols_n_values,
1884
-                    $combined_pk_fields_n_values
1885
-                );
1886
-            } else {
1887
-                $results = $model->insert($save_cols_n_values);
1888
-            }
1889
-        }
1890
-        // restore the old assumption about values being prepared by the model object
1891
-        $model->assume_values_already_prepared_by_model_object(
1892
-            $old_assumption_concerning_value_preparation
1893
-        );
1894
-        /**
1895
-         * After saving the model object this action is called
1896
-         *
1897
-         * @param EE_Base_Class $model_object which was just saved
1898
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1899
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1900
-         */
1901
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1902
-        $this->_has_changes = false;
1903
-        return $results;
1904
-    }
1905
-
1906
-
1907
-    /**
1908
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1909
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1910
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1911
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1912
-     * 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
1913
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1914
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1915
-     *
1916
-     * @return void
1917
-     * @throws ReflectionException
1918
-     * @throws InvalidArgumentException
1919
-     * @throws InvalidInterfaceException
1920
-     * @throws InvalidDataTypeException
1921
-     * @throws EE_Error
1922
-     */
1923
-    protected function _update_cached_related_model_objs_fks()
1924
-    {
1925
-        $model = $this->get_model();
1926
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1927
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1928
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1929
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1930
-                        $model->get_this_model_name()
1931
-                    );
1932
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1933
-                    if ($related_model_obj_in_cache->ID()) {
1934
-                        $related_model_obj_in_cache->save();
1935
-                    }
1936
-                }
1937
-            }
1938
-        }
1939
-    }
1940
-
1941
-
1942
-    /**
1943
-     * Saves this model object and its NEW cached relations to the database.
1944
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1945
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1946
-     * because otherwise, there's a potential for infinite looping of saving
1947
-     * Saves the cached related model objects, and ensures the relation between them
1948
-     * and this object and properly setup
1949
-     *
1950
-     * @return int ID of new model object on save; 0 on failure+
1951
-     * @throws ReflectionException
1952
-     * @throws InvalidArgumentException
1953
-     * @throws InvalidInterfaceException
1954
-     * @throws InvalidDataTypeException
1955
-     * @throws EE_Error
1956
-     */
1957
-    public function save_new_cached_related_model_objs()
1958
-    {
1959
-        // make sure this has been saved
1960
-        if (! $this->ID()) {
1961
-            $id = $this->save();
1962
-        } else {
1963
-            $id = $this->ID();
1964
-        }
1965
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1966
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1967
-            if ($this->_model_relations[ $relation_name ]) {
1968
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1969
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1970
-                /* @var $related_model_obj EE_Base_Class */
1971
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1972
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
1973
-                    // but ONLY if it DOES NOT exist in the DB
1974
-                    $related_model_obj = $this->_model_relations[ $relation_name ];
1975
-                    // if( ! $related_model_obj->ID()){
1976
-                    $this->_add_relation_to($related_model_obj, $relation_name);
1977
-                    $related_model_obj->save_new_cached_related_model_objs();
1978
-                    // }
1979
-                } else {
1980
-                    foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1981
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
1982
-                        // but ONLY if it DOES NOT exist in the DB
1983
-                        // if( ! $related_model_obj->ID()){
1984
-                        $this->_add_relation_to($related_model_obj, $relation_name);
1985
-                        $related_model_obj->save_new_cached_related_model_objs();
1986
-                        // }
1987
-                    }
1988
-                }
1989
-            }
1990
-        }
1991
-        return $id;
1992
-    }
1993
-
1994
-
1995
-    /**
1996
-     * for getting a model while instantiated.
1997
-     *
1998
-     * @return EEM_Base | EEM_CPT_Base
1999
-     * @throws ReflectionException
2000
-     * @throws InvalidArgumentException
2001
-     * @throws InvalidInterfaceException
2002
-     * @throws InvalidDataTypeException
2003
-     * @throws EE_Error
2004
-     */
2005
-    public function get_model()
2006
-    {
2007
-        if (! $this->_model) {
2008
-            $modelName    = self::_get_model_classname(get_class($this));
2009
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2010
-        } else {
2011
-            $this->_model->set_timezone($this->_timezone);
2012
-        }
2013
-        return $this->_model;
2014
-    }
2015
-
2016
-
2017
-    /**
2018
-     * @param $props_n_values
2019
-     * @param $classname
2020
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2021
-     * @throws ReflectionException
2022
-     * @throws InvalidArgumentException
2023
-     * @throws InvalidInterfaceException
2024
-     * @throws InvalidDataTypeException
2025
-     * @throws EE_Error
2026
-     */
2027
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2028
-    {
2029
-        // TODO: will not work for Term_Relationships because they have no PK!
2030
-        $primary_id_ref = self::_get_primary_key_name($classname);
2031
-        if (
2032
-            array_key_exists($primary_id_ref, $props_n_values)
2033
-            && ! empty($props_n_values[ $primary_id_ref ])
2034
-        ) {
2035
-            $id = $props_n_values[ $primary_id_ref ];
2036
-            return self::_get_model($classname)->get_from_entity_map($id);
2037
-        }
2038
-        return false;
2039
-    }
2040
-
2041
-
2042
-    /**
2043
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2044
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2045
-     * 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
2046
-     * we return false.
2047
-     *
2048
-     * @param array  $props_n_values    incoming array of properties and their values
2049
-     * @param string $classname         the classname of the child class
2050
-     * @param null   $timezone
2051
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the
2052
-     *                                  date_format and the second value is the time format
2053
-     * @return mixed (EE_Base_Class|bool)
2054
-     * @throws InvalidArgumentException
2055
-     * @throws InvalidInterfaceException
2056
-     * @throws InvalidDataTypeException
2057
-     * @throws EE_Error
2058
-     * @throws ReflectionException
2059
-     */
2060
-    protected static function _check_for_object($props_n_values, $classname, $timezone = '', $date_formats = [])
2061
-    {
2062
-        $existing = null;
2063
-        $model    = self::_get_model($classname, $timezone);
2064
-        if ($model->has_primary_key_field()) {
2065
-            $primary_id_ref = self::_get_primary_key_name($classname);
2066
-            if (
2067
-                array_key_exists($primary_id_ref, $props_n_values)
2068
-                && ! empty($props_n_values[ $primary_id_ref ])
2069
-            ) {
2070
-                $existing = $model->get_one_by_ID(
2071
-                    $props_n_values[ $primary_id_ref ]
2072
-                );
2073
-            }
2074
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2075
-            // no primary key on this model, but there's still a matching item in the DB
2076
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2077
-                self::_get_model($classname, $timezone)
2078
-                    ->get_index_primary_key_string($props_n_values)
2079
-            );
2080
-        }
2081
-        if ($existing) {
2082
-            // set date formats if present before setting values
2083
-            if (! empty($date_formats) && is_array($date_formats)) {
2084
-                $existing->set_date_format($date_formats[0]);
2085
-                $existing->set_time_format($date_formats[1]);
2086
-            } else {
2087
-                // set default formats for date and time
2088
-                $existing->set_date_format(get_option('date_format'));
2089
-                $existing->set_time_format(get_option('time_format'));
2090
-            }
2091
-            foreach ($props_n_values as $property => $field_value) {
2092
-                $existing->set($property, $field_value);
2093
-            }
2094
-            return $existing;
2095
-        }
2096
-        return false;
2097
-    }
2098
-
2099
-
2100
-    /**
2101
-     * Gets the EEM_*_Model for this class
2102
-     *
2103
-     * @access public now, as this is more convenient
2104
-     * @param      $classname
2105
-     * @param null $timezone
2106
-     * @return EEM_Base
2107
-     * @throws InvalidArgumentException
2108
-     * @throws InvalidInterfaceException
2109
-     * @throws InvalidDataTypeException
2110
-     * @throws EE_Error
2111
-     * @throws ReflectionException
2112
-     */
2113
-    protected static function _get_model($classname, $timezone = '')
2114
-    {
2115
-        // find model for this class
2116
-        if (! $classname) {
2117
-            throw new EE_Error(
2118
-                sprintf(
2119
-                    esc_html__(
2120
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2121
-                        'event_espresso'
2122
-                    ),
2123
-                    $classname
2124
-                )
2125
-            );
2126
-        }
2127
-        $modelName = self::_get_model_classname($classname);
2128
-        return self::_get_model_instance_with_name($modelName, $timezone);
2129
-    }
2130
-
2131
-
2132
-    /**
2133
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2134
-     *
2135
-     * @param string $model_classname
2136
-     * @param null   $timezone
2137
-     * @return EEM_Base
2138
-     * @throws ReflectionException
2139
-     * @throws InvalidArgumentException
2140
-     * @throws InvalidInterfaceException
2141
-     * @throws InvalidDataTypeException
2142
-     * @throws EE_Error
2143
-     */
2144
-    protected static function _get_model_instance_with_name($model_classname, $timezone = '')
2145
-    {
2146
-        $model_classname = str_replace('EEM_', '', $model_classname);
2147
-        $model           = EE_Registry::instance()->load_model($model_classname);
2148
-        $model->set_timezone($timezone);
2149
-        return $model;
2150
-    }
2151
-
2152
-
2153
-    /**
2154
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2155
-     * Also works if a model class's classname is provided (eg EE_Registration).
2156
-     *
2157
-     * @param string|null $model_name
2158
-     * @return string like EEM_Attendee
2159
-     */
2160
-    private static function _get_model_classname($model_name = '')
2161
-    {
2162
-        return strpos((string) $model_name, 'EE_') === 0
2163
-            ? str_replace('EE_', 'EEM_', $model_name)
2164
-            : 'EEM_' . $model_name;
2165
-    }
2166
-
2167
-
2168
-    /**
2169
-     * returns the name of the primary key attribute
2170
-     *
2171
-     * @param null $classname
2172
-     * @return string
2173
-     * @throws InvalidArgumentException
2174
-     * @throws InvalidInterfaceException
2175
-     * @throws InvalidDataTypeException
2176
-     * @throws EE_Error
2177
-     * @throws ReflectionException
2178
-     */
2179
-    protected static function _get_primary_key_name($classname = null)
2180
-    {
2181
-        if (! $classname) {
2182
-            throw new EE_Error(
2183
-                sprintf(
2184
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2185
-                    $classname
2186
-                )
2187
-            );
2188
-        }
2189
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2190
-    }
2191
-
2192
-
2193
-    /**
2194
-     * Gets the value of the primary key.
2195
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2196
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2197
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2198
-     *
2199
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2200
-     * @throws ReflectionException
2201
-     * @throws InvalidArgumentException
2202
-     * @throws InvalidInterfaceException
2203
-     * @throws InvalidDataTypeException
2204
-     * @throws EE_Error
2205
-     */
2206
-    public function ID()
2207
-    {
2208
-        $model = $this->get_model();
2209
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2210
-        if ($model->has_primary_key_field()) {
2211
-            return $this->_fields[ $model->primary_key_name() ];
2212
-        }
2213
-        return $model->get_index_primary_key_string($this->_fields);
2214
-    }
2215
-
2216
-
2217
-    /**
2218
-     * @param EE_Base_Class|int|string $otherModelObjectOrID
2219
-     * @param string                   $relation_name
2220
-     * @return bool
2221
-     * @throws EE_Error
2222
-     * @throws ReflectionException
2223
-     * @since   5.0.0.p
2224
-     */
2225
-    public function hasRelation($otherModelObjectOrID, string $relation_name): bool
2226
-    {
2227
-        $other_model = self::_get_model_instance_with_name(
2228
-            self::_get_model_classname($relation_name),
2229
-            $this->_timezone
2230
-        );
2231
-        $primary_key = $other_model->primary_key_name();
2232
-        /** @var EE_Base_Class $otherModelObject */
2233
-        $otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relation_name);
2234
-        return $this->count_related($relation_name, [[$primary_key => $otherModelObject->ID()]]) > 0;
2235
-    }
2236
-
2237
-
2238
-    /**
2239
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2240
-     * model is related to a group of events, the $relation_name should be 'Event', and should be a key in the EE
2241
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2242
-     *
2243
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2244
-     * @param string $relation_name                    eg 'Events','Question',etc.
2245
-     *                                                 an attendee to a group, you also want to specify which role they
2246
-     *                                                 will have in that group. So you would use this parameter to
2247
-     *                                                 specify array('role-column-name'=>'role-id')
2248
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2249
-     *                                                 allow you to further constrict the relation to being added.
2250
-     *                                                 However, keep in mind that the columns (keys) given must match a
2251
-     *                                                 column on the JOIN table and currently only the HABTM models
2252
-     *                                                 accept these additional conditions.  Also remember that if an
2253
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2254
-     *                                                 NEW row is created in the join table.
2255
-     * @param null   $cache_id
2256
-     * @return EE_Base_Class the object the relation was added to
2257
-     * @throws ReflectionException
2258
-     * @throws InvalidArgumentException
2259
-     * @throws InvalidInterfaceException
2260
-     * @throws InvalidDataTypeException
2261
-     * @throws EE_Error
2262
-     */
2263
-    public function _add_relation_to(
2264
-        $otherObjectModelObjectOrID,
2265
-        $relation_name,
2266
-        $extra_join_model_fields_n_values = [],
2267
-        $cache_id = null
2268
-    ) {
2269
-        $model = $this->get_model();
2270
-        // if this thing exists in the DB, save the relation to the DB
2271
-        if ($this->ID()) {
2272
-            $otherObject = $model->add_relationship_to(
2273
-                $this,
2274
-                $otherObjectModelObjectOrID,
2275
-                $relation_name,
2276
-                $extra_join_model_fields_n_values
2277
-            );
2278
-            // clear cache so future get_many_related and get_first_related() return new results.
2279
-            $this->clear_cache($relation_name, $otherObject, true);
2280
-            if ($otherObject instanceof EE_Base_Class) {
2281
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2282
-            }
2283
-        } else {
2284
-            // this thing doesn't exist in the DB,  so just cache it
2285
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2286
-                throw new EE_Error(
2287
-                    sprintf(
2288
-                        esc_html__(
2289
-                            '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',
2290
-                            'event_espresso'
2291
-                        ),
2292
-                        $otherObjectModelObjectOrID,
2293
-                        get_class($this)
2294
-                    )
2295
-                );
2296
-            }
2297
-            $otherObject = $otherObjectModelObjectOrID;
2298
-            $this->cache($relation_name, $otherObjectModelObjectOrID, $cache_id);
2299
-        }
2300
-        if ($otherObject instanceof EE_Base_Class) {
2301
-            // fix the reciprocal relation too
2302
-            if ($otherObject->ID()) {
2303
-                // its saved so assumed relations exist in the DB, so we can just
2304
-                // clear the cache so future queries use the updated info in the DB
2305
-                $otherObject->clear_cache(
2306
-                    $model->get_this_model_name(),
2307
-                    null,
2308
-                    true
2309
-                );
2310
-            } else {
2311
-                // it's not saved, so it caches relations like this
2312
-                $otherObject->cache($model->get_this_model_name(), $this);
2313
-            }
2314
-        }
2315
-        return $otherObject;
2316
-    }
2317
-
2318
-
2319
-    /**
2320
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2321
-     * model is related to a group of events, the $relation_name should be 'Events', and should be a key in the EE
2322
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2323
-     * from the cache
2324
-     *
2325
-     * @param mixed  $otherObjectModelObjectOrID
2326
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2327
-     *                to the DB yet
2328
-     * @param string $relation_name
2329
-     * @param array  $where_query
2330
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2331
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2332
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2333
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2334
-     *                deleted.
2335
-     * @return EE_Base_Class the relation was removed from
2336
-     * @throws ReflectionException
2337
-     * @throws InvalidArgumentException
2338
-     * @throws InvalidInterfaceException
2339
-     * @throws InvalidDataTypeException
2340
-     * @throws EE_Error
2341
-     */
2342
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relation_name, $where_query = [])
2343
-    {
2344
-        if ($this->ID()) {
2345
-            // if this exists in the DB, save the relation change to the DB too
2346
-            $otherObject = $this->get_model()->remove_relationship_to(
2347
-                $this,
2348
-                $otherObjectModelObjectOrID,
2349
-                $relation_name,
2350
-                $where_query
2351
-            );
2352
-            $this->clear_cache(
2353
-                $relation_name,
2354
-                $otherObject
2355
-            );
2356
-        } else {
2357
-            // this doesn't exist in the DB, just remove it from the cache
2358
-            $otherObject = $this->clear_cache(
2359
-                $relation_name,
2360
-                $otherObjectModelObjectOrID
2361
-            );
2362
-        }
2363
-        if ($otherObject instanceof EE_Base_Class) {
2364
-            $otherObject->clear_cache(
2365
-                $this->get_model()->get_this_model_name(),
2366
-                $this
2367
-            );
2368
-        }
2369
-        return $otherObject;
2370
-    }
2371
-
2372
-
2373
-    /**
2374
-     * Removes ALL the related things for the $relation_name.
2375
-     *
2376
-     * @param string $relation_name
2377
-     * @param array  $where_query_params @see
2378
-     *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2379
-     * @return EE_Base_Class
2380
-     * @throws ReflectionException
2381
-     * @throws InvalidArgumentException
2382
-     * @throws InvalidInterfaceException
2383
-     * @throws InvalidDataTypeException
2384
-     * @throws EE_Error
2385
-     */
2386
-    public function _remove_relations($relation_name, $where_query_params = [])
2387
-    {
2388
-        if ($this->ID()) {
2389
-            // if this exists in the DB, save the relation change to the DB too
2390
-            $otherObjects = $this->get_model()->remove_relations(
2391
-                $this,
2392
-                $relation_name,
2393
-                $where_query_params
2394
-            );
2395
-            $this->clear_cache(
2396
-                $relation_name,
2397
-                null,
2398
-                true
2399
-            );
2400
-        } else {
2401
-            // this doesn't exist in the DB, just remove it from the cache
2402
-            $otherObjects = $this->clear_cache(
2403
-                $relation_name,
2404
-                null,
2405
-                true
2406
-            );
2407
-        }
2408
-        if (is_array($otherObjects)) {
2409
-            foreach ($otherObjects as $otherObject) {
2410
-                $otherObject->clear_cache(
2411
-                    $this->get_model()->get_this_model_name(),
2412
-                    $this
2413
-                );
2414
-            }
2415
-        }
2416
-        return $otherObjects;
2417
-    }
2418
-
2419
-
2420
-    /**
2421
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2422
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2423
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2424
-     * because we want to get even deleted items etc.
2425
-     *
2426
-     * @param string      $relation_name key in the model's _model_relations array
2427
-     * @param array|null  $query_params  @see
2428
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2429
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2430
-     *                              keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2431
-     *                              results if you want IDs
2432
-     * @throws ReflectionException
2433
-     * @throws InvalidArgumentException
2434
-     * @throws InvalidInterfaceException
2435
-     * @throws InvalidDataTypeException
2436
-     * @throws EE_Error
2437
-     */
2438
-    public function get_many_related($relation_name, $query_params = [])
2439
-    {
2440
-        if ($this->ID()) {
2441
-            // this exists in the DB, so get the related things from either the cache or the DB
2442
-            // if there are query parameters, forget about caching the related model objects.
2443
-            if ($query_params) {
2444
-                $related_model_objects = $this->get_model()->get_all_related(
2445
-                    $this,
2446
-                    $relation_name,
2447
-                    $query_params
2448
-                );
2449
-            } else {
2450
-                // did we already cache the result of this query?
2451
-                $cached_results = $this->get_all_from_cache($relation_name);
2452
-                if (! $cached_results) {
2453
-                    $related_model_objects = $this->get_model()->get_all_related(
2454
-                        $this,
2455
-                        $relation_name,
2456
-                        $query_params
2457
-                    );
2458
-                    // if no query parameters were passed, then we got all the related model objects
2459
-                    // for that relation. We can cache them then.
2460
-                    foreach ($related_model_objects as $related_model_object) {
2461
-                        $this->cache($relation_name, $related_model_object);
2462
-                    }
2463
-                } else {
2464
-                    $related_model_objects = $cached_results;
2465
-                }
2466
-            }
2467
-        } else {
2468
-            // this doesn't exist in the DB, so just get the related things from the cache
2469
-            $related_model_objects = $this->get_all_from_cache($relation_name);
2470
-        }
2471
-        return $related_model_objects;
2472
-    }
2473
-
2474
-
2475
-    /**
2476
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2477
-     * unless otherwise specified in the $query_params
2478
-     *
2479
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2480
-     * @param array  $query_params   @see
2481
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2482
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2483
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2484
-     *                               that by the setting $distinct to TRUE;
2485
-     * @return int
2486
-     * @throws ReflectionException
2487
-     * @throws InvalidArgumentException
2488
-     * @throws InvalidInterfaceException
2489
-     * @throws InvalidDataTypeException
2490
-     * @throws EE_Error
2491
-     */
2492
-    public function count_related($relation_name, $query_params = [], $field_to_count = null, $distinct = false)
2493
-    {
2494
-        return $this->get_model()->count_related(
2495
-            $this,
2496
-            $relation_name,
2497
-            $query_params,
2498
-            $field_to_count,
2499
-            $distinct
2500
-        );
2501
-    }
2502
-
2503
-
2504
-    /**
2505
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2506
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2507
-     *
2508
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2509
-     * @param array  $query_params  @see
2510
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2511
-     * @param string $field_to_sum  name of field to count by.
2512
-     *                              By default, uses primary key
2513
-     *                              (which doesn't make much sense, so you should probably change it)
2514
-     * @return int
2515
-     * @throws ReflectionException
2516
-     * @throws InvalidArgumentException
2517
-     * @throws InvalidInterfaceException
2518
-     * @throws InvalidDataTypeException
2519
-     * @throws EE_Error
2520
-     */
2521
-    public function sum_related($relation_name, $query_params = [], $field_to_sum = null)
2522
-    {
2523
-        return $this->get_model()->sum_related(
2524
-            $this,
2525
-            $relation_name,
2526
-            $query_params,
2527
-            $field_to_sum
2528
-        );
2529
-    }
2530
-
2531
-
2532
-    /**
2533
-     * Gets the first (ie, one) related model object of the specified type.
2534
-     *
2535
-     * @param string $relation_name key in the model's _model_relations array
2536
-     * @param array  $query_params  @see
2537
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2538
-     * @return EE_Base_Class|null (not an array, a single object)
2539
-     * @throws ReflectionException
2540
-     * @throws InvalidArgumentException
2541
-     * @throws InvalidInterfaceException
2542
-     * @throws InvalidDataTypeException
2543
-     * @throws EE_Error
2544
-     */
2545
-    public function get_first_related(string $relation_name, array $query_params = []): ?EE_Base_Class
2546
-    {
2547
-        $model = $this->get_model();
2548
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2549
-            // if they've provided some query parameters, don't bother trying to cache the result
2550
-            // also make sure we're not caching the result of get_first_related
2551
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2552
-            if (
2553
-                $query_params
2554
-                || ! $model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation
2555
-            ) {
2556
-                $related_model_object = $model->get_first_related(
2557
-                    $this,
2558
-                    $relation_name,
2559
-                    $query_params
2560
-                );
2561
-            } else {
2562
-                // first, check if we've already cached the result of this query
2563
-                $cached_result = $this->get_one_from_cache($relation_name);
2564
-                if (! $cached_result) {
2565
-                    $related_model_object = $model->get_first_related(
2566
-                        $this,
2567
-                        $relation_name,
2568
-                        $query_params
2569
-                    );
2570
-                    $this->cache($relation_name, $related_model_object);
2571
-                } else {
2572
-                    $related_model_object = $cached_result;
2573
-                }
2574
-            }
2575
-        } else {
2576
-            $related_model_object = null;
2577
-            // this doesn't exist in the Db,
2578
-            // but maybe the relation is of type belongs to, and so the related thing might
2579
-            if ($model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation) {
2580
-                $related_model_object = $model->get_first_related(
2581
-                    $this,
2582
-                    $relation_name,
2583
-                    $query_params
2584
-                );
2585
-            }
2586
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2587
-            // just get what's cached on this object
2588
-            if (! $related_model_object) {
2589
-                $related_model_object = $this->get_one_from_cache($relation_name);
2590
-            }
2591
-        }
2592
-        return $related_model_object;
2593
-    }
2594
-
2595
-
2596
-    /**
2597
-     * Does a delete on all related objects of type $relation_name and removes
2598
-     * the current model object's relation to them. If they can't be deleted (because
2599
-     * of blocking related model objects) does nothing. If the related model objects are
2600
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2601
-     * If this model object doesn't exist yet in the DB, just removes its related things
2602
-     *
2603
-     * @param string $relation_name
2604
-     * @param array  $query_params @see
2605
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2606
-     * @return int how many deleted
2607
-     * @throws ReflectionException
2608
-     * @throws InvalidArgumentException
2609
-     * @throws InvalidInterfaceException
2610
-     * @throws InvalidDataTypeException
2611
-     * @throws EE_Error
2612
-     */
2613
-    public function delete_related($relation_name, $query_params = [])
2614
-    {
2615
-        if ($this->ID()) {
2616
-            $count = $this->get_model()->delete_related(
2617
-                $this,
2618
-                $relation_name,
2619
-                $query_params
2620
-            );
2621
-        } else {
2622
-            $count = count($this->get_all_from_cache($relation_name));
2623
-            $this->clear_cache($relation_name, null, true);
2624
-        }
2625
-        return $count;
2626
-    }
2627
-
2628
-
2629
-    /**
2630
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relation_name and removes
2631
-     * the current model object's relation to them. If they can't be deleted (because
2632
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2633
-     * If the related thing isn't a soft-deletable model object, this function is identical
2634
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2635
-     *
2636
-     * @param string $relation_name
2637
-     * @param array  $query_params @see
2638
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2639
-     * @return int how many deleted (including those soft deleted)
2640
-     * @throws ReflectionException
2641
-     * @throws InvalidArgumentException
2642
-     * @throws InvalidInterfaceException
2643
-     * @throws InvalidDataTypeException
2644
-     * @throws EE_Error
2645
-     */
2646
-    public function delete_related_permanently($relation_name, $query_params = [])
2647
-    {
2648
-        $count = $this->ID()
2649
-            ? $this->get_model()->delete_related_permanently(
2650
-                $this,
2651
-                $relation_name,
2652
-                $query_params
2653
-            )
2654
-            : count($this->get_all_from_cache($relation_name));
2655
-
2656
-        $this->clear_cache($relation_name, null, true);
2657
-        return $count;
2658
-    }
2659
-
2660
-
2661
-    /**
2662
-     * is_set
2663
-     * Just a simple utility function children can use for checking if property exists
2664
-     *
2665
-     * @access  public
2666
-     * @param string $field_name property to check
2667
-     * @return bool                              TRUE if existing,FALSE if not.
2668
-     */
2669
-    public function is_set($field_name)
2670
-    {
2671
-        return isset($this->_fields[ $field_name ]);
2672
-    }
2673
-
2674
-
2675
-    /**
2676
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2677
-     * EE_Error exception if they don't
2678
-     *
2679
-     * @param mixed (string|array) $properties properties to check
2680
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2681
-     * @throws EE_Error
2682
-     */
2683
-    protected function _property_exists($properties)
2684
-    {
2685
-        foreach ((array) $properties as $property_name) {
2686
-            // first make sure this property exists
2687
-            if (! $this->_fields[ $property_name ]) {
2688
-                throw new EE_Error(
2689
-                    sprintf(
2690
-                        esc_html__(
2691
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2692
-                            'event_espresso'
2693
-                        ),
2694
-                        $property_name
2695
-                    )
2696
-                );
2697
-            }
2698
-        }
2699
-        return true;
2700
-    }
2701
-
2702
-
2703
-    /**
2704
-     * This simply returns an array of model fields for this object
2705
-     *
2706
-     * @return array
2707
-     * @throws ReflectionException
2708
-     * @throws InvalidArgumentException
2709
-     * @throws InvalidInterfaceException
2710
-     * @throws InvalidDataTypeException
2711
-     * @throws EE_Error
2712
-     */
2713
-    public function model_field_array()
2714
-    {
2715
-        $fields     = $this->get_model()->field_settings(false);
2716
-        $properties = [];
2717
-        // remove prepended underscore
2718
-        foreach ($fields as $field_name => $settings) {
2719
-            $properties[ $field_name ] = $this->get($field_name);
2720
-        }
2721
-        return $properties;
2722
-    }
2723
-
2724
-
2725
-    /**
2726
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2727
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2728
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2729
-     * Instead of requiring a plugin to extend the EE_Base_Class
2730
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2731
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2732
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2733
-     * and accepts 2 arguments: the object on which the function was called,
2734
-     * and an array of the original arguments passed to the function.
2735
-     * Whatever their callback function returns will be returned by this function.
2736
-     * Example: in functions.php (or in a plugin):
2737
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2738
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2739
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2740
-     *          return $previousReturnValue.$returnString;
2741
-     *      }
2742
-     * require('EE_Answer.class.php');
2743
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2744
-     *      ->my_callback('monkeys',100);
2745
-     * // will output "you called my_callback! and passed args:monkeys,100"
2746
-     *
2747
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2748
-     * @param array  $args       array of original arguments passed to the function
2749
-     * @return mixed whatever the plugin which calls add_filter decides
2750
-     * @throws EE_Error
2751
-     */
2752
-    public function __call($methodName, $args)
2753
-    {
2754
-        $className = get_class($this);
2755
-        $tagName   = "FHEE__{$className}__{$methodName}";
2756
-        if (! has_filter($tagName)) {
2757
-            throw new EE_Error(
2758
-                sprintf(
2759
-                    esc_html__(
2760
-                        "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;}",
2761
-                        'event_espresso'
2762
-                    ),
2763
-                    $methodName,
2764
-                    $className,
2765
-                    $tagName
2766
-                )
2767
-            );
2768
-        }
2769
-        return apply_filters($tagName, null, $this, $args);
2770
-    }
2771
-
2772
-
2773
-    /**
2774
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2775
-     * A $previous_value can be specified in case there are many meta rows with the same key
2776
-     *
2777
-     * @param string $meta_key
2778
-     * @param mixed  $meta_value
2779
-     * @param mixed  $previous_value
2780
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2781
-     *                  NOTE: if the values haven't changed, returns 0
2782
-     * @throws InvalidArgumentException
2783
-     * @throws InvalidInterfaceException
2784
-     * @throws InvalidDataTypeException
2785
-     * @throws EE_Error
2786
-     * @throws ReflectionException
2787
-     */
2788
-    public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2789
-    {
2790
-        $query_params = [
2791
-            [
2792
-                'EXM_key'  => $meta_key,
2793
-                'OBJ_ID'   => $this->ID(),
2794
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2795
-            ],
2796
-        ];
2797
-        if ($previous_value !== null) {
2798
-            $query_params[0]['EXM_value'] = $meta_value;
2799
-        }
2800
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2801
-        if (! $existing_rows_like_that) {
2802
-            return $this->add_extra_meta($meta_key, $meta_value);
2803
-        }
2804
-        foreach ($existing_rows_like_that as $existing_row) {
2805
-            $existing_row->save(['EXM_value' => $meta_value]);
2806
-        }
2807
-        return count($existing_rows_like_that);
2808
-    }
2809
-
2810
-
2811
-    /**
2812
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2813
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2814
-     * extra meta row was entered, false if not
2815
-     *
2816
-     * @param string $meta_key
2817
-     * @param mixed  $meta_value
2818
-     * @param bool   $unique
2819
-     * @return bool
2820
-     * @throws InvalidArgumentException
2821
-     * @throws InvalidInterfaceException
2822
-     * @throws InvalidDataTypeException
2823
-     * @throws EE_Error
2824
-     * @throws ReflectionException
2825
-     */
2826
-    public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2827
-    {
2828
-        if ($unique) {
2829
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2830
-                [
2831
-                    [
2832
-                        'EXM_key'  => $meta_key,
2833
-                        'OBJ_ID'   => $this->ID(),
2834
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2835
-                    ],
2836
-                ]
2837
-            );
2838
-            if ($existing_extra_meta) {
2839
-                return false;
2840
-            }
2841
-        }
2842
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2843
-            [
2844
-                'EXM_key'   => $meta_key,
2845
-                'EXM_value' => $meta_value,
2846
-                'OBJ_ID'    => $this->ID(),
2847
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2848
-            ]
2849
-        );
2850
-        $new_extra_meta->save();
2851
-        return true;
2852
-    }
2853
-
2854
-
2855
-    /**
2856
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2857
-     * is specified, only deletes extra meta records with that value.
2858
-     *
2859
-     * @param string $meta_key
2860
-     * @param mixed  $meta_value
2861
-     * @return int|bool number of extra meta rows deleted
2862
-     * @throws InvalidArgumentException
2863
-     * @throws InvalidInterfaceException
2864
-     * @throws InvalidDataTypeException
2865
-     * @throws EE_Error
2866
-     * @throws ReflectionException
2867
-     */
2868
-    public function delete_extra_meta(string $meta_key, $meta_value = null)
2869
-    {
2870
-        $query_params = [
2871
-            [
2872
-                'EXM_key'  => $meta_key,
2873
-                'OBJ_ID'   => $this->ID(),
2874
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2875
-            ],
2876
-        ];
2877
-        if ($meta_value !== null) {
2878
-            $query_params[0]['EXM_value'] = $meta_value;
2879
-        }
2880
-        return EEM_Extra_Meta::instance()->delete($query_params);
2881
-    }
2882
-
2883
-
2884
-    /**
2885
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2886
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2887
-     * You can specify $default is case you haven't found the extra meta
2888
-     *
2889
-     * @param string     $meta_key
2890
-     * @param bool       $single
2891
-     * @param mixed      $default if we don't find anything, what should we return?
2892
-     * @param array|null $extra_where
2893
-     * @return mixed single value if $single; array if ! $single
2894
-     * @throws ReflectionException
2895
-     * @throws EE_Error
2896
-     */
2897
-    public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2898
-    {
2899
-        $query_params = [$extra_where + ['EXM_key' => $meta_key]];
2900
-        if ($single) {
2901
-            $result = $this->get_first_related('Extra_Meta', $query_params);
2902
-            if ($result instanceof EE_Extra_Meta) {
2903
-                return $result->value();
2904
-            }
2905
-        } else {
2906
-            $results = $this->get_many_related('Extra_Meta', $query_params);
2907
-            if ($results) {
2908
-                $values = [];
2909
-                foreach ($results as $result) {
2910
-                    if ($result instanceof EE_Extra_Meta) {
2911
-                        $values[ $result->ID() ] = $result->value();
2912
-                    }
2913
-                }
2914
-                return $values;
2915
-            }
2916
-        }
2917
-        // if nothing discovered yet return default.
2918
-        return apply_filters(
2919
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2920
-            $default,
2921
-            $meta_key,
2922
-            $single,
2923
-            $this
2924
-        );
2925
-    }
2926
-
2927
-
2928
-    /**
2929
-     * Returns a simple array of all the extra meta associated with this model object.
2930
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2931
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2932
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2933
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2934
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2935
-     * finally the extra meta's value as each sub-value. (eg
2936
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2937
-     *
2938
-     * @param bool $one_of_each_key
2939
-     * @return array
2940
-     * @throws ReflectionException
2941
-     * @throws InvalidArgumentException
2942
-     * @throws InvalidInterfaceException
2943
-     * @throws InvalidDataTypeException
2944
-     * @throws EE_Error
2945
-     */
2946
-    public function all_extra_meta_array(bool $one_of_each_key = true): array
2947
-    {
2948
-        $return_array = [];
2949
-        if ($one_of_each_key) {
2950
-            $extra_meta_objs = $this->get_many_related(
2951
-                'Extra_Meta',
2952
-                ['group_by' => 'EXM_key']
2953
-            );
2954
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2955
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2956
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2957
-                }
2958
-            }
2959
-        } else {
2960
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2961
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2962
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2963
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2964
-                        $return_array[ $extra_meta_obj->key() ] = [];
2965
-                    }
2966
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2967
-                }
2968
-            }
2969
-        }
2970
-        return $return_array;
2971
-    }
2972
-
2973
-
2974
-    /**
2975
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2976
-     *
2977
-     * @return string
2978
-     * @throws ReflectionException
2979
-     * @throws InvalidArgumentException
2980
-     * @throws InvalidInterfaceException
2981
-     * @throws InvalidDataTypeException
2982
-     * @throws EE_Error
2983
-     */
2984
-    public function name()
2985
-    {
2986
-        // find a field that's not a text field
2987
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2988
-        if ($field_we_can_use) {
2989
-            return $this->get($field_we_can_use->get_name());
2990
-        }
2991
-        $first_few_properties = $this->model_field_array();
2992
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
2993
-        $name_parts           = [];
2994
-        foreach ($first_few_properties as $name => $value) {
2995
-            $name_parts[] = "$name:$value";
2996
-        }
2997
-        return implode(',', $name_parts);
2998
-    }
2999
-
3000
-
3001
-    /**
3002
-     * in_entity_map
3003
-     * Checks if this model object has been proven to already be in the entity map
3004
-     *
3005
-     * @return boolean
3006
-     * @throws ReflectionException
3007
-     * @throws InvalidArgumentException
3008
-     * @throws InvalidInterfaceException
3009
-     * @throws InvalidDataTypeException
3010
-     * @throws EE_Error
3011
-     */
3012
-    public function in_entity_map()
3013
-    {
3014
-        // well, if we looked, did we find it in the entity map?
3015
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3016
-    }
3017
-
3018
-
3019
-    /**
3020
-     * refresh_from_db
3021
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3022
-     *
3023
-     * @throws ReflectionException
3024
-     * @throws InvalidArgumentException
3025
-     * @throws InvalidInterfaceException
3026
-     * @throws InvalidDataTypeException
3027
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3028
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3029
-     */
3030
-    public function refresh_from_db()
3031
-    {
3032
-        if ($this->ID() && $this->in_entity_map()) {
3033
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3034
-        } else {
3035
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3036
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3037
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3038
-            // absolutely nothing in it for this ID
3039
-            if (WP_DEBUG) {
3040
-                throw new EE_Error(
3041
-                    sprintf(
3042
-                        esc_html__(
3043
-                            '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.',
3044
-                            'event_espresso'
3045
-                        ),
3046
-                        $this->ID(),
3047
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3048
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3049
-                    )
3050
-                );
3051
-            }
3052
-        }
3053
-    }
3054
-
3055
-
3056
-    /**
3057
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3058
-     *
3059
-     * @param EE_Model_Field_Base[] $fields
3060
-     * @param string                $new_value_sql
3061
-     *          example: 'column_name=123',
3062
-     *          or 'column_name=column_name+1',
3063
-     *          or 'column_name= CASE
3064
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3065
-     *          THEN `column_name` + 5
3066
-     *          ELSE `column_name`
3067
-     *          END'
3068
-     *          Also updates $field on this model object with the latest value from the database.
3069
-     * @return bool
3070
-     * @throws EE_Error
3071
-     * @throws InvalidArgumentException
3072
-     * @throws InvalidDataTypeException
3073
-     * @throws InvalidInterfaceException
3074
-     * @throws ReflectionException
3075
-     * @since 4.9.80.p
3076
-     */
3077
-    protected function updateFieldsInDB($fields, $new_value_sql)
3078
-    {
3079
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3080
-        // if it wasn't even there to start off.
3081
-        if (! $this->ID()) {
3082
-            $this->save();
3083
-        }
3084
-        global $wpdb;
3085
-        if (empty($fields)) {
3086
-            throw new InvalidArgumentException(
3087
-                esc_html__(
3088
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3089
-                    'event_espresso'
3090
-                )
3091
-            );
3092
-        }
3093
-        $first_field = reset($fields);
3094
-        $table_alias = $first_field->get_table_alias();
3095
-        foreach ($fields as $field) {
3096
-            if ($table_alias !== $field->get_table_alias()) {
3097
-                throw new InvalidArgumentException(
3098
-                    sprintf(
3099
-                        esc_html__(
3100
-                        // @codingStandardsIgnoreStart
3101
-                            '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.',
3102
-                            // @codingStandardsIgnoreEnd
3103
-                            'event_espresso'
3104
-                        ),
3105
-                        $table_alias,
3106
-                        $field->get_table_alias()
3107
-                    )
3108
-                );
3109
-            }
3110
-        }
3111
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3112
-        $table_obj      = $this->get_model()->get_table_obj_by_alias($table_alias);
3113
-        $table_pk_value = $this->ID();
3114
-        $table_name     = $table_obj->get_table_name();
3115
-        if ($table_obj instanceof EE_Secondary_Table) {
3116
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3117
-        } else {
3118
-            $table_pk_field_name = $table_obj->get_pk_column();
3119
-        }
3120
-
3121
-        $query  =
3122
-            "UPDATE `{$table_name}`
19
+	/**
20
+	 * @var EEM_Base|null
21
+	 */
22
+	protected $_model = null;
23
+
24
+	/**
25
+	 * This is an array of the original properties and values provided during construction
26
+	 * of this model object. (keys are model field names, values are their values).
27
+	 * This list is important to remember so that when we are merging data from the db, we know
28
+	 * which values to override and which to not override.
29
+	 */
30
+	protected ?array $_props_n_values_provided_in_constructor = null;
31
+
32
+	/**
33
+	 * Timezone
34
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
35
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
36
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
37
+	 * access to it.
38
+	 */
39
+	protected string $_timezone = '';
40
+
41
+	/**
42
+	 * date format
43
+	 * pattern or format for displaying dates
44
+	 */
45
+	protected string $_dt_frmt = '';
46
+
47
+	/**
48
+	 * time format
49
+	 * pattern or format for displaying time
50
+	 */
51
+	protected string $_tm_frmt = '';
52
+
53
+	/**
54
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
55
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
56
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
+	 */
59
+	protected array $_cached_properties = [];
60
+
61
+	/**
62
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
63
+	 * single
64
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
65
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
66
+	 * all others have an array)
67
+	 */
68
+	protected array $_model_relations = [];
69
+
70
+	/**
71
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
72
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
73
+	 */
74
+	protected array $_fields = [];
75
+
76
+	/**
77
+	 * indicating whether or not this model object is intended to ever be saved
78
+	 * For example, we might create model objects intended to only be used for the duration
79
+	 * of this request and to be thrown away, and if they were accidentally saved
80
+	 * it would be a bug.
81
+	 */
82
+	protected bool $_allow_persist = true;
83
+
84
+	/**
85
+	 * indicating whether or not this model object's properties have changed since construction
86
+	 */
87
+	protected bool $_has_changes = false;
88
+
89
+	/**
90
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
91
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
92
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
93
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
94
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
95
+	 * array as:
96
+	 * array(
97
+	 *  'Registration_Count' => 24
98
+	 * );
99
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
100
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
101
+	 * info)
102
+	 */
103
+	protected array $custom_selection_results = [];
104
+
105
+
106
+	/**
107
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
108
+	 * play nice
109
+	 *
110
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
111
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
112
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
113
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
114
+	 *                                                         corresponding db model or not.
115
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
116
+	 *                                                         be in when instantiating a EE_Base_Class object.
117
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
118
+	 *                                                         value is the date_format and second value is the time
119
+	 *                                                         format.
120
+	 * @throws InvalidArgumentException
121
+	 * @throws InvalidInterfaceException
122
+	 * @throws InvalidDataTypeException
123
+	 * @throws EE_Error
124
+	 * @throws ReflectionException
125
+	 */
126
+	protected function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
127
+	{
128
+		$className = get_class($this);
129
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
130
+		$model        = $this->get_model();
131
+		$model_fields = $model->field_settings();
132
+		// ensure $fieldValues is an array
133
+		$fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
134
+		// verify client code has not passed any invalid field names
135
+		foreach ($fieldValues as $field_name => $field_value) {
136
+			if (! isset($model_fields[ $field_name ])) {
137
+				throw new EE_Error(
138
+					sprintf(
139
+						esc_html__(
140
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
141
+							'event_espresso'
142
+						),
143
+						$field_name,
144
+						get_class($this),
145
+						implode(', ', array_keys($model_fields))
146
+					)
147
+				);
148
+			}
149
+		}
150
+
151
+		$date_format     = null;
152
+		$time_format     = null;
153
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
154
+		if (! empty($date_formats) && is_array($date_formats)) {
155
+			[$date_format, $time_format] = $date_formats;
156
+		}
157
+		$this->set_date_format($date_format);
158
+		$this->set_time_format($time_format);
159
+		// if db model is instantiating
160
+		foreach ($model_fields as $fieldName => $field) {
161
+			if ($bydb) {
162
+				// client code has indicated these field values are from the database
163
+				$this->set_from_db(
164
+					$fieldName,
165
+					$fieldValues[ $fieldName ] ?? null
166
+				);
167
+			} else {
168
+				// we're constructing a brand new instance of the model object.
169
+				// Generally, this means we'll need to do more field validation
170
+				$this->set(
171
+					$fieldName,
172
+					$fieldValues[ $fieldName ] ?? null,
173
+					true
174
+				);
175
+			}
176
+		}
177
+		// remember what values were passed to this constructor
178
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
179
+		// remember in entity mapper
180
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
181
+			$model->add_to_entity_map($this);
182
+		}
183
+		// setup all the relations
184
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
185
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
186
+				$this->_model_relations[ $relation_name ] = null;
187
+			} else {
188
+				$this->_model_relations[ $relation_name ] = [];
189
+			}
190
+		}
191
+		/**
192
+		 * Action done at the end of each model object construction
193
+		 *
194
+		 * @param EE_Base_Class $this the model object just created
195
+		 */
196
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
197
+	}
198
+
199
+
200
+	/**
201
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
202
+	 *
203
+	 * @return boolean
204
+	 */
205
+	public function allow_persist()
206
+	{
207
+		return $this->_allow_persist;
208
+	}
209
+
210
+
211
+	/**
212
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
213
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
214
+	 * you got new information that somehow made you change your mind.
215
+	 *
216
+	 * @param boolean $allow_persist
217
+	 * @return boolean
218
+	 */
219
+	public function set_allow_persist($allow_persist)
220
+	{
221
+		return $this->_allow_persist = $allow_persist;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Gets the field's original value when this object was constructed during this request.
227
+	 * This can be helpful when determining if a model object has changed or not
228
+	 *
229
+	 * @param string $field_name
230
+	 * @return mixed|null
231
+	 * @throws ReflectionException
232
+	 * @throws InvalidArgumentException
233
+	 * @throws InvalidInterfaceException
234
+	 * @throws InvalidDataTypeException
235
+	 * @throws EE_Error
236
+	 */
237
+	public function get_original($field_name)
238
+	{
239
+		if (
240
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
241
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
242
+		) {
243
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
244
+		}
245
+		return null;
246
+	}
247
+
248
+
249
+	/**
250
+	 * @param EE_Base_Class $obj
251
+	 * @return string
252
+	 */
253
+	public function get_class($obj)
254
+	{
255
+		return get_class($obj);
256
+	}
257
+
258
+
259
+	/**
260
+	 * Overrides parent because parent expects old models.
261
+	 * This also doesn't do any validation, and won't work for serialized arrays
262
+	 *
263
+	 * @param string $field_name
264
+	 * @param mixed  $field_value
265
+	 * @param bool   $use_default
266
+	 * @throws InvalidArgumentException
267
+	 * @throws InvalidInterfaceException
268
+	 * @throws InvalidDataTypeException
269
+	 * @throws EE_Error
270
+	 * @throws ReflectionException
271
+	 * @throws Exception
272
+	 */
273
+	public function set(string $field_name, $field_value, bool $use_default = false)
274
+	{
275
+		// if not using default and nothing has changed, and object has already been setup (has ID),
276
+		// then don't do anything
277
+		if (
278
+			! $use_default
279
+			&& $this->_fields[ $field_name ] === $field_value
280
+			&& $this->ID()
281
+		) {
282
+			return;
283
+		}
284
+		$model              = $this->get_model();
285
+		$this->_has_changes = true;
286
+		$field_obj          = $model->field_settings_for($field_name);
287
+		if (! $field_obj instanceof EE_Model_Field_Base) {
288
+			throw new EE_Error(
289
+				sprintf(
290
+					esc_html__(
291
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
292
+						'event_espresso'
293
+					),
294
+					$field_name
295
+				)
296
+			);
297
+		}
298
+		// if ( method_exists( $field_obj, 'set_timezone' )) {
299
+		if ($field_obj instanceof EE_Datetime_Field) {
300
+			$field_obj->set_timezone($this->_timezone);
301
+			$field_obj->set_date_format($this->_dt_frmt);
302
+			$field_obj->set_time_format($this->_tm_frmt);
303
+		}
304
+
305
+		// should the value be null?
306
+		$value = $field_value === null && ($use_default || ! $field_obj->is_nullable())
307
+			? $field_obj->get_default_value()
308
+			: $field_value;
309
+
310
+		$this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
311
+
312
+		// if we're not in the constructor...
313
+		// now check if what we set was a primary key
314
+		if (
315
+			// note: props_n_values_provided_in_constructor is only set at the END of the constructor
316
+			$this->_props_n_values_provided_in_constructor
317
+			&& $field_value
318
+			&& $field_name === $model->primary_key_name()
319
+		) {
320
+			// if so, we want all this object's fields to be filled either with
321
+			// what we've explicitly set on this model
322
+			// or what we have in the db
323
+			// echo "setting primary key!";
324
+			$fields_on_model = self::_get_model(get_class($this))->field_settings();
325
+			$obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
326
+			foreach ($fields_on_model as $field_obj) {
327
+				if (
328
+					! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
329
+					&& $field_obj->get_name() !== $field_name
330
+				) {
331
+					$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
332
+				}
333
+			}
334
+			// oh this model object has an ID? well make sure its in the entity mapper
335
+			$model->add_to_entity_map($this);
336
+		}
337
+		// let's unset any cache for this field_name from the $_cached_properties property.
338
+		$this->_clear_cached_property($field_name);
339
+	}
340
+
341
+
342
+	/**
343
+	 * Overrides parent because parent expects old models.
344
+	 * This also doesn't do any validation, and won't work for serialized arrays
345
+	 *
346
+	 * @param string $field_name
347
+	 * @param mixed  $field_value_from_db
348
+	 * @throws ReflectionException
349
+	 * @throws InvalidArgumentException
350
+	 * @throws InvalidInterfaceException
351
+	 * @throws InvalidDataTypeException
352
+	 * @throws EE_Error
353
+	 */
354
+	public function set_from_db(string $field_name, $field_value_from_db)
355
+	{
356
+		$field_obj = $this->get_model()->field_settings_for($field_name);
357
+		if ($field_obj instanceof EE_Model_Field_Base) {
358
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
359
+			// eg, a CPT model object could have an entry in the posts table, but no
360
+			// entry in the meta table. Meaning that all its columns in the meta table
361
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
362
+			if ($field_value_from_db === null) {
363
+				if ($field_obj->is_nullable()) {
364
+					// if the field allows nulls, then let it be null
365
+					$field_value = null;
366
+				} else {
367
+					$field_value = $field_obj->get_default_value();
368
+				}
369
+			} else {
370
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
371
+			}
372
+			$this->_fields[ $field_name ] = $field_value;
373
+			$this->_clear_cached_property($field_name);
374
+		}
375
+	}
376
+
377
+
378
+	/**
379
+	 * Set custom select values for model.
380
+	 *
381
+	 * @param array $custom_select_values
382
+	 */
383
+	public function setCustomSelectsValues(array $custom_select_values)
384
+	{
385
+		$this->custom_selection_results = $custom_select_values;
386
+	}
387
+
388
+
389
+	/**
390
+	 * Returns the custom select value for the provided alias if its set.
391
+	 * If not set, returns null.
392
+	 *
393
+	 * @param string $alias
394
+	 * @return string|int|float|null
395
+	 */
396
+	public function getCustomSelect($alias)
397
+	{
398
+		return $this->custom_selection_results[ $alias ] ?? null;
399
+	}
400
+
401
+
402
+	/**
403
+	 * This sets the field value on the db column if it exists for the given $column_name or
404
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
405
+	 *
406
+	 * @param string $field_name  Must be the exact column name.
407
+	 * @param mixed  $field_value The value to set.
408
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
409
+	 * @throws InvalidArgumentException
410
+	 * @throws InvalidInterfaceException
411
+	 * @throws InvalidDataTypeException
412
+	 * @throws EE_Error
413
+	 * @throws ReflectionException
414
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
415
+	 */
416
+	public function set_field_or_extra_meta($field_name, $field_value)
417
+	{
418
+		if ($this->get_model()->has_field($field_name)) {
419
+			$this->set($field_name, $field_value);
420
+			return true;
421
+		}
422
+		// ensure this object is saved first so that extra meta can be properly related.
423
+		$this->save();
424
+		return $this->update_extra_meta($field_name, $field_value);
425
+	}
426
+
427
+
428
+	/**
429
+	 * This retrieves the value of the db column set on this class or if that's not present
430
+	 * it will attempt to retrieve from extra_meta if found.
431
+	 * Example Usage:
432
+	 * Via EE_Message child class:
433
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
434
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
435
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
436
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
437
+	 * value for those extra fields dynamically via the EE_message object.
438
+	 *
439
+	 * @param string $field_name expecting the fully qualified field name.
440
+	 * @return mixed|null  value for the field if found.  null if not found.
441
+	 * @throws ReflectionException
442
+	 * @throws InvalidArgumentException
443
+	 * @throws InvalidInterfaceException
444
+	 * @throws InvalidDataTypeException
445
+	 * @throws EE_Error
446
+	 */
447
+	public function get_field_or_extra_meta($field_name)
448
+	{
449
+		if ($this->get_model()->has_field($field_name)) {
450
+			$column_value = $this->get($field_name);
451
+		} else {
452
+			// This isn't a column in the main table, let's see if it is in the extra meta.
453
+			$column_value = $this->get_extra_meta($field_name, true, null);
454
+		}
455
+		return $column_value;
456
+	}
457
+
458
+
459
+	/**
460
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
461
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
462
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
463
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
464
+	 *
465
+	 * @access public
466
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
467
+	 * @return void
468
+	 * @throws InvalidArgumentException
469
+	 * @throws InvalidInterfaceException
470
+	 * @throws InvalidDataTypeException
471
+	 * @throws EE_Error
472
+	 * @throws ReflectionException
473
+	 * @throws Exception
474
+	 */
475
+	public function set_timezone($timezone = '')
476
+	{
477
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
478
+		// make sure we clear all cached properties because they won't be relevant now
479
+		$this->_clear_cached_properties();
480
+		// make sure we update field settings and the date for all EE_Datetime_Fields
481
+		$model_fields = $this->get_model()->field_settings(false);
482
+		foreach ($model_fields as $field_name => $field_obj) {
483
+			if ($field_obj instanceof EE_Datetime_Field) {
484
+				$field_obj->set_timezone($this->_timezone);
485
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
486
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
487
+				}
488
+			}
489
+		}
490
+	}
491
+
492
+
493
+	/**
494
+	 * This just returns whatever is set for the current timezone.
495
+	 *
496
+	 * @access public
497
+	 * @return string timezone string
498
+	 */
499
+	public function get_timezone()
500
+	{
501
+		return $this->_timezone;
502
+	}
503
+
504
+
505
+	/**
506
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
507
+	 * internally instead of wp set date format options
508
+	 *
509
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
510
+	 * @since 4.6
511
+	 */
512
+	public function set_date_format(?string $format)
513
+	{
514
+		$this->_dt_frmt = new DateFormat($format);
515
+		// clear cached_properties because they won't be relevant now.
516
+		$this->_clear_cached_properties();
517
+	}
518
+
519
+
520
+	/**
521
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
522
+	 * class internally instead of wp set time format options.
523
+	 *
524
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
525
+	 * @since 4.6
526
+	 */
527
+	public function set_time_format(?string $format)
528
+	{
529
+		$this->_tm_frmt = new TimeFormat($format);
530
+		// clear cached_properties because they won't be relevant now.
531
+		$this->_clear_cached_properties();
532
+	}
533
+
534
+
535
+	/**
536
+	 * This returns the current internal set format for the date and time formats.
537
+	 *
538
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
539
+	 *                             where the first value is the date format and the second value is the time format.
540
+	 * @return string|array
541
+	 */
542
+	public function get_format($full = true)
543
+	{
544
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
545
+	}
546
+
547
+
548
+	/**
549
+	 * cache
550
+	 * stores the passed model object on the current model object.
551
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
552
+	 *
553
+	 * @param string        $relation_name   one of the keys in the _model_relations array on the model. Eg
554
+	 *                                       'Registration' associated with this model object
555
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
556
+	 *                                       that could be a payment or a registration)
557
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
558
+	 *                                       items which will be stored in an array on this object
559
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
560
+	 *                                       related thing, no array)
561
+	 * @throws InvalidArgumentException
562
+	 * @throws InvalidInterfaceException
563
+	 * @throws InvalidDataTypeException
564
+	 * @throws EE_Error
565
+	 * @throws ReflectionException
566
+	 */
567
+	public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
568
+	{
569
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
570
+		if (! $object_to_cache instanceof EE_Base_Class) {
571
+			return false;
572
+		}
573
+		// also get "how" the object is related, or throw an error
574
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
575
+			throw new EE_Error(
576
+				sprintf(
577
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
578
+					$relation_name,
579
+					get_class($this)
580
+				)
581
+			);
582
+		}
583
+		// how many things are related ?
584
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
585
+			// if it's a "belongs to" relationship, then there's only one related model object
586
+			// eg, if this is a registration, there's only 1 attendee for it
587
+			// so for these model objects just set it to be cached
588
+			$this->_model_relations[ $relation_name ] = $object_to_cache;
589
+			$return                                   = true;
590
+		} else {
591
+			// otherwise, this is the "many" side of a one to many relationship,
592
+			// so we'll add the object to the array of related objects for that type.
593
+			// eg: if this is an event, there are many registrations for that event,
594
+			// so we cache the registrations in an array
595
+			if (! is_array($this->_model_relations[ $relation_name ])) {
596
+				// if for some reason, the cached item is a model object,
597
+				// then stick that in the array, otherwise start with an empty array
598
+				$this->_model_relations[ $relation_name ] =
599
+					$this->_model_relations[ $relation_name ] instanceof EE_Base_Class
600
+						? [$this->_model_relations[ $relation_name ]]
601
+						: [];
602
+			}
603
+			// first check for a cache_id which is normally empty
604
+			if (! empty($cache_id)) {
605
+				// if the cache_id exists, then it means we are purposely trying to cache this
606
+				// with a known key that can then be used to retrieve the object later on
607
+				$this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
608
+				$return                                                = $cache_id;
609
+			} elseif ($object_to_cache->ID()) {
610
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
611
+				$this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
612
+				$return                                                             = $object_to_cache->ID();
613
+			} else {
614
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
615
+				$this->_model_relations[ $relation_name ][] = $object_to_cache;
616
+				// move the internal pointer to the end of the array
617
+				end($this->_model_relations[ $relation_name ]);
618
+				// and grab the key so that we can return it
619
+				$return = key($this->_model_relations[ $relation_name ]);
620
+			}
621
+		}
622
+		return $return;
623
+	}
624
+
625
+
626
+	/**
627
+	 * For adding an item to the cached_properties property.
628
+	 *
629
+	 * @access protected
630
+	 * @param string      $fieldname the property item the corresponding value is for.
631
+	 * @param mixed       $value     The value we are caching.
632
+	 * @param string|null $cache_type
633
+	 * @return void
634
+	 * @throws ReflectionException
635
+	 * @throws InvalidArgumentException
636
+	 * @throws InvalidInterfaceException
637
+	 * @throws InvalidDataTypeException
638
+	 * @throws EE_Error
639
+	 */
640
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
641
+	{
642
+		// first make sure this property exists
643
+		$this->get_model()->field_settings_for($fieldname);
644
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
645
+
646
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
647
+	}
648
+
649
+
650
+	/**
651
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
652
+	 * This also SETS the cache if we return the actual property!
653
+	 *
654
+	 * @param string $fieldname        the name of the property we're trying to retrieve
655
+	 * @param bool   $pretty
656
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
657
+	 *                                 (in cases where the same property may be used for different outputs
658
+	 *                                 - i.e. datetime, money etc.)
659
+	 *                                 It can also accept certain pre-defined "schema" strings
660
+	 *                                 to define how to output the property.
661
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
662
+	 * @return mixed                   whatever the value for the property is we're retrieving
663
+	 * @throws ReflectionException
664
+	 * @throws InvalidArgumentException
665
+	 * @throws InvalidInterfaceException
666
+	 * @throws InvalidDataTypeException
667
+	 * @throws EE_Error
668
+	 */
669
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
670
+	{
671
+		// verify the field exists
672
+		$model = $this->get_model();
673
+		$model->field_settings_for($fieldname);
674
+		$cache_type = $pretty ? 'pretty' : 'standard';
675
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
676
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
677
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
678
+		}
679
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
680
+		$this->_set_cached_property($fieldname, $value, $cache_type);
681
+		return $value;
682
+	}
683
+
684
+
685
+	/**
686
+	 * If the cache didn't fetch the needed item, this fetches it.
687
+	 *
688
+	 * @param string $fieldname
689
+	 * @param bool   $pretty
690
+	 * @param string $extra_cache_ref
691
+	 * @return mixed
692
+	 * @throws InvalidArgumentException
693
+	 * @throws InvalidInterfaceException
694
+	 * @throws InvalidDataTypeException
695
+	 * @throws EE_Error
696
+	 * @throws ReflectionException
697
+	 */
698
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
699
+	{
700
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
701
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
702
+		if ($field_obj instanceof EE_Datetime_Field) {
703
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
704
+		}
705
+		if (! isset($this->_fields[ $fieldname ])) {
706
+			$this->_fields[ $fieldname ] = null;
707
+		}
708
+		return $pretty
709
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
710
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
711
+	}
712
+
713
+
714
+	/**
715
+	 * set timezone, formats, and output for EE_Datetime_Field objects
716
+	 *
717
+	 * @param EE_Datetime_Field $datetime_field
718
+	 * @param bool              $pretty
719
+	 * @param null              $date_or_time
720
+	 * @return void
721
+	 * @throws InvalidArgumentException
722
+	 * @throws InvalidInterfaceException
723
+	 * @throws InvalidDataTypeException
724
+	 */
725
+	protected function _prepare_datetime_field(
726
+		EE_Datetime_Field $datetime_field,
727
+		$pretty = false,
728
+		$date_or_time = null
729
+	) {
730
+		$datetime_field->set_timezone($this->_timezone);
731
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
732
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
733
+		// set the output returned
734
+		switch ($date_or_time) {
735
+			case 'D':
736
+				$datetime_field->set_date_time_output('date');
737
+				break;
738
+			case 'T':
739
+				$datetime_field->set_date_time_output('time');
740
+				break;
741
+			default:
742
+				$datetime_field->set_date_time_output();
743
+		}
744
+	}
745
+
746
+
747
+	/**
748
+	 * This just takes care of clearing out the cached_properties
749
+	 *
750
+	 * @return void
751
+	 */
752
+	protected function _clear_cached_properties()
753
+	{
754
+		$this->_cached_properties = [];
755
+	}
756
+
757
+
758
+	/**
759
+	 * This just clears out ONE property if it exists in the cache
760
+	 *
761
+	 * @param string $property_name the property to remove if it exists (from the _cached_properties array)
762
+	 * @return void
763
+	 */
764
+	protected function _clear_cached_property($property_name)
765
+	{
766
+		if (isset($this->_cached_properties[ $property_name ])) {
767
+			unset($this->_cached_properties[ $property_name ]);
768
+		}
769
+	}
770
+
771
+
772
+	/**
773
+	 * Ensures that this related thing is a model object.
774
+	 *
775
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
776
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
777
+	 * @return EE_Base_Class
778
+	 * @throws ReflectionException
779
+	 * @throws InvalidArgumentException
780
+	 * @throws InvalidInterfaceException
781
+	 * @throws InvalidDataTypeException
782
+	 * @throws EE_Error
783
+	 */
784
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
785
+	{
786
+		$other_model_instance = self::_get_model_instance_with_name(
787
+			self::_get_model_classname($model_name),
788
+			$this->_timezone
789
+		);
790
+		return $other_model_instance->ensure_is_obj($object_or_id);
791
+	}
792
+
793
+
794
+	/**
795
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
796
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
797
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
798
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
799
+	 *
800
+	 * @param string $relation_name                        one of the keys in the _model_relations array on the model.
801
+	 *                                                     Eg 'Registration'
802
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
803
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
804
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
805
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
806
+	 *                                                     this is HasMany or HABTM.
807
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
808
+	 *                                                     relation from all
809
+	 * @throws InvalidArgumentException
810
+	 * @throws InvalidInterfaceException
811
+	 * @throws InvalidDataTypeException
812
+	 * @throws EE_Error
813
+	 * @throws ReflectionException
814
+	 */
815
+	public function clear_cache($relation_name, $object_to_remove_or_index_into_array = null, $clear_all = false)
816
+	{
817
+		$relationship_to_model = $this->get_model()->related_settings_for($relation_name);
818
+		$index_in_cache        = '';
819
+		if (! $relationship_to_model) {
820
+			throw new EE_Error(
821
+				sprintf(
822
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
823
+					$relation_name,
824
+					get_class($this)
825
+				)
826
+			);
827
+		}
828
+		if ($clear_all) {
829
+			$obj_removed                              = true;
830
+			$this->_model_relations[ $relation_name ] = null;
831
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
+			$obj_removed                              = $this->_model_relations[ $relation_name ];
833
+			$this->_model_relations[ $relation_name ] = null;
834
+		} else {
835
+			if (
836
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
837
+				&& $object_to_remove_or_index_into_array->ID()
838
+			) {
839
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
840
+				if (
841
+					is_array($this->_model_relations[ $relation_name ])
842
+					&& ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
843
+				) {
844
+					$index_found_at = null;
845
+					// find this object in the array even though it has a different key
846
+					foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
847
+						/** @noinspection TypeUnsafeComparisonInspection */
848
+						if (
849
+							$obj instanceof EE_Base_Class
850
+							&& (
851
+								$obj == $object_to_remove_or_index_into_array
852
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
853
+							)
854
+						) {
855
+							$index_found_at = $index;
856
+							break;
857
+						}
858
+					}
859
+					if ($index_found_at) {
860
+						$index_in_cache = $index_found_at;
861
+					} else {
862
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
863
+						// if it wasn't in it to begin with. So we're done
864
+						return $object_to_remove_or_index_into_array;
865
+					}
866
+				}
867
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
868
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
869
+				foreach ($this->get_all_from_cache($relation_name) as $index => $potentially_obj_we_want) {
870
+					/** @noinspection TypeUnsafeComparisonInspection */
871
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
872
+						$index_in_cache = $index;
873
+					}
874
+				}
875
+			} else {
876
+				$index_in_cache = $object_to_remove_or_index_into_array;
877
+			}
878
+			// supposedly we've found it. But it could just be that the client code
879
+			// provided a bad index/object
880
+			if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
881
+				$obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
882
+				unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
883
+			} else {
884
+				// that thing was never cached anyways.
885
+				$obj_removed = null;
886
+			}
887
+		}
888
+		return $obj_removed;
889
+	}
890
+
891
+
892
+	/**
893
+	 * update_cache_after_object_save
894
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
895
+	 * obtained after being saved to the db
896
+	 *
897
+	 * @param string        $relation_name      - the type of object that is cached
898
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
899
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
900
+	 * @return boolean TRUE on success, FALSE on fail
901
+	 * @throws ReflectionException
902
+	 * @throws InvalidArgumentException
903
+	 * @throws InvalidInterfaceException
904
+	 * @throws InvalidDataTypeException
905
+	 * @throws EE_Error
906
+	 */
907
+	public function update_cache_after_object_save(
908
+		$relation_name,
909
+		EE_Base_Class $newly_saved_object,
910
+		$current_cache_id = ''
911
+	) {
912
+		// verify that incoming object is of the correct type
913
+		$obj_class = 'EE_' . $relation_name;
914
+		if ($newly_saved_object instanceof $obj_class) {
915
+			/* @type EE_Base_Class $newly_saved_object */
916
+			// now get the type of relation
917
+			$relationship_to_model = $this->get_model()->related_settings_for($relation_name);
918
+			// if this is a 1:1 relationship
919
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
920
+				// then just replace the cached object with the newly saved object
921
+				$this->_model_relations[ $relation_name ] = $newly_saved_object;
922
+				return true;
923
+				// or if it's some kind of sordid feral polyamorous relationship...
924
+			}
925
+			if (
926
+				is_array($this->_model_relations[ $relation_name ])
927
+				&& isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
928
+			) {
929
+				// then remove the current cached item
930
+				unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
931
+				// and cache the newly saved object using it's new ID
932
+				$this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
933
+				return true;
934
+			}
935
+		}
936
+		return false;
937
+	}
938
+
939
+
940
+	/**
941
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
942
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
943
+	 *
944
+	 * @param string $relation_name
945
+	 * @return EE_Base_Class
946
+	 */
947
+	public function get_one_from_cache($relation_name)
948
+	{
949
+		$cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
950
+		if (is_array($cached_array_or_object)) {
951
+			return array_shift($cached_array_or_object);
952
+		}
953
+		return $cached_array_or_object;
954
+	}
955
+
956
+
957
+	/**
958
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
959
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
960
+	 *
961
+	 * @param string $relation_name
962
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
963
+	 * @throws InvalidArgumentException
964
+	 * @throws InvalidInterfaceException
965
+	 * @throws InvalidDataTypeException
966
+	 * @throws EE_Error
967
+	 * @throws ReflectionException
968
+	 */
969
+	public function get_all_from_cache($relation_name)
970
+	{
971
+		$objects = $this->_model_relations[ $relation_name ] ?? [];
972
+		// if the result is not an array, but exists, make it an array
973
+		$objects = is_array($objects)
974
+			? $objects
975
+			: [$objects];
976
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
977
+		// basically, if this model object was stored in the session, and these cached model objects
978
+		// already have IDs, let's make sure they're in their model's entity mapper
979
+		// otherwise we will have duplicates next time we call
980
+		// EE_Registry::instance()->load_model( $relation_name )->get_one_by_ID( $result->ID() );
981
+		$model = EE_Registry::instance()->load_model($relation_name);
982
+		foreach ($objects as $model_object) {
983
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
984
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
985
+				if ($model_object->ID()) {
986
+					$model->add_to_entity_map($model_object);
987
+				}
988
+			} else {
989
+				throw new EE_Error(
990
+					sprintf(
991
+						esc_html__(
992
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
993
+							'event_espresso'
994
+						),
995
+						$relation_name,
996
+						gettype($model_object)
997
+					)
998
+				);
999
+			}
1000
+		}
1001
+		return $objects;
1002
+	}
1003
+
1004
+
1005
+	/**
1006
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1007
+	 * matching the given query conditions.
1008
+	 *
1009
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1010
+	 * @param int   $limit              How many objects to return.
1011
+	 * @param array $query_params       Any additional conditions on the query.
1012
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1013
+	 *                                  you can indicate just the columns you want returned
1014
+	 * @return array|EE_Base_Class[]
1015
+	 * @throws ReflectionException
1016
+	 * @throws InvalidArgumentException
1017
+	 * @throws InvalidInterfaceException
1018
+	 * @throws InvalidDataTypeException
1019
+	 * @throws EE_Error
1020
+	 */
1021
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = [], $columns_to_select = null)
1022
+	{
1023
+		$model         = $this->get_model();
1024
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1025
+			? $model->get_primary_key_field()->get_name()
1026
+			: $field_to_order_by;
1027
+		$current_value = ! empty($field)
1028
+			? $this->get($field)
1029
+			: null;
1030
+		if (empty($field) || empty($current_value)) {
1031
+			return [];
1032
+		}
1033
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1039
+	 * matching the given query conditions.
1040
+	 *
1041
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1042
+	 * @param int   $limit              How many objects to return.
1043
+	 * @param array $query_params       Any additional conditions on the query.
1044
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1045
+	 *                                  you can indicate just the columns you want returned
1046
+	 * @return array|EE_Base_Class[]
1047
+	 * @throws ReflectionException
1048
+	 * @throws InvalidArgumentException
1049
+	 * @throws InvalidInterfaceException
1050
+	 * @throws InvalidDataTypeException
1051
+	 * @throws EE_Error
1052
+	 */
1053
+	public function previous_x(
1054
+		$field_to_order_by = null,
1055
+		$limit = 1,
1056
+		$query_params = [],
1057
+		$columns_to_select = null
1058
+	) {
1059
+		$model         = $this->get_model();
1060
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1061
+			? $model->get_primary_key_field()->get_name()
1062
+			: $field_to_order_by;
1063
+		$current_value = ! empty($field) ? $this->get($field) : null;
1064
+		if (empty($field) || empty($current_value)) {
1065
+			return [];
1066
+		}
1067
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1068
+	}
1069
+
1070
+
1071
+	/**
1072
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1073
+	 * matching the given query conditions.
1074
+	 *
1075
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1076
+	 * @param array $query_params       Any additional conditions on the query.
1077
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1078
+	 *                                  you can indicate just the columns you want returned
1079
+	 * @return array|EE_Base_Class
1080
+	 * @throws ReflectionException
1081
+	 * @throws InvalidArgumentException
1082
+	 * @throws InvalidInterfaceException
1083
+	 * @throws InvalidDataTypeException
1084
+	 * @throws EE_Error
1085
+	 */
1086
+	public function next($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1087
+	{
1088
+		$model         = $this->get_model();
1089
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1090
+			? $model->get_primary_key_field()->get_name()
1091
+			: $field_to_order_by;
1092
+		$current_value = ! empty($field) ? $this->get($field) : null;
1093
+		if (empty($field) || empty($current_value)) {
1094
+			return [];
1095
+		}
1096
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1097
+	}
1098
+
1099
+
1100
+	/**
1101
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1102
+	 * matching the given query conditions.
1103
+	 *
1104
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1105
+	 * @param array $query_params       Any additional conditions on the query.
1106
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1107
+	 *                                  you can indicate just the column you want returned
1108
+	 * @return array|EE_Base_Class
1109
+	 * @throws ReflectionException
1110
+	 * @throws InvalidArgumentException
1111
+	 * @throws InvalidInterfaceException
1112
+	 * @throws InvalidDataTypeException
1113
+	 * @throws EE_Error
1114
+	 */
1115
+	public function previous($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1116
+	{
1117
+		$model         = $this->get_model();
1118
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1119
+			? $model->get_primary_key_field()->get_name()
1120
+			: $field_to_order_by;
1121
+		$current_value = ! empty($field) ? $this->get($field) : null;
1122
+		if (empty($field) || empty($current_value)) {
1123
+			return [];
1124
+		}
1125
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * verifies that the specified field is of the correct type
1131
+	 *
1132
+	 * @param string $field_name
1133
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1134
+	 *                                (in cases where the same property may be used for different outputs
1135
+	 *                                - i.e. datetime, money etc.)
1136
+	 * @return mixed
1137
+	 * @throws ReflectionException
1138
+	 * @throws InvalidArgumentException
1139
+	 * @throws InvalidInterfaceException
1140
+	 * @throws InvalidDataTypeException
1141
+	 * @throws EE_Error
1142
+	 */
1143
+	public function get($field_name, $extra_cache_ref = null)
1144
+	{
1145
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1146
+	}
1147
+
1148
+
1149
+	/**
1150
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1151
+	 *
1152
+	 * @param string $field_name A valid fieldname
1153
+	 * @return mixed              Whatever the raw value stored on the property is.
1154
+	 * @throws ReflectionException
1155
+	 * @throws InvalidArgumentException
1156
+	 * @throws InvalidInterfaceException
1157
+	 * @throws InvalidDataTypeException
1158
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1159
+	 */
1160
+	public function get_raw($field_name)
1161
+	{
1162
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1163
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1164
+			? $this->_fields[ $field_name ]->format('U')
1165
+			: $this->_fields[ $field_name ];
1166
+	}
1167
+
1168
+
1169
+	/**
1170
+	 * This is used to return the internal DateTime object used for a field that is a
1171
+	 * EE_Datetime_Field.
1172
+	 *
1173
+	 * @param string $field_name               The field name retrieving the DateTime object.
1174
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1175
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1176
+	 *                                         EE_Datetime_Field and but the field value is null, then
1177
+	 *                                         just null is returned (because that indicates that likely
1178
+	 *                                         this field is nullable).
1179
+	 * @throws InvalidArgumentException
1180
+	 * @throws InvalidDataTypeException
1181
+	 * @throws InvalidInterfaceException
1182
+	 * @throws ReflectionException
1183
+	 */
1184
+	public function get_DateTime_object($field_name)
1185
+	{
1186
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1187
+		if (! $field_settings instanceof EE_Datetime_Field) {
1188
+			EE_Error::add_error(
1189
+				sprintf(
1190
+					esc_html__(
1191
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1192
+						'event_espresso'
1193
+					),
1194
+					$field_name
1195
+				),
1196
+				__FILE__,
1197
+				__FUNCTION__,
1198
+				__LINE__
1199
+			);
1200
+			return false;
1201
+		}
1202
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1203
+			? clone $this->_fields[ $field_name ]
1204
+			: null;
1205
+	}
1206
+
1207
+
1208
+	/**
1209
+	 * To be used in template to immediately echo out the value, and format it for output.
1210
+	 * Eg, should call stripslashes and whatnot before echoing
1211
+	 *
1212
+	 * @param string $field_name      the name of the field as it appears in the DB
1213
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1214
+	 *                                (in cases where the same property may be used for different outputs
1215
+	 *                                - i.e. datetime, money etc.)
1216
+	 * @return void
1217
+	 * @throws ReflectionException
1218
+	 * @throws InvalidArgumentException
1219
+	 * @throws InvalidInterfaceException
1220
+	 * @throws InvalidDataTypeException
1221
+	 * @throws EE_Error
1222
+	 */
1223
+	public function e($field_name, $extra_cache_ref = null)
1224
+	{
1225
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1231
+	 * can be easily used as the value of form input.
1232
+	 *
1233
+	 * @param string $field_name
1234
+	 * @return void
1235
+	 * @throws ReflectionException
1236
+	 * @throws InvalidArgumentException
1237
+	 * @throws InvalidInterfaceException
1238
+	 * @throws InvalidDataTypeException
1239
+	 * @throws EE_Error
1240
+	 */
1241
+	public function f($field_name)
1242
+	{
1243
+		$this->e($field_name, 'form_input');
1244
+	}
1245
+
1246
+
1247
+	/**
1248
+	 * Same as `f()` but just returns the value instead of echoing it
1249
+	 *
1250
+	 * @param string $field_name
1251
+	 * @return string
1252
+	 * @throws ReflectionException
1253
+	 * @throws InvalidArgumentException
1254
+	 * @throws InvalidInterfaceException
1255
+	 * @throws InvalidDataTypeException
1256
+	 * @throws EE_Error
1257
+	 */
1258
+	public function get_f($field_name)
1259
+	{
1260
+		return (string) $this->get_pretty($field_name, 'form_input');
1261
+	}
1262
+
1263
+
1264
+	/**
1265
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1266
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1267
+	 * to see what options are available.
1268
+	 *
1269
+	 * @param string $field_name
1270
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1271
+	 *                                (in cases where the same property may be used for different outputs
1272
+	 *                                - i.e. datetime, money etc.)
1273
+	 * @return mixed
1274
+	 * @throws ReflectionException
1275
+	 * @throws InvalidArgumentException
1276
+	 * @throws InvalidInterfaceException
1277
+	 * @throws InvalidDataTypeException
1278
+	 * @throws EE_Error
1279
+	 */
1280
+	public function get_pretty($field_name, $extra_cache_ref = null)
1281
+	{
1282
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1283
+	}
1284
+
1285
+
1286
+	/**
1287
+	 * This simply returns the datetime for the given field name
1288
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1289
+	 * (and the equivalent e_date, e_time, e_datetime).
1290
+	 *
1291
+	 * @access   protected
1292
+	 * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1293
+	 * @param string|null $date_format  valid datetime format used for date
1294
+	 *                                  (if '' then we just use the default on the field,
1295
+	 *                                  if NULL we use the last-used format)
1296
+	 * @param string|null $time_format  Same as above except this is for time format
1297
+	 * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1298
+	 * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1299
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1300
+	 *                                  if field is not a valid dtt field, or void if echoing
1301
+	 * @throws EE_Error
1302
+	 * @throws ReflectionException
1303
+	 */
1304
+	protected function _get_datetime(
1305
+		string $field_name,
1306
+		?string $date_format = '',
1307
+		?string $time_format = '',
1308
+		?string $date_or_time = '',
1309
+		?bool $echo = false
1310
+	) {
1311
+		// clear cached property
1312
+		$this->_clear_cached_property($field_name);
1313
+		// reset format properties because they are used in get()
1314
+		$this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1315
+		$this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1316
+		if ($echo) {
1317
+			$this->e($field_name, $date_or_time);
1318
+			return '';
1319
+		}
1320
+		return $this->get($field_name, $date_or_time);
1321
+	}
1322
+
1323
+
1324
+	/**
1325
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1326
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1327
+	 * other echoes the pretty value for dtt)
1328
+	 *
1329
+	 * @param string $field_name name of model object datetime field holding the value
1330
+	 * @param string $format     format for the date returned (if NULL we use default in dt_frmt property)
1331
+	 * @return string            datetime value formatted
1332
+	 * @throws ReflectionException
1333
+	 * @throws InvalidArgumentException
1334
+	 * @throws InvalidInterfaceException
1335
+	 * @throws InvalidDataTypeException
1336
+	 * @throws EE_Error
1337
+	 */
1338
+	public function get_date($field_name, $format = '')
1339
+	{
1340
+		return $this->_get_datetime($field_name, $format, null, 'D');
1341
+	}
1342
+
1343
+
1344
+	/**
1345
+	 * @param        $field_name
1346
+	 * @param string $format
1347
+	 * @throws ReflectionException
1348
+	 * @throws InvalidArgumentException
1349
+	 * @throws InvalidInterfaceException
1350
+	 * @throws InvalidDataTypeException
1351
+	 * @throws EE_Error
1352
+	 */
1353
+	public function e_date($field_name, $format = '')
1354
+	{
1355
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1356
+	}
1357
+
1358
+
1359
+	/**
1360
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1361
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1362
+	 * other echoes the pretty value for dtt)
1363
+	 *
1364
+	 * @param string $field_name name of model object datetime field holding the value
1365
+	 * @param string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1366
+	 * @return string             datetime value formatted
1367
+	 * @throws ReflectionException
1368
+	 * @throws InvalidArgumentException
1369
+	 * @throws InvalidInterfaceException
1370
+	 * @throws InvalidDataTypeException
1371
+	 * @throws EE_Error
1372
+	 */
1373
+	public function get_time($field_name, $format = '')
1374
+	{
1375
+		return $this->_get_datetime($field_name, null, $format, 'T');
1376
+	}
1377
+
1378
+
1379
+	/**
1380
+	 * @param        $field_name
1381
+	 * @param string $format
1382
+	 * @throws ReflectionException
1383
+	 * @throws InvalidArgumentException
1384
+	 * @throws InvalidInterfaceException
1385
+	 * @throws InvalidDataTypeException
1386
+	 * @throws EE_Error
1387
+	 */
1388
+	public function e_time($field_name, $format = '')
1389
+	{
1390
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1391
+	}
1392
+
1393
+
1394
+	/**
1395
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1396
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1397
+	 * other echoes the pretty value for dtt)
1398
+	 *
1399
+	 * @param string $field_name  name of model object datetime field holding the value
1400
+	 * @param string $date_format format for the date returned (if NULL we use default in dt_frmt property)
1401
+	 * @param string $time_format format for the time returned (if NULL we use default in tm_frmt property)
1402
+	 * @return string             datetime value formatted
1403
+	 * @throws ReflectionException
1404
+	 * @throws InvalidArgumentException
1405
+	 * @throws InvalidInterfaceException
1406
+	 * @throws InvalidDataTypeException
1407
+	 * @throws EE_Error
1408
+	 */
1409
+	public function get_datetime($field_name, $date_format = '', $time_format = '')
1410
+	{
1411
+		return $this->_get_datetime($field_name, $date_format, $time_format);
1412
+	}
1413
+
1414
+
1415
+	/**
1416
+	 * @param string $field_name
1417
+	 * @param string $date_format
1418
+	 * @param string $time_format
1419
+	 * @throws ReflectionException
1420
+	 * @throws InvalidArgumentException
1421
+	 * @throws InvalidInterfaceException
1422
+	 * @throws InvalidDataTypeException
1423
+	 * @throws EE_Error
1424
+	 */
1425
+	public function e_datetime($field_name, $date_format = '', $time_format = '')
1426
+	{
1427
+		$this->_get_datetime($field_name, $date_format, $time_format, null, true);
1428
+	}
1429
+
1430
+
1431
+	/**
1432
+	 * Get the i8ln value for a date using the WordPress @param string $field_name The EE_Datetime_Field reference for
1433
+	 *                           the date being retrieved.
1434
+	 *
1435
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1436
+	 *                           on the object will be used.
1437
+	 * @return string Date and time string in set locale or false if no field exists for the given
1438
+	 * @throws ReflectionException
1439
+	 * @throws InvalidArgumentException
1440
+	 * @throws InvalidInterfaceException
1441
+	 * @throws InvalidDataTypeException
1442
+	 * @throws EE_Error
1443
+	 *                           field name.
1444
+	 * @see date_i18n function.
1445
+	 */
1446
+	public function get_i18n_datetime(string $field_name, string $format = ''): string
1447
+	{
1448
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1449
+		return date_i18n(
1450
+			$format,
1451
+			EEH_DTT_Helper::get_timestamp_with_offset(
1452
+				$this->get_raw($field_name),
1453
+				$this->_timezone
1454
+			)
1455
+		);
1456
+	}
1457
+
1458
+
1459
+	/**
1460
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1461
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1462
+	 * thrown.
1463
+	 *
1464
+	 * @param string $field_name The field name being checked
1465
+	 * @return EE_Datetime_Field
1466
+	 * @throws InvalidArgumentException
1467
+	 * @throws InvalidInterfaceException
1468
+	 * @throws InvalidDataTypeException
1469
+	 * @throws EE_Error
1470
+	 * @throws ReflectionException
1471
+	 */
1472
+	protected function _get_dtt_field_settings($field_name)
1473
+	{
1474
+		$field = $this->get_model()->field_settings_for($field_name);
1475
+		// check if field is dtt
1476
+		if ($field instanceof EE_Datetime_Field) {
1477
+			return $field;
1478
+		}
1479
+		throw new EE_Error(
1480
+			sprintf(
1481
+				esc_html__(
1482
+					'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',
1483
+					'event_espresso'
1484
+				),
1485
+				$field_name,
1486
+				self::_get_model_classname(get_class($this))
1487
+			)
1488
+		);
1489
+	}
1490
+
1491
+
1492
+
1493
+
1494
+	/**
1495
+	 * NOTE ABOUT BELOW:
1496
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1497
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1498
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1499
+	 * method and make sure you send the entire datetime value for setting.
1500
+	 */
1501
+	/**
1502
+	 * sets the time on a datetime property
1503
+	 *
1504
+	 * @access protected
1505
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1506
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1507
+	 * @throws ReflectionException
1508
+	 * @throws InvalidArgumentException
1509
+	 * @throws InvalidInterfaceException
1510
+	 * @throws InvalidDataTypeException
1511
+	 * @throws EE_Error
1512
+	 */
1513
+	protected function _set_time_for($time, $fieldname)
1514
+	{
1515
+		$this->_set_date_time('T', $time, $fieldname);
1516
+	}
1517
+
1518
+
1519
+	/**
1520
+	 * sets the date on a datetime property
1521
+	 *
1522
+	 * @access protected
1523
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1524
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1525
+	 * @throws ReflectionException
1526
+	 * @throws InvalidArgumentException
1527
+	 * @throws InvalidInterfaceException
1528
+	 * @throws InvalidDataTypeException
1529
+	 * @throws EE_Error
1530
+	 */
1531
+	protected function _set_date_for($date, $fieldname)
1532
+	{
1533
+		$this->_set_date_time('D', $date, $fieldname);
1534
+	}
1535
+
1536
+
1537
+	/**
1538
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1539
+	 * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1540
+	 *
1541
+	 * @access protected
1542
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1543
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1544
+	 * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1545
+	 *                                        EE_Datetime_Field property)
1546
+	 * @throws ReflectionException
1547
+	 * @throws InvalidArgumentException
1548
+	 * @throws InvalidInterfaceException
1549
+	 * @throws InvalidDataTypeException
1550
+	 * @throws EE_Error
1551
+	 */
1552
+	protected function _set_date_time(string $what, $datetime_value, string $field_name)
1553
+	{
1554
+		$field = $this->_get_dtt_field_settings($field_name);
1555
+		$field->set_timezone($this->_timezone);
1556
+		$field->set_date_format($this->_dt_frmt);
1557
+		$field->set_time_format($this->_tm_frmt);
1558
+		switch ($what) {
1559
+			case 'T':
1560
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1561
+					$datetime_value,
1562
+					$this->_fields[ $field_name ]
1563
+				);
1564
+				$this->_has_changes           = true;
1565
+				break;
1566
+			case 'D':
1567
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1568
+					$datetime_value,
1569
+					$this->_fields[ $field_name ]
1570
+				);
1571
+				$this->_has_changes           = true;
1572
+				break;
1573
+			case 'B':
1574
+				$this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1575
+				$this->_has_changes           = true;
1576
+				break;
1577
+		}
1578
+		$this->_clear_cached_property($field_name);
1579
+	}
1580
+
1581
+
1582
+	/**
1583
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1584
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1585
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1586
+	 * that could lead to some unexpected results!
1587
+	 *
1588
+	 * @access public
1589
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1590
+	 *                                         value being returned.
1591
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1592
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1593
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1594
+	 * @param string $append                   You can include something to append on the timestamp
1595
+	 * @return string timestamp
1596
+	 * @throws ReflectionException
1597
+	 * @throws InvalidArgumentException
1598
+	 * @throws InvalidInterfaceException
1599
+	 * @throws InvalidDataTypeException
1600
+	 * @throws EE_Error
1601
+	 */
1602
+	public function display_in_my_timezone(
1603
+		$field_name,
1604
+		$callback = 'get_datetime',
1605
+		$args = null,
1606
+		$prepend = '',
1607
+		$append = ''
1608
+	) {
1609
+		$timezone = EEH_DTT_Helper::get_timezone();
1610
+		if ($timezone === $this->_timezone) {
1611
+			return '';
1612
+		}
1613
+		$original_timezone = $this->_timezone;
1614
+		$this->set_timezone($timezone);
1615
+		$fn   = (array) $field_name;
1616
+		$args = array_merge($fn, (array) $args);
1617
+		if (! method_exists($this, $callback)) {
1618
+			throw new EE_Error(
1619
+				sprintf(
1620
+					esc_html__(
1621
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1622
+						'event_espresso'
1623
+					),
1624
+					$callback
1625
+				)
1626
+			);
1627
+		}
1628
+		$args   = (array) $args;
1629
+		$return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1630
+		$this->set_timezone($original_timezone);
1631
+		return $return;
1632
+	}
1633
+
1634
+
1635
+	/**
1636
+	 * Deletes this model object.
1637
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1638
+	 * override
1639
+	 * `EE_Base_Class::_delete` NOT this class.
1640
+	 *
1641
+	 * @return boolean | int
1642
+	 * @throws ReflectionException
1643
+	 * @throws InvalidArgumentException
1644
+	 * @throws InvalidInterfaceException
1645
+	 * @throws InvalidDataTypeException
1646
+	 * @throws EE_Error
1647
+	 */
1648
+	public function delete()
1649
+	{
1650
+		/**
1651
+		 * Called just before the `EE_Base_Class::_delete` method call.
1652
+		 * Note:
1653
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1654
+		 * should be aware that `_delete` may not always result in a permanent delete.
1655
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1656
+		 * soft deletes (trash) the object and does not permanently delete it.
1657
+		 *
1658
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1659
+		 */
1660
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1661
+		$result = $this->_delete();
1662
+		/**
1663
+		 * Called just after the `EE_Base_Class::_delete` method call.
1664
+		 * Note:
1665
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1666
+		 * should be aware that `_delete` may not always result in a permanent delete.
1667
+		 * For example `EE_Soft_Base_Class::_delete`
1668
+		 * soft deletes (trash) the object and does not permanently delete it.
1669
+		 *
1670
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1671
+		 * @param boolean       $result
1672
+		 */
1673
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1674
+		return $result;
1675
+	}
1676
+
1677
+
1678
+	/**
1679
+	 * Calls the specific delete method for the instantiated class.
1680
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1681
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1682
+	 * `EE_Base_Class::delete`
1683
+	 *
1684
+	 * @return bool|int
1685
+	 * @throws ReflectionException
1686
+	 * @throws InvalidArgumentException
1687
+	 * @throws InvalidInterfaceException
1688
+	 * @throws InvalidDataTypeException
1689
+	 * @throws EE_Error
1690
+	 */
1691
+	protected function _delete()
1692
+	{
1693
+		return $this->delete_permanently();
1694
+	}
1695
+
1696
+
1697
+	/**
1698
+	 * Deletes this model object permanently from db
1699
+	 * (but keep in mind related models may block the delete and return an error)
1700
+	 *
1701
+	 * @return bool | int
1702
+	 * @throws ReflectionException
1703
+	 * @throws InvalidArgumentException
1704
+	 * @throws InvalidInterfaceException
1705
+	 * @throws InvalidDataTypeException
1706
+	 * @throws EE_Error
1707
+	 */
1708
+	public function delete_permanently()
1709
+	{
1710
+		/**
1711
+		 * Called just before HARD deleting a model object
1712
+		 *
1713
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1714
+		 */
1715
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1716
+		$model  = $this->get_model();
1717
+		$result = $model->delete_permanently_by_ID($this->ID());
1718
+		$this->refresh_cache_of_related_objects();
1719
+		/**
1720
+		 * Called just after HARD deleting a model object
1721
+		 *
1722
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1723
+		 * @param boolean       $result
1724
+		 */
1725
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1726
+		return $result;
1727
+	}
1728
+
1729
+
1730
+	/**
1731
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1732
+	 * related model objects
1733
+	 *
1734
+	 * @throws ReflectionException
1735
+	 * @throws InvalidArgumentException
1736
+	 * @throws InvalidInterfaceException
1737
+	 * @throws InvalidDataTypeException
1738
+	 * @throws EE_Error
1739
+	 */
1740
+	public function refresh_cache_of_related_objects()
1741
+	{
1742
+		$model = $this->get_model();
1743
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1744
+			if (! empty($this->_model_relations[ $relation_name ])) {
1745
+				$related_objects = $this->_model_relations[ $relation_name ];
1746
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1747
+					// this relation only stores a single model object, not an array
1748
+					// but let's make it consistent
1749
+					$related_objects = [$related_objects];
1750
+				}
1751
+				foreach ($related_objects as $related_object) {
1752
+					// only refresh their cache if they're in memory
1753
+					if ($related_object instanceof EE_Base_Class) {
1754
+						$related_object->clear_cache(
1755
+							$model->get_this_model_name(),
1756
+							$this
1757
+						);
1758
+					}
1759
+				}
1760
+			}
1761
+		}
1762
+	}
1763
+
1764
+
1765
+	/**
1766
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1767
+	 * object just before saving.
1768
+	 *
1769
+	 * @access public
1770
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1771
+	 *                                 if provided during the save() method (often client code will change the fields'
1772
+	 *                                 values before calling save)
1773
+	 * @return bool|int|string         1 on a successful update
1774
+	 *                                 the ID of the new entry on insert
1775
+	 *                                 0 on failure or if the model object isn't allowed to persist
1776
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1777
+	 * @throws InvalidInterfaceException
1778
+	 * @throws InvalidDataTypeException
1779
+	 * @throws EE_Error
1780
+	 * @throws InvalidArgumentException
1781
+	 * @throws ReflectionException
1782
+	 */
1783
+	public function save($set_cols_n_values = [])
1784
+	{
1785
+		$model = $this->get_model();
1786
+		/**
1787
+		 * Filters the fields we're about to save on the model object
1788
+		 *
1789
+		 * @param array         $set_cols_n_values
1790
+		 * @param EE_Base_Class $model_object
1791
+		 */
1792
+		$set_cols_n_values = (array) apply_filters(
1793
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1794
+			$set_cols_n_values,
1795
+			$this
1796
+		);
1797
+		// set attributes as provided in $set_cols_n_values
1798
+		foreach ($set_cols_n_values as $column => $value) {
1799
+			$this->set($column, $value);
1800
+		}
1801
+		// no changes ? then don't do anything
1802
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1803
+			return 0;
1804
+		}
1805
+		/**
1806
+		 * Saving a model object.
1807
+		 * Before we perform a save, this action is fired.
1808
+		 *
1809
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1810
+		 */
1811
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1812
+		if (! $this->allow_persist()) {
1813
+			return 0;
1814
+		}
1815
+		// now get current attribute values
1816
+		$save_cols_n_values = $this->_fields;
1817
+		// if the object already has an ID, update it. Otherwise, insert it
1818
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1819
+		// They have been
1820
+		$old_assumption_concerning_value_preparation = $model
1821
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1822
+		$model->assume_values_already_prepared_by_model_object(true);
1823
+		// does this model have an autoincrement PK?
1824
+		if ($model->has_primary_key_field()) {
1825
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1826
+				// ok check if it's set, if so: update; if not, insert
1827
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1828
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1829
+				} else {
1830
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1831
+					$results = $model->insert($save_cols_n_values);
1832
+					if ($results) {
1833
+						// if successful, set the primary key
1834
+						// but don't use the normal SET method, because it will check if
1835
+						// an item with the same ID exists in the mapper & db, then
1836
+						// will find it in the db (because we just added it) and THAT object
1837
+						// will get added to the mapper before we can add this one!
1838
+						// but if we just avoid using the SET method, all that headache can be avoided
1839
+						$pk_field_name                   = $model->primary_key_name();
1840
+						$this->_fields[ $pk_field_name ] = $results;
1841
+						$this->_clear_cached_property($pk_field_name);
1842
+						$model->add_to_entity_map($this);
1843
+						$this->_update_cached_related_model_objs_fks();
1844
+					}
1845
+				}
1846
+			} else {// PK is NOT auto-increment
1847
+				// so check if one like it already exists in the db
1848
+				if ($model->exists_by_ID($this->ID())) {
1849
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1850
+						throw new EE_Error(
1851
+							sprintf(
1852
+								esc_html__(
1853
+									'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',
1854
+									'event_espresso'
1855
+								),
1856
+								get_class($this),
1857
+								get_class($model) . '::instance()->add_to_entity_map()',
1858
+								get_class($model) . '::instance()->get_one_by_ID()',
1859
+								'<br />'
1860
+							)
1861
+						);
1862
+					}
1863
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1864
+				} else {
1865
+					$results = $model->insert($save_cols_n_values);
1866
+					$this->_update_cached_related_model_objs_fks();
1867
+				}
1868
+			}
1869
+		} else {// there is NO primary key
1870
+			$already_in_db = false;
1871
+			foreach ($model->unique_indexes() as $index) {
1872
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1873
+				if ($model->exists([$uniqueness_where_params])) {
1874
+					$already_in_db = true;
1875
+				}
1876
+			}
1877
+			if ($already_in_db) {
1878
+				$combined_pk_fields_n_values = array_intersect_key(
1879
+					$save_cols_n_values,
1880
+					$model->get_combined_primary_key_fields()
1881
+				);
1882
+				$results                     = $model->update(
1883
+					$save_cols_n_values,
1884
+					$combined_pk_fields_n_values
1885
+				);
1886
+			} else {
1887
+				$results = $model->insert($save_cols_n_values);
1888
+			}
1889
+		}
1890
+		// restore the old assumption about values being prepared by the model object
1891
+		$model->assume_values_already_prepared_by_model_object(
1892
+			$old_assumption_concerning_value_preparation
1893
+		);
1894
+		/**
1895
+		 * After saving the model object this action is called
1896
+		 *
1897
+		 * @param EE_Base_Class $model_object which was just saved
1898
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1899
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1900
+		 */
1901
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1902
+		$this->_has_changes = false;
1903
+		return $results;
1904
+	}
1905
+
1906
+
1907
+	/**
1908
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1909
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1910
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1911
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1912
+	 * 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
1913
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1914
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1915
+	 *
1916
+	 * @return void
1917
+	 * @throws ReflectionException
1918
+	 * @throws InvalidArgumentException
1919
+	 * @throws InvalidInterfaceException
1920
+	 * @throws InvalidDataTypeException
1921
+	 * @throws EE_Error
1922
+	 */
1923
+	protected function _update_cached_related_model_objs_fks()
1924
+	{
1925
+		$model = $this->get_model();
1926
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1927
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1928
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1929
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1930
+						$model->get_this_model_name()
1931
+					);
1932
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1933
+					if ($related_model_obj_in_cache->ID()) {
1934
+						$related_model_obj_in_cache->save();
1935
+					}
1936
+				}
1937
+			}
1938
+		}
1939
+	}
1940
+
1941
+
1942
+	/**
1943
+	 * Saves this model object and its NEW cached relations to the database.
1944
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1945
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1946
+	 * because otherwise, there's a potential for infinite looping of saving
1947
+	 * Saves the cached related model objects, and ensures the relation between them
1948
+	 * and this object and properly setup
1949
+	 *
1950
+	 * @return int ID of new model object on save; 0 on failure+
1951
+	 * @throws ReflectionException
1952
+	 * @throws InvalidArgumentException
1953
+	 * @throws InvalidInterfaceException
1954
+	 * @throws InvalidDataTypeException
1955
+	 * @throws EE_Error
1956
+	 */
1957
+	public function save_new_cached_related_model_objs()
1958
+	{
1959
+		// make sure this has been saved
1960
+		if (! $this->ID()) {
1961
+			$id = $this->save();
1962
+		} else {
1963
+			$id = $this->ID();
1964
+		}
1965
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1966
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1967
+			if ($this->_model_relations[ $relation_name ]) {
1968
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1969
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1970
+				/* @var $related_model_obj EE_Base_Class */
1971
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1972
+					// add a relation to that relation type (which saves the appropriate thing in the process)
1973
+					// but ONLY if it DOES NOT exist in the DB
1974
+					$related_model_obj = $this->_model_relations[ $relation_name ];
1975
+					// if( ! $related_model_obj->ID()){
1976
+					$this->_add_relation_to($related_model_obj, $relation_name);
1977
+					$related_model_obj->save_new_cached_related_model_objs();
1978
+					// }
1979
+				} else {
1980
+					foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1981
+						// add a relation to that relation type (which saves the appropriate thing in the process)
1982
+						// but ONLY if it DOES NOT exist in the DB
1983
+						// if( ! $related_model_obj->ID()){
1984
+						$this->_add_relation_to($related_model_obj, $relation_name);
1985
+						$related_model_obj->save_new_cached_related_model_objs();
1986
+						// }
1987
+					}
1988
+				}
1989
+			}
1990
+		}
1991
+		return $id;
1992
+	}
1993
+
1994
+
1995
+	/**
1996
+	 * for getting a model while instantiated.
1997
+	 *
1998
+	 * @return EEM_Base | EEM_CPT_Base
1999
+	 * @throws ReflectionException
2000
+	 * @throws InvalidArgumentException
2001
+	 * @throws InvalidInterfaceException
2002
+	 * @throws InvalidDataTypeException
2003
+	 * @throws EE_Error
2004
+	 */
2005
+	public function get_model()
2006
+	{
2007
+		if (! $this->_model) {
2008
+			$modelName    = self::_get_model_classname(get_class($this));
2009
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2010
+		} else {
2011
+			$this->_model->set_timezone($this->_timezone);
2012
+		}
2013
+		return $this->_model;
2014
+	}
2015
+
2016
+
2017
+	/**
2018
+	 * @param $props_n_values
2019
+	 * @param $classname
2020
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2021
+	 * @throws ReflectionException
2022
+	 * @throws InvalidArgumentException
2023
+	 * @throws InvalidInterfaceException
2024
+	 * @throws InvalidDataTypeException
2025
+	 * @throws EE_Error
2026
+	 */
2027
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2028
+	{
2029
+		// TODO: will not work for Term_Relationships because they have no PK!
2030
+		$primary_id_ref = self::_get_primary_key_name($classname);
2031
+		if (
2032
+			array_key_exists($primary_id_ref, $props_n_values)
2033
+			&& ! empty($props_n_values[ $primary_id_ref ])
2034
+		) {
2035
+			$id = $props_n_values[ $primary_id_ref ];
2036
+			return self::_get_model($classname)->get_from_entity_map($id);
2037
+		}
2038
+		return false;
2039
+	}
2040
+
2041
+
2042
+	/**
2043
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2044
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2045
+	 * 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
2046
+	 * we return false.
2047
+	 *
2048
+	 * @param array  $props_n_values    incoming array of properties and their values
2049
+	 * @param string $classname         the classname of the child class
2050
+	 * @param null   $timezone
2051
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the
2052
+	 *                                  date_format and the second value is the time format
2053
+	 * @return mixed (EE_Base_Class|bool)
2054
+	 * @throws InvalidArgumentException
2055
+	 * @throws InvalidInterfaceException
2056
+	 * @throws InvalidDataTypeException
2057
+	 * @throws EE_Error
2058
+	 * @throws ReflectionException
2059
+	 */
2060
+	protected static function _check_for_object($props_n_values, $classname, $timezone = '', $date_formats = [])
2061
+	{
2062
+		$existing = null;
2063
+		$model    = self::_get_model($classname, $timezone);
2064
+		if ($model->has_primary_key_field()) {
2065
+			$primary_id_ref = self::_get_primary_key_name($classname);
2066
+			if (
2067
+				array_key_exists($primary_id_ref, $props_n_values)
2068
+				&& ! empty($props_n_values[ $primary_id_ref ])
2069
+			) {
2070
+				$existing = $model->get_one_by_ID(
2071
+					$props_n_values[ $primary_id_ref ]
2072
+				);
2073
+			}
2074
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2075
+			// no primary key on this model, but there's still a matching item in the DB
2076
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2077
+				self::_get_model($classname, $timezone)
2078
+					->get_index_primary_key_string($props_n_values)
2079
+			);
2080
+		}
2081
+		if ($existing) {
2082
+			// set date formats if present before setting values
2083
+			if (! empty($date_formats) && is_array($date_formats)) {
2084
+				$existing->set_date_format($date_formats[0]);
2085
+				$existing->set_time_format($date_formats[1]);
2086
+			} else {
2087
+				// set default formats for date and time
2088
+				$existing->set_date_format(get_option('date_format'));
2089
+				$existing->set_time_format(get_option('time_format'));
2090
+			}
2091
+			foreach ($props_n_values as $property => $field_value) {
2092
+				$existing->set($property, $field_value);
2093
+			}
2094
+			return $existing;
2095
+		}
2096
+		return false;
2097
+	}
2098
+
2099
+
2100
+	/**
2101
+	 * Gets the EEM_*_Model for this class
2102
+	 *
2103
+	 * @access public now, as this is more convenient
2104
+	 * @param      $classname
2105
+	 * @param null $timezone
2106
+	 * @return EEM_Base
2107
+	 * @throws InvalidArgumentException
2108
+	 * @throws InvalidInterfaceException
2109
+	 * @throws InvalidDataTypeException
2110
+	 * @throws EE_Error
2111
+	 * @throws ReflectionException
2112
+	 */
2113
+	protected static function _get_model($classname, $timezone = '')
2114
+	{
2115
+		// find model for this class
2116
+		if (! $classname) {
2117
+			throw new EE_Error(
2118
+				sprintf(
2119
+					esc_html__(
2120
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2121
+						'event_espresso'
2122
+					),
2123
+					$classname
2124
+				)
2125
+			);
2126
+		}
2127
+		$modelName = self::_get_model_classname($classname);
2128
+		return self::_get_model_instance_with_name($modelName, $timezone);
2129
+	}
2130
+
2131
+
2132
+	/**
2133
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2134
+	 *
2135
+	 * @param string $model_classname
2136
+	 * @param null   $timezone
2137
+	 * @return EEM_Base
2138
+	 * @throws ReflectionException
2139
+	 * @throws InvalidArgumentException
2140
+	 * @throws InvalidInterfaceException
2141
+	 * @throws InvalidDataTypeException
2142
+	 * @throws EE_Error
2143
+	 */
2144
+	protected static function _get_model_instance_with_name($model_classname, $timezone = '')
2145
+	{
2146
+		$model_classname = str_replace('EEM_', '', $model_classname);
2147
+		$model           = EE_Registry::instance()->load_model($model_classname);
2148
+		$model->set_timezone($timezone);
2149
+		return $model;
2150
+	}
2151
+
2152
+
2153
+	/**
2154
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2155
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2156
+	 *
2157
+	 * @param string|null $model_name
2158
+	 * @return string like EEM_Attendee
2159
+	 */
2160
+	private static function _get_model_classname($model_name = '')
2161
+	{
2162
+		return strpos((string) $model_name, 'EE_') === 0
2163
+			? str_replace('EE_', 'EEM_', $model_name)
2164
+			: 'EEM_' . $model_name;
2165
+	}
2166
+
2167
+
2168
+	/**
2169
+	 * returns the name of the primary key attribute
2170
+	 *
2171
+	 * @param null $classname
2172
+	 * @return string
2173
+	 * @throws InvalidArgumentException
2174
+	 * @throws InvalidInterfaceException
2175
+	 * @throws InvalidDataTypeException
2176
+	 * @throws EE_Error
2177
+	 * @throws ReflectionException
2178
+	 */
2179
+	protected static function _get_primary_key_name($classname = null)
2180
+	{
2181
+		if (! $classname) {
2182
+			throw new EE_Error(
2183
+				sprintf(
2184
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2185
+					$classname
2186
+				)
2187
+			);
2188
+		}
2189
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2190
+	}
2191
+
2192
+
2193
+	/**
2194
+	 * Gets the value of the primary key.
2195
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2196
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2197
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2198
+	 *
2199
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2200
+	 * @throws ReflectionException
2201
+	 * @throws InvalidArgumentException
2202
+	 * @throws InvalidInterfaceException
2203
+	 * @throws InvalidDataTypeException
2204
+	 * @throws EE_Error
2205
+	 */
2206
+	public function ID()
2207
+	{
2208
+		$model = $this->get_model();
2209
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2210
+		if ($model->has_primary_key_field()) {
2211
+			return $this->_fields[ $model->primary_key_name() ];
2212
+		}
2213
+		return $model->get_index_primary_key_string($this->_fields);
2214
+	}
2215
+
2216
+
2217
+	/**
2218
+	 * @param EE_Base_Class|int|string $otherModelObjectOrID
2219
+	 * @param string                   $relation_name
2220
+	 * @return bool
2221
+	 * @throws EE_Error
2222
+	 * @throws ReflectionException
2223
+	 * @since   5.0.0.p
2224
+	 */
2225
+	public function hasRelation($otherModelObjectOrID, string $relation_name): bool
2226
+	{
2227
+		$other_model = self::_get_model_instance_with_name(
2228
+			self::_get_model_classname($relation_name),
2229
+			$this->_timezone
2230
+		);
2231
+		$primary_key = $other_model->primary_key_name();
2232
+		/** @var EE_Base_Class $otherModelObject */
2233
+		$otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relation_name);
2234
+		return $this->count_related($relation_name, [[$primary_key => $otherModelObject->ID()]]) > 0;
2235
+	}
2236
+
2237
+
2238
+	/**
2239
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2240
+	 * model is related to a group of events, the $relation_name should be 'Event', and should be a key in the EE
2241
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2242
+	 *
2243
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2244
+	 * @param string $relation_name                    eg 'Events','Question',etc.
2245
+	 *                                                 an attendee to a group, you also want to specify which role they
2246
+	 *                                                 will have in that group. So you would use this parameter to
2247
+	 *                                                 specify array('role-column-name'=>'role-id')
2248
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2249
+	 *                                                 allow you to further constrict the relation to being added.
2250
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2251
+	 *                                                 column on the JOIN table and currently only the HABTM models
2252
+	 *                                                 accept these additional conditions.  Also remember that if an
2253
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2254
+	 *                                                 NEW row is created in the join table.
2255
+	 * @param null   $cache_id
2256
+	 * @return EE_Base_Class the object the relation was added to
2257
+	 * @throws ReflectionException
2258
+	 * @throws InvalidArgumentException
2259
+	 * @throws InvalidInterfaceException
2260
+	 * @throws InvalidDataTypeException
2261
+	 * @throws EE_Error
2262
+	 */
2263
+	public function _add_relation_to(
2264
+		$otherObjectModelObjectOrID,
2265
+		$relation_name,
2266
+		$extra_join_model_fields_n_values = [],
2267
+		$cache_id = null
2268
+	) {
2269
+		$model = $this->get_model();
2270
+		// if this thing exists in the DB, save the relation to the DB
2271
+		if ($this->ID()) {
2272
+			$otherObject = $model->add_relationship_to(
2273
+				$this,
2274
+				$otherObjectModelObjectOrID,
2275
+				$relation_name,
2276
+				$extra_join_model_fields_n_values
2277
+			);
2278
+			// clear cache so future get_many_related and get_first_related() return new results.
2279
+			$this->clear_cache($relation_name, $otherObject, true);
2280
+			if ($otherObject instanceof EE_Base_Class) {
2281
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2282
+			}
2283
+		} else {
2284
+			// this thing doesn't exist in the DB,  so just cache it
2285
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2286
+				throw new EE_Error(
2287
+					sprintf(
2288
+						esc_html__(
2289
+							'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',
2290
+							'event_espresso'
2291
+						),
2292
+						$otherObjectModelObjectOrID,
2293
+						get_class($this)
2294
+					)
2295
+				);
2296
+			}
2297
+			$otherObject = $otherObjectModelObjectOrID;
2298
+			$this->cache($relation_name, $otherObjectModelObjectOrID, $cache_id);
2299
+		}
2300
+		if ($otherObject instanceof EE_Base_Class) {
2301
+			// fix the reciprocal relation too
2302
+			if ($otherObject->ID()) {
2303
+				// its saved so assumed relations exist in the DB, so we can just
2304
+				// clear the cache so future queries use the updated info in the DB
2305
+				$otherObject->clear_cache(
2306
+					$model->get_this_model_name(),
2307
+					null,
2308
+					true
2309
+				);
2310
+			} else {
2311
+				// it's not saved, so it caches relations like this
2312
+				$otherObject->cache($model->get_this_model_name(), $this);
2313
+			}
2314
+		}
2315
+		return $otherObject;
2316
+	}
2317
+
2318
+
2319
+	/**
2320
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2321
+	 * model is related to a group of events, the $relation_name should be 'Events', and should be a key in the EE
2322
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2323
+	 * from the cache
2324
+	 *
2325
+	 * @param mixed  $otherObjectModelObjectOrID
2326
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2327
+	 *                to the DB yet
2328
+	 * @param string $relation_name
2329
+	 * @param array  $where_query
2330
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2331
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2332
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2333
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2334
+	 *                deleted.
2335
+	 * @return EE_Base_Class the relation was removed from
2336
+	 * @throws ReflectionException
2337
+	 * @throws InvalidArgumentException
2338
+	 * @throws InvalidInterfaceException
2339
+	 * @throws InvalidDataTypeException
2340
+	 * @throws EE_Error
2341
+	 */
2342
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relation_name, $where_query = [])
2343
+	{
2344
+		if ($this->ID()) {
2345
+			// if this exists in the DB, save the relation change to the DB too
2346
+			$otherObject = $this->get_model()->remove_relationship_to(
2347
+				$this,
2348
+				$otherObjectModelObjectOrID,
2349
+				$relation_name,
2350
+				$where_query
2351
+			);
2352
+			$this->clear_cache(
2353
+				$relation_name,
2354
+				$otherObject
2355
+			);
2356
+		} else {
2357
+			// this doesn't exist in the DB, just remove it from the cache
2358
+			$otherObject = $this->clear_cache(
2359
+				$relation_name,
2360
+				$otherObjectModelObjectOrID
2361
+			);
2362
+		}
2363
+		if ($otherObject instanceof EE_Base_Class) {
2364
+			$otherObject->clear_cache(
2365
+				$this->get_model()->get_this_model_name(),
2366
+				$this
2367
+			);
2368
+		}
2369
+		return $otherObject;
2370
+	}
2371
+
2372
+
2373
+	/**
2374
+	 * Removes ALL the related things for the $relation_name.
2375
+	 *
2376
+	 * @param string $relation_name
2377
+	 * @param array  $where_query_params @see
2378
+	 *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2379
+	 * @return EE_Base_Class
2380
+	 * @throws ReflectionException
2381
+	 * @throws InvalidArgumentException
2382
+	 * @throws InvalidInterfaceException
2383
+	 * @throws InvalidDataTypeException
2384
+	 * @throws EE_Error
2385
+	 */
2386
+	public function _remove_relations($relation_name, $where_query_params = [])
2387
+	{
2388
+		if ($this->ID()) {
2389
+			// if this exists in the DB, save the relation change to the DB too
2390
+			$otherObjects = $this->get_model()->remove_relations(
2391
+				$this,
2392
+				$relation_name,
2393
+				$where_query_params
2394
+			);
2395
+			$this->clear_cache(
2396
+				$relation_name,
2397
+				null,
2398
+				true
2399
+			);
2400
+		} else {
2401
+			// this doesn't exist in the DB, just remove it from the cache
2402
+			$otherObjects = $this->clear_cache(
2403
+				$relation_name,
2404
+				null,
2405
+				true
2406
+			);
2407
+		}
2408
+		if (is_array($otherObjects)) {
2409
+			foreach ($otherObjects as $otherObject) {
2410
+				$otherObject->clear_cache(
2411
+					$this->get_model()->get_this_model_name(),
2412
+					$this
2413
+				);
2414
+			}
2415
+		}
2416
+		return $otherObjects;
2417
+	}
2418
+
2419
+
2420
+	/**
2421
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2422
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2423
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2424
+	 * because we want to get even deleted items etc.
2425
+	 *
2426
+	 * @param string      $relation_name key in the model's _model_relations array
2427
+	 * @param array|null  $query_params  @see
2428
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2429
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2430
+	 *                              keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2431
+	 *                              results if you want IDs
2432
+	 * @throws ReflectionException
2433
+	 * @throws InvalidArgumentException
2434
+	 * @throws InvalidInterfaceException
2435
+	 * @throws InvalidDataTypeException
2436
+	 * @throws EE_Error
2437
+	 */
2438
+	public function get_many_related($relation_name, $query_params = [])
2439
+	{
2440
+		if ($this->ID()) {
2441
+			// this exists in the DB, so get the related things from either the cache or the DB
2442
+			// if there are query parameters, forget about caching the related model objects.
2443
+			if ($query_params) {
2444
+				$related_model_objects = $this->get_model()->get_all_related(
2445
+					$this,
2446
+					$relation_name,
2447
+					$query_params
2448
+				);
2449
+			} else {
2450
+				// did we already cache the result of this query?
2451
+				$cached_results = $this->get_all_from_cache($relation_name);
2452
+				if (! $cached_results) {
2453
+					$related_model_objects = $this->get_model()->get_all_related(
2454
+						$this,
2455
+						$relation_name,
2456
+						$query_params
2457
+					);
2458
+					// if no query parameters were passed, then we got all the related model objects
2459
+					// for that relation. We can cache them then.
2460
+					foreach ($related_model_objects as $related_model_object) {
2461
+						$this->cache($relation_name, $related_model_object);
2462
+					}
2463
+				} else {
2464
+					$related_model_objects = $cached_results;
2465
+				}
2466
+			}
2467
+		} else {
2468
+			// this doesn't exist in the DB, so just get the related things from the cache
2469
+			$related_model_objects = $this->get_all_from_cache($relation_name);
2470
+		}
2471
+		return $related_model_objects;
2472
+	}
2473
+
2474
+
2475
+	/**
2476
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2477
+	 * unless otherwise specified in the $query_params
2478
+	 *
2479
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2480
+	 * @param array  $query_params   @see
2481
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2482
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2483
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2484
+	 *                               that by the setting $distinct to TRUE;
2485
+	 * @return int
2486
+	 * @throws ReflectionException
2487
+	 * @throws InvalidArgumentException
2488
+	 * @throws InvalidInterfaceException
2489
+	 * @throws InvalidDataTypeException
2490
+	 * @throws EE_Error
2491
+	 */
2492
+	public function count_related($relation_name, $query_params = [], $field_to_count = null, $distinct = false)
2493
+	{
2494
+		return $this->get_model()->count_related(
2495
+			$this,
2496
+			$relation_name,
2497
+			$query_params,
2498
+			$field_to_count,
2499
+			$distinct
2500
+		);
2501
+	}
2502
+
2503
+
2504
+	/**
2505
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2506
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2507
+	 *
2508
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2509
+	 * @param array  $query_params  @see
2510
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2511
+	 * @param string $field_to_sum  name of field to count by.
2512
+	 *                              By default, uses primary key
2513
+	 *                              (which doesn't make much sense, so you should probably change it)
2514
+	 * @return int
2515
+	 * @throws ReflectionException
2516
+	 * @throws InvalidArgumentException
2517
+	 * @throws InvalidInterfaceException
2518
+	 * @throws InvalidDataTypeException
2519
+	 * @throws EE_Error
2520
+	 */
2521
+	public function sum_related($relation_name, $query_params = [], $field_to_sum = null)
2522
+	{
2523
+		return $this->get_model()->sum_related(
2524
+			$this,
2525
+			$relation_name,
2526
+			$query_params,
2527
+			$field_to_sum
2528
+		);
2529
+	}
2530
+
2531
+
2532
+	/**
2533
+	 * Gets the first (ie, one) related model object of the specified type.
2534
+	 *
2535
+	 * @param string $relation_name key in the model's _model_relations array
2536
+	 * @param array  $query_params  @see
2537
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2538
+	 * @return EE_Base_Class|null (not an array, a single object)
2539
+	 * @throws ReflectionException
2540
+	 * @throws InvalidArgumentException
2541
+	 * @throws InvalidInterfaceException
2542
+	 * @throws InvalidDataTypeException
2543
+	 * @throws EE_Error
2544
+	 */
2545
+	public function get_first_related(string $relation_name, array $query_params = []): ?EE_Base_Class
2546
+	{
2547
+		$model = $this->get_model();
2548
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2549
+			// if they've provided some query parameters, don't bother trying to cache the result
2550
+			// also make sure we're not caching the result of get_first_related
2551
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2552
+			if (
2553
+				$query_params
2554
+				|| ! $model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation
2555
+			) {
2556
+				$related_model_object = $model->get_first_related(
2557
+					$this,
2558
+					$relation_name,
2559
+					$query_params
2560
+				);
2561
+			} else {
2562
+				// first, check if we've already cached the result of this query
2563
+				$cached_result = $this->get_one_from_cache($relation_name);
2564
+				if (! $cached_result) {
2565
+					$related_model_object = $model->get_first_related(
2566
+						$this,
2567
+						$relation_name,
2568
+						$query_params
2569
+					);
2570
+					$this->cache($relation_name, $related_model_object);
2571
+				} else {
2572
+					$related_model_object = $cached_result;
2573
+				}
2574
+			}
2575
+		} else {
2576
+			$related_model_object = null;
2577
+			// this doesn't exist in the Db,
2578
+			// but maybe the relation is of type belongs to, and so the related thing might
2579
+			if ($model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation) {
2580
+				$related_model_object = $model->get_first_related(
2581
+					$this,
2582
+					$relation_name,
2583
+					$query_params
2584
+				);
2585
+			}
2586
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2587
+			// just get what's cached on this object
2588
+			if (! $related_model_object) {
2589
+				$related_model_object = $this->get_one_from_cache($relation_name);
2590
+			}
2591
+		}
2592
+		return $related_model_object;
2593
+	}
2594
+
2595
+
2596
+	/**
2597
+	 * Does a delete on all related objects of type $relation_name and removes
2598
+	 * the current model object's relation to them. If they can't be deleted (because
2599
+	 * of blocking related model objects) does nothing. If the related model objects are
2600
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2601
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2602
+	 *
2603
+	 * @param string $relation_name
2604
+	 * @param array  $query_params @see
2605
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2606
+	 * @return int how many deleted
2607
+	 * @throws ReflectionException
2608
+	 * @throws InvalidArgumentException
2609
+	 * @throws InvalidInterfaceException
2610
+	 * @throws InvalidDataTypeException
2611
+	 * @throws EE_Error
2612
+	 */
2613
+	public function delete_related($relation_name, $query_params = [])
2614
+	{
2615
+		if ($this->ID()) {
2616
+			$count = $this->get_model()->delete_related(
2617
+				$this,
2618
+				$relation_name,
2619
+				$query_params
2620
+			);
2621
+		} else {
2622
+			$count = count($this->get_all_from_cache($relation_name));
2623
+			$this->clear_cache($relation_name, null, true);
2624
+		}
2625
+		return $count;
2626
+	}
2627
+
2628
+
2629
+	/**
2630
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relation_name and removes
2631
+	 * the current model object's relation to them. If they can't be deleted (because
2632
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2633
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2634
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2635
+	 *
2636
+	 * @param string $relation_name
2637
+	 * @param array  $query_params @see
2638
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2639
+	 * @return int how many deleted (including those soft deleted)
2640
+	 * @throws ReflectionException
2641
+	 * @throws InvalidArgumentException
2642
+	 * @throws InvalidInterfaceException
2643
+	 * @throws InvalidDataTypeException
2644
+	 * @throws EE_Error
2645
+	 */
2646
+	public function delete_related_permanently($relation_name, $query_params = [])
2647
+	{
2648
+		$count = $this->ID()
2649
+			? $this->get_model()->delete_related_permanently(
2650
+				$this,
2651
+				$relation_name,
2652
+				$query_params
2653
+			)
2654
+			: count($this->get_all_from_cache($relation_name));
2655
+
2656
+		$this->clear_cache($relation_name, null, true);
2657
+		return $count;
2658
+	}
2659
+
2660
+
2661
+	/**
2662
+	 * is_set
2663
+	 * Just a simple utility function children can use for checking if property exists
2664
+	 *
2665
+	 * @access  public
2666
+	 * @param string $field_name property to check
2667
+	 * @return bool                              TRUE if existing,FALSE if not.
2668
+	 */
2669
+	public function is_set($field_name)
2670
+	{
2671
+		return isset($this->_fields[ $field_name ]);
2672
+	}
2673
+
2674
+
2675
+	/**
2676
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2677
+	 * EE_Error exception if they don't
2678
+	 *
2679
+	 * @param mixed (string|array) $properties properties to check
2680
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2681
+	 * @throws EE_Error
2682
+	 */
2683
+	protected function _property_exists($properties)
2684
+	{
2685
+		foreach ((array) $properties as $property_name) {
2686
+			// first make sure this property exists
2687
+			if (! $this->_fields[ $property_name ]) {
2688
+				throw new EE_Error(
2689
+					sprintf(
2690
+						esc_html__(
2691
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2692
+							'event_espresso'
2693
+						),
2694
+						$property_name
2695
+					)
2696
+				);
2697
+			}
2698
+		}
2699
+		return true;
2700
+	}
2701
+
2702
+
2703
+	/**
2704
+	 * This simply returns an array of model fields for this object
2705
+	 *
2706
+	 * @return array
2707
+	 * @throws ReflectionException
2708
+	 * @throws InvalidArgumentException
2709
+	 * @throws InvalidInterfaceException
2710
+	 * @throws InvalidDataTypeException
2711
+	 * @throws EE_Error
2712
+	 */
2713
+	public function model_field_array()
2714
+	{
2715
+		$fields     = $this->get_model()->field_settings(false);
2716
+		$properties = [];
2717
+		// remove prepended underscore
2718
+		foreach ($fields as $field_name => $settings) {
2719
+			$properties[ $field_name ] = $this->get($field_name);
2720
+		}
2721
+		return $properties;
2722
+	}
2723
+
2724
+
2725
+	/**
2726
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2727
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2728
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2729
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2730
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2731
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2732
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2733
+	 * and accepts 2 arguments: the object on which the function was called,
2734
+	 * and an array of the original arguments passed to the function.
2735
+	 * Whatever their callback function returns will be returned by this function.
2736
+	 * Example: in functions.php (or in a plugin):
2737
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2738
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2739
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2740
+	 *          return $previousReturnValue.$returnString;
2741
+	 *      }
2742
+	 * require('EE_Answer.class.php');
2743
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2744
+	 *      ->my_callback('monkeys',100);
2745
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2746
+	 *
2747
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2748
+	 * @param array  $args       array of original arguments passed to the function
2749
+	 * @return mixed whatever the plugin which calls add_filter decides
2750
+	 * @throws EE_Error
2751
+	 */
2752
+	public function __call($methodName, $args)
2753
+	{
2754
+		$className = get_class($this);
2755
+		$tagName   = "FHEE__{$className}__{$methodName}";
2756
+		if (! has_filter($tagName)) {
2757
+			throw new EE_Error(
2758
+				sprintf(
2759
+					esc_html__(
2760
+						"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;}",
2761
+						'event_espresso'
2762
+					),
2763
+					$methodName,
2764
+					$className,
2765
+					$tagName
2766
+				)
2767
+			);
2768
+		}
2769
+		return apply_filters($tagName, null, $this, $args);
2770
+	}
2771
+
2772
+
2773
+	/**
2774
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2775
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2776
+	 *
2777
+	 * @param string $meta_key
2778
+	 * @param mixed  $meta_value
2779
+	 * @param mixed  $previous_value
2780
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2781
+	 *                  NOTE: if the values haven't changed, returns 0
2782
+	 * @throws InvalidArgumentException
2783
+	 * @throws InvalidInterfaceException
2784
+	 * @throws InvalidDataTypeException
2785
+	 * @throws EE_Error
2786
+	 * @throws ReflectionException
2787
+	 */
2788
+	public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2789
+	{
2790
+		$query_params = [
2791
+			[
2792
+				'EXM_key'  => $meta_key,
2793
+				'OBJ_ID'   => $this->ID(),
2794
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2795
+			],
2796
+		];
2797
+		if ($previous_value !== null) {
2798
+			$query_params[0]['EXM_value'] = $meta_value;
2799
+		}
2800
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2801
+		if (! $existing_rows_like_that) {
2802
+			return $this->add_extra_meta($meta_key, $meta_value);
2803
+		}
2804
+		foreach ($existing_rows_like_that as $existing_row) {
2805
+			$existing_row->save(['EXM_value' => $meta_value]);
2806
+		}
2807
+		return count($existing_rows_like_that);
2808
+	}
2809
+
2810
+
2811
+	/**
2812
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2813
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2814
+	 * extra meta row was entered, false if not
2815
+	 *
2816
+	 * @param string $meta_key
2817
+	 * @param mixed  $meta_value
2818
+	 * @param bool   $unique
2819
+	 * @return bool
2820
+	 * @throws InvalidArgumentException
2821
+	 * @throws InvalidInterfaceException
2822
+	 * @throws InvalidDataTypeException
2823
+	 * @throws EE_Error
2824
+	 * @throws ReflectionException
2825
+	 */
2826
+	public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2827
+	{
2828
+		if ($unique) {
2829
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2830
+				[
2831
+					[
2832
+						'EXM_key'  => $meta_key,
2833
+						'OBJ_ID'   => $this->ID(),
2834
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2835
+					],
2836
+				]
2837
+			);
2838
+			if ($existing_extra_meta) {
2839
+				return false;
2840
+			}
2841
+		}
2842
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2843
+			[
2844
+				'EXM_key'   => $meta_key,
2845
+				'EXM_value' => $meta_value,
2846
+				'OBJ_ID'    => $this->ID(),
2847
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2848
+			]
2849
+		);
2850
+		$new_extra_meta->save();
2851
+		return true;
2852
+	}
2853
+
2854
+
2855
+	/**
2856
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2857
+	 * is specified, only deletes extra meta records with that value.
2858
+	 *
2859
+	 * @param string $meta_key
2860
+	 * @param mixed  $meta_value
2861
+	 * @return int|bool number of extra meta rows deleted
2862
+	 * @throws InvalidArgumentException
2863
+	 * @throws InvalidInterfaceException
2864
+	 * @throws InvalidDataTypeException
2865
+	 * @throws EE_Error
2866
+	 * @throws ReflectionException
2867
+	 */
2868
+	public function delete_extra_meta(string $meta_key, $meta_value = null)
2869
+	{
2870
+		$query_params = [
2871
+			[
2872
+				'EXM_key'  => $meta_key,
2873
+				'OBJ_ID'   => $this->ID(),
2874
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2875
+			],
2876
+		];
2877
+		if ($meta_value !== null) {
2878
+			$query_params[0]['EXM_value'] = $meta_value;
2879
+		}
2880
+		return EEM_Extra_Meta::instance()->delete($query_params);
2881
+	}
2882
+
2883
+
2884
+	/**
2885
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2886
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2887
+	 * You can specify $default is case you haven't found the extra meta
2888
+	 *
2889
+	 * @param string     $meta_key
2890
+	 * @param bool       $single
2891
+	 * @param mixed      $default if we don't find anything, what should we return?
2892
+	 * @param array|null $extra_where
2893
+	 * @return mixed single value if $single; array if ! $single
2894
+	 * @throws ReflectionException
2895
+	 * @throws EE_Error
2896
+	 */
2897
+	public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2898
+	{
2899
+		$query_params = [$extra_where + ['EXM_key' => $meta_key]];
2900
+		if ($single) {
2901
+			$result = $this->get_first_related('Extra_Meta', $query_params);
2902
+			if ($result instanceof EE_Extra_Meta) {
2903
+				return $result->value();
2904
+			}
2905
+		} else {
2906
+			$results = $this->get_many_related('Extra_Meta', $query_params);
2907
+			if ($results) {
2908
+				$values = [];
2909
+				foreach ($results as $result) {
2910
+					if ($result instanceof EE_Extra_Meta) {
2911
+						$values[ $result->ID() ] = $result->value();
2912
+					}
2913
+				}
2914
+				return $values;
2915
+			}
2916
+		}
2917
+		// if nothing discovered yet return default.
2918
+		return apply_filters(
2919
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2920
+			$default,
2921
+			$meta_key,
2922
+			$single,
2923
+			$this
2924
+		);
2925
+	}
2926
+
2927
+
2928
+	/**
2929
+	 * Returns a simple array of all the extra meta associated with this model object.
2930
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2931
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2932
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2933
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2934
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2935
+	 * finally the extra meta's value as each sub-value. (eg
2936
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2937
+	 *
2938
+	 * @param bool $one_of_each_key
2939
+	 * @return array
2940
+	 * @throws ReflectionException
2941
+	 * @throws InvalidArgumentException
2942
+	 * @throws InvalidInterfaceException
2943
+	 * @throws InvalidDataTypeException
2944
+	 * @throws EE_Error
2945
+	 */
2946
+	public function all_extra_meta_array(bool $one_of_each_key = true): array
2947
+	{
2948
+		$return_array = [];
2949
+		if ($one_of_each_key) {
2950
+			$extra_meta_objs = $this->get_many_related(
2951
+				'Extra_Meta',
2952
+				['group_by' => 'EXM_key']
2953
+			);
2954
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2955
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2956
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2957
+				}
2958
+			}
2959
+		} else {
2960
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2961
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2962
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2963
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2964
+						$return_array[ $extra_meta_obj->key() ] = [];
2965
+					}
2966
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2967
+				}
2968
+			}
2969
+		}
2970
+		return $return_array;
2971
+	}
2972
+
2973
+
2974
+	/**
2975
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2976
+	 *
2977
+	 * @return string
2978
+	 * @throws ReflectionException
2979
+	 * @throws InvalidArgumentException
2980
+	 * @throws InvalidInterfaceException
2981
+	 * @throws InvalidDataTypeException
2982
+	 * @throws EE_Error
2983
+	 */
2984
+	public function name()
2985
+	{
2986
+		// find a field that's not a text field
2987
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2988
+		if ($field_we_can_use) {
2989
+			return $this->get($field_we_can_use->get_name());
2990
+		}
2991
+		$first_few_properties = $this->model_field_array();
2992
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
2993
+		$name_parts           = [];
2994
+		foreach ($first_few_properties as $name => $value) {
2995
+			$name_parts[] = "$name:$value";
2996
+		}
2997
+		return implode(',', $name_parts);
2998
+	}
2999
+
3000
+
3001
+	/**
3002
+	 * in_entity_map
3003
+	 * Checks if this model object has been proven to already be in the entity map
3004
+	 *
3005
+	 * @return boolean
3006
+	 * @throws ReflectionException
3007
+	 * @throws InvalidArgumentException
3008
+	 * @throws InvalidInterfaceException
3009
+	 * @throws InvalidDataTypeException
3010
+	 * @throws EE_Error
3011
+	 */
3012
+	public function in_entity_map()
3013
+	{
3014
+		// well, if we looked, did we find it in the entity map?
3015
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3016
+	}
3017
+
3018
+
3019
+	/**
3020
+	 * refresh_from_db
3021
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3022
+	 *
3023
+	 * @throws ReflectionException
3024
+	 * @throws InvalidArgumentException
3025
+	 * @throws InvalidInterfaceException
3026
+	 * @throws InvalidDataTypeException
3027
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3028
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3029
+	 */
3030
+	public function refresh_from_db()
3031
+	{
3032
+		if ($this->ID() && $this->in_entity_map()) {
3033
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3034
+		} else {
3035
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3036
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3037
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3038
+			// absolutely nothing in it for this ID
3039
+			if (WP_DEBUG) {
3040
+				throw new EE_Error(
3041
+					sprintf(
3042
+						esc_html__(
3043
+							'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.',
3044
+							'event_espresso'
3045
+						),
3046
+						$this->ID(),
3047
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3048
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3049
+					)
3050
+				);
3051
+			}
3052
+		}
3053
+	}
3054
+
3055
+
3056
+	/**
3057
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3058
+	 *
3059
+	 * @param EE_Model_Field_Base[] $fields
3060
+	 * @param string                $new_value_sql
3061
+	 *          example: 'column_name=123',
3062
+	 *          or 'column_name=column_name+1',
3063
+	 *          or 'column_name= CASE
3064
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3065
+	 *          THEN `column_name` + 5
3066
+	 *          ELSE `column_name`
3067
+	 *          END'
3068
+	 *          Also updates $field on this model object with the latest value from the database.
3069
+	 * @return bool
3070
+	 * @throws EE_Error
3071
+	 * @throws InvalidArgumentException
3072
+	 * @throws InvalidDataTypeException
3073
+	 * @throws InvalidInterfaceException
3074
+	 * @throws ReflectionException
3075
+	 * @since 4.9.80.p
3076
+	 */
3077
+	protected function updateFieldsInDB($fields, $new_value_sql)
3078
+	{
3079
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3080
+		// if it wasn't even there to start off.
3081
+		if (! $this->ID()) {
3082
+			$this->save();
3083
+		}
3084
+		global $wpdb;
3085
+		if (empty($fields)) {
3086
+			throw new InvalidArgumentException(
3087
+				esc_html__(
3088
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3089
+					'event_espresso'
3090
+				)
3091
+			);
3092
+		}
3093
+		$first_field = reset($fields);
3094
+		$table_alias = $first_field->get_table_alias();
3095
+		foreach ($fields as $field) {
3096
+			if ($table_alias !== $field->get_table_alias()) {
3097
+				throw new InvalidArgumentException(
3098
+					sprintf(
3099
+						esc_html__(
3100
+						// @codingStandardsIgnoreStart
3101
+							'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.',
3102
+							// @codingStandardsIgnoreEnd
3103
+							'event_espresso'
3104
+						),
3105
+						$table_alias,
3106
+						$field->get_table_alias()
3107
+					)
3108
+				);
3109
+			}
3110
+		}
3111
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3112
+		$table_obj      = $this->get_model()->get_table_obj_by_alias($table_alias);
3113
+		$table_pk_value = $this->ID();
3114
+		$table_name     = $table_obj->get_table_name();
3115
+		if ($table_obj instanceof EE_Secondary_Table) {
3116
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3117
+		} else {
3118
+			$table_pk_field_name = $table_obj->get_pk_column();
3119
+		}
3120
+
3121
+		$query  =
3122
+			"UPDATE `{$table_name}`
3123 3123
             SET "
3124
-            . $new_value_sql
3125
-            . $wpdb->prepare(
3126
-                "
3124
+			. $new_value_sql
3125
+			. $wpdb->prepare(
3126
+				"
3127 3127
             WHERE `{$table_pk_field_name}` = %d;",
3128
-                $table_pk_value
3129
-            );
3130
-        $result = $wpdb->query($query);
3131
-        foreach ($fields as $field) {
3132
-            // If it was successful, we'd like to know the new value.
3133
-            // If it failed, we'd also like to know the new value.
3134
-            $new_value = $this->get_model()->get_var(
3135
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3136
-                    $this->get_model()->get_index_primary_key_string(
3137
-                        $this->model_field_array()
3138
-                    ),
3139
-                    [
3140
-                        'default_where_conditions' => 'minimum',
3141
-                    ]
3142
-                ),
3143
-                $field->get_name()
3144
-            );
3145
-            $this->set_from_db(
3146
-                $field->get_name(),
3147
-                $new_value
3148
-            );
3149
-        }
3150
-        return (bool) $result;
3151
-    }
3152
-
3153
-
3154
-    /**
3155
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3156
-     * Does not allow negative values, however.
3157
-     *
3158
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3159
-     *                                   (positive or negative). One important gotcha: all these values must be
3160
-     *                                   on the same table (eg don't pass in one field for the posts table and
3161
-     *                                   another for the event meta table.)
3162
-     * @return bool
3163
-     * @throws EE_Error
3164
-     * @throws InvalidArgumentException
3165
-     * @throws InvalidDataTypeException
3166
-     * @throws InvalidInterfaceException
3167
-     * @throws ReflectionException
3168
-     * @since 4.9.80.p
3169
-     */
3170
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3171
-    {
3172
-        global $wpdb;
3173
-        if (empty($fields_n_quantities)) {
3174
-            // No fields to update? Well sure, we updated them to that value just fine.
3175
-            return true;
3176
-        }
3177
-        $fields             = [];
3178
-        $set_sql_statements = [];
3179
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3180
-            $field       = $this->get_model()->field_settings_for($field_name, true);
3181
-            $fields[]    = $field;
3182
-            $column_name = $field->get_table_column();
3183
-
3184
-            $abs_qty = absint($quantity);
3185
-            if ($quantity > 0) {
3186
-                // don't let the value be negative as often these fields are unsigned
3187
-                $set_sql_statements[] = $wpdb->prepare(
3188
-                    "`{$column_name}` = `{$column_name}` + %d",
3189
-                    $abs_qty
3190
-                );
3191
-            } else {
3192
-                $set_sql_statements[] = $wpdb->prepare(
3193
-                    "`{$column_name}` = CASE
3128
+				$table_pk_value
3129
+			);
3130
+		$result = $wpdb->query($query);
3131
+		foreach ($fields as $field) {
3132
+			// If it was successful, we'd like to know the new value.
3133
+			// If it failed, we'd also like to know the new value.
3134
+			$new_value = $this->get_model()->get_var(
3135
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3136
+					$this->get_model()->get_index_primary_key_string(
3137
+						$this->model_field_array()
3138
+					),
3139
+					[
3140
+						'default_where_conditions' => 'minimum',
3141
+					]
3142
+				),
3143
+				$field->get_name()
3144
+			);
3145
+			$this->set_from_db(
3146
+				$field->get_name(),
3147
+				$new_value
3148
+			);
3149
+		}
3150
+		return (bool) $result;
3151
+	}
3152
+
3153
+
3154
+	/**
3155
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3156
+	 * Does not allow negative values, however.
3157
+	 *
3158
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3159
+	 *                                   (positive or negative). One important gotcha: all these values must be
3160
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3161
+	 *                                   another for the event meta table.)
3162
+	 * @return bool
3163
+	 * @throws EE_Error
3164
+	 * @throws InvalidArgumentException
3165
+	 * @throws InvalidDataTypeException
3166
+	 * @throws InvalidInterfaceException
3167
+	 * @throws ReflectionException
3168
+	 * @since 4.9.80.p
3169
+	 */
3170
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3171
+	{
3172
+		global $wpdb;
3173
+		if (empty($fields_n_quantities)) {
3174
+			// No fields to update? Well sure, we updated them to that value just fine.
3175
+			return true;
3176
+		}
3177
+		$fields             = [];
3178
+		$set_sql_statements = [];
3179
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3180
+			$field       = $this->get_model()->field_settings_for($field_name, true);
3181
+			$fields[]    = $field;
3182
+			$column_name = $field->get_table_column();
3183
+
3184
+			$abs_qty = absint($quantity);
3185
+			if ($quantity > 0) {
3186
+				// don't let the value be negative as often these fields are unsigned
3187
+				$set_sql_statements[] = $wpdb->prepare(
3188
+					"`{$column_name}` = `{$column_name}` + %d",
3189
+					$abs_qty
3190
+				);
3191
+			} else {
3192
+				$set_sql_statements[] = $wpdb->prepare(
3193
+					"`{$column_name}` = CASE
3194 3194
                        WHEN (`{$column_name}` >= %d)
3195 3195
                        THEN `{$column_name}` - %d
3196 3196
                        ELSE 0
3197 3197
                     END",
3198
-                    $abs_qty,
3199
-                    $abs_qty
3200
-                );
3201
-            }
3202
-        }
3203
-        return $this->updateFieldsInDB(
3204
-            $fields,
3205
-            implode(', ', $set_sql_statements)
3206
-        );
3207
-    }
3208
-
3209
-
3210
-    /**
3211
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3212
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3213
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3214
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3215
-     * Otherwise returns false.
3216
-     *
3217
-     * @param string $field_name_to_bump
3218
-     * @param string $field_name_affecting_total
3219
-     * @param string $limit_field_name
3220
-     * @param int    $quantity
3221
-     * @return bool
3222
-     * @throws EE_Error
3223
-     * @throws InvalidArgumentException
3224
-     * @throws InvalidDataTypeException
3225
-     * @throws InvalidInterfaceException
3226
-     * @throws ReflectionException
3227
-     * @since 4.9.80.p
3228
-     */
3229
-    public function incrementFieldConditionallyInDb(
3230
-        $field_name_to_bump,
3231
-        $field_name_affecting_total,
3232
-        $limit_field_name,
3233
-        $quantity
3234
-    ) {
3235
-        global $wpdb;
3236
-        $field       = $this->get_model()->field_settings_for($field_name_to_bump, true);
3237
-        $column_name = $field->get_table_column();
3238
-
3239
-        $field_affecting_total  = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3240
-        $column_affecting_total = $field_affecting_total->get_table_column();
3241
-
3242
-        $limiting_field  = $this->get_model()->field_settings_for($limit_field_name, true);
3243
-        $limiting_column = $limiting_field->get_table_column();
3244
-        return $this->updateFieldsInDB(
3245
-            [$field],
3246
-            $wpdb->prepare(
3247
-                "`{$column_name}` =
3198
+					$abs_qty,
3199
+					$abs_qty
3200
+				);
3201
+			}
3202
+		}
3203
+		return $this->updateFieldsInDB(
3204
+			$fields,
3205
+			implode(', ', $set_sql_statements)
3206
+		);
3207
+	}
3208
+
3209
+
3210
+	/**
3211
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3212
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3213
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3214
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3215
+	 * Otherwise returns false.
3216
+	 *
3217
+	 * @param string $field_name_to_bump
3218
+	 * @param string $field_name_affecting_total
3219
+	 * @param string $limit_field_name
3220
+	 * @param int    $quantity
3221
+	 * @return bool
3222
+	 * @throws EE_Error
3223
+	 * @throws InvalidArgumentException
3224
+	 * @throws InvalidDataTypeException
3225
+	 * @throws InvalidInterfaceException
3226
+	 * @throws ReflectionException
3227
+	 * @since 4.9.80.p
3228
+	 */
3229
+	public function incrementFieldConditionallyInDb(
3230
+		$field_name_to_bump,
3231
+		$field_name_affecting_total,
3232
+		$limit_field_name,
3233
+		$quantity
3234
+	) {
3235
+		global $wpdb;
3236
+		$field       = $this->get_model()->field_settings_for($field_name_to_bump, true);
3237
+		$column_name = $field->get_table_column();
3238
+
3239
+		$field_affecting_total  = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3240
+		$column_affecting_total = $field_affecting_total->get_table_column();
3241
+
3242
+		$limiting_field  = $this->get_model()->field_settings_for($limit_field_name, true);
3243
+		$limiting_column = $limiting_field->get_table_column();
3244
+		return $this->updateFieldsInDB(
3245
+			[$field],
3246
+			$wpdb->prepare(
3247
+				"`{$column_name}` =
3248 3248
             CASE
3249 3249
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3250 3250
                THEN `{$column_name}` + %d
3251 3251
                ELSE `{$column_name}`
3252 3252
             END",
3253
-                $quantity,
3254
-                EE_INF_IN_DB,
3255
-                $quantity
3256
-            )
3257
-        );
3258
-    }
3259
-
3260
-
3261
-    /**
3262
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3263
-     * (probably a bad assumption they have made, oh well)
3264
-     *
3265
-     * @return string
3266
-     */
3267
-    public function __toString()
3268
-    {
3269
-        try {
3270
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3271
-        } catch (Exception $e) {
3272
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3273
-            return '';
3274
-        }
3275
-    }
3276
-
3277
-
3278
-    /**
3279
-     * Clear related model objects if they're already in the DB, because otherwise when we
3280
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3281
-     * This means if we have made changes to those related model objects, and want to unserialize
3282
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3283
-     * Instead, those related model objects should be directly serialized and stored.
3284
-     * Eg, the following won't work:
3285
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3286
-     * $att = $reg->attendee();
3287
-     * $att->set( 'ATT_fname', 'Dirk' );
3288
-     * update_option( 'my_option', serialize( $reg ) );
3289
-     * //END REQUEST
3290
-     * //START NEXT REQUEST
3291
-     * $reg = get_option( 'my_option' );
3292
-     * $reg->attendee()->save();
3293
-     * And would need to be replace with:
3294
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3295
-     * $att = $reg->attendee();
3296
-     * $att->set( 'ATT_fname', 'Dirk' );
3297
-     * update_option( 'my_option', serialize( $reg ) );
3298
-     * //END REQUEST
3299
-     * //START NEXT REQUEST
3300
-     * $att = get_option( 'my_option' );
3301
-     * $att->save();
3302
-     *
3303
-     * @return array
3304
-     * @throws ReflectionException
3305
-     * @throws InvalidArgumentException
3306
-     * @throws InvalidInterfaceException
3307
-     * @throws InvalidDataTypeException
3308
-     * @throws EE_Error
3309
-     */
3310
-    public function __sleep()
3311
-    {
3312
-        $model = $this->get_model();
3313
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3314
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3315
-                $classname = 'EE_' . $model->get_this_model_name();
3316
-                if (
3317
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3318
-                    && $this->get_one_from_cache($relation_name)->ID()
3319
-                ) {
3320
-                    $this->clear_cache(
3321
-                        $relation_name,
3322
-                        $this->get_one_from_cache($relation_name)->ID()
3323
-                    );
3324
-                }
3325
-            }
3326
-        }
3327
-        $this->_props_n_values_provided_in_constructor = [];
3328
-        $properties_to_serialize                       = get_object_vars($this);
3329
-        // don't serialize the model. It's big and that risks recursion
3330
-        unset($properties_to_serialize['_model']);
3331
-        return array_keys($properties_to_serialize);
3332
-    }
3333
-
3334
-
3335
-    /**
3336
-     * restore _props_n_values_provided_in_constructor
3337
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3338
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3339
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3340
-     */
3341
-    public function __wakeup()
3342
-    {
3343
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3344
-    }
3345
-
3346
-
3347
-    /**
3348
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3349
-     * distinct with the clone host instance are also cloned.
3350
-     */
3351
-    public function __clone()
3352
-    {
3353
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3354
-        foreach ($this->_fields as $field => $value) {
3355
-            if ($value instanceof DateTime) {
3356
-                $this->_fields[ $field ] = clone $value;
3357
-            }
3358
-        }
3359
-    }
3360
-
3361
-
3362
-    public function debug()
3363
-    {
3364
-        $this->echoProperty(get_class($this), get_object_vars($this));
3365
-        echo "\n\n";
3366
-    }
3367
-
3368
-
3369
-    private function echoProperty($field, $value, int $indent = 0)
3370
-    {
3371
-        $bullets = str_repeat(' -', $indent) . ' ';
3372
-        $field = strpos($field, '_') === 0 ? substr($field, 1) : $field;
3373
-        echo "\n$bullets$field: ";
3374
-        if ($value instanceof EEM_Base) {
3375
-            $value = get_class($value);
3376
-        } elseif (is_object($value)) {
3377
-            $value = get_object_vars($value);
3378
-        }
3379
-        if (is_array($value)) {
3380
-            foreach ($value as $f => $v ) {
3381
-                $this->echoProperty($f, $v, $indent+1);
3382
-            }
3383
-            return;
3384
-        }
3385
-        ob_start();
3386
-        var_dump($value);
3387
-        echo rtrim(ob_get_clean(), "\n");
3388
-    }
3253
+				$quantity,
3254
+				EE_INF_IN_DB,
3255
+				$quantity
3256
+			)
3257
+		);
3258
+	}
3259
+
3260
+
3261
+	/**
3262
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3263
+	 * (probably a bad assumption they have made, oh well)
3264
+	 *
3265
+	 * @return string
3266
+	 */
3267
+	public function __toString()
3268
+	{
3269
+		try {
3270
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3271
+		} catch (Exception $e) {
3272
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3273
+			return '';
3274
+		}
3275
+	}
3276
+
3277
+
3278
+	/**
3279
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3280
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3281
+	 * This means if we have made changes to those related model objects, and want to unserialize
3282
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3283
+	 * Instead, those related model objects should be directly serialized and stored.
3284
+	 * Eg, the following won't work:
3285
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3286
+	 * $att = $reg->attendee();
3287
+	 * $att->set( 'ATT_fname', 'Dirk' );
3288
+	 * update_option( 'my_option', serialize( $reg ) );
3289
+	 * //END REQUEST
3290
+	 * //START NEXT REQUEST
3291
+	 * $reg = get_option( 'my_option' );
3292
+	 * $reg->attendee()->save();
3293
+	 * And would need to be replace with:
3294
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3295
+	 * $att = $reg->attendee();
3296
+	 * $att->set( 'ATT_fname', 'Dirk' );
3297
+	 * update_option( 'my_option', serialize( $reg ) );
3298
+	 * //END REQUEST
3299
+	 * //START NEXT REQUEST
3300
+	 * $att = get_option( 'my_option' );
3301
+	 * $att->save();
3302
+	 *
3303
+	 * @return array
3304
+	 * @throws ReflectionException
3305
+	 * @throws InvalidArgumentException
3306
+	 * @throws InvalidInterfaceException
3307
+	 * @throws InvalidDataTypeException
3308
+	 * @throws EE_Error
3309
+	 */
3310
+	public function __sleep()
3311
+	{
3312
+		$model = $this->get_model();
3313
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3314
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3315
+				$classname = 'EE_' . $model->get_this_model_name();
3316
+				if (
3317
+					$this->get_one_from_cache($relation_name) instanceof $classname
3318
+					&& $this->get_one_from_cache($relation_name)->ID()
3319
+				) {
3320
+					$this->clear_cache(
3321
+						$relation_name,
3322
+						$this->get_one_from_cache($relation_name)->ID()
3323
+					);
3324
+				}
3325
+			}
3326
+		}
3327
+		$this->_props_n_values_provided_in_constructor = [];
3328
+		$properties_to_serialize                       = get_object_vars($this);
3329
+		// don't serialize the model. It's big and that risks recursion
3330
+		unset($properties_to_serialize['_model']);
3331
+		return array_keys($properties_to_serialize);
3332
+	}
3333
+
3334
+
3335
+	/**
3336
+	 * restore _props_n_values_provided_in_constructor
3337
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3338
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3339
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3340
+	 */
3341
+	public function __wakeup()
3342
+	{
3343
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3344
+	}
3345
+
3346
+
3347
+	/**
3348
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3349
+	 * distinct with the clone host instance are also cloned.
3350
+	 */
3351
+	public function __clone()
3352
+	{
3353
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3354
+		foreach ($this->_fields as $field => $value) {
3355
+			if ($value instanceof DateTime) {
3356
+				$this->_fields[ $field ] = clone $value;
3357
+			}
3358
+		}
3359
+	}
3360
+
3361
+
3362
+	public function debug()
3363
+	{
3364
+		$this->echoProperty(get_class($this), get_object_vars($this));
3365
+		echo "\n\n";
3366
+	}
3367
+
3368
+
3369
+	private function echoProperty($field, $value, int $indent = 0)
3370
+	{
3371
+		$bullets = str_repeat(' -', $indent) . ' ';
3372
+		$field = strpos($field, '_') === 0 ? substr($field, 1) : $field;
3373
+		echo "\n$bullets$field: ";
3374
+		if ($value instanceof EEM_Base) {
3375
+			$value = get_class($value);
3376
+		} elseif (is_object($value)) {
3377
+			$value = get_object_vars($value);
3378
+		}
3379
+		if (is_array($value)) {
3380
+			foreach ($value as $f => $v ) {
3381
+				$this->echoProperty($f, $v, $indent+1);
3382
+			}
3383
+			return;
3384
+		}
3385
+		ob_start();
3386
+		var_dump($value);
3387
+		echo rtrim(ob_get_clean(), "\n");
3388
+	}
3389 3389
 }
Please login to merge, or discard this patch.
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
         $fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
134 134
         // verify client code has not passed any invalid field names
135 135
         foreach ($fieldValues as $field_name => $field_value) {
136
-            if (! isset($model_fields[ $field_name ])) {
136
+            if ( ! isset($model_fields[$field_name])) {
137 137
                 throw new EE_Error(
138 138
                     sprintf(
139 139
                         esc_html__(
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
         $date_format     = null;
152 152
         $time_format     = null;
153 153
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
154
-        if (! empty($date_formats) && is_array($date_formats)) {
154
+        if ( ! empty($date_formats) && is_array($date_formats)) {
155 155
             [$date_format, $time_format] = $date_formats;
156 156
         }
157 157
         $this->set_date_format($date_format);
@@ -162,14 +162,14 @@  discard block
 block discarded – undo
162 162
                 // client code has indicated these field values are from the database
163 163
                 $this->set_from_db(
164 164
                     $fieldName,
165
-                    $fieldValues[ $fieldName ] ?? null
165
+                    $fieldValues[$fieldName] ?? null
166 166
                 );
167 167
             } else {
168 168
                 // we're constructing a brand new instance of the model object.
169 169
                 // Generally, this means we'll need to do more field validation
170 170
                 $this->set(
171 171
                     $fieldName,
172
-                    $fieldValues[ $fieldName ] ?? null,
172
+                    $fieldValues[$fieldName] ?? null,
173 173
                     true
174 174
                 );
175 175
             }
@@ -177,15 +177,15 @@  discard block
 block discarded – undo
177 177
         // remember what values were passed to this constructor
178 178
         $this->_props_n_values_provided_in_constructor = $fieldValues;
179 179
         // remember in entity mapper
180
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
180
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
181 181
             $model->add_to_entity_map($this);
182 182
         }
183 183
         // setup all the relations
184 184
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
185 185
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
186
-                $this->_model_relations[ $relation_name ] = null;
186
+                $this->_model_relations[$relation_name] = null;
187 187
             } else {
188
-                $this->_model_relations[ $relation_name ] = [];
188
+                $this->_model_relations[$relation_name] = [];
189 189
             }
190 190
         }
191 191
         /**
@@ -237,10 +237,10 @@  discard block
 block discarded – undo
237 237
     public function get_original($field_name)
238 238
     {
239 239
         if (
240
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
240
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
241 241
             && $field_settings = $this->get_model()->field_settings_for($field_name)
242 242
         ) {
243
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
243
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
244 244
         }
245 245
         return null;
246 246
     }
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
         // then don't do anything
277 277
         if (
278 278
             ! $use_default
279
-            && $this->_fields[ $field_name ] === $field_value
279
+            && $this->_fields[$field_name] === $field_value
280 280
             && $this->ID()
281 281
         ) {
282 282
             return;
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
         $model              = $this->get_model();
285 285
         $this->_has_changes = true;
286 286
         $field_obj          = $model->field_settings_for($field_name);
287
-        if (! $field_obj instanceof EE_Model_Field_Base) {
287
+        if ( ! $field_obj instanceof EE_Model_Field_Base) {
288 288
             throw new EE_Error(
289 289
                 sprintf(
290 290
                     esc_html__(
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
             ? $field_obj->get_default_value()
308 308
             : $field_value;
309 309
 
310
-        $this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
310
+        $this->_fields[$field_name] = $field_obj->prepare_for_set($value);
311 311
 
312 312
         // if we're not in the constructor...
313 313
         // now check if what we set was a primary key
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
             } else {
370 370
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
371 371
             }
372
-            $this->_fields[ $field_name ] = $field_value;
372
+            $this->_fields[$field_name] = $field_value;
373 373
             $this->_clear_cached_property($field_name);
374 374
         }
375 375
     }
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
      */
396 396
     public function getCustomSelect($alias)
397 397
     {
398
-        return $this->custom_selection_results[ $alias ] ?? null;
398
+        return $this->custom_selection_results[$alias] ?? null;
399 399
     }
400 400
 
401 401
 
@@ -482,8 +482,8 @@  discard block
 block discarded – undo
482 482
         foreach ($model_fields as $field_name => $field_obj) {
483 483
             if ($field_obj instanceof EE_Datetime_Field) {
484 484
                 $field_obj->set_timezone($this->_timezone);
485
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
486
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
485
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
486
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
487 487
                 }
488 488
             }
489 489
         }
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
      */
542 542
     public function get_format($full = true)
543 543
     {
544
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
544
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
545 545
     }
546 546
 
547 547
 
@@ -567,11 +567,11 @@  discard block
 block discarded – undo
567 567
     public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
568 568
     {
569 569
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
570
-        if (! $object_to_cache instanceof EE_Base_Class) {
570
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
571 571
             return false;
572 572
         }
573 573
         // also get "how" the object is related, or throw an error
574
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
574
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
575 575
             throw new EE_Error(
576 576
                 sprintf(
577 577
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -585,38 +585,38 @@  discard block
 block discarded – undo
585 585
             // if it's a "belongs to" relationship, then there's only one related model object
586 586
             // eg, if this is a registration, there's only 1 attendee for it
587 587
             // so for these model objects just set it to be cached
588
-            $this->_model_relations[ $relation_name ] = $object_to_cache;
588
+            $this->_model_relations[$relation_name] = $object_to_cache;
589 589
             $return                                   = true;
590 590
         } else {
591 591
             // otherwise, this is the "many" side of a one to many relationship,
592 592
             // so we'll add the object to the array of related objects for that type.
593 593
             // eg: if this is an event, there are many registrations for that event,
594 594
             // so we cache the registrations in an array
595
-            if (! is_array($this->_model_relations[ $relation_name ])) {
595
+            if ( ! is_array($this->_model_relations[$relation_name])) {
596 596
                 // if for some reason, the cached item is a model object,
597 597
                 // then stick that in the array, otherwise start with an empty array
598
-                $this->_model_relations[ $relation_name ] =
599
-                    $this->_model_relations[ $relation_name ] instanceof EE_Base_Class
600
-                        ? [$this->_model_relations[ $relation_name ]]
598
+                $this->_model_relations[$relation_name] =
599
+                    $this->_model_relations[$relation_name] instanceof EE_Base_Class
600
+                        ? [$this->_model_relations[$relation_name]]
601 601
                         : [];
602 602
             }
603 603
             // first check for a cache_id which is normally empty
604
-            if (! empty($cache_id)) {
604
+            if ( ! empty($cache_id)) {
605 605
                 // if the cache_id exists, then it means we are purposely trying to cache this
606 606
                 // with a known key that can then be used to retrieve the object later on
607
-                $this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
607
+                $this->_model_relations[$relation_name][$cache_id] = $object_to_cache;
608 608
                 $return                                                = $cache_id;
609 609
             } elseif ($object_to_cache->ID()) {
610 610
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
611
-                $this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
611
+                $this->_model_relations[$relation_name][$object_to_cache->ID()] = $object_to_cache;
612 612
                 $return                                                             = $object_to_cache->ID();
613 613
             } else {
614 614
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
615
-                $this->_model_relations[ $relation_name ][] = $object_to_cache;
615
+                $this->_model_relations[$relation_name][] = $object_to_cache;
616 616
                 // move the internal pointer to the end of the array
617
-                end($this->_model_relations[ $relation_name ]);
617
+                end($this->_model_relations[$relation_name]);
618 618
                 // and grab the key so that we can return it
619
-                $return = key($this->_model_relations[ $relation_name ]);
619
+                $return = key($this->_model_relations[$relation_name]);
620 620
             }
621 621
         }
622 622
         return $return;
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
         $this->get_model()->field_settings_for($fieldname);
644 644
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
645 645
 
646
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
646
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
647 647
     }
648 648
 
649 649
 
@@ -672,9 +672,9 @@  discard block
 block discarded – undo
672 672
         $model = $this->get_model();
673 673
         $model->field_settings_for($fieldname);
674 674
         $cache_type = $pretty ? 'pretty' : 'standard';
675
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
676
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
677
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
675
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
676
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
677
+            return $this->_cached_properties[$fieldname][$cache_type];
678 678
         }
679 679
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
680 680
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -702,12 +702,12 @@  discard block
 block discarded – undo
702 702
         if ($field_obj instanceof EE_Datetime_Field) {
703 703
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
704 704
         }
705
-        if (! isset($this->_fields[ $fieldname ])) {
706
-            $this->_fields[ $fieldname ] = null;
705
+        if ( ! isset($this->_fields[$fieldname])) {
706
+            $this->_fields[$fieldname] = null;
707 707
         }
708 708
         return $pretty
709
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
710
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
709
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
710
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
711 711
     }
712 712
 
713 713
 
@@ -763,8 +763,8 @@  discard block
 block discarded – undo
763 763
      */
764 764
     protected function _clear_cached_property($property_name)
765 765
     {
766
-        if (isset($this->_cached_properties[ $property_name ])) {
767
-            unset($this->_cached_properties[ $property_name ]);
766
+        if (isset($this->_cached_properties[$property_name])) {
767
+            unset($this->_cached_properties[$property_name]);
768 768
         }
769 769
     }
770 770
 
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
     {
817 817
         $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
818 818
         $index_in_cache        = '';
819
-        if (! $relationship_to_model) {
819
+        if ( ! $relationship_to_model) {
820 820
             throw new EE_Error(
821 821
                 sprintf(
822 822
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -827,10 +827,10 @@  discard block
 block discarded – undo
827 827
         }
828 828
         if ($clear_all) {
829 829
             $obj_removed                              = true;
830
-            $this->_model_relations[ $relation_name ] = null;
830
+            $this->_model_relations[$relation_name] = null;
831 831
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
-            $obj_removed                              = $this->_model_relations[ $relation_name ];
833
-            $this->_model_relations[ $relation_name ] = null;
832
+            $obj_removed                              = $this->_model_relations[$relation_name];
833
+            $this->_model_relations[$relation_name] = null;
834 834
         } else {
835 835
             if (
836 836
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -838,12 +838,12 @@  discard block
 block discarded – undo
838 838
             ) {
839 839
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
840 840
                 if (
841
-                    is_array($this->_model_relations[ $relation_name ])
842
-                    && ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
841
+                    is_array($this->_model_relations[$relation_name])
842
+                    && ! isset($this->_model_relations[$relation_name][$index_in_cache])
843 843
                 ) {
844 844
                     $index_found_at = null;
845 845
                     // find this object in the array even though it has a different key
846
-                    foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
846
+                    foreach ($this->_model_relations[$relation_name] as $index => $obj) {
847 847
                         /** @noinspection TypeUnsafeComparisonInspection */
848 848
                         if (
849 849
                             $obj instanceof EE_Base_Class
@@ -877,9 +877,9 @@  discard block
 block discarded – undo
877 877
             }
878 878
             // supposedly we've found it. But it could just be that the client code
879 879
             // provided a bad index/object
880
-            if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
881
-                $obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
882
-                unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
880
+            if (isset($this->_model_relations[$relation_name][$index_in_cache])) {
881
+                $obj_removed = $this->_model_relations[$relation_name][$index_in_cache];
882
+                unset($this->_model_relations[$relation_name][$index_in_cache]);
883 883
             } else {
884 884
                 // that thing was never cached anyways.
885 885
                 $obj_removed = null;
@@ -910,7 +910,7 @@  discard block
 block discarded – undo
910 910
         $current_cache_id = ''
911 911
     ) {
912 912
         // verify that incoming object is of the correct type
913
-        $obj_class = 'EE_' . $relation_name;
913
+        $obj_class = 'EE_'.$relation_name;
914 914
         if ($newly_saved_object instanceof $obj_class) {
915 915
             /* @type EE_Base_Class $newly_saved_object */
916 916
             // now get the type of relation
@@ -918,18 +918,18 @@  discard block
 block discarded – undo
918 918
             // if this is a 1:1 relationship
919 919
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
920 920
                 // then just replace the cached object with the newly saved object
921
-                $this->_model_relations[ $relation_name ] = $newly_saved_object;
921
+                $this->_model_relations[$relation_name] = $newly_saved_object;
922 922
                 return true;
923 923
                 // or if it's some kind of sordid feral polyamorous relationship...
924 924
             }
925 925
             if (
926
-                is_array($this->_model_relations[ $relation_name ])
927
-                && isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
926
+                is_array($this->_model_relations[$relation_name])
927
+                && isset($this->_model_relations[$relation_name][$current_cache_id])
928 928
             ) {
929 929
                 // then remove the current cached item
930
-                unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
930
+                unset($this->_model_relations[$relation_name][$current_cache_id]);
931 931
                 // and cache the newly saved object using it's new ID
932
-                $this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
932
+                $this->_model_relations[$relation_name][$newly_saved_object->ID()] = $newly_saved_object;
933 933
                 return true;
934 934
             }
935 935
         }
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
      */
947 947
     public function get_one_from_cache($relation_name)
948 948
     {
949
-        $cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
949
+        $cached_array_or_object = $this->_model_relations[$relation_name] ?? null;
950 950
         if (is_array($cached_array_or_object)) {
951 951
             return array_shift($cached_array_or_object);
952 952
         }
@@ -968,7 +968,7 @@  discard block
 block discarded – undo
968 968
      */
969 969
     public function get_all_from_cache($relation_name)
970 970
     {
971
-        $objects = $this->_model_relations[ $relation_name ] ?? [];
971
+        $objects = $this->_model_relations[$relation_name] ?? [];
972 972
         // if the result is not an array, but exists, make it an array
973 973
         $objects = is_array($objects)
974 974
             ? $objects
@@ -1160,9 +1160,9 @@  discard block
 block discarded – undo
1160 1160
     public function get_raw($field_name)
1161 1161
     {
1162 1162
         $field_settings = $this->get_model()->field_settings_for($field_name);
1163
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1164
-            ? $this->_fields[ $field_name ]->format('U')
1165
-            : $this->_fields[ $field_name ];
1163
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1164
+            ? $this->_fields[$field_name]->format('U')
1165
+            : $this->_fields[$field_name];
1166 1166
     }
1167 1167
 
1168 1168
 
@@ -1184,7 +1184,7 @@  discard block
 block discarded – undo
1184 1184
     public function get_DateTime_object($field_name)
1185 1185
     {
1186 1186
         $field_settings = $this->get_model()->field_settings_for($field_name);
1187
-        if (! $field_settings instanceof EE_Datetime_Field) {
1187
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1188 1188
             EE_Error::add_error(
1189 1189
                 sprintf(
1190 1190
                     esc_html__(
@@ -1199,8 +1199,8 @@  discard block
 block discarded – undo
1199 1199
             );
1200 1200
             return false;
1201 1201
         }
1202
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1203
-            ? clone $this->_fields[ $field_name ]
1202
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1203
+            ? clone $this->_fields[$field_name]
1204 1204
             : null;
1205 1205
     }
1206 1206
 
@@ -1445,7 +1445,7 @@  discard block
 block discarded – undo
1445 1445
      */
1446 1446
     public function get_i18n_datetime(string $field_name, string $format = ''): string
1447 1447
     {
1448
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1448
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1449 1449
         return date_i18n(
1450 1450
             $format,
1451 1451
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1557,21 +1557,21 @@  discard block
 block discarded – undo
1557 1557
         $field->set_time_format($this->_tm_frmt);
1558 1558
         switch ($what) {
1559 1559
             case 'T':
1560
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1560
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_time(
1561 1561
                     $datetime_value,
1562
-                    $this->_fields[ $field_name ]
1562
+                    $this->_fields[$field_name]
1563 1563
                 );
1564 1564
                 $this->_has_changes           = true;
1565 1565
                 break;
1566 1566
             case 'D':
1567
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1567
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_date(
1568 1568
                     $datetime_value,
1569
-                    $this->_fields[ $field_name ]
1569
+                    $this->_fields[$field_name]
1570 1570
                 );
1571 1571
                 $this->_has_changes           = true;
1572 1572
                 break;
1573 1573
             case 'B':
1574
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1574
+                $this->_fields[$field_name] = $field->prepare_for_set($datetime_value);
1575 1575
                 $this->_has_changes           = true;
1576 1576
                 break;
1577 1577
         }
@@ -1614,7 +1614,7 @@  discard block
 block discarded – undo
1614 1614
         $this->set_timezone($timezone);
1615 1615
         $fn   = (array) $field_name;
1616 1616
         $args = array_merge($fn, (array) $args);
1617
-        if (! method_exists($this, $callback)) {
1617
+        if ( ! method_exists($this, $callback)) {
1618 1618
             throw new EE_Error(
1619 1619
                 sprintf(
1620 1620
                     esc_html__(
@@ -1626,7 +1626,7 @@  discard block
 block discarded – undo
1626 1626
             );
1627 1627
         }
1628 1628
         $args   = (array) $args;
1629
-        $return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1629
+        $return = $prepend.call_user_func_array([$this, $callback], $args).$append;
1630 1630
         $this->set_timezone($original_timezone);
1631 1631
         return $return;
1632 1632
     }
@@ -1741,8 +1741,8 @@  discard block
 block discarded – undo
1741 1741
     {
1742 1742
         $model = $this->get_model();
1743 1743
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1744
-            if (! empty($this->_model_relations[ $relation_name ])) {
1745
-                $related_objects = $this->_model_relations[ $relation_name ];
1744
+            if ( ! empty($this->_model_relations[$relation_name])) {
1745
+                $related_objects = $this->_model_relations[$relation_name];
1746 1746
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1747 1747
                     // this relation only stores a single model object, not an array
1748 1748
                     // but let's make it consistent
@@ -1799,7 +1799,7 @@  discard block
 block discarded – undo
1799 1799
             $this->set($column, $value);
1800 1800
         }
1801 1801
         // no changes ? then don't do anything
1802
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1802
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1803 1803
             return 0;
1804 1804
         }
1805 1805
         /**
@@ -1809,7 +1809,7 @@  discard block
 block discarded – undo
1809 1809
          * @param EE_Base_Class $model_object the model object about to be saved.
1810 1810
          */
1811 1811
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1812
-        if (! $this->allow_persist()) {
1812
+        if ( ! $this->allow_persist()) {
1813 1813
             return 0;
1814 1814
         }
1815 1815
         // now get current attribute values
@@ -1824,10 +1824,10 @@  discard block
 block discarded – undo
1824 1824
         if ($model->has_primary_key_field()) {
1825 1825
             if ($model->get_primary_key_field()->is_auto_increment()) {
1826 1826
                 // ok check if it's set, if so: update; if not, insert
1827
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1827
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1828 1828
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1829 1829
                 } else {
1830
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1830
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1831 1831
                     $results = $model->insert($save_cols_n_values);
1832 1832
                     if ($results) {
1833 1833
                         // if successful, set the primary key
@@ -1837,7 +1837,7 @@  discard block
 block discarded – undo
1837 1837
                         // will get added to the mapper before we can add this one!
1838 1838
                         // but if we just avoid using the SET method, all that headache can be avoided
1839 1839
                         $pk_field_name                   = $model->primary_key_name();
1840
-                        $this->_fields[ $pk_field_name ] = $results;
1840
+                        $this->_fields[$pk_field_name] = $results;
1841 1841
                         $this->_clear_cached_property($pk_field_name);
1842 1842
                         $model->add_to_entity_map($this);
1843 1843
                         $this->_update_cached_related_model_objs_fks();
@@ -1854,8 +1854,8 @@  discard block
 block discarded – undo
1854 1854
                                     'event_espresso'
1855 1855
                                 ),
1856 1856
                                 get_class($this),
1857
-                                get_class($model) . '::instance()->add_to_entity_map()',
1858
-                                get_class($model) . '::instance()->get_one_by_ID()',
1857
+                                get_class($model).'::instance()->add_to_entity_map()',
1858
+                                get_class($model).'::instance()->get_one_by_ID()',
1859 1859
                                 '<br />'
1860 1860
                             )
1861 1861
                         );
@@ -1879,7 +1879,7 @@  discard block
 block discarded – undo
1879 1879
                     $save_cols_n_values,
1880 1880
                     $model->get_combined_primary_key_fields()
1881 1881
                 );
1882
-                $results                     = $model->update(
1882
+                $results = $model->update(
1883 1883
                     $save_cols_n_values,
1884 1884
                     $combined_pk_fields_n_values
1885 1885
                 );
@@ -1957,27 +1957,27 @@  discard block
 block discarded – undo
1957 1957
     public function save_new_cached_related_model_objs()
1958 1958
     {
1959 1959
         // make sure this has been saved
1960
-        if (! $this->ID()) {
1960
+        if ( ! $this->ID()) {
1961 1961
             $id = $this->save();
1962 1962
         } else {
1963 1963
             $id = $this->ID();
1964 1964
         }
1965 1965
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1966 1966
         foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1967
-            if ($this->_model_relations[ $relation_name ]) {
1967
+            if ($this->_model_relations[$relation_name]) {
1968 1968
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1969 1969
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1970 1970
                 /* @var $related_model_obj EE_Base_Class */
1971 1971
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
1972 1972
                     // add a relation to that relation type (which saves the appropriate thing in the process)
1973 1973
                     // but ONLY if it DOES NOT exist in the DB
1974
-                    $related_model_obj = $this->_model_relations[ $relation_name ];
1974
+                    $related_model_obj = $this->_model_relations[$relation_name];
1975 1975
                     // if( ! $related_model_obj->ID()){
1976 1976
                     $this->_add_relation_to($related_model_obj, $relation_name);
1977 1977
                     $related_model_obj->save_new_cached_related_model_objs();
1978 1978
                     // }
1979 1979
                 } else {
1980
-                    foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1980
+                    foreach ($this->_model_relations[$relation_name] as $related_model_obj) {
1981 1981
                         // add a relation to that relation type (which saves the appropriate thing in the process)
1982 1982
                         // but ONLY if it DOES NOT exist in the DB
1983 1983
                         // if( ! $related_model_obj->ID()){
@@ -2004,7 +2004,7 @@  discard block
 block discarded – undo
2004 2004
      */
2005 2005
     public function get_model()
2006 2006
     {
2007
-        if (! $this->_model) {
2007
+        if ( ! $this->_model) {
2008 2008
             $modelName    = self::_get_model_classname(get_class($this));
2009 2009
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2010 2010
         } else {
@@ -2030,9 +2030,9 @@  discard block
 block discarded – undo
2030 2030
         $primary_id_ref = self::_get_primary_key_name($classname);
2031 2031
         if (
2032 2032
             array_key_exists($primary_id_ref, $props_n_values)
2033
-            && ! empty($props_n_values[ $primary_id_ref ])
2033
+            && ! empty($props_n_values[$primary_id_ref])
2034 2034
         ) {
2035
-            $id = $props_n_values[ $primary_id_ref ];
2035
+            $id = $props_n_values[$primary_id_ref];
2036 2036
             return self::_get_model($classname)->get_from_entity_map($id);
2037 2037
         }
2038 2038
         return false;
@@ -2065,10 +2065,10 @@  discard block
 block discarded – undo
2065 2065
             $primary_id_ref = self::_get_primary_key_name($classname);
2066 2066
             if (
2067 2067
                 array_key_exists($primary_id_ref, $props_n_values)
2068
-                && ! empty($props_n_values[ $primary_id_ref ])
2068
+                && ! empty($props_n_values[$primary_id_ref])
2069 2069
             ) {
2070 2070
                 $existing = $model->get_one_by_ID(
2071
-                    $props_n_values[ $primary_id_ref ]
2071
+                    $props_n_values[$primary_id_ref]
2072 2072
                 );
2073 2073
             }
2074 2074
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
         }
2081 2081
         if ($existing) {
2082 2082
             // set date formats if present before setting values
2083
-            if (! empty($date_formats) && is_array($date_formats)) {
2083
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2084 2084
                 $existing->set_date_format($date_formats[0]);
2085 2085
                 $existing->set_time_format($date_formats[1]);
2086 2086
             } else {
@@ -2113,7 +2113,7 @@  discard block
 block discarded – undo
2113 2113
     protected static function _get_model($classname, $timezone = '')
2114 2114
     {
2115 2115
         // find model for this class
2116
-        if (! $classname) {
2116
+        if ( ! $classname) {
2117 2117
             throw new EE_Error(
2118 2118
                 sprintf(
2119 2119
                     esc_html__(
@@ -2161,7 +2161,7 @@  discard block
 block discarded – undo
2161 2161
     {
2162 2162
         return strpos((string) $model_name, 'EE_') === 0
2163 2163
             ? str_replace('EE_', 'EEM_', $model_name)
2164
-            : 'EEM_' . $model_name;
2164
+            : 'EEM_'.$model_name;
2165 2165
     }
2166 2166
 
2167 2167
 
@@ -2178,7 +2178,7 @@  discard block
 block discarded – undo
2178 2178
      */
2179 2179
     protected static function _get_primary_key_name($classname = null)
2180 2180
     {
2181
-        if (! $classname) {
2181
+        if ( ! $classname) {
2182 2182
             throw new EE_Error(
2183 2183
                 sprintf(
2184 2184
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2208,7 +2208,7 @@  discard block
 block discarded – undo
2208 2208
         $model = $this->get_model();
2209 2209
         // now that we know the name of the variable, use a variable variable to get its value and return its
2210 2210
         if ($model->has_primary_key_field()) {
2211
-            return $this->_fields[ $model->primary_key_name() ];
2211
+            return $this->_fields[$model->primary_key_name()];
2212 2212
         }
2213 2213
         return $model->get_index_primary_key_string($this->_fields);
2214 2214
     }
@@ -2282,7 +2282,7 @@  discard block
 block discarded – undo
2282 2282
             }
2283 2283
         } else {
2284 2284
             // this thing doesn't exist in the DB,  so just cache it
2285
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2285
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2286 2286
                 throw new EE_Error(
2287 2287
                     sprintf(
2288 2288
                         esc_html__(
@@ -2449,7 +2449,7 @@  discard block
 block discarded – undo
2449 2449
             } else {
2450 2450
                 // did we already cache the result of this query?
2451 2451
                 $cached_results = $this->get_all_from_cache($relation_name);
2452
-                if (! $cached_results) {
2452
+                if ( ! $cached_results) {
2453 2453
                     $related_model_objects = $this->get_model()->get_all_related(
2454 2454
                         $this,
2455 2455
                         $relation_name,
@@ -2561,7 +2561,7 @@  discard block
 block discarded – undo
2561 2561
             } else {
2562 2562
                 // first, check if we've already cached the result of this query
2563 2563
                 $cached_result = $this->get_one_from_cache($relation_name);
2564
-                if (! $cached_result) {
2564
+                if ( ! $cached_result) {
2565 2565
                     $related_model_object = $model->get_first_related(
2566 2566
                         $this,
2567 2567
                         $relation_name,
@@ -2585,7 +2585,7 @@  discard block
 block discarded – undo
2585 2585
             }
2586 2586
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2587 2587
             // just get what's cached on this object
2588
-            if (! $related_model_object) {
2588
+            if ( ! $related_model_object) {
2589 2589
                 $related_model_object = $this->get_one_from_cache($relation_name);
2590 2590
             }
2591 2591
         }
@@ -2668,7 +2668,7 @@  discard block
 block discarded – undo
2668 2668
      */
2669 2669
     public function is_set($field_name)
2670 2670
     {
2671
-        return isset($this->_fields[ $field_name ]);
2671
+        return isset($this->_fields[$field_name]);
2672 2672
     }
2673 2673
 
2674 2674
 
@@ -2684,7 +2684,7 @@  discard block
 block discarded – undo
2684 2684
     {
2685 2685
         foreach ((array) $properties as $property_name) {
2686 2686
             // first make sure this property exists
2687
-            if (! $this->_fields[ $property_name ]) {
2687
+            if ( ! $this->_fields[$property_name]) {
2688 2688
                 throw new EE_Error(
2689 2689
                     sprintf(
2690 2690
                         esc_html__(
@@ -2716,7 +2716,7 @@  discard block
 block discarded – undo
2716 2716
         $properties = [];
2717 2717
         // remove prepended underscore
2718 2718
         foreach ($fields as $field_name => $settings) {
2719
-            $properties[ $field_name ] = $this->get($field_name);
2719
+            $properties[$field_name] = $this->get($field_name);
2720 2720
         }
2721 2721
         return $properties;
2722 2722
     }
@@ -2753,7 +2753,7 @@  discard block
 block discarded – undo
2753 2753
     {
2754 2754
         $className = get_class($this);
2755 2755
         $tagName   = "FHEE__{$className}__{$methodName}";
2756
-        if (! has_filter($tagName)) {
2756
+        if ( ! has_filter($tagName)) {
2757 2757
             throw new EE_Error(
2758 2758
                 sprintf(
2759 2759
                     esc_html__(
@@ -2798,7 +2798,7 @@  discard block
 block discarded – undo
2798 2798
             $query_params[0]['EXM_value'] = $meta_value;
2799 2799
         }
2800 2800
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2801
-        if (! $existing_rows_like_that) {
2801
+        if ( ! $existing_rows_like_that) {
2802 2802
             return $this->add_extra_meta($meta_key, $meta_value);
2803 2803
         }
2804 2804
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2908,7 +2908,7 @@  discard block
 block discarded – undo
2908 2908
                 $values = [];
2909 2909
                 foreach ($results as $result) {
2910 2910
                     if ($result instanceof EE_Extra_Meta) {
2911
-                        $values[ $result->ID() ] = $result->value();
2911
+                        $values[$result->ID()] = $result->value();
2912 2912
                     }
2913 2913
                 }
2914 2914
                 return $values;
@@ -2953,17 +2953,17 @@  discard block
 block discarded – undo
2953 2953
             );
2954 2954
             foreach ($extra_meta_objs as $extra_meta_obj) {
2955 2955
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2956
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2956
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2957 2957
                 }
2958 2958
             }
2959 2959
         } else {
2960 2960
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2961 2961
             foreach ($extra_meta_objs as $extra_meta_obj) {
2962 2962
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2963
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2964
-                        $return_array[ $extra_meta_obj->key() ] = [];
2963
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2964
+                        $return_array[$extra_meta_obj->key()] = [];
2965 2965
                     }
2966
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2966
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2967 2967
                 }
2968 2968
             }
2969 2969
         }
@@ -3044,8 +3044,8 @@  discard block
 block discarded – undo
3044 3044
                             'event_espresso'
3045 3045
                         ),
3046 3046
                         $this->ID(),
3047
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3048
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3047
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3048
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3049 3049
                     )
3050 3050
                 );
3051 3051
             }
@@ -3078,7 +3078,7 @@  discard block
 block discarded – undo
3078 3078
     {
3079 3079
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3080 3080
         // if it wasn't even there to start off.
3081
-        if (! $this->ID()) {
3081
+        if ( ! $this->ID()) {
3082 3082
             $this->save();
3083 3083
         }
3084 3084
         global $wpdb;
@@ -3118,7 +3118,7 @@  discard block
 block discarded – undo
3118 3118
             $table_pk_field_name = $table_obj->get_pk_column();
3119 3119
         }
3120 3120
 
3121
-        $query  =
3121
+        $query =
3122 3122
             "UPDATE `{$table_name}`
3123 3123
             SET "
3124 3124
             . $new_value_sql
@@ -3312,7 +3312,7 @@  discard block
 block discarded – undo
3312 3312
         $model = $this->get_model();
3313 3313
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3314 3314
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3315
-                $classname = 'EE_' . $model->get_this_model_name();
3315
+                $classname = 'EE_'.$model->get_this_model_name();
3316 3316
                 if (
3317 3317
                     $this->get_one_from_cache($relation_name) instanceof $classname
3318 3318
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3353,7 +3353,7 @@  discard block
 block discarded – undo
3353 3353
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3354 3354
         foreach ($this->_fields as $field => $value) {
3355 3355
             if ($value instanceof DateTime) {
3356
-                $this->_fields[ $field ] = clone $value;
3356
+                $this->_fields[$field] = clone $value;
3357 3357
             }
3358 3358
         }
3359 3359
     }
@@ -3368,7 +3368,7 @@  discard block
 block discarded – undo
3368 3368
 
3369 3369
     private function echoProperty($field, $value, int $indent = 0)
3370 3370
     {
3371
-        $bullets = str_repeat(' -', $indent) . ' ';
3371
+        $bullets = str_repeat(' -', $indent).' ';
3372 3372
         $field = strpos($field, '_') === 0 ? substr($field, 1) : $field;
3373 3373
         echo "\n$bullets$field: ";
3374 3374
         if ($value instanceof EEM_Base) {
@@ -3377,8 +3377,8 @@  discard block
 block discarded – undo
3377 3377
             $value = get_object_vars($value);
3378 3378
         }
3379 3379
         if (is_array($value)) {
3380
-            foreach ($value as $f => $v ) {
3381
-                $this->echoProperty($f, $v, $indent+1);
3380
+            foreach ($value as $f => $v) {
3381
+                $this->echoProperty($f, $v, $indent + 1);
3382 3382
             }
3383 3383
             return;
3384 3384
         }
Please login to merge, or discard this patch.
core/db_classes/EE_Registration_Payment.class.php 1 patch
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -12,99 +12,99 @@
 block discarded – undo
12 12
  */
13 13
 class EE_Registration_Payment extends EE_Base_Class
14 14
 {
15
-    /**
16
-     * @param array  $props_n_values
17
-     * @param string $timezone
18
-     * @param array  $date_formats
19
-     * @return EE_Registration_Payment
20
-     * @throws EE_Error
21
-     * @throws ReflectionException
22
-     */
23
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
24
-    {
25
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
26
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
27
-    }
15
+	/**
16
+	 * @param array  $props_n_values
17
+	 * @param string $timezone
18
+	 * @param array  $date_formats
19
+	 * @return EE_Registration_Payment
20
+	 * @throws EE_Error
21
+	 * @throws ReflectionException
22
+	 */
23
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
24
+	{
25
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
26
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
27
+	}
28 28
 
29 29
 
30
-    /**
31
-     * @param array  $props_n_values
32
-     * @param string $timezone
33
-     * @return EE_Registration_Payment
34
-     * @throws EE_Error
35
-     * @throws ReflectionException
36
-     */
37
-    public static function new_instance_from_db($props_n_values = [], $timezone = '')
38
-    {
39
-        return new self($props_n_values, true, $timezone);
40
-    }
30
+	/**
31
+	 * @param array  $props_n_values
32
+	 * @param string $timezone
33
+	 * @return EE_Registration_Payment
34
+	 * @throws EE_Error
35
+	 * @throws ReflectionException
36
+	 */
37
+	public static function new_instance_from_db($props_n_values = [], $timezone = '')
38
+	{
39
+		return new self($props_n_values, true, $timezone);
40
+	}
41 41
 
42 42
 
43
-    /**
44
-     * @return    int
45
-     * @throws EE_Error
46
-     * @throws ReflectionException
47
-     */
48
-    public function registration_ID(): int
49
-    {
50
-        return (int) $this->get('REG_ID');
51
-    }
43
+	/**
44
+	 * @return    int
45
+	 * @throws EE_Error
46
+	 * @throws ReflectionException
47
+	 */
48
+	public function registration_ID(): int
49
+	{
50
+		return (int) $this->get('REG_ID');
51
+	}
52 52
 
53 53
 
54
-    /**
55
-     * @return    int
56
-     * @throws EE_Error
57
-     * @throws ReflectionException
58
-     */
59
-    public function payment_ID(): int
60
-    {
61
-        return (int) $this->get('PAY_ID');
62
-    }
54
+	/**
55
+	 * @return    int
56
+	 * @throws EE_Error
57
+	 * @throws ReflectionException
58
+	 */
59
+	public function payment_ID(): int
60
+	{
61
+		return (int) $this->get('PAY_ID');
62
+	}
63 63
 
64 64
 
65
-    /**
66
-     * amount
67
-     *
68
-     * @access    public
69
-     * @return    float
70
-     * @throws EE_Error
71
-     * @throws ReflectionException
72
-     */
73
-    public function amount(): float
74
-    {
75
-        return (float) $this->get('RPY_amount');
76
-    }
65
+	/**
66
+	 * amount
67
+	 *
68
+	 * @access    public
69
+	 * @return    float
70
+	 * @throws EE_Error
71
+	 * @throws ReflectionException
72
+	 */
73
+	public function amount(): float
74
+	{
75
+		return (float) $this->get('RPY_amount');
76
+	}
77 77
 
78 78
 
79
-    /**
80
-     * @param float|int|string $amount
81
-     * @throws EE_Error
82
-     * @throws ReflectionException
83
-     */
84
-    public function set_amount($amount = 0.000)
85
-    {
86
-        $this->set('RPY_amount', (float) $amount);
87
-    }
79
+	/**
80
+	 * @param float|int|string $amount
81
+	 * @throws EE_Error
82
+	 * @throws ReflectionException
83
+	 */
84
+	public function set_amount($amount = 0.000)
85
+	{
86
+		$this->set('RPY_amount', (float) $amount);
87
+	}
88 88
 
89 89
 
90
-    /**
91
-     * @return EE_Registration|null
92
-     * @throws EE_Error
93
-     * @throws ReflectionException
94
-     */
95
-    public function registration(): ?EE_Registration
96
-    {
97
-        return $this->get_first_related('Registration');
98
-    }
90
+	/**
91
+	 * @return EE_Registration|null
92
+	 * @throws EE_Error
93
+	 * @throws ReflectionException
94
+	 */
95
+	public function registration(): ?EE_Registration
96
+	{
97
+		return $this->get_first_related('Registration');
98
+	}
99 99
 
100 100
 
101
-    /**
102
-     * @return EE_Payment|null
103
-     * @throws EE_Error
104
-     * @throws ReflectionException
105
-     */
106
-    public function payment(): ?EE_Payment
107
-    {
108
-        return $this->get_first_related('Payment');
109
-    }
101
+	/**
102
+	 * @return EE_Payment|null
103
+	 * @throws EE_Error
104
+	 * @throws ReflectionException
105
+	 */
106
+	public function payment(): ?EE_Payment
107
+	{
108
+		return $this->get_first_related('Payment');
109
+	}
110 110
 }
Please login to merge, or discard this patch.