Completed
Branch yet-another-batch-of-ui-fixes (371f49)
by
unknown
30:27 queued 22:46
created
core/db_classes/EE_Line_Item.class.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
     {
97 97
         $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
98 98
         parent::__construct($fieldValues, $bydb, $timezone);
99
-        if (! $this->get('LIN_code')) {
99
+        if ( ! $this->get('LIN_code')) {
100 100
             $this->set_code($this->generate_code());
101 101
         }
102 102
     }
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
     public function name()
164 164
     {
165 165
         $name = $this->get('LIN_name');
166
-        if (! $name) {
166
+        if ( ! $name) {
167 167
             $name = ucwords(str_replace('-', ' ', $this->type()));
168 168
         }
169 169
         return $name;
@@ -655,7 +655,7 @@  discard block
 block discarded – undo
655 655
             $query_params += ['order_by' => ['LIN_order' => 'ASC']];
656 656
             return $this->get_model()->get_all($query_params);
657 657
         }
658
-        if (! is_array($this->_children)) {
658
+        if ( ! is_array($this->_children)) {
659 659
             $this->_children = array();
660 660
         }
661 661
         return $this->_children;
@@ -896,7 +896,7 @@  discard block
 block discarded – undo
896 896
             }
897 897
             return $line_item->save();
898 898
         }
899
-        $this->_children[ $line_item->code() ] = $line_item;
899
+        $this->_children[$line_item->code()] = $line_item;
900 900
         if ($line_item->parent() !== $this) {
901 901
             $line_item->set_parent($this);
902 902
         }
@@ -920,7 +920,7 @@  discard block
 block discarded – undo
920 920
     public function set_parent($line_item)
921 921
     {
922 922
         if ($this->ID()) {
923
-            if (! $line_item->ID()) {
923
+            if ( ! $line_item->ID()) {
924 924
                 $line_item->save();
925 925
             }
926 926
             $this->set_parent_ID($line_item->ID());
@@ -952,8 +952,8 @@  discard block
 block discarded – undo
952 952
                 array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
953 953
             );
954 954
         }
955
-        return isset($this->_children[ $code ])
956
-            ? $this->_children[ $code ]
955
+        return isset($this->_children[$code])
956
+            ? $this->_children[$code]
957 957
             : null;
958 958
     }
959 959
 
@@ -1013,8 +1013,8 @@  discard block
 block discarded – undo
1013 1013
             }
1014 1014
             return $items_deleted;
1015 1015
         }
1016
-        if (isset($this->_children[ $code ])) {
1017
-            unset($this->_children[ $code ]);
1016
+        if (isset($this->_children[$code])) {
1017
+            unset($this->_children[$code]);
1018 1018
             return 1;
1019 1019
         }
1020 1020
         return 0;
@@ -1055,7 +1055,7 @@  discard block
 block discarded – undo
1055 1055
     public function generate_code()
1056 1056
     {
1057 1057
         // each line item in the cart requires a unique identifier
1058
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1058
+        return md5($this->get('OBJ_type').$this->get('OBJ_ID').microtime());
1059 1059
     }
1060 1060
 
1061 1061
 
@@ -1099,7 +1099,7 @@  discard block
 block discarded – undo
1099 1099
      */
1100 1100
     public function getSubTaxes(): array
1101 1101
     {
1102
-        if (! $this->is_line_item()) {
1102
+        if ( ! $this->is_line_item()) {
1103 1103
             return [];
1104 1104
         }
1105 1105
         return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
@@ -1118,7 +1118,7 @@  discard block
 block discarded – undo
1118 1118
      */
1119 1119
     public function hasSubTaxes(): bool
1120 1120
     {
1121
-        if (! $this->is_line_item()) {
1121
+        if ( ! $this->is_line_item()) {
1122 1122
             return false;
1123 1123
         }
1124 1124
         $sub_taxes = $this->getSubTaxes();
@@ -1450,7 +1450,7 @@  discard block
 block discarded – undo
1450 1450
     public function save_this_and_descendants_to_txn($txn_id = null)
1451 1451
     {
1452 1452
         $count = 0;
1453
-        if (! $txn_id) {
1453
+        if ( ! $txn_id) {
1454 1454
             $txn_id = $this->TXN_ID();
1455 1455
         }
1456 1456
         $this->set_TXN_ID($txn_id);
Please login to merge, or discard this patch.
Indentation   +1647 added lines, -1647 removed lines patch added patch discarded remove patch
@@ -15,1651 +15,1651 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Line_Item extends EE_Base_Class implements EEI_Line_Item
17 17
 {
18
-    /**
19
-     * for children line items (currently not a normal relation)
20
-     *
21
-     * @type EE_Line_Item[]
22
-     */
23
-    protected $_children = array();
24
-
25
-    /**
26
-     * for the parent line item
27
-     *
28
-     * @var EE_Line_Item
29
-     */
30
-    protected $_parent;
31
-
32
-    /**
33
-     * @var LineItemCalculator
34
-     */
35
-    protected $calculator;
36
-
37
-
38
-    /**
39
-     * @param array  $props_n_values          incoming values
40
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
41
-     *                                        used.)
42
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
43
-     *                                        date_format and the second value is the time format
44
-     * @return EE_Line_Item
45
-     * @throws EE_Error
46
-     * @throws InvalidArgumentException
47
-     * @throws InvalidDataTypeException
48
-     * @throws InvalidInterfaceException
49
-     * @throws ReflectionException
50
-     */
51
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
-    {
53
-        $has_object = parent::_check_for_object(
54
-            $props_n_values,
55
-            __CLASS__,
56
-            $timezone,
57
-            $date_formats
58
-        );
59
-        return $has_object
60
-            ? $has_object
61
-            : new self($props_n_values, false, $timezone);
62
-    }
63
-
64
-
65
-    /**
66
-     * @param array  $props_n_values  incoming values from the database
67
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
68
-     *                                the website will be used.
69
-     * @return EE_Line_Item
70
-     * @throws EE_Error
71
-     * @throws InvalidArgumentException
72
-     * @throws InvalidDataTypeException
73
-     * @throws InvalidInterfaceException
74
-     * @throws ReflectionException
75
-     */
76
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
77
-    {
78
-        return new self($props_n_values, true, $timezone);
79
-    }
80
-
81
-
82
-    /**
83
-     * Adds some defaults if they're not specified
84
-     *
85
-     * @param array  $fieldValues
86
-     * @param bool   $bydb
87
-     * @param string $timezone
88
-     * @throws EE_Error
89
-     * @throws InvalidArgumentException
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     * @throws ReflectionException
93
-     */
94
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
95
-    {
96
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
97
-        parent::__construct($fieldValues, $bydb, $timezone);
98
-        if (! $this->get('LIN_code')) {
99
-            $this->set_code($this->generate_code());
100
-        }
101
-    }
102
-
103
-
104
-    public function __wakeup()
105
-    {
106
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
107
-        parent::__wakeup();
108
-    }
109
-
110
-
111
-    /**
112
-     * Gets ID
113
-     *
114
-     * @return int
115
-     * @throws EE_Error
116
-     * @throws InvalidArgumentException
117
-     * @throws InvalidDataTypeException
118
-     * @throws InvalidInterfaceException
119
-     * @throws ReflectionException
120
-     */
121
-    public function ID()
122
-    {
123
-        return $this->get('LIN_ID');
124
-    }
125
-
126
-
127
-    /**
128
-     * Gets TXN_ID
129
-     *
130
-     * @return int
131
-     * @throws EE_Error
132
-     * @throws InvalidArgumentException
133
-     * @throws InvalidDataTypeException
134
-     * @throws InvalidInterfaceException
135
-     * @throws ReflectionException
136
-     */
137
-    public function TXN_ID()
138
-    {
139
-        return $this->get('TXN_ID');
140
-    }
141
-
142
-
143
-    /**
144
-     * Sets TXN_ID
145
-     *
146
-     * @param int $TXN_ID
147
-     * @throws EE_Error
148
-     * @throws InvalidArgumentException
149
-     * @throws InvalidDataTypeException
150
-     * @throws InvalidInterfaceException
151
-     * @throws ReflectionException
152
-     */
153
-    public function set_TXN_ID($TXN_ID)
154
-    {
155
-        $this->set('TXN_ID', $TXN_ID);
156
-    }
157
-
158
-
159
-    /**
160
-     * Gets name
161
-     *
162
-     * @return string
163
-     * @throws EE_Error
164
-     * @throws InvalidArgumentException
165
-     * @throws InvalidDataTypeException
166
-     * @throws InvalidInterfaceException
167
-     * @throws ReflectionException
168
-     */
169
-    public function name()
170
-    {
171
-        $name = $this->get('LIN_name');
172
-        if (! $name) {
173
-            $name = ucwords(str_replace('-', ' ', $this->type()));
174
-        }
175
-        return $name;
176
-    }
177
-
178
-
179
-    /**
180
-     * Sets name
181
-     *
182
-     * @param string $name
183
-     * @throws EE_Error
184
-     * @throws InvalidArgumentException
185
-     * @throws InvalidDataTypeException
186
-     * @throws InvalidInterfaceException
187
-     * @throws ReflectionException
188
-     */
189
-    public function set_name($name)
190
-    {
191
-        $this->set('LIN_name', $name);
192
-    }
193
-
194
-
195
-    /**
196
-     * Gets desc
197
-     *
198
-     * @return string
199
-     * @throws EE_Error
200
-     * @throws InvalidArgumentException
201
-     * @throws InvalidDataTypeException
202
-     * @throws InvalidInterfaceException
203
-     * @throws ReflectionException
204
-     */
205
-    public function desc()
206
-    {
207
-        return $this->get('LIN_desc');
208
-    }
209
-
210
-
211
-    /**
212
-     * Sets desc
213
-     *
214
-     * @param string $desc
215
-     * @throws EE_Error
216
-     * @throws InvalidArgumentException
217
-     * @throws InvalidDataTypeException
218
-     * @throws InvalidInterfaceException
219
-     * @throws ReflectionException
220
-     */
221
-    public function set_desc($desc)
222
-    {
223
-        $this->set('LIN_desc', $desc);
224
-    }
225
-
226
-
227
-    /**
228
-     * Gets quantity
229
-     *
230
-     * @return int
231
-     * @throws EE_Error
232
-     * @throws InvalidArgumentException
233
-     * @throws InvalidDataTypeException
234
-     * @throws InvalidInterfaceException
235
-     * @throws ReflectionException
236
-     */
237
-    public function quantity(): int
238
-    {
239
-        return (int) $this->get('LIN_quantity');
240
-    }
241
-
242
-
243
-    /**
244
-     * Sets quantity
245
-     *
246
-     * @param int $quantity
247
-     * @throws EE_Error
248
-     * @throws InvalidArgumentException
249
-     * @throws InvalidDataTypeException
250
-     * @throws InvalidInterfaceException
251
-     * @throws ReflectionException
252
-     */
253
-    public function set_quantity($quantity)
254
-    {
255
-        $this->set('LIN_quantity', max($quantity, 0));
256
-    }
257
-
258
-
259
-    /**
260
-     * Gets item_id
261
-     *
262
-     * @return string
263
-     * @throws EE_Error
264
-     * @throws InvalidArgumentException
265
-     * @throws InvalidDataTypeException
266
-     * @throws InvalidInterfaceException
267
-     * @throws ReflectionException
268
-     */
269
-    public function OBJ_ID()
270
-    {
271
-        return $this->get('OBJ_ID');
272
-    }
273
-
274
-
275
-    /**
276
-     * Sets item_id
277
-     *
278
-     * @param string $item_id
279
-     * @throws EE_Error
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidDataTypeException
282
-     * @throws InvalidInterfaceException
283
-     * @throws ReflectionException
284
-     */
285
-    public function set_OBJ_ID($item_id)
286
-    {
287
-        $this->set('OBJ_ID', $item_id);
288
-    }
289
-
290
-
291
-    /**
292
-     * Gets item_type
293
-     *
294
-     * @return string
295
-     * @throws EE_Error
296
-     * @throws InvalidArgumentException
297
-     * @throws InvalidDataTypeException
298
-     * @throws InvalidInterfaceException
299
-     * @throws ReflectionException
300
-     */
301
-    public function OBJ_type()
302
-    {
303
-        return $this->get('OBJ_type');
304
-    }
305
-
306
-
307
-    /**
308
-     * Gets item_type
309
-     *
310
-     * @return string
311
-     * @throws EE_Error
312
-     * @throws InvalidArgumentException
313
-     * @throws InvalidDataTypeException
314
-     * @throws InvalidInterfaceException
315
-     * @throws ReflectionException
316
-     */
317
-    public function OBJ_type_i18n()
318
-    {
319
-        $obj_type = $this->OBJ_type();
320
-        switch ($obj_type) {
321
-            case EEM_Line_Item::OBJ_TYPE_EVENT:
322
-                $obj_type = esc_html__('Event', 'event_espresso');
323
-                break;
324
-            case EEM_Line_Item::OBJ_TYPE_PRICE:
325
-                $obj_type = esc_html__('Price', 'event_espresso');
326
-                break;
327
-            case EEM_Line_Item::OBJ_TYPE_PROMOTION:
328
-                $obj_type = esc_html__('Promotion', 'event_espresso');
329
-                break;
330
-            case EEM_Line_Item::OBJ_TYPE_TICKET:
331
-                $obj_type = esc_html__('Ticket', 'event_espresso');
332
-                break;
333
-            case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
334
-                $obj_type = esc_html__('Transaction', 'event_espresso');
335
-                break;
336
-        }
337
-        return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
338
-    }
339
-
340
-
341
-    /**
342
-     * Sets item_type
343
-     *
344
-     * @param string $OBJ_type
345
-     * @throws EE_Error
346
-     * @throws InvalidArgumentException
347
-     * @throws InvalidDataTypeException
348
-     * @throws InvalidInterfaceException
349
-     * @throws ReflectionException
350
-     */
351
-    public function set_OBJ_type($OBJ_type)
352
-    {
353
-        $this->set('OBJ_type', $OBJ_type);
354
-    }
355
-
356
-
357
-    /**
358
-     * Gets unit_price
359
-     *
360
-     * @return float
361
-     * @throws EE_Error
362
-     * @throws InvalidArgumentException
363
-     * @throws InvalidDataTypeException
364
-     * @throws InvalidInterfaceException
365
-     * @throws ReflectionException
366
-     */
367
-    public function unit_price()
368
-    {
369
-        return $this->get('LIN_unit_price');
370
-    }
371
-
372
-
373
-    /**
374
-     * Sets unit_price
375
-     *
376
-     * @param float $unit_price
377
-     * @throws EE_Error
378
-     * @throws InvalidArgumentException
379
-     * @throws InvalidDataTypeException
380
-     * @throws InvalidInterfaceException
381
-     * @throws ReflectionException
382
-     */
383
-    public function set_unit_price($unit_price)
384
-    {
385
-        $this->set('LIN_unit_price', $unit_price);
386
-    }
387
-
388
-
389
-    /**
390
-     * Checks if this item is a percentage modifier or not
391
-     *
392
-     * @return boolean
393
-     * @throws EE_Error
394
-     * @throws InvalidArgumentException
395
-     * @throws InvalidDataTypeException
396
-     * @throws InvalidInterfaceException
397
-     * @throws ReflectionException
398
-     */
399
-    public function is_percent()
400
-    {
401
-        if ($this->is_tax_sub_total()) {
402
-            // tax subtotals HAVE a percent on them, that percentage only applies
403
-            // to taxable items, so its' an exception. Treat it like a flat line item
404
-            return false;
405
-        }
406
-        $unit_price = abs($this->get('LIN_unit_price'));
407
-        $percent = abs($this->get('LIN_percent'));
408
-        if ($unit_price < .001 && $percent) {
409
-            return true;
410
-        }
411
-        if ($unit_price >= .001 && ! $percent) {
412
-            return false;
413
-        }
414
-        if ($unit_price >= .001 && $percent) {
415
-            throw new EE_Error(
416
-                sprintf(
417
-                    esc_html__(
418
-                        'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
419
-                        'event_espresso'
420
-                    ),
421
-                    $unit_price,
422
-                    $percent
423
-                )
424
-            );
425
-        }
426
-        // if they're both 0, assume its not a percent item
427
-        return false;
428
-    }
429
-
430
-
431
-    /**
432
-     * Gets percent (between 100-.001)
433
-     *
434
-     * @return float
435
-     * @throws EE_Error
436
-     * @throws InvalidArgumentException
437
-     * @throws InvalidDataTypeException
438
-     * @throws InvalidInterfaceException
439
-     * @throws ReflectionException
440
-     */
441
-    public function percent()
442
-    {
443
-        return $this->get('LIN_percent');
444
-    }
445
-
446
-
447
-    /**
448
-     * @return string
449
-     * @throws EE_Error
450
-     * @throws ReflectionException
451
-     * @since $VID:$
452
-     */
453
-    public function prettyPercent(): string
454
-    {
455
-        return $this->get_pretty('LIN_percent');
456
-    }
457
-
458
-
459
-    /**
460
-     * Sets percent (between 100-0.01)
461
-     *
462
-     * @param float $percent
463
-     * @throws EE_Error
464
-     * @throws InvalidArgumentException
465
-     * @throws InvalidDataTypeException
466
-     * @throws InvalidInterfaceException
467
-     * @throws ReflectionException
468
-     */
469
-    public function set_percent($percent)
470
-    {
471
-        $this->set('LIN_percent', $percent);
472
-    }
473
-
474
-
475
-    /**
476
-     * Gets total
477
-     *
478
-     * @return float
479
-     * @throws EE_Error
480
-     * @throws InvalidArgumentException
481
-     * @throws InvalidDataTypeException
482
-     * @throws InvalidInterfaceException
483
-     * @throws ReflectionException
484
-     */
485
-    public function pretaxTotal(): float
486
-    {
487
-        return (float) $this->get('LIN_pretax');
488
-    }
489
-
490
-
491
-    /**
492
-     * Sets total
493
-     *
494
-     * @param float $pretax_total
495
-     * @throws EE_Error
496
-     * @throws InvalidArgumentException
497
-     * @throws InvalidDataTypeException
498
-     * @throws InvalidInterfaceException
499
-     * @throws ReflectionException
500
-     */
501
-    public function setPretaxTotal(float $pretax_total)
502
-    {
503
-        $this->set('LIN_pretax', $pretax_total);
504
-    }
505
-
506
-
507
-    /**
508
-     * @return float
509
-     * @throws EE_Error
510
-     * @throws ReflectionException
511
-     * @since  $VID:$
512
-     */
513
-    public function totalWithTax(): float
514
-    {
515
-        return (float) $this->get('LIN_total');
516
-    }
517
-
518
-
519
-    /**
520
-     * Sets total
521
-     *
522
-     * @param float $total
523
-     * @throws EE_Error
524
-     * @throws ReflectionException
525
-     * @since  $VID:$
526
-     */
527
-    public function setTotalWithTax(float $total)
528
-    {
529
-        $this->set('LIN_total', $total);
530
-    }
531
-
532
-
533
-    /**
534
-     * Gets total
535
-     *
536
-     * @return float
537
-     * @throws EE_Error
538
-     * @throws ReflectionException
539
-     * @deprecatd $VID:$
540
-     */
541
-    public function total(): float
542
-    {
543
-        return $this->totalWithTax();
544
-    }
545
-
546
-
547
-    /**
548
-     * Sets total
549
-     *
550
-     * @param float $total
551
-     * @throws EE_Error
552
-     * @throws ReflectionException
553
-     * @deprecatd $VID:$
554
-     */
555
-    public function set_total($total)
556
-    {
557
-        $this->setTotalWithTax($total);
558
-    }
559
-
560
-
561
-    /**
562
-     * Gets order
563
-     *
564
-     * @return int
565
-     * @throws EE_Error
566
-     * @throws InvalidArgumentException
567
-     * @throws InvalidDataTypeException
568
-     * @throws InvalidInterfaceException
569
-     * @throws ReflectionException
570
-     */
571
-    public function order()
572
-    {
573
-        return $this->get('LIN_order');
574
-    }
575
-
576
-
577
-    /**
578
-     * Sets order
579
-     *
580
-     * @param int $order
581
-     * @throws EE_Error
582
-     * @throws InvalidArgumentException
583
-     * @throws InvalidDataTypeException
584
-     * @throws InvalidInterfaceException
585
-     * @throws ReflectionException
586
-     */
587
-    public function set_order($order)
588
-    {
589
-        $this->set('LIN_order', $order);
590
-    }
591
-
592
-
593
-    /**
594
-     * Gets parent
595
-     *
596
-     * @return int
597
-     * @throws EE_Error
598
-     * @throws InvalidArgumentException
599
-     * @throws InvalidDataTypeException
600
-     * @throws InvalidInterfaceException
601
-     * @throws ReflectionException
602
-     */
603
-    public function parent_ID()
604
-    {
605
-        return $this->get('LIN_parent');
606
-    }
607
-
608
-
609
-    /**
610
-     * Sets parent
611
-     *
612
-     * @param int $parent
613
-     * @throws EE_Error
614
-     * @throws InvalidArgumentException
615
-     * @throws InvalidDataTypeException
616
-     * @throws InvalidInterfaceException
617
-     * @throws ReflectionException
618
-     */
619
-    public function set_parent_ID($parent)
620
-    {
621
-        $this->set('LIN_parent', $parent);
622
-    }
623
-
624
-
625
-    /**
626
-     * Gets type
627
-     *
628
-     * @return string
629
-     * @throws EE_Error
630
-     * @throws InvalidArgumentException
631
-     * @throws InvalidDataTypeException
632
-     * @throws InvalidInterfaceException
633
-     * @throws ReflectionException
634
-     */
635
-    public function type()
636
-    {
637
-        return $this->get('LIN_type');
638
-    }
639
-
640
-
641
-    /**
642
-     * Sets type
643
-     *
644
-     * @param string $type
645
-     * @throws EE_Error
646
-     * @throws InvalidArgumentException
647
-     * @throws InvalidDataTypeException
648
-     * @throws InvalidInterfaceException
649
-     * @throws ReflectionException
650
-     */
651
-    public function set_type($type)
652
-    {
653
-        $this->set('LIN_type', $type);
654
-    }
655
-
656
-
657
-    /**
658
-     * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
659
-     * 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
660
-     * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
661
-     * or indirectly by `EE_Line_item::add_child_line_item()`)
662
-     *
663
-     * @return EE_Base_Class|EE_Line_Item
664
-     * @throws EE_Error
665
-     * @throws InvalidArgumentException
666
-     * @throws InvalidDataTypeException
667
-     * @throws InvalidInterfaceException
668
-     * @throws ReflectionException
669
-     */
670
-    public function parent()
671
-    {
672
-        return $this->ID()
673
-            ? $this->get_model()->get_one_by_ID($this->parent_ID())
674
-            : $this->_parent;
675
-    }
676
-
677
-
678
-    /**
679
-     * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
680
-     *
681
-     * @return EE_Line_Item[]
682
-     * @throws EE_Error
683
-     * @throws InvalidArgumentException
684
-     * @throws InvalidDataTypeException
685
-     * @throws InvalidInterfaceException
686
-     * @throws ReflectionException
687
-     */
688
-    public function children(array $query_params = []): array
689
-    {
690
-        if ($this->ID()) {
691
-            // ensure where params are an array
692
-            $query_params[0] = $query_params[0] ?? [];
693
-            // add defaults for line item parent and orderby
694
-            $query_params[0] += ['LIN_parent' => $this->ID()];
695
-            $query_params += ['order_by' => ['LIN_order' => 'ASC']];
696
-            return $this->get_model()->get_all($query_params);
697
-        }
698
-        if (! is_array($this->_children)) {
699
-            $this->_children = array();
700
-        }
701
-        return $this->_children;
702
-    }
703
-
704
-
705
-    /**
706
-     * Gets code
707
-     *
708
-     * @return string
709
-     * @throws EE_Error
710
-     * @throws InvalidArgumentException
711
-     * @throws InvalidDataTypeException
712
-     * @throws InvalidInterfaceException
713
-     * @throws ReflectionException
714
-     */
715
-    public function code()
716
-    {
717
-        return $this->get('LIN_code');
718
-    }
719
-
720
-
721
-    /**
722
-     * Sets code
723
-     *
724
-     * @param string $code
725
-     * @throws EE_Error
726
-     * @throws InvalidArgumentException
727
-     * @throws InvalidDataTypeException
728
-     * @throws InvalidInterfaceException
729
-     * @throws ReflectionException
730
-     */
731
-    public function set_code($code)
732
-    {
733
-        $this->set('LIN_code', $code);
734
-    }
735
-
736
-
737
-    /**
738
-     * Gets is_taxable
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_taxable()
748
-    {
749
-        return $this->get('LIN_is_taxable');
750
-    }
751
-
752
-
753
-    /**
754
-     * Sets is_taxable
755
-     *
756
-     * @param boolean $is_taxable
757
-     * @throws EE_Error
758
-     * @throws InvalidArgumentException
759
-     * @throws InvalidDataTypeException
760
-     * @throws InvalidInterfaceException
761
-     * @throws ReflectionException
762
-     */
763
-    public function set_is_taxable($is_taxable)
764
-    {
765
-        $this->set('LIN_is_taxable', $is_taxable);
766
-    }
767
-
768
-
769
-    /**
770
-     * Gets the object that this model-joins-to.
771
-     * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
772
-     * EEM_Promotion_Object
773
-     *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
774
-     *
775
-     * @return EE_Base_Class | NULL
776
-     * @throws EE_Error
777
-     * @throws InvalidArgumentException
778
-     * @throws InvalidDataTypeException
779
-     * @throws InvalidInterfaceException
780
-     * @throws ReflectionException
781
-     */
782
-    public function get_object()
783
-    {
784
-        $model_name_of_related_obj = $this->OBJ_type();
785
-        return $this->get_model()->has_relation($model_name_of_related_obj)
786
-            ? $this->get_first_related($model_name_of_related_obj)
787
-            : null;
788
-    }
789
-
790
-
791
-    /**
792
-     * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
793
-     * (IE, if this line item is for a price or something else, will return NULL)
794
-     *
795
-     * @param array $query_params
796
-     * @return EE_Base_Class|EE_Ticket
797
-     * @throws EE_Error
798
-     * @throws InvalidArgumentException
799
-     * @throws InvalidDataTypeException
800
-     * @throws InvalidInterfaceException
801
-     * @throws ReflectionException
802
-     */
803
-    public function ticket($query_params = array())
804
-    {
805
-        // we're going to assume that when this method is called
806
-        // we always want to receive the attached ticket EVEN if that ticket is archived.
807
-        // This can be overridden via the incoming $query_params argument
808
-        $remove_defaults = array('default_where_conditions' => 'none');
809
-        $query_params = array_merge($remove_defaults, $query_params);
810
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
811
-    }
812
-
813
-
814
-    /**
815
-     * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
816
-     *
817
-     * @return EE_Datetime | NULL
818
-     * @throws EE_Error
819
-     * @throws InvalidArgumentException
820
-     * @throws InvalidDataTypeException
821
-     * @throws InvalidInterfaceException
822
-     * @throws ReflectionException
823
-     */
824
-    public function get_ticket_datetime()
825
-    {
826
-        if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
827
-            $ticket = $this->ticket();
828
-            if ($ticket instanceof EE_Ticket) {
829
-                $datetime = $ticket->first_datetime();
830
-                if ($datetime instanceof EE_Datetime) {
831
-                    return $datetime;
832
-                }
833
-            }
834
-        }
835
-        return null;
836
-    }
837
-
838
-
839
-    /**
840
-     * Gets the event's name that's related to the ticket, if this is for
841
-     * a ticket
842
-     *
843
-     * @return string
844
-     * @throws EE_Error
845
-     * @throws InvalidArgumentException
846
-     * @throws InvalidDataTypeException
847
-     * @throws InvalidInterfaceException
848
-     * @throws ReflectionException
849
-     */
850
-    public function ticket_event_name()
851
-    {
852
-        $event_name = esc_html__('Unknown', 'event_espresso');
853
-        $event = $this->ticket_event();
854
-        if ($event instanceof EE_Event) {
855
-            $event_name = $event->name();
856
-        }
857
-        return $event_name;
858
-    }
859
-
860
-
861
-    /**
862
-     * Gets the event that's related to the ticket, if this line item represents a ticket.
863
-     *
864
-     * @return EE_Event|null
865
-     * @throws EE_Error
866
-     * @throws InvalidArgumentException
867
-     * @throws InvalidDataTypeException
868
-     * @throws InvalidInterfaceException
869
-     * @throws ReflectionException
870
-     */
871
-    public function ticket_event()
872
-    {
873
-        $event = null;
874
-        $ticket = $this->ticket();
875
-        if ($ticket instanceof EE_Ticket) {
876
-            $datetime = $ticket->first_datetime();
877
-            if ($datetime instanceof EE_Datetime) {
878
-                $event = $datetime->event();
879
-            }
880
-        }
881
-        return $event;
882
-    }
883
-
884
-
885
-    /**
886
-     * Gets the first datetime for this lien item, assuming it's for a ticket
887
-     *
888
-     * @param string $date_format
889
-     * @param string $time_format
890
-     * @return string
891
-     * @throws EE_Error
892
-     * @throws InvalidArgumentException
893
-     * @throws InvalidDataTypeException
894
-     * @throws InvalidInterfaceException
895
-     * @throws ReflectionException
896
-     */
897
-    public function ticket_datetime_start($date_format = '', $time_format = '')
898
-    {
899
-        $first_datetime_string = esc_html__('Unknown', 'event_espresso');
900
-        $datetime = $this->get_ticket_datetime();
901
-        if ($datetime) {
902
-            $first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
903
-        }
904
-        return $first_datetime_string;
905
-    }
906
-
907
-
908
-    /**
909
-     * Adds the line item as a child to this line item. If there is another child line
910
-     * item with the same LIN_code, it is overwritten by this new one
911
-     *
912
-     * @param EE_Line_Item $line_item
913
-     * @param bool          $set_order
914
-     * @return bool success
915
-     * @throws EE_Error
916
-     * @throws InvalidArgumentException
917
-     * @throws InvalidDataTypeException
918
-     * @throws InvalidInterfaceException
919
-     * @throws ReflectionException
920
-     */
921
-    public function add_child_line_item(EE_Line_Item $line_item, $set_order = true)
922
-    {
923
-        // should we calculate the LIN_order for this line item ?
924
-        if ($set_order || $line_item->order() === null) {
925
-            $line_item->set_order(count($this->children()));
926
-        }
927
-        if ($this->ID()) {
928
-            // check for any duplicate line items (with the same code), if so, this replaces it
929
-            $line_item_with_same_code = $this->get_child_line_item($line_item->code());
930
-            if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
931
-                $this->delete_child_line_item($line_item_with_same_code->code());
932
-            }
933
-            $line_item->set_parent_ID($this->ID());
934
-            if ($this->TXN_ID()) {
935
-                $line_item->set_TXN_ID($this->TXN_ID());
936
-            }
937
-            return $line_item->save();
938
-        }
939
-        $this->_children[ $line_item->code() ] = $line_item;
940
-        if ($line_item->parent() !== $this) {
941
-            $line_item->set_parent($this);
942
-        }
943
-        return true;
944
-    }
945
-
946
-
947
-    /**
948
-     * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
949
-     * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
950
-     * However, if this line item is NOT saved to the DB, this just caches the parent on
951
-     * the EE_Line_Item::_parent property.
952
-     *
953
-     * @param EE_Line_Item $line_item
954
-     * @throws EE_Error
955
-     * @throws InvalidArgumentException
956
-     * @throws InvalidDataTypeException
957
-     * @throws InvalidInterfaceException
958
-     * @throws ReflectionException
959
-     */
960
-    public function set_parent($line_item)
961
-    {
962
-        if ($this->ID()) {
963
-            if (! $line_item->ID()) {
964
-                $line_item->save();
965
-            }
966
-            $this->set_parent_ID($line_item->ID());
967
-            $this->save();
968
-        } else {
969
-            $this->_parent = $line_item;
970
-            $this->set_parent_ID($line_item->ID());
971
-        }
972
-    }
973
-
974
-
975
-    /**
976
-     * Gets the child line item as specified by its code. Because this returns an object (by reference)
977
-     * you can modify this child line item and the parent (this object) can know about them
978
-     * because it also has a reference to that line item
979
-     *
980
-     * @param string $code
981
-     * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
982
-     * @throws EE_Error
983
-     * @throws InvalidArgumentException
984
-     * @throws InvalidDataTypeException
985
-     * @throws InvalidInterfaceException
986
-     * @throws ReflectionException
987
-     */
988
-    public function get_child_line_item($code)
989
-    {
990
-        if ($this->ID()) {
991
-            return $this->get_model()->get_one(
992
-                array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
993
-            );
994
-        }
995
-        return isset($this->_children[ $code ])
996
-            ? $this->_children[ $code ]
997
-            : null;
998
-    }
999
-
1000
-
1001
-    /**
1002
-     * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1003
-     * cached on it)
1004
-     *
1005
-     * @return int
1006
-     * @throws EE_Error
1007
-     * @throws InvalidArgumentException
1008
-     * @throws InvalidDataTypeException
1009
-     * @throws InvalidInterfaceException
1010
-     * @throws ReflectionException
1011
-     */
1012
-    public function delete_children_line_items()
1013
-    {
1014
-        if ($this->ID()) {
1015
-            return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
1016
-        }
1017
-        $count = count($this->_children);
1018
-        $this->_children = array();
1019
-        return $count;
1020
-    }
1021
-
1022
-
1023
-    /**
1024
-     * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1025
-     * HAS NOT been saved to the DB, removes the child line item with index $code.
1026
-     * Also searches through the child's children for a matching line item. However, once a line item has been found
1027
-     * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1028
-     * deleted)
1029
-     *
1030
-     * @param string $code
1031
-     * @param bool   $stop_search_once_found
1032
-     * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1033
-     *             the DB yet)
1034
-     * @throws EE_Error
1035
-     * @throws InvalidArgumentException
1036
-     * @throws InvalidDataTypeException
1037
-     * @throws InvalidInterfaceException
1038
-     * @throws ReflectionException
1039
-     */
1040
-    public function delete_child_line_item($code, $stop_search_once_found = true)
1041
-    {
1042
-        if ($this->ID()) {
1043
-            $items_deleted = 0;
1044
-            if ($this->code() === $code) {
1045
-                $items_deleted += EEH_Line_Item::delete_all_child_items($this);
1046
-                $items_deleted += (int) $this->delete();
1047
-                if ($stop_search_once_found) {
1048
-                    return $items_deleted;
1049
-                }
1050
-            }
1051
-            foreach ($this->children() as $child_line_item) {
1052
-                $items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1053
-            }
1054
-            return $items_deleted;
1055
-        }
1056
-        if (isset($this->_children[ $code ])) {
1057
-            unset($this->_children[ $code ]);
1058
-            return 1;
1059
-        }
1060
-        return 0;
1061
-    }
1062
-
1063
-
1064
-    /**
1065
-     * If this line item is in the database, is of the type subtotal, and
1066
-     * has no children, why do we have it? It should be deleted so this function
1067
-     * does that
1068
-     *
1069
-     * @return boolean
1070
-     * @throws EE_Error
1071
-     * @throws InvalidArgumentException
1072
-     * @throws InvalidDataTypeException
1073
-     * @throws InvalidInterfaceException
1074
-     * @throws ReflectionException
1075
-     */
1076
-    public function delete_if_childless_subtotal()
1077
-    {
1078
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1079
-            return $this->delete();
1080
-        }
1081
-        return false;
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     * Creates a code and returns a string. doesn't assign the code to this model object
1087
-     *
1088
-     * @return string
1089
-     * @throws EE_Error
1090
-     * @throws InvalidArgumentException
1091
-     * @throws InvalidDataTypeException
1092
-     * @throws InvalidInterfaceException
1093
-     * @throws ReflectionException
1094
-     */
1095
-    public function generate_code()
1096
-    {
1097
-        // each line item in the cart requires a unique identifier
1098
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1099
-    }
1100
-
1101
-
1102
-    /**
1103
-     * @return bool
1104
-     * @throws EE_Error
1105
-     * @throws InvalidArgumentException
1106
-     * @throws InvalidDataTypeException
1107
-     * @throws InvalidInterfaceException
1108
-     * @throws ReflectionException
1109
-     */
1110
-    public function isGlobalTax(): bool
1111
-    {
1112
-        return $this->type() === EEM_Line_Item::type_tax;
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     * @return bool
1118
-     * @throws EE_Error
1119
-     * @throws InvalidArgumentException
1120
-     * @throws InvalidDataTypeException
1121
-     * @throws InvalidInterfaceException
1122
-     * @throws ReflectionException
1123
-     */
1124
-    public function isSubTax(): bool
1125
-    {
1126
-        return $this->type() === EEM_Line_Item::type_sub_tax;
1127
-    }
1128
-
1129
-
1130
-    /**
1131
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1132
-     *
1133
-     * @return array
1134
-     * @throws EE_Error
1135
-     * @throws InvalidArgumentException
1136
-     * @throws InvalidDataTypeException
1137
-     * @throws InvalidInterfaceException
1138
-     * @throws ReflectionException
1139
-     */
1140
-    public function getSubTaxes(): array
1141
-    {
1142
-        if (! $this->is_line_item()) {
1143
-            return [];
1144
-        }
1145
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1146
-    }
1147
-
1148
-
1149
-    /**
1150
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1151
-     *
1152
-     * @return bool
1153
-     * @throws EE_Error
1154
-     * @throws InvalidArgumentException
1155
-     * @throws InvalidDataTypeException
1156
-     * @throws InvalidInterfaceException
1157
-     * @throws ReflectionException
1158
-     */
1159
-    public function hasSubTaxes(): bool
1160
-    {
1161
-        if (! $this->is_line_item()) {
1162
-            return false;
1163
-        }
1164
-        $sub_taxes = $this->getSubTaxes();
1165
-        return ! empty($sub_taxes);
1166
-    }
1167
-
1168
-
1169
-    /**
1170
-     * @return bool
1171
-     * @throws EE_Error
1172
-     * @throws ReflectionException
1173
-     * @deprecated   $VID:$
1174
-     */
1175
-    public function is_tax(): bool
1176
-    {
1177
-        return $this->isGlobalTax();
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * @return bool
1183
-     * @throws EE_Error
1184
-     * @throws InvalidArgumentException
1185
-     * @throws InvalidDataTypeException
1186
-     * @throws InvalidInterfaceException
1187
-     * @throws ReflectionException
1188
-     */
1189
-    public function is_tax_sub_total()
1190
-    {
1191
-        return $this->type() === EEM_Line_Item::type_tax_sub_total;
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * @return bool
1197
-     * @throws EE_Error
1198
-     * @throws InvalidArgumentException
1199
-     * @throws InvalidDataTypeException
1200
-     * @throws InvalidInterfaceException
1201
-     * @throws ReflectionException
1202
-     */
1203
-    public function is_line_item()
1204
-    {
1205
-        return $this->type() === EEM_Line_Item::type_line_item;
1206
-    }
1207
-
1208
-
1209
-    /**
1210
-     * @return bool
1211
-     * @throws EE_Error
1212
-     * @throws InvalidArgumentException
1213
-     * @throws InvalidDataTypeException
1214
-     * @throws InvalidInterfaceException
1215
-     * @throws ReflectionException
1216
-     */
1217
-    public function is_sub_line_item()
1218
-    {
1219
-        return $this->type() === EEM_Line_Item::type_sub_line_item;
1220
-    }
1221
-
1222
-
1223
-    /**
1224
-     * @return bool
1225
-     * @throws EE_Error
1226
-     * @throws InvalidArgumentException
1227
-     * @throws InvalidDataTypeException
1228
-     * @throws InvalidInterfaceException
1229
-     * @throws ReflectionException
1230
-     */
1231
-    public function is_sub_total()
1232
-    {
1233
-        return $this->type() === EEM_Line_Item::type_sub_total;
1234
-    }
1235
-
1236
-
1237
-    /**
1238
-     * Whether or not this line item is a cancellation line item
1239
-     *
1240
-     * @return boolean
1241
-     * @throws EE_Error
1242
-     * @throws InvalidArgumentException
1243
-     * @throws InvalidDataTypeException
1244
-     * @throws InvalidInterfaceException
1245
-     * @throws ReflectionException
1246
-     */
1247
-    public function is_cancellation()
1248
-    {
1249
-        return EEM_Line_Item::type_cancellation === $this->type();
1250
-    }
1251
-
1252
-
1253
-    /**
1254
-     * @return bool
1255
-     * @throws EE_Error
1256
-     * @throws InvalidArgumentException
1257
-     * @throws InvalidDataTypeException
1258
-     * @throws InvalidInterfaceException
1259
-     * @throws ReflectionException
1260
-     */
1261
-    public function is_total()
1262
-    {
1263
-        return $this->type() === EEM_Line_Item::type_total;
1264
-    }
1265
-
1266
-
1267
-    /**
1268
-     * @return bool
1269
-     * @throws EE_Error
1270
-     * @throws InvalidArgumentException
1271
-     * @throws InvalidDataTypeException
1272
-     * @throws InvalidInterfaceException
1273
-     * @throws ReflectionException
1274
-     */
1275
-    public function is_cancelled()
1276
-    {
1277
-        return $this->type() === EEM_Line_Item::type_cancellation;
1278
-    }
1279
-
1280
-
1281
-    /**
1282
-     * @return string like '2, 004.00', formatted according to the localized currency
1283
-     * @throws EE_Error
1284
-     * @throws ReflectionException
1285
-     */
1286
-    public function unit_price_no_code(): string
1287
-    {
1288
-        return $this->prettyUnitPrice();
1289
-    }
1290
-
1291
-
1292
-    /**
1293
-     * @return string like '2, 004.00', formatted according to the localized currency
1294
-     * @throws EE_Error
1295
-     * @throws ReflectionException
1296
-     * @since $VID:$
1297
-     */
1298
-    public function prettyUnitPrice(): string
1299
-    {
1300
-        return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1301
-    }
1302
-
1303
-
1304
-    /**
1305
-     * @return string like '2, 004.00', formatted according to the localized currency
1306
-     * @throws EE_Error
1307
-     * @throws ReflectionException
1308
-     */
1309
-    public function total_no_code(): string
1310
-    {
1311
-        return $this->prettyTotal();
1312
-    }
1313
-
1314
-
1315
-    /**
1316
-     * @return string like '2, 004.00', formatted according to the localized currency
1317
-     * @throws EE_Error
1318
-     * @throws ReflectionException
1319
-     * @since $VID:$
1320
-     */
1321
-    public function prettyTotal(): string
1322
-    {
1323
-        return $this->get_pretty('LIN_total', 'no_currency_code');
1324
-    }
1325
-
1326
-
1327
-    /**
1328
-     * Gets the final total on this item, taking taxes into account.
1329
-     * Has the side-effect of setting the sub-total as it was just calculated.
1330
-     * If this is used on a grand-total line item, also updates the transaction's
1331
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
1332
-     * want to change a persistable transaction with info from a non-persistent line item)
1333
-     *
1334
-     * @param bool $update_txn_status
1335
-     * @return float
1336
-     * @throws EE_Error
1337
-     * @throws InvalidArgumentException
1338
-     * @throws InvalidDataTypeException
1339
-     * @throws InvalidInterfaceException
1340
-     * @throws ReflectionException
1341
-     * @throws RuntimeException
1342
-     */
1343
-    public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1344
-    {
1345
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1346
-        return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1347
-    }
1348
-
1349
-
1350
-    /**
1351
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1352
-     * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1353
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1354
-     * when this is called on the grand total
1355
-     *
1356
-     * @return float
1357
-     * @throws EE_Error
1358
-     * @throws InvalidArgumentException
1359
-     * @throws InvalidDataTypeException
1360
-     * @throws InvalidInterfaceException
1361
-     * @throws ReflectionException
1362
-     */
1363
-    public function recalculate_pre_tax_total(): float
1364
-    {
1365
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1366
-        [$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1367
-        return (float) $total;
1368
-    }
1369
-
1370
-
1371
-    /**
1372
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1373
-     * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1374
-     * and tax sub-total if already in the DB
1375
-     *
1376
-     * @return float
1377
-     * @throws EE_Error
1378
-     * @throws InvalidArgumentException
1379
-     * @throws InvalidDataTypeException
1380
-     * @throws InvalidInterfaceException
1381
-     * @throws ReflectionException
1382
-     */
1383
-    public function recalculate_taxes_and_tax_total(): float
1384
-    {
1385
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1386
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1387
-    }
1388
-
1389
-
1390
-    /**
1391
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
1392
-     * recalculate_taxes_and_total
1393
-     *
1394
-     * @return float
1395
-     * @throws EE_Error
1396
-     * @throws InvalidArgumentException
1397
-     * @throws InvalidDataTypeException
1398
-     * @throws InvalidInterfaceException
1399
-     * @throws ReflectionException
1400
-     */
1401
-    public function get_total_tax()
1402
-    {
1403
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1404
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1405
-    }
1406
-
1407
-
1408
-    /**
1409
-     * Gets the total for all the items purchased only
1410
-     *
1411
-     * @return float
1412
-     * @throws EE_Error
1413
-     * @throws InvalidArgumentException
1414
-     * @throws InvalidDataTypeException
1415
-     * @throws InvalidInterfaceException
1416
-     * @throws ReflectionException
1417
-     */
1418
-    public function get_items_total()
1419
-    {
1420
-        // by default, let's make sure we're consistent with the existing line item
1421
-        if ($this->is_total()) {
1422
-            return $this->pretaxTotal();
1423
-        }
1424
-        $total = 0;
1425
-        foreach ($this->get_items() as $item) {
1426
-            if ($item instanceof EE_Line_Item) {
1427
-                $total += $item->pretaxTotal();
1428
-            }
1429
-        }
1430
-        return $total;
1431
-    }
1432
-
1433
-
1434
-    /**
1435
-     * Gets all the descendants (ie, children or children of children etc) that
1436
-     * are of the type 'tax'
1437
-     *
1438
-     * @return EE_Line_Item[]
1439
-     * @throws EE_Error
1440
-     */
1441
-    public function tax_descendants()
1442
-    {
1443
-        return EEH_Line_Item::get_tax_descendants($this);
1444
-    }
1445
-
1446
-
1447
-    /**
1448
-     * Gets all the real items purchased which are children of this item
1449
-     *
1450
-     * @return EE_Line_Item[]
1451
-     * @throws EE_Error
1452
-     */
1453
-    public function get_items()
1454
-    {
1455
-        return EEH_Line_Item::get_line_item_descendants($this);
1456
-    }
1457
-
1458
-
1459
-    /**
1460
-     * Returns the amount taxable among this line item's children (or if it has no children,
1461
-     * how much of it is taxable). Does not recalculate totals or subtotals.
1462
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
1463
-     * but there is a "Taxable" discount), returns 0.
1464
-     *
1465
-     * @return float
1466
-     * @throws EE_Error
1467
-     * @throws InvalidArgumentException
1468
-     * @throws InvalidDataTypeException
1469
-     * @throws InvalidInterfaceException
1470
-     * @throws ReflectionException
1471
-     */
1472
-    public function taxable_total(): float
1473
-    {
1474
-        return $this->calculator->taxableAmountForGlobalTaxes($this);
1475
-    }
1476
-
1477
-
1478
-    /**
1479
-     * Gets the transaction for this line item
1480
-     *
1481
-     * @return EE_Base_Class|EE_Transaction
1482
-     * @throws EE_Error
1483
-     * @throws InvalidArgumentException
1484
-     * @throws InvalidDataTypeException
1485
-     * @throws InvalidInterfaceException
1486
-     * @throws ReflectionException
1487
-     */
1488
-    public function transaction()
1489
-    {
1490
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1491
-    }
1492
-
1493
-
1494
-    /**
1495
-     * Saves this line item to the DB, and recursively saves its descendants.
1496
-     * Because there currently is no proper parent-child relation on the model,
1497
-     * save_this_and_cached() will NOT save the descendants.
1498
-     * Also sets the transaction on this line item and all its descendants before saving
1499
-     *
1500
-     * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1501
-     * @return int count of items saved
1502
-     * @throws EE_Error
1503
-     * @throws InvalidArgumentException
1504
-     * @throws InvalidDataTypeException
1505
-     * @throws InvalidInterfaceException
1506
-     * @throws ReflectionException
1507
-     */
1508
-    public function save_this_and_descendants_to_txn($txn_id = null)
1509
-    {
1510
-        $count = 0;
1511
-        if (! $txn_id) {
1512
-            $txn_id = $this->TXN_ID();
1513
-        }
1514
-        $this->set_TXN_ID($txn_id);
1515
-        $children = $this->children();
1516
-        $count += $this->save()
1517
-            ? 1
1518
-            : 0;
1519
-        foreach ($children as $child_line_item) {
1520
-            if ($child_line_item instanceof EE_Line_Item) {
1521
-                $child_line_item->set_parent_ID($this->ID());
1522
-                $count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1523
-            }
1524
-        }
1525
-        return $count;
1526
-    }
1527
-
1528
-
1529
-    /**
1530
-     * Saves this line item to the DB, and recursively saves its descendants.
1531
-     *
1532
-     * @return int count of items saved
1533
-     * @throws EE_Error
1534
-     * @throws InvalidArgumentException
1535
-     * @throws InvalidDataTypeException
1536
-     * @throws InvalidInterfaceException
1537
-     * @throws ReflectionException
1538
-     */
1539
-    public function save_this_and_descendants()
1540
-    {
1541
-        $count = 0;
1542
-        $children = $this->children();
1543
-        $count += $this->save()
1544
-            ? 1
1545
-            : 0;
1546
-        foreach ($children as $child_line_item) {
1547
-            if ($child_line_item instanceof EE_Line_Item) {
1548
-                $child_line_item->set_parent_ID($this->ID());
1549
-                $count += $child_line_item->save_this_and_descendants();
1550
-            }
1551
-        }
1552
-        return $count;
1553
-    }
1554
-
1555
-
1556
-    /**
1557
-     * returns the cancellation line item if this item was cancelled
1558
-     *
1559
-     * @return EE_Line_Item[]
1560
-     * @throws InvalidArgumentException
1561
-     * @throws InvalidInterfaceException
1562
-     * @throws InvalidDataTypeException
1563
-     * @throws ReflectionException
1564
-     * @throws EE_Error
1565
-     */
1566
-    public function get_cancellations()
1567
-    {
1568
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1569
-    }
1570
-
1571
-
1572
-    /**
1573
-     * If this item has an ID, then this saves it again to update the db
1574
-     *
1575
-     * @return int count of items saved
1576
-     * @throws EE_Error
1577
-     * @throws InvalidArgumentException
1578
-     * @throws InvalidDataTypeException
1579
-     * @throws InvalidInterfaceException
1580
-     * @throws ReflectionException
1581
-     */
1582
-    public function maybe_save()
1583
-    {
1584
-        if ($this->ID()) {
1585
-            return $this->save();
1586
-        }
1587
-        return false;
1588
-    }
1589
-
1590
-
1591
-    /**
1592
-     * clears the cached children and parent from the line item
1593
-     *
1594
-     * @return void
1595
-     */
1596
-    public function clear_related_line_item_cache()
1597
-    {
1598
-        $this->_children = array();
1599
-        $this->_parent = null;
1600
-    }
1601
-
1602
-
1603
-    /**
1604
-     * @param bool $raw
1605
-     * @return int
1606
-     * @throws EE_Error
1607
-     * @throws InvalidArgumentException
1608
-     * @throws InvalidDataTypeException
1609
-     * @throws InvalidInterfaceException
1610
-     * @throws ReflectionException
1611
-     */
1612
-    public function timestamp($raw = false)
1613
-    {
1614
-        return $raw
1615
-            ? $this->get_raw('LIN_timestamp')
1616
-            : $this->get('LIN_timestamp');
1617
-    }
1618
-
1619
-
1620
-
1621
-
1622
-    /************************* DEPRECATED *************************/
1623
-    /**
1624
-     * @deprecated 4.6.0
1625
-     * @param string $type one of the constants on EEM_Line_Item
1626
-     * @return EE_Line_Item[]
1627
-     * @throws EE_Error
1628
-     */
1629
-    protected function _get_descendants_of_type($type)
1630
-    {
1631
-        EE_Error::doing_it_wrong(
1632
-            'EE_Line_Item::_get_descendants_of_type()',
1633
-            sprintf(
1634
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1635
-                'EEH_Line_Item::get_descendants_of_type()'
1636
-            ),
1637
-            '4.6.0'
1638
-        );
1639
-        return EEH_Line_Item::get_descendants_of_type($this, $type);
1640
-    }
1641
-
1642
-
1643
-    /**
1644
-     * @deprecated 4.6.0
1645
-     * @param string $type like one of the EEM_Line_Item::type_*
1646
-     * @return EE_Line_Item
1647
-     * @throws EE_Error
1648
-     * @throws InvalidArgumentException
1649
-     * @throws InvalidDataTypeException
1650
-     * @throws InvalidInterfaceException
1651
-     * @throws ReflectionException
1652
-     */
1653
-    public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1654
-    {
1655
-        EE_Error::doing_it_wrong(
1656
-            'EE_Line_Item::get_nearest_descendant_of_type()',
1657
-            sprintf(
1658
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1659
-                'EEH_Line_Item::get_nearest_descendant_of_type()'
1660
-            ),
1661
-            '4.6.0'
1662
-        );
1663
-        return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1664
-    }
18
+	/**
19
+	 * for children line items (currently not a normal relation)
20
+	 *
21
+	 * @type EE_Line_Item[]
22
+	 */
23
+	protected $_children = array();
24
+
25
+	/**
26
+	 * for the parent line item
27
+	 *
28
+	 * @var EE_Line_Item
29
+	 */
30
+	protected $_parent;
31
+
32
+	/**
33
+	 * @var LineItemCalculator
34
+	 */
35
+	protected $calculator;
36
+
37
+
38
+	/**
39
+	 * @param array  $props_n_values          incoming values
40
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
41
+	 *                                        used.)
42
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
43
+	 *                                        date_format and the second value is the time format
44
+	 * @return EE_Line_Item
45
+	 * @throws EE_Error
46
+	 * @throws InvalidArgumentException
47
+	 * @throws InvalidDataTypeException
48
+	 * @throws InvalidInterfaceException
49
+	 * @throws ReflectionException
50
+	 */
51
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
+	{
53
+		$has_object = parent::_check_for_object(
54
+			$props_n_values,
55
+			__CLASS__,
56
+			$timezone,
57
+			$date_formats
58
+		);
59
+		return $has_object
60
+			? $has_object
61
+			: new self($props_n_values, false, $timezone);
62
+	}
63
+
64
+
65
+	/**
66
+	 * @param array  $props_n_values  incoming values from the database
67
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
68
+	 *                                the website will be used.
69
+	 * @return EE_Line_Item
70
+	 * @throws EE_Error
71
+	 * @throws InvalidArgumentException
72
+	 * @throws InvalidDataTypeException
73
+	 * @throws InvalidInterfaceException
74
+	 * @throws ReflectionException
75
+	 */
76
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
77
+	{
78
+		return new self($props_n_values, true, $timezone);
79
+	}
80
+
81
+
82
+	/**
83
+	 * Adds some defaults if they're not specified
84
+	 *
85
+	 * @param array  $fieldValues
86
+	 * @param bool   $bydb
87
+	 * @param string $timezone
88
+	 * @throws EE_Error
89
+	 * @throws InvalidArgumentException
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 * @throws ReflectionException
93
+	 */
94
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
95
+	{
96
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
97
+		parent::__construct($fieldValues, $bydb, $timezone);
98
+		if (! $this->get('LIN_code')) {
99
+			$this->set_code($this->generate_code());
100
+		}
101
+	}
102
+
103
+
104
+	public function __wakeup()
105
+	{
106
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
107
+		parent::__wakeup();
108
+	}
109
+
110
+
111
+	/**
112
+	 * Gets ID
113
+	 *
114
+	 * @return int
115
+	 * @throws EE_Error
116
+	 * @throws InvalidArgumentException
117
+	 * @throws InvalidDataTypeException
118
+	 * @throws InvalidInterfaceException
119
+	 * @throws ReflectionException
120
+	 */
121
+	public function ID()
122
+	{
123
+		return $this->get('LIN_ID');
124
+	}
125
+
126
+
127
+	/**
128
+	 * Gets TXN_ID
129
+	 *
130
+	 * @return int
131
+	 * @throws EE_Error
132
+	 * @throws InvalidArgumentException
133
+	 * @throws InvalidDataTypeException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws ReflectionException
136
+	 */
137
+	public function TXN_ID()
138
+	{
139
+		return $this->get('TXN_ID');
140
+	}
141
+
142
+
143
+	/**
144
+	 * Sets TXN_ID
145
+	 *
146
+	 * @param int $TXN_ID
147
+	 * @throws EE_Error
148
+	 * @throws InvalidArgumentException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws InvalidInterfaceException
151
+	 * @throws ReflectionException
152
+	 */
153
+	public function set_TXN_ID($TXN_ID)
154
+	{
155
+		$this->set('TXN_ID', $TXN_ID);
156
+	}
157
+
158
+
159
+	/**
160
+	 * Gets name
161
+	 *
162
+	 * @return string
163
+	 * @throws EE_Error
164
+	 * @throws InvalidArgumentException
165
+	 * @throws InvalidDataTypeException
166
+	 * @throws InvalidInterfaceException
167
+	 * @throws ReflectionException
168
+	 */
169
+	public function name()
170
+	{
171
+		$name = $this->get('LIN_name');
172
+		if (! $name) {
173
+			$name = ucwords(str_replace('-', ' ', $this->type()));
174
+		}
175
+		return $name;
176
+	}
177
+
178
+
179
+	/**
180
+	 * Sets name
181
+	 *
182
+	 * @param string $name
183
+	 * @throws EE_Error
184
+	 * @throws InvalidArgumentException
185
+	 * @throws InvalidDataTypeException
186
+	 * @throws InvalidInterfaceException
187
+	 * @throws ReflectionException
188
+	 */
189
+	public function set_name($name)
190
+	{
191
+		$this->set('LIN_name', $name);
192
+	}
193
+
194
+
195
+	/**
196
+	 * Gets desc
197
+	 *
198
+	 * @return string
199
+	 * @throws EE_Error
200
+	 * @throws InvalidArgumentException
201
+	 * @throws InvalidDataTypeException
202
+	 * @throws InvalidInterfaceException
203
+	 * @throws ReflectionException
204
+	 */
205
+	public function desc()
206
+	{
207
+		return $this->get('LIN_desc');
208
+	}
209
+
210
+
211
+	/**
212
+	 * Sets desc
213
+	 *
214
+	 * @param string $desc
215
+	 * @throws EE_Error
216
+	 * @throws InvalidArgumentException
217
+	 * @throws InvalidDataTypeException
218
+	 * @throws InvalidInterfaceException
219
+	 * @throws ReflectionException
220
+	 */
221
+	public function set_desc($desc)
222
+	{
223
+		$this->set('LIN_desc', $desc);
224
+	}
225
+
226
+
227
+	/**
228
+	 * Gets quantity
229
+	 *
230
+	 * @return int
231
+	 * @throws EE_Error
232
+	 * @throws InvalidArgumentException
233
+	 * @throws InvalidDataTypeException
234
+	 * @throws InvalidInterfaceException
235
+	 * @throws ReflectionException
236
+	 */
237
+	public function quantity(): int
238
+	{
239
+		return (int) $this->get('LIN_quantity');
240
+	}
241
+
242
+
243
+	/**
244
+	 * Sets quantity
245
+	 *
246
+	 * @param int $quantity
247
+	 * @throws EE_Error
248
+	 * @throws InvalidArgumentException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws InvalidInterfaceException
251
+	 * @throws ReflectionException
252
+	 */
253
+	public function set_quantity($quantity)
254
+	{
255
+		$this->set('LIN_quantity', max($quantity, 0));
256
+	}
257
+
258
+
259
+	/**
260
+	 * Gets item_id
261
+	 *
262
+	 * @return string
263
+	 * @throws EE_Error
264
+	 * @throws InvalidArgumentException
265
+	 * @throws InvalidDataTypeException
266
+	 * @throws InvalidInterfaceException
267
+	 * @throws ReflectionException
268
+	 */
269
+	public function OBJ_ID()
270
+	{
271
+		return $this->get('OBJ_ID');
272
+	}
273
+
274
+
275
+	/**
276
+	 * Sets item_id
277
+	 *
278
+	 * @param string $item_id
279
+	 * @throws EE_Error
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidDataTypeException
282
+	 * @throws InvalidInterfaceException
283
+	 * @throws ReflectionException
284
+	 */
285
+	public function set_OBJ_ID($item_id)
286
+	{
287
+		$this->set('OBJ_ID', $item_id);
288
+	}
289
+
290
+
291
+	/**
292
+	 * Gets item_type
293
+	 *
294
+	 * @return string
295
+	 * @throws EE_Error
296
+	 * @throws InvalidArgumentException
297
+	 * @throws InvalidDataTypeException
298
+	 * @throws InvalidInterfaceException
299
+	 * @throws ReflectionException
300
+	 */
301
+	public function OBJ_type()
302
+	{
303
+		return $this->get('OBJ_type');
304
+	}
305
+
306
+
307
+	/**
308
+	 * Gets item_type
309
+	 *
310
+	 * @return string
311
+	 * @throws EE_Error
312
+	 * @throws InvalidArgumentException
313
+	 * @throws InvalidDataTypeException
314
+	 * @throws InvalidInterfaceException
315
+	 * @throws ReflectionException
316
+	 */
317
+	public function OBJ_type_i18n()
318
+	{
319
+		$obj_type = $this->OBJ_type();
320
+		switch ($obj_type) {
321
+			case EEM_Line_Item::OBJ_TYPE_EVENT:
322
+				$obj_type = esc_html__('Event', 'event_espresso');
323
+				break;
324
+			case EEM_Line_Item::OBJ_TYPE_PRICE:
325
+				$obj_type = esc_html__('Price', 'event_espresso');
326
+				break;
327
+			case EEM_Line_Item::OBJ_TYPE_PROMOTION:
328
+				$obj_type = esc_html__('Promotion', 'event_espresso');
329
+				break;
330
+			case EEM_Line_Item::OBJ_TYPE_TICKET:
331
+				$obj_type = esc_html__('Ticket', 'event_espresso');
332
+				break;
333
+			case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
334
+				$obj_type = esc_html__('Transaction', 'event_espresso');
335
+				break;
336
+		}
337
+		return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
338
+	}
339
+
340
+
341
+	/**
342
+	 * Sets item_type
343
+	 *
344
+	 * @param string $OBJ_type
345
+	 * @throws EE_Error
346
+	 * @throws InvalidArgumentException
347
+	 * @throws InvalidDataTypeException
348
+	 * @throws InvalidInterfaceException
349
+	 * @throws ReflectionException
350
+	 */
351
+	public function set_OBJ_type($OBJ_type)
352
+	{
353
+		$this->set('OBJ_type', $OBJ_type);
354
+	}
355
+
356
+
357
+	/**
358
+	 * Gets unit_price
359
+	 *
360
+	 * @return float
361
+	 * @throws EE_Error
362
+	 * @throws InvalidArgumentException
363
+	 * @throws InvalidDataTypeException
364
+	 * @throws InvalidInterfaceException
365
+	 * @throws ReflectionException
366
+	 */
367
+	public function unit_price()
368
+	{
369
+		return $this->get('LIN_unit_price');
370
+	}
371
+
372
+
373
+	/**
374
+	 * Sets unit_price
375
+	 *
376
+	 * @param float $unit_price
377
+	 * @throws EE_Error
378
+	 * @throws InvalidArgumentException
379
+	 * @throws InvalidDataTypeException
380
+	 * @throws InvalidInterfaceException
381
+	 * @throws ReflectionException
382
+	 */
383
+	public function set_unit_price($unit_price)
384
+	{
385
+		$this->set('LIN_unit_price', $unit_price);
386
+	}
387
+
388
+
389
+	/**
390
+	 * Checks if this item is a percentage modifier or not
391
+	 *
392
+	 * @return boolean
393
+	 * @throws EE_Error
394
+	 * @throws InvalidArgumentException
395
+	 * @throws InvalidDataTypeException
396
+	 * @throws InvalidInterfaceException
397
+	 * @throws ReflectionException
398
+	 */
399
+	public function is_percent()
400
+	{
401
+		if ($this->is_tax_sub_total()) {
402
+			// tax subtotals HAVE a percent on them, that percentage only applies
403
+			// to taxable items, so its' an exception. Treat it like a flat line item
404
+			return false;
405
+		}
406
+		$unit_price = abs($this->get('LIN_unit_price'));
407
+		$percent = abs($this->get('LIN_percent'));
408
+		if ($unit_price < .001 && $percent) {
409
+			return true;
410
+		}
411
+		if ($unit_price >= .001 && ! $percent) {
412
+			return false;
413
+		}
414
+		if ($unit_price >= .001 && $percent) {
415
+			throw new EE_Error(
416
+				sprintf(
417
+					esc_html__(
418
+						'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
419
+						'event_espresso'
420
+					),
421
+					$unit_price,
422
+					$percent
423
+				)
424
+			);
425
+		}
426
+		// if they're both 0, assume its not a percent item
427
+		return false;
428
+	}
429
+
430
+
431
+	/**
432
+	 * Gets percent (between 100-.001)
433
+	 *
434
+	 * @return float
435
+	 * @throws EE_Error
436
+	 * @throws InvalidArgumentException
437
+	 * @throws InvalidDataTypeException
438
+	 * @throws InvalidInterfaceException
439
+	 * @throws ReflectionException
440
+	 */
441
+	public function percent()
442
+	{
443
+		return $this->get('LIN_percent');
444
+	}
445
+
446
+
447
+	/**
448
+	 * @return string
449
+	 * @throws EE_Error
450
+	 * @throws ReflectionException
451
+	 * @since $VID:$
452
+	 */
453
+	public function prettyPercent(): string
454
+	{
455
+		return $this->get_pretty('LIN_percent');
456
+	}
457
+
458
+
459
+	/**
460
+	 * Sets percent (between 100-0.01)
461
+	 *
462
+	 * @param float $percent
463
+	 * @throws EE_Error
464
+	 * @throws InvalidArgumentException
465
+	 * @throws InvalidDataTypeException
466
+	 * @throws InvalidInterfaceException
467
+	 * @throws ReflectionException
468
+	 */
469
+	public function set_percent($percent)
470
+	{
471
+		$this->set('LIN_percent', $percent);
472
+	}
473
+
474
+
475
+	/**
476
+	 * Gets total
477
+	 *
478
+	 * @return float
479
+	 * @throws EE_Error
480
+	 * @throws InvalidArgumentException
481
+	 * @throws InvalidDataTypeException
482
+	 * @throws InvalidInterfaceException
483
+	 * @throws ReflectionException
484
+	 */
485
+	public function pretaxTotal(): float
486
+	{
487
+		return (float) $this->get('LIN_pretax');
488
+	}
489
+
490
+
491
+	/**
492
+	 * Sets total
493
+	 *
494
+	 * @param float $pretax_total
495
+	 * @throws EE_Error
496
+	 * @throws InvalidArgumentException
497
+	 * @throws InvalidDataTypeException
498
+	 * @throws InvalidInterfaceException
499
+	 * @throws ReflectionException
500
+	 */
501
+	public function setPretaxTotal(float $pretax_total)
502
+	{
503
+		$this->set('LIN_pretax', $pretax_total);
504
+	}
505
+
506
+
507
+	/**
508
+	 * @return float
509
+	 * @throws EE_Error
510
+	 * @throws ReflectionException
511
+	 * @since  $VID:$
512
+	 */
513
+	public function totalWithTax(): float
514
+	{
515
+		return (float) $this->get('LIN_total');
516
+	}
517
+
518
+
519
+	/**
520
+	 * Sets total
521
+	 *
522
+	 * @param float $total
523
+	 * @throws EE_Error
524
+	 * @throws ReflectionException
525
+	 * @since  $VID:$
526
+	 */
527
+	public function setTotalWithTax(float $total)
528
+	{
529
+		$this->set('LIN_total', $total);
530
+	}
531
+
532
+
533
+	/**
534
+	 * Gets total
535
+	 *
536
+	 * @return float
537
+	 * @throws EE_Error
538
+	 * @throws ReflectionException
539
+	 * @deprecatd $VID:$
540
+	 */
541
+	public function total(): float
542
+	{
543
+		return $this->totalWithTax();
544
+	}
545
+
546
+
547
+	/**
548
+	 * Sets total
549
+	 *
550
+	 * @param float $total
551
+	 * @throws EE_Error
552
+	 * @throws ReflectionException
553
+	 * @deprecatd $VID:$
554
+	 */
555
+	public function set_total($total)
556
+	{
557
+		$this->setTotalWithTax($total);
558
+	}
559
+
560
+
561
+	/**
562
+	 * Gets order
563
+	 *
564
+	 * @return int
565
+	 * @throws EE_Error
566
+	 * @throws InvalidArgumentException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws InvalidInterfaceException
569
+	 * @throws ReflectionException
570
+	 */
571
+	public function order()
572
+	{
573
+		return $this->get('LIN_order');
574
+	}
575
+
576
+
577
+	/**
578
+	 * Sets order
579
+	 *
580
+	 * @param int $order
581
+	 * @throws EE_Error
582
+	 * @throws InvalidArgumentException
583
+	 * @throws InvalidDataTypeException
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws ReflectionException
586
+	 */
587
+	public function set_order($order)
588
+	{
589
+		$this->set('LIN_order', $order);
590
+	}
591
+
592
+
593
+	/**
594
+	 * Gets parent
595
+	 *
596
+	 * @return int
597
+	 * @throws EE_Error
598
+	 * @throws InvalidArgumentException
599
+	 * @throws InvalidDataTypeException
600
+	 * @throws InvalidInterfaceException
601
+	 * @throws ReflectionException
602
+	 */
603
+	public function parent_ID()
604
+	{
605
+		return $this->get('LIN_parent');
606
+	}
607
+
608
+
609
+	/**
610
+	 * Sets parent
611
+	 *
612
+	 * @param int $parent
613
+	 * @throws EE_Error
614
+	 * @throws InvalidArgumentException
615
+	 * @throws InvalidDataTypeException
616
+	 * @throws InvalidInterfaceException
617
+	 * @throws ReflectionException
618
+	 */
619
+	public function set_parent_ID($parent)
620
+	{
621
+		$this->set('LIN_parent', $parent);
622
+	}
623
+
624
+
625
+	/**
626
+	 * Gets type
627
+	 *
628
+	 * @return string
629
+	 * @throws EE_Error
630
+	 * @throws InvalidArgumentException
631
+	 * @throws InvalidDataTypeException
632
+	 * @throws InvalidInterfaceException
633
+	 * @throws ReflectionException
634
+	 */
635
+	public function type()
636
+	{
637
+		return $this->get('LIN_type');
638
+	}
639
+
640
+
641
+	/**
642
+	 * Sets type
643
+	 *
644
+	 * @param string $type
645
+	 * @throws EE_Error
646
+	 * @throws InvalidArgumentException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws InvalidInterfaceException
649
+	 * @throws ReflectionException
650
+	 */
651
+	public function set_type($type)
652
+	{
653
+		$this->set('LIN_type', $type);
654
+	}
655
+
656
+
657
+	/**
658
+	 * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
659
+	 * 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
660
+	 * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
661
+	 * or indirectly by `EE_Line_item::add_child_line_item()`)
662
+	 *
663
+	 * @return EE_Base_Class|EE_Line_Item
664
+	 * @throws EE_Error
665
+	 * @throws InvalidArgumentException
666
+	 * @throws InvalidDataTypeException
667
+	 * @throws InvalidInterfaceException
668
+	 * @throws ReflectionException
669
+	 */
670
+	public function parent()
671
+	{
672
+		return $this->ID()
673
+			? $this->get_model()->get_one_by_ID($this->parent_ID())
674
+			: $this->_parent;
675
+	}
676
+
677
+
678
+	/**
679
+	 * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
680
+	 *
681
+	 * @return EE_Line_Item[]
682
+	 * @throws EE_Error
683
+	 * @throws InvalidArgumentException
684
+	 * @throws InvalidDataTypeException
685
+	 * @throws InvalidInterfaceException
686
+	 * @throws ReflectionException
687
+	 */
688
+	public function children(array $query_params = []): array
689
+	{
690
+		if ($this->ID()) {
691
+			// ensure where params are an array
692
+			$query_params[0] = $query_params[0] ?? [];
693
+			// add defaults for line item parent and orderby
694
+			$query_params[0] += ['LIN_parent' => $this->ID()];
695
+			$query_params += ['order_by' => ['LIN_order' => 'ASC']];
696
+			return $this->get_model()->get_all($query_params);
697
+		}
698
+		if (! is_array($this->_children)) {
699
+			$this->_children = array();
700
+		}
701
+		return $this->_children;
702
+	}
703
+
704
+
705
+	/**
706
+	 * Gets code
707
+	 *
708
+	 * @return string
709
+	 * @throws EE_Error
710
+	 * @throws InvalidArgumentException
711
+	 * @throws InvalidDataTypeException
712
+	 * @throws InvalidInterfaceException
713
+	 * @throws ReflectionException
714
+	 */
715
+	public function code()
716
+	{
717
+		return $this->get('LIN_code');
718
+	}
719
+
720
+
721
+	/**
722
+	 * Sets code
723
+	 *
724
+	 * @param string $code
725
+	 * @throws EE_Error
726
+	 * @throws InvalidArgumentException
727
+	 * @throws InvalidDataTypeException
728
+	 * @throws InvalidInterfaceException
729
+	 * @throws ReflectionException
730
+	 */
731
+	public function set_code($code)
732
+	{
733
+		$this->set('LIN_code', $code);
734
+	}
735
+
736
+
737
+	/**
738
+	 * Gets is_taxable
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_taxable()
748
+	{
749
+		return $this->get('LIN_is_taxable');
750
+	}
751
+
752
+
753
+	/**
754
+	 * Sets is_taxable
755
+	 *
756
+	 * @param boolean $is_taxable
757
+	 * @throws EE_Error
758
+	 * @throws InvalidArgumentException
759
+	 * @throws InvalidDataTypeException
760
+	 * @throws InvalidInterfaceException
761
+	 * @throws ReflectionException
762
+	 */
763
+	public function set_is_taxable($is_taxable)
764
+	{
765
+		$this->set('LIN_is_taxable', $is_taxable);
766
+	}
767
+
768
+
769
+	/**
770
+	 * Gets the object that this model-joins-to.
771
+	 * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
772
+	 * EEM_Promotion_Object
773
+	 *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
774
+	 *
775
+	 * @return EE_Base_Class | NULL
776
+	 * @throws EE_Error
777
+	 * @throws InvalidArgumentException
778
+	 * @throws InvalidDataTypeException
779
+	 * @throws InvalidInterfaceException
780
+	 * @throws ReflectionException
781
+	 */
782
+	public function get_object()
783
+	{
784
+		$model_name_of_related_obj = $this->OBJ_type();
785
+		return $this->get_model()->has_relation($model_name_of_related_obj)
786
+			? $this->get_first_related($model_name_of_related_obj)
787
+			: null;
788
+	}
789
+
790
+
791
+	/**
792
+	 * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
793
+	 * (IE, if this line item is for a price or something else, will return NULL)
794
+	 *
795
+	 * @param array $query_params
796
+	 * @return EE_Base_Class|EE_Ticket
797
+	 * @throws EE_Error
798
+	 * @throws InvalidArgumentException
799
+	 * @throws InvalidDataTypeException
800
+	 * @throws InvalidInterfaceException
801
+	 * @throws ReflectionException
802
+	 */
803
+	public function ticket($query_params = array())
804
+	{
805
+		// we're going to assume that when this method is called
806
+		// we always want to receive the attached ticket EVEN if that ticket is archived.
807
+		// This can be overridden via the incoming $query_params argument
808
+		$remove_defaults = array('default_where_conditions' => 'none');
809
+		$query_params = array_merge($remove_defaults, $query_params);
810
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
811
+	}
812
+
813
+
814
+	/**
815
+	 * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
816
+	 *
817
+	 * @return EE_Datetime | NULL
818
+	 * @throws EE_Error
819
+	 * @throws InvalidArgumentException
820
+	 * @throws InvalidDataTypeException
821
+	 * @throws InvalidInterfaceException
822
+	 * @throws ReflectionException
823
+	 */
824
+	public function get_ticket_datetime()
825
+	{
826
+		if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
827
+			$ticket = $this->ticket();
828
+			if ($ticket instanceof EE_Ticket) {
829
+				$datetime = $ticket->first_datetime();
830
+				if ($datetime instanceof EE_Datetime) {
831
+					return $datetime;
832
+				}
833
+			}
834
+		}
835
+		return null;
836
+	}
837
+
838
+
839
+	/**
840
+	 * Gets the event's name that's related to the ticket, if this is for
841
+	 * a ticket
842
+	 *
843
+	 * @return string
844
+	 * @throws EE_Error
845
+	 * @throws InvalidArgumentException
846
+	 * @throws InvalidDataTypeException
847
+	 * @throws InvalidInterfaceException
848
+	 * @throws ReflectionException
849
+	 */
850
+	public function ticket_event_name()
851
+	{
852
+		$event_name = esc_html__('Unknown', 'event_espresso');
853
+		$event = $this->ticket_event();
854
+		if ($event instanceof EE_Event) {
855
+			$event_name = $event->name();
856
+		}
857
+		return $event_name;
858
+	}
859
+
860
+
861
+	/**
862
+	 * Gets the event that's related to the ticket, if this line item represents a ticket.
863
+	 *
864
+	 * @return EE_Event|null
865
+	 * @throws EE_Error
866
+	 * @throws InvalidArgumentException
867
+	 * @throws InvalidDataTypeException
868
+	 * @throws InvalidInterfaceException
869
+	 * @throws ReflectionException
870
+	 */
871
+	public function ticket_event()
872
+	{
873
+		$event = null;
874
+		$ticket = $this->ticket();
875
+		if ($ticket instanceof EE_Ticket) {
876
+			$datetime = $ticket->first_datetime();
877
+			if ($datetime instanceof EE_Datetime) {
878
+				$event = $datetime->event();
879
+			}
880
+		}
881
+		return $event;
882
+	}
883
+
884
+
885
+	/**
886
+	 * Gets the first datetime for this lien item, assuming it's for a ticket
887
+	 *
888
+	 * @param string $date_format
889
+	 * @param string $time_format
890
+	 * @return string
891
+	 * @throws EE_Error
892
+	 * @throws InvalidArgumentException
893
+	 * @throws InvalidDataTypeException
894
+	 * @throws InvalidInterfaceException
895
+	 * @throws ReflectionException
896
+	 */
897
+	public function ticket_datetime_start($date_format = '', $time_format = '')
898
+	{
899
+		$first_datetime_string = esc_html__('Unknown', 'event_espresso');
900
+		$datetime = $this->get_ticket_datetime();
901
+		if ($datetime) {
902
+			$first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
903
+		}
904
+		return $first_datetime_string;
905
+	}
906
+
907
+
908
+	/**
909
+	 * Adds the line item as a child to this line item. If there is another child line
910
+	 * item with the same LIN_code, it is overwritten by this new one
911
+	 *
912
+	 * @param EE_Line_Item $line_item
913
+	 * @param bool          $set_order
914
+	 * @return bool success
915
+	 * @throws EE_Error
916
+	 * @throws InvalidArgumentException
917
+	 * @throws InvalidDataTypeException
918
+	 * @throws InvalidInterfaceException
919
+	 * @throws ReflectionException
920
+	 */
921
+	public function add_child_line_item(EE_Line_Item $line_item, $set_order = true)
922
+	{
923
+		// should we calculate the LIN_order for this line item ?
924
+		if ($set_order || $line_item->order() === null) {
925
+			$line_item->set_order(count($this->children()));
926
+		}
927
+		if ($this->ID()) {
928
+			// check for any duplicate line items (with the same code), if so, this replaces it
929
+			$line_item_with_same_code = $this->get_child_line_item($line_item->code());
930
+			if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
931
+				$this->delete_child_line_item($line_item_with_same_code->code());
932
+			}
933
+			$line_item->set_parent_ID($this->ID());
934
+			if ($this->TXN_ID()) {
935
+				$line_item->set_TXN_ID($this->TXN_ID());
936
+			}
937
+			return $line_item->save();
938
+		}
939
+		$this->_children[ $line_item->code() ] = $line_item;
940
+		if ($line_item->parent() !== $this) {
941
+			$line_item->set_parent($this);
942
+		}
943
+		return true;
944
+	}
945
+
946
+
947
+	/**
948
+	 * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
949
+	 * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
950
+	 * However, if this line item is NOT saved to the DB, this just caches the parent on
951
+	 * the EE_Line_Item::_parent property.
952
+	 *
953
+	 * @param EE_Line_Item $line_item
954
+	 * @throws EE_Error
955
+	 * @throws InvalidArgumentException
956
+	 * @throws InvalidDataTypeException
957
+	 * @throws InvalidInterfaceException
958
+	 * @throws ReflectionException
959
+	 */
960
+	public function set_parent($line_item)
961
+	{
962
+		if ($this->ID()) {
963
+			if (! $line_item->ID()) {
964
+				$line_item->save();
965
+			}
966
+			$this->set_parent_ID($line_item->ID());
967
+			$this->save();
968
+		} else {
969
+			$this->_parent = $line_item;
970
+			$this->set_parent_ID($line_item->ID());
971
+		}
972
+	}
973
+
974
+
975
+	/**
976
+	 * Gets the child line item as specified by its code. Because this returns an object (by reference)
977
+	 * you can modify this child line item and the parent (this object) can know about them
978
+	 * because it also has a reference to that line item
979
+	 *
980
+	 * @param string $code
981
+	 * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
982
+	 * @throws EE_Error
983
+	 * @throws InvalidArgumentException
984
+	 * @throws InvalidDataTypeException
985
+	 * @throws InvalidInterfaceException
986
+	 * @throws ReflectionException
987
+	 */
988
+	public function get_child_line_item($code)
989
+	{
990
+		if ($this->ID()) {
991
+			return $this->get_model()->get_one(
992
+				array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
993
+			);
994
+		}
995
+		return isset($this->_children[ $code ])
996
+			? $this->_children[ $code ]
997
+			: null;
998
+	}
999
+
1000
+
1001
+	/**
1002
+	 * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1003
+	 * cached on it)
1004
+	 *
1005
+	 * @return int
1006
+	 * @throws EE_Error
1007
+	 * @throws InvalidArgumentException
1008
+	 * @throws InvalidDataTypeException
1009
+	 * @throws InvalidInterfaceException
1010
+	 * @throws ReflectionException
1011
+	 */
1012
+	public function delete_children_line_items()
1013
+	{
1014
+		if ($this->ID()) {
1015
+			return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
1016
+		}
1017
+		$count = count($this->_children);
1018
+		$this->_children = array();
1019
+		return $count;
1020
+	}
1021
+
1022
+
1023
+	/**
1024
+	 * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1025
+	 * HAS NOT been saved to the DB, removes the child line item with index $code.
1026
+	 * Also searches through the child's children for a matching line item. However, once a line item has been found
1027
+	 * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1028
+	 * deleted)
1029
+	 *
1030
+	 * @param string $code
1031
+	 * @param bool   $stop_search_once_found
1032
+	 * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1033
+	 *             the DB yet)
1034
+	 * @throws EE_Error
1035
+	 * @throws InvalidArgumentException
1036
+	 * @throws InvalidDataTypeException
1037
+	 * @throws InvalidInterfaceException
1038
+	 * @throws ReflectionException
1039
+	 */
1040
+	public function delete_child_line_item($code, $stop_search_once_found = true)
1041
+	{
1042
+		if ($this->ID()) {
1043
+			$items_deleted = 0;
1044
+			if ($this->code() === $code) {
1045
+				$items_deleted += EEH_Line_Item::delete_all_child_items($this);
1046
+				$items_deleted += (int) $this->delete();
1047
+				if ($stop_search_once_found) {
1048
+					return $items_deleted;
1049
+				}
1050
+			}
1051
+			foreach ($this->children() as $child_line_item) {
1052
+				$items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1053
+			}
1054
+			return $items_deleted;
1055
+		}
1056
+		if (isset($this->_children[ $code ])) {
1057
+			unset($this->_children[ $code ]);
1058
+			return 1;
1059
+		}
1060
+		return 0;
1061
+	}
1062
+
1063
+
1064
+	/**
1065
+	 * If this line item is in the database, is of the type subtotal, and
1066
+	 * has no children, why do we have it? It should be deleted so this function
1067
+	 * does that
1068
+	 *
1069
+	 * @return boolean
1070
+	 * @throws EE_Error
1071
+	 * @throws InvalidArgumentException
1072
+	 * @throws InvalidDataTypeException
1073
+	 * @throws InvalidInterfaceException
1074
+	 * @throws ReflectionException
1075
+	 */
1076
+	public function delete_if_childless_subtotal()
1077
+	{
1078
+		if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1079
+			return $this->delete();
1080
+		}
1081
+		return false;
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 * Creates a code and returns a string. doesn't assign the code to this model object
1087
+	 *
1088
+	 * @return string
1089
+	 * @throws EE_Error
1090
+	 * @throws InvalidArgumentException
1091
+	 * @throws InvalidDataTypeException
1092
+	 * @throws InvalidInterfaceException
1093
+	 * @throws ReflectionException
1094
+	 */
1095
+	public function generate_code()
1096
+	{
1097
+		// each line item in the cart requires a unique identifier
1098
+		return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1099
+	}
1100
+
1101
+
1102
+	/**
1103
+	 * @return bool
1104
+	 * @throws EE_Error
1105
+	 * @throws InvalidArgumentException
1106
+	 * @throws InvalidDataTypeException
1107
+	 * @throws InvalidInterfaceException
1108
+	 * @throws ReflectionException
1109
+	 */
1110
+	public function isGlobalTax(): bool
1111
+	{
1112
+		return $this->type() === EEM_Line_Item::type_tax;
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 * @return bool
1118
+	 * @throws EE_Error
1119
+	 * @throws InvalidArgumentException
1120
+	 * @throws InvalidDataTypeException
1121
+	 * @throws InvalidInterfaceException
1122
+	 * @throws ReflectionException
1123
+	 */
1124
+	public function isSubTax(): bool
1125
+	{
1126
+		return $this->type() === EEM_Line_Item::type_sub_tax;
1127
+	}
1128
+
1129
+
1130
+	/**
1131
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1132
+	 *
1133
+	 * @return array
1134
+	 * @throws EE_Error
1135
+	 * @throws InvalidArgumentException
1136
+	 * @throws InvalidDataTypeException
1137
+	 * @throws InvalidInterfaceException
1138
+	 * @throws ReflectionException
1139
+	 */
1140
+	public function getSubTaxes(): array
1141
+	{
1142
+		if (! $this->is_line_item()) {
1143
+			return [];
1144
+		}
1145
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1146
+	}
1147
+
1148
+
1149
+	/**
1150
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1151
+	 *
1152
+	 * @return bool
1153
+	 * @throws EE_Error
1154
+	 * @throws InvalidArgumentException
1155
+	 * @throws InvalidDataTypeException
1156
+	 * @throws InvalidInterfaceException
1157
+	 * @throws ReflectionException
1158
+	 */
1159
+	public function hasSubTaxes(): bool
1160
+	{
1161
+		if (! $this->is_line_item()) {
1162
+			return false;
1163
+		}
1164
+		$sub_taxes = $this->getSubTaxes();
1165
+		return ! empty($sub_taxes);
1166
+	}
1167
+
1168
+
1169
+	/**
1170
+	 * @return bool
1171
+	 * @throws EE_Error
1172
+	 * @throws ReflectionException
1173
+	 * @deprecated   $VID:$
1174
+	 */
1175
+	public function is_tax(): bool
1176
+	{
1177
+		return $this->isGlobalTax();
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * @return bool
1183
+	 * @throws EE_Error
1184
+	 * @throws InvalidArgumentException
1185
+	 * @throws InvalidDataTypeException
1186
+	 * @throws InvalidInterfaceException
1187
+	 * @throws ReflectionException
1188
+	 */
1189
+	public function is_tax_sub_total()
1190
+	{
1191
+		return $this->type() === EEM_Line_Item::type_tax_sub_total;
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * @return bool
1197
+	 * @throws EE_Error
1198
+	 * @throws InvalidArgumentException
1199
+	 * @throws InvalidDataTypeException
1200
+	 * @throws InvalidInterfaceException
1201
+	 * @throws ReflectionException
1202
+	 */
1203
+	public function is_line_item()
1204
+	{
1205
+		return $this->type() === EEM_Line_Item::type_line_item;
1206
+	}
1207
+
1208
+
1209
+	/**
1210
+	 * @return bool
1211
+	 * @throws EE_Error
1212
+	 * @throws InvalidArgumentException
1213
+	 * @throws InvalidDataTypeException
1214
+	 * @throws InvalidInterfaceException
1215
+	 * @throws ReflectionException
1216
+	 */
1217
+	public function is_sub_line_item()
1218
+	{
1219
+		return $this->type() === EEM_Line_Item::type_sub_line_item;
1220
+	}
1221
+
1222
+
1223
+	/**
1224
+	 * @return bool
1225
+	 * @throws EE_Error
1226
+	 * @throws InvalidArgumentException
1227
+	 * @throws InvalidDataTypeException
1228
+	 * @throws InvalidInterfaceException
1229
+	 * @throws ReflectionException
1230
+	 */
1231
+	public function is_sub_total()
1232
+	{
1233
+		return $this->type() === EEM_Line_Item::type_sub_total;
1234
+	}
1235
+
1236
+
1237
+	/**
1238
+	 * Whether or not this line item is a cancellation line item
1239
+	 *
1240
+	 * @return boolean
1241
+	 * @throws EE_Error
1242
+	 * @throws InvalidArgumentException
1243
+	 * @throws InvalidDataTypeException
1244
+	 * @throws InvalidInterfaceException
1245
+	 * @throws ReflectionException
1246
+	 */
1247
+	public function is_cancellation()
1248
+	{
1249
+		return EEM_Line_Item::type_cancellation === $this->type();
1250
+	}
1251
+
1252
+
1253
+	/**
1254
+	 * @return bool
1255
+	 * @throws EE_Error
1256
+	 * @throws InvalidArgumentException
1257
+	 * @throws InvalidDataTypeException
1258
+	 * @throws InvalidInterfaceException
1259
+	 * @throws ReflectionException
1260
+	 */
1261
+	public function is_total()
1262
+	{
1263
+		return $this->type() === EEM_Line_Item::type_total;
1264
+	}
1265
+
1266
+
1267
+	/**
1268
+	 * @return bool
1269
+	 * @throws EE_Error
1270
+	 * @throws InvalidArgumentException
1271
+	 * @throws InvalidDataTypeException
1272
+	 * @throws InvalidInterfaceException
1273
+	 * @throws ReflectionException
1274
+	 */
1275
+	public function is_cancelled()
1276
+	{
1277
+		return $this->type() === EEM_Line_Item::type_cancellation;
1278
+	}
1279
+
1280
+
1281
+	/**
1282
+	 * @return string like '2, 004.00', formatted according to the localized currency
1283
+	 * @throws EE_Error
1284
+	 * @throws ReflectionException
1285
+	 */
1286
+	public function unit_price_no_code(): string
1287
+	{
1288
+		return $this->prettyUnitPrice();
1289
+	}
1290
+
1291
+
1292
+	/**
1293
+	 * @return string like '2, 004.00', formatted according to the localized currency
1294
+	 * @throws EE_Error
1295
+	 * @throws ReflectionException
1296
+	 * @since $VID:$
1297
+	 */
1298
+	public function prettyUnitPrice(): string
1299
+	{
1300
+		return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1301
+	}
1302
+
1303
+
1304
+	/**
1305
+	 * @return string like '2, 004.00', formatted according to the localized currency
1306
+	 * @throws EE_Error
1307
+	 * @throws ReflectionException
1308
+	 */
1309
+	public function total_no_code(): string
1310
+	{
1311
+		return $this->prettyTotal();
1312
+	}
1313
+
1314
+
1315
+	/**
1316
+	 * @return string like '2, 004.00', formatted according to the localized currency
1317
+	 * @throws EE_Error
1318
+	 * @throws ReflectionException
1319
+	 * @since $VID:$
1320
+	 */
1321
+	public function prettyTotal(): string
1322
+	{
1323
+		return $this->get_pretty('LIN_total', 'no_currency_code');
1324
+	}
1325
+
1326
+
1327
+	/**
1328
+	 * Gets the final total on this item, taking taxes into account.
1329
+	 * Has the side-effect of setting the sub-total as it was just calculated.
1330
+	 * If this is used on a grand-total line item, also updates the transaction's
1331
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
1332
+	 * want to change a persistable transaction with info from a non-persistent line item)
1333
+	 *
1334
+	 * @param bool $update_txn_status
1335
+	 * @return float
1336
+	 * @throws EE_Error
1337
+	 * @throws InvalidArgumentException
1338
+	 * @throws InvalidDataTypeException
1339
+	 * @throws InvalidInterfaceException
1340
+	 * @throws ReflectionException
1341
+	 * @throws RuntimeException
1342
+	 */
1343
+	public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1344
+	{
1345
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1346
+		return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1347
+	}
1348
+
1349
+
1350
+	/**
1351
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1352
+	 * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1353
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1354
+	 * when this is called on the grand total
1355
+	 *
1356
+	 * @return float
1357
+	 * @throws EE_Error
1358
+	 * @throws InvalidArgumentException
1359
+	 * @throws InvalidDataTypeException
1360
+	 * @throws InvalidInterfaceException
1361
+	 * @throws ReflectionException
1362
+	 */
1363
+	public function recalculate_pre_tax_total(): float
1364
+	{
1365
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1366
+		[$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1367
+		return (float) $total;
1368
+	}
1369
+
1370
+
1371
+	/**
1372
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1373
+	 * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1374
+	 * and tax sub-total if already in the DB
1375
+	 *
1376
+	 * @return float
1377
+	 * @throws EE_Error
1378
+	 * @throws InvalidArgumentException
1379
+	 * @throws InvalidDataTypeException
1380
+	 * @throws InvalidInterfaceException
1381
+	 * @throws ReflectionException
1382
+	 */
1383
+	public function recalculate_taxes_and_tax_total(): float
1384
+	{
1385
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1386
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1387
+	}
1388
+
1389
+
1390
+	/**
1391
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
1392
+	 * recalculate_taxes_and_total
1393
+	 *
1394
+	 * @return float
1395
+	 * @throws EE_Error
1396
+	 * @throws InvalidArgumentException
1397
+	 * @throws InvalidDataTypeException
1398
+	 * @throws InvalidInterfaceException
1399
+	 * @throws ReflectionException
1400
+	 */
1401
+	public function get_total_tax()
1402
+	{
1403
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1404
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1405
+	}
1406
+
1407
+
1408
+	/**
1409
+	 * Gets the total for all the items purchased only
1410
+	 *
1411
+	 * @return float
1412
+	 * @throws EE_Error
1413
+	 * @throws InvalidArgumentException
1414
+	 * @throws InvalidDataTypeException
1415
+	 * @throws InvalidInterfaceException
1416
+	 * @throws ReflectionException
1417
+	 */
1418
+	public function get_items_total()
1419
+	{
1420
+		// by default, let's make sure we're consistent with the existing line item
1421
+		if ($this->is_total()) {
1422
+			return $this->pretaxTotal();
1423
+		}
1424
+		$total = 0;
1425
+		foreach ($this->get_items() as $item) {
1426
+			if ($item instanceof EE_Line_Item) {
1427
+				$total += $item->pretaxTotal();
1428
+			}
1429
+		}
1430
+		return $total;
1431
+	}
1432
+
1433
+
1434
+	/**
1435
+	 * Gets all the descendants (ie, children or children of children etc) that
1436
+	 * are of the type 'tax'
1437
+	 *
1438
+	 * @return EE_Line_Item[]
1439
+	 * @throws EE_Error
1440
+	 */
1441
+	public function tax_descendants()
1442
+	{
1443
+		return EEH_Line_Item::get_tax_descendants($this);
1444
+	}
1445
+
1446
+
1447
+	/**
1448
+	 * Gets all the real items purchased which are children of this item
1449
+	 *
1450
+	 * @return EE_Line_Item[]
1451
+	 * @throws EE_Error
1452
+	 */
1453
+	public function get_items()
1454
+	{
1455
+		return EEH_Line_Item::get_line_item_descendants($this);
1456
+	}
1457
+
1458
+
1459
+	/**
1460
+	 * Returns the amount taxable among this line item's children (or if it has no children,
1461
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
1462
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
1463
+	 * but there is a "Taxable" discount), returns 0.
1464
+	 *
1465
+	 * @return float
1466
+	 * @throws EE_Error
1467
+	 * @throws InvalidArgumentException
1468
+	 * @throws InvalidDataTypeException
1469
+	 * @throws InvalidInterfaceException
1470
+	 * @throws ReflectionException
1471
+	 */
1472
+	public function taxable_total(): float
1473
+	{
1474
+		return $this->calculator->taxableAmountForGlobalTaxes($this);
1475
+	}
1476
+
1477
+
1478
+	/**
1479
+	 * Gets the transaction for this line item
1480
+	 *
1481
+	 * @return EE_Base_Class|EE_Transaction
1482
+	 * @throws EE_Error
1483
+	 * @throws InvalidArgumentException
1484
+	 * @throws InvalidDataTypeException
1485
+	 * @throws InvalidInterfaceException
1486
+	 * @throws ReflectionException
1487
+	 */
1488
+	public function transaction()
1489
+	{
1490
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1491
+	}
1492
+
1493
+
1494
+	/**
1495
+	 * Saves this line item to the DB, and recursively saves its descendants.
1496
+	 * Because there currently is no proper parent-child relation on the model,
1497
+	 * save_this_and_cached() will NOT save the descendants.
1498
+	 * Also sets the transaction on this line item and all its descendants before saving
1499
+	 *
1500
+	 * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1501
+	 * @return int count of items saved
1502
+	 * @throws EE_Error
1503
+	 * @throws InvalidArgumentException
1504
+	 * @throws InvalidDataTypeException
1505
+	 * @throws InvalidInterfaceException
1506
+	 * @throws ReflectionException
1507
+	 */
1508
+	public function save_this_and_descendants_to_txn($txn_id = null)
1509
+	{
1510
+		$count = 0;
1511
+		if (! $txn_id) {
1512
+			$txn_id = $this->TXN_ID();
1513
+		}
1514
+		$this->set_TXN_ID($txn_id);
1515
+		$children = $this->children();
1516
+		$count += $this->save()
1517
+			? 1
1518
+			: 0;
1519
+		foreach ($children as $child_line_item) {
1520
+			if ($child_line_item instanceof EE_Line_Item) {
1521
+				$child_line_item->set_parent_ID($this->ID());
1522
+				$count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1523
+			}
1524
+		}
1525
+		return $count;
1526
+	}
1527
+
1528
+
1529
+	/**
1530
+	 * Saves this line item to the DB, and recursively saves its descendants.
1531
+	 *
1532
+	 * @return int count of items saved
1533
+	 * @throws EE_Error
1534
+	 * @throws InvalidArgumentException
1535
+	 * @throws InvalidDataTypeException
1536
+	 * @throws InvalidInterfaceException
1537
+	 * @throws ReflectionException
1538
+	 */
1539
+	public function save_this_and_descendants()
1540
+	{
1541
+		$count = 0;
1542
+		$children = $this->children();
1543
+		$count += $this->save()
1544
+			? 1
1545
+			: 0;
1546
+		foreach ($children as $child_line_item) {
1547
+			if ($child_line_item instanceof EE_Line_Item) {
1548
+				$child_line_item->set_parent_ID($this->ID());
1549
+				$count += $child_line_item->save_this_and_descendants();
1550
+			}
1551
+		}
1552
+		return $count;
1553
+	}
1554
+
1555
+
1556
+	/**
1557
+	 * returns the cancellation line item if this item was cancelled
1558
+	 *
1559
+	 * @return EE_Line_Item[]
1560
+	 * @throws InvalidArgumentException
1561
+	 * @throws InvalidInterfaceException
1562
+	 * @throws InvalidDataTypeException
1563
+	 * @throws ReflectionException
1564
+	 * @throws EE_Error
1565
+	 */
1566
+	public function get_cancellations()
1567
+	{
1568
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1569
+	}
1570
+
1571
+
1572
+	/**
1573
+	 * If this item has an ID, then this saves it again to update the db
1574
+	 *
1575
+	 * @return int count of items saved
1576
+	 * @throws EE_Error
1577
+	 * @throws InvalidArgumentException
1578
+	 * @throws InvalidDataTypeException
1579
+	 * @throws InvalidInterfaceException
1580
+	 * @throws ReflectionException
1581
+	 */
1582
+	public function maybe_save()
1583
+	{
1584
+		if ($this->ID()) {
1585
+			return $this->save();
1586
+		}
1587
+		return false;
1588
+	}
1589
+
1590
+
1591
+	/**
1592
+	 * clears the cached children and parent from the line item
1593
+	 *
1594
+	 * @return void
1595
+	 */
1596
+	public function clear_related_line_item_cache()
1597
+	{
1598
+		$this->_children = array();
1599
+		$this->_parent = null;
1600
+	}
1601
+
1602
+
1603
+	/**
1604
+	 * @param bool $raw
1605
+	 * @return int
1606
+	 * @throws EE_Error
1607
+	 * @throws InvalidArgumentException
1608
+	 * @throws InvalidDataTypeException
1609
+	 * @throws InvalidInterfaceException
1610
+	 * @throws ReflectionException
1611
+	 */
1612
+	public function timestamp($raw = false)
1613
+	{
1614
+		return $raw
1615
+			? $this->get_raw('LIN_timestamp')
1616
+			: $this->get('LIN_timestamp');
1617
+	}
1618
+
1619
+
1620
+
1621
+
1622
+	/************************* DEPRECATED *************************/
1623
+	/**
1624
+	 * @deprecated 4.6.0
1625
+	 * @param string $type one of the constants on EEM_Line_Item
1626
+	 * @return EE_Line_Item[]
1627
+	 * @throws EE_Error
1628
+	 */
1629
+	protected function _get_descendants_of_type($type)
1630
+	{
1631
+		EE_Error::doing_it_wrong(
1632
+			'EE_Line_Item::_get_descendants_of_type()',
1633
+			sprintf(
1634
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1635
+				'EEH_Line_Item::get_descendants_of_type()'
1636
+			),
1637
+			'4.6.0'
1638
+		);
1639
+		return EEH_Line_Item::get_descendants_of_type($this, $type);
1640
+	}
1641
+
1642
+
1643
+	/**
1644
+	 * @deprecated 4.6.0
1645
+	 * @param string $type like one of the EEM_Line_Item::type_*
1646
+	 * @return EE_Line_Item
1647
+	 * @throws EE_Error
1648
+	 * @throws InvalidArgumentException
1649
+	 * @throws InvalidDataTypeException
1650
+	 * @throws InvalidInterfaceException
1651
+	 * @throws ReflectionException
1652
+	 */
1653
+	public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1654
+	{
1655
+		EE_Error::doing_it_wrong(
1656
+			'EE_Line_Item::get_nearest_descendant_of_type()',
1657
+			sprintf(
1658
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1659
+				'EEH_Line_Item::get_nearest_descendant_of_type()'
1660
+			),
1661
+			'4.6.0'
1662
+		);
1663
+		return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1664
+	}
1665 1665
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
         $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147 147
         // verify client code has not passed any invalid field names
148 148
         foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
149
+            if ( ! isset($model_fields[$field_name])) {
150 150
                 throw new EE_Error(
151 151
                     sprintf(
152 152
                         esc_html__(
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
             }
162 162
         }
163 163
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
164
+        if ( ! empty($date_formats) && is_array($date_formats)) {
165 165
             [$this->_dt_frmt, $this->_tm_frmt] = $date_formats;
166 166
         } else {
167 167
             // set default formats for date and time
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
             foreach ($model_fields as $fieldName => $field) {
175 175
                 $this->set_from_db(
176 176
                     $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
177
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null
178 178
                 );
179 179
             }
180 180
         } else {
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
             foreach ($model_fields as $fieldName => $field) {
184 184
                 $this->set(
185 185
                     $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
186
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null,
187 187
                     true
188 188
                 );
189 189
             }
@@ -191,15 +191,15 @@  discard block
 block discarded – undo
191 191
         // remember what values were passed to this constructor
192 192
         $this->_props_n_values_provided_in_constructor = $fieldValues;
193 193
         // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
194
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
195 195
             $model->add_to_entity_map($this);
196 196
         }
197 197
         // setup all the relations
198 198
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199 199
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
200
+                $this->_model_relations[$relation_name] = null;
201 201
             } else {
202
-                $this->_model_relations[ $relation_name ] = array();
202
+                $this->_model_relations[$relation_name] = array();
203 203
             }
204 204
         }
205 205
         /**
@@ -251,10 +251,10 @@  discard block
 block discarded – undo
251 251
     public function get_original($field_name)
252 252
     {
253 253
         if (
254
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
254
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
255 255
             && $field_settings = $this->get_model()->field_settings_for($field_name)
256 256
         ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
257
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
258 258
         }
259 259
         return null;
260 260
     }
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         // then don't do anything
292 292
         if (
293 293
             ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
294
+            && $this->_fields[$field_name] === $field_value
295 295
             && $this->ID()
296 296
         ) {
297 297
             return;
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
             $holder_of_value = $field_obj->prepare_for_set($field_value);
310 310
             // should the value be null?
311 311
             if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
312
+                $this->_fields[$field_name] = $field_obj->get_default_value();
313 313
                 /**
314 314
                  * To save having to refactor all the models, if a default value is used for a
315 315
                  * EE_Datetime_Field, and that value is not null nor is it a DateTime
@@ -320,15 +320,15 @@  discard block
 block discarded – undo
320 320
                  */
321 321
                 if (
322 322
                     $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
323
+                    && $this->_fields[$field_name] !== null
324
+                    && ! $this->_fields[$field_name] instanceof DateTime
325 325
                 ) {
326
-                    empty($this->_fields[ $field_name ])
326
+                    empty($this->_fields[$field_name])
327 327
                         ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
328
+                        : $this->set($field_name, $this->_fields[$field_name]);
329 329
                 }
330 330
             } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
331
+                $this->_fields[$field_name] = $holder_of_value;
332 332
             }
333 333
             // if we're not in the constructor...
334 334
             // now check if what we set was a primary key
@@ -391,8 +391,8 @@  discard block
 block discarded – undo
391 391
      */
392 392
     public function getCustomSelect($alias)
393 393
     {
394
-        return isset($this->custom_selection_results[ $alias ])
395
-            ? $this->custom_selection_results[ $alias ]
394
+        return isset($this->custom_selection_results[$alias])
395
+            ? $this->custom_selection_results[$alias]
396 396
             : null;
397 397
     }
398 398
 
@@ -479,8 +479,8 @@  discard block
 block discarded – undo
479 479
         foreach ($model_fields as $field_name => $field_obj) {
480 480
             if ($field_obj instanceof EE_Datetime_Field) {
481 481
                 $field_obj->set_timezone($this->_timezone);
482
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
482
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
483
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
484 484
                 }
485 485
             }
486 486
         }
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
      */
539 539
     public function get_format($full = true)
540 540
     {
541
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
541
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542 542
     }
543 543
 
544 544
 
@@ -564,11 +564,11 @@  discard block
 block discarded – undo
564 564
     public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565 565
     {
566 566
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
-        if (! $object_to_cache instanceof EE_Base_Class) {
567
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
568 568
             return false;
569 569
         }
570 570
         // also get "how" the object is related, or throw an error
571
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
571
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572 572
             throw new EE_Error(
573 573
                 sprintf(
574 574
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -582,38 +582,38 @@  discard block
 block discarded – undo
582 582
             // if it's a "belongs to" relationship, then there's only one related model object
583 583
             // eg, if this is a registration, there's only 1 attendee for it
584 584
             // so for these model objects just set it to be cached
585
-            $this->_model_relations[ $relationName ] = $object_to_cache;
585
+            $this->_model_relations[$relationName] = $object_to_cache;
586 586
             $return = true;
587 587
         } else {
588 588
             // otherwise, this is the "many" side of a one to many relationship,
589 589
             // so we'll add the object to the array of related objects for that type.
590 590
             // eg: if this is an event, there are many registrations for that event,
591 591
             // so we cache the registrations in an array
592
-            if (! is_array($this->_model_relations[ $relationName ])) {
592
+            if ( ! is_array($this->_model_relations[$relationName])) {
593 593
                 // if for some reason, the cached item is a model object,
594 594
                 // then stick that in the array, otherwise start with an empty array
595
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
595
+                $this->_model_relations[$relationName] = $this->_model_relations[$relationName]
596 596
                                                            instanceof
597 597
                                                            EE_Base_Class
598
-                    ? array($this->_model_relations[ $relationName ]) : array();
598
+                    ? array($this->_model_relations[$relationName]) : array();
599 599
             }
600 600
             // first check for a cache_id which is normally empty
601
-            if (! empty($cache_id)) {
601
+            if ( ! empty($cache_id)) {
602 602
                 // if the cache_id exists, then it means we are purposely trying to cache this
603 603
                 // with a known key that can then be used to retrieve the object later on
604
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
604
+                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
605 605
                 $return = $cache_id;
606 606
             } elseif ($object_to_cache->ID()) {
607 607
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
608
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
608
+                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
609 609
                 $return = $object_to_cache->ID();
610 610
             } else {
611 611
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
612
+                $this->_model_relations[$relationName][] = $object_to_cache;
613 613
                 // move the internal pointer to the end of the array
614
-                end($this->_model_relations[ $relationName ]);
614
+                end($this->_model_relations[$relationName]);
615 615
                 // and grab the key so that we can return it
616
-                $return = key($this->_model_relations[ $relationName ]);
616
+                $return = key($this->_model_relations[$relationName]);
617 617
             }
618 618
         }
619 619
         return $return;
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
         // first make sure this property exists
640 640
         $this->get_model()->field_settings_for($fieldname);
641 641
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
642
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
643 643
     }
644 644
 
645 645
 
@@ -668,9 +668,9 @@  discard block
 block discarded – undo
668 668
         $model = $this->get_model();
669 669
         $model->field_settings_for($fieldname);
670 670
         $cache_type = $pretty ? 'pretty' : 'standard';
671
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
671
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
672
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
673
+            return $this->_cached_properties[$fieldname][$cache_type];
674 674
         }
675 675
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676 676
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -698,12 +698,12 @@  discard block
 block discarded – undo
698 698
         if ($field_obj instanceof EE_Datetime_Field) {
699 699
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700 700
         }
701
-        if (! isset($this->_fields[ $fieldname ])) {
702
-            $this->_fields[ $fieldname ] = null;
701
+        if ( ! isset($this->_fields[$fieldname])) {
702
+            $this->_fields[$fieldname] = null;
703 703
         }
704 704
         $value = $pretty
705
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
705
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
706
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
707 707
         return $value;
708 708
     }
709 709
 
@@ -761,8 +761,8 @@  discard block
 block discarded – undo
761 761
      */
762 762
     protected function _clear_cached_property($property_name)
763 763
     {
764
-        if (isset($this->_cached_properties[ $property_name ])) {
765
-            unset($this->_cached_properties[ $property_name ]);
764
+        if (isset($this->_cached_properties[$property_name])) {
765
+            unset($this->_cached_properties[$property_name]);
766 766
         }
767 767
     }
768 768
 
@@ -814,7 +814,7 @@  discard block
 block discarded – undo
814 814
     {
815 815
         $relationship_to_model = $this->get_model()->related_settings_for($relationName);
816 816
         $index_in_cache = '';
817
-        if (! $relationship_to_model) {
817
+        if ( ! $relationship_to_model) {
818 818
             throw new EE_Error(
819 819
                 sprintf(
820 820
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -825,10 +825,10 @@  discard block
 block discarded – undo
825 825
         }
826 826
         if ($clear_all) {
827 827
             $obj_removed = true;
828
-            $this->_model_relations[ $relationName ] = null;
828
+            $this->_model_relations[$relationName] = null;
829 829
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
830
-            $obj_removed = $this->_model_relations[ $relationName ];
831
-            $this->_model_relations[ $relationName ] = null;
830
+            $obj_removed = $this->_model_relations[$relationName];
831
+            $this->_model_relations[$relationName] = null;
832 832
         } else {
833 833
             if (
834 834
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -836,12 +836,12 @@  discard block
 block discarded – undo
836 836
             ) {
837 837
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
838 838
                 if (
839
-                    is_array($this->_model_relations[ $relationName ])
840
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
839
+                    is_array($this->_model_relations[$relationName])
840
+                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
841 841
                 ) {
842 842
                     $index_found_at = null;
843 843
                     // find this object in the array even though it has a different key
844
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
844
+                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
845 845
                         /** @noinspection TypeUnsafeComparisonInspection */
846 846
                         if (
847 847
                             $obj instanceof EE_Base_Class
@@ -875,9 +875,9 @@  discard block
 block discarded – undo
875 875
             }
876 876
             // supposedly we've found it. But it could just be that the client code
877 877
             // provided a bad index/object
878
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
878
+            if (isset($this->_model_relations[$relationName][$index_in_cache])) {
879
+                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
880
+                unset($this->_model_relations[$relationName][$index_in_cache]);
881 881
             } else {
882 882
                 // that thing was never cached anyways.
883 883
                 $obj_removed = null;
@@ -908,7 +908,7 @@  discard block
 block discarded – undo
908 908
         $current_cache_id = ''
909 909
     ) {
910 910
         // verify that incoming object is of the correct type
911
-        $obj_class = 'EE_' . $relationName;
911
+        $obj_class = 'EE_'.$relationName;
912 912
         if ($newly_saved_object instanceof $obj_class) {
913 913
             /* @type EE_Base_Class $newly_saved_object */
914 914
             // now get the type of relation
@@ -916,18 +916,18 @@  discard block
 block discarded – undo
916 916
             // if this is a 1:1 relationship
917 917
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918 918
                 // then just replace the cached object with the newly saved object
919
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
919
+                $this->_model_relations[$relationName] = $newly_saved_object;
920 920
                 return true;
921 921
                 // or if it's some kind of sordid feral polyamorous relationship...
922 922
             }
923 923
             if (
924
-                is_array($this->_model_relations[ $relationName ])
925
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
924
+                is_array($this->_model_relations[$relationName])
925
+                && isset($this->_model_relations[$relationName][$current_cache_id])
926 926
             ) {
927 927
                 // then remove the current cached item
928
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
928
+                unset($this->_model_relations[$relationName][$current_cache_id]);
929 929
                 // and cache the newly saved object using it's new ID
930
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
930
+                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
931 931
                 return true;
932 932
             }
933 933
         }
@@ -944,8 +944,8 @@  discard block
 block discarded – undo
944 944
      */
945 945
     public function get_one_from_cache($relationName)
946 946
     {
947
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
948
-            ? $this->_model_relations[ $relationName ]
947
+        $cached_array_or_object = isset($this->_model_relations[$relationName])
948
+            ? $this->_model_relations[$relationName]
949 949
             : null;
950 950
         if (is_array($cached_array_or_object)) {
951 951
             return array_shift($cached_array_or_object);
@@ -968,7 +968,7 @@  discard block
 block discarded – undo
968 968
      */
969 969
     public function get_all_from_cache($relationName)
970 970
     {
971
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
971
+        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
972 972
         // if the result is not an array, but exists, make it an array
973 973
         $objects = is_array($objects) ? $objects : array($objects);
974 974
         // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
@@ -1152,7 +1152,7 @@  discard block
 block discarded – undo
1152 1152
             } else {
1153 1153
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1154 1154
             }
1155
-            $this->_fields[ $field_name ] = $field_value;
1155
+            $this->_fields[$field_name] = $field_value;
1156 1156
             $this->_clear_cached_property($field_name);
1157 1157
         }
1158 1158
     }
@@ -1192,9 +1192,9 @@  discard block
 block discarded – undo
1192 1192
     public function get_raw($field_name)
1193 1193
     {
1194 1194
         $field_settings = $this->get_model()->field_settings_for($field_name);
1195
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
-            ? $this->_fields[ $field_name ]->format('U')
1197
-            : $this->_fields[ $field_name ];
1195
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1196
+            ? $this->_fields[$field_name]->format('U')
1197
+            : $this->_fields[$field_name];
1198 1198
     }
1199 1199
 
1200 1200
 
@@ -1216,7 +1216,7 @@  discard block
 block discarded – undo
1216 1216
     public function get_DateTime_object($field_name)
1217 1217
     {
1218 1218
         $field_settings = $this->get_model()->field_settings_for($field_name);
1219
-        if (! $field_settings instanceof EE_Datetime_Field) {
1219
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1220 1220
             EE_Error::add_error(
1221 1221
                 sprintf(
1222 1222
                     esc_html__(
@@ -1231,8 +1231,8 @@  discard block
 block discarded – undo
1231 1231
             );
1232 1232
             return false;
1233 1233
         }
1234
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
-            ? clone $this->_fields[ $field_name ]
1234
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1235
+            ? clone $this->_fields[$field_name]
1236 1236
             : null;
1237 1237
     }
1238 1238
 
@@ -1474,7 +1474,7 @@  discard block
 block discarded – undo
1474 1474
      */
1475 1475
     public function get_i18n_datetime($field_name, $format = '')
1476 1476
     {
1477
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1477
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1478 1478
         return date_i18n(
1479 1479
             $format,
1480 1480
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1586,21 +1586,21 @@  discard block
 block discarded – undo
1586 1586
         $field->set_time_format($this->_tm_frmt);
1587 1587
         switch ($what) {
1588 1588
             case 'T':
1589
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1589
+                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1590 1590
                     $datetime_value,
1591
-                    $this->_fields[ $fieldname ]
1591
+                    $this->_fields[$fieldname]
1592 1592
                 );
1593 1593
                 $this->_has_changes = true;
1594 1594
                 break;
1595 1595
             case 'D':
1596
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1596
+                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1597 1597
                     $datetime_value,
1598
-                    $this->_fields[ $fieldname ]
1598
+                    $this->_fields[$fieldname]
1599 1599
                 );
1600 1600
                 $this->_has_changes = true;
1601 1601
                 break;
1602 1602
             case 'B':
1603
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1603
+                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1604 1604
                 $this->_has_changes = true;
1605 1605
                 break;
1606 1606
         }
@@ -1643,7 +1643,7 @@  discard block
 block discarded – undo
1643 1643
         $this->set_timezone($timezone);
1644 1644
         $fn = (array) $field_name;
1645 1645
         $args = array_merge($fn, (array) $args);
1646
-        if (! method_exists($this, $callback)) {
1646
+        if ( ! method_exists($this, $callback)) {
1647 1647
             throw new EE_Error(
1648 1648
                 sprintf(
1649 1649
                     esc_html__(
@@ -1655,7 +1655,7 @@  discard block
 block discarded – undo
1655 1655
             );
1656 1656
         }
1657 1657
         $args = (array) $args;
1658
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1658
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1659 1659
         $this->set_timezone($original_timezone);
1660 1660
         return $return;
1661 1661
     }
@@ -1770,8 +1770,8 @@  discard block
 block discarded – undo
1770 1770
     {
1771 1771
         $model = $this->get_model();
1772 1772
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
-            if (! empty($this->_model_relations[ $relation_name ])) {
1774
-                $related_objects = $this->_model_relations[ $relation_name ];
1773
+            if ( ! empty($this->_model_relations[$relation_name])) {
1774
+                $related_objects = $this->_model_relations[$relation_name];
1775 1775
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776 1776
                     // this relation only stores a single model object, not an array
1777 1777
                     // but let's make it consistent
@@ -1830,7 +1830,7 @@  discard block
 block discarded – undo
1830 1830
             $this->set($column, $value);
1831 1831
         }
1832 1832
         // no changes ? then don't do anything
1833
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1833
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834 1834
             return 0;
1835 1835
         }
1836 1836
         /**
@@ -1840,7 +1840,7 @@  discard block
 block discarded – undo
1840 1840
          * @param EE_Base_Class $model_object the model object about to be saved.
1841 1841
          */
1842 1842
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
-        if (! $this->allow_persist()) {
1843
+        if ( ! $this->allow_persist()) {
1844 1844
             return 0;
1845 1845
         }
1846 1846
         // now get current attribute values
@@ -1855,10 +1855,10 @@  discard block
 block discarded – undo
1855 1855
         if ($model->has_primary_key_field()) {
1856 1856
             if ($model->get_primary_key_field()->is_auto_increment()) {
1857 1857
                 // ok check if it's set, if so: update; if not, insert
1858
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1858
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1859 1859
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860 1860
                 } else {
1861
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1861
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1862 1862
                     $results = $model->insert($save_cols_n_values);
1863 1863
                     if ($results) {
1864 1864
                         // if successful, set the primary key
@@ -1868,7 +1868,7 @@  discard block
 block discarded – undo
1868 1868
                         // will get added to the mapper before we can add this one!
1869 1869
                         // but if we just avoid using the SET method, all that headache can be avoided
1870 1870
                         $pk_field_name = $model->primary_key_name();
1871
-                        $this->_fields[ $pk_field_name ] = $results;
1871
+                        $this->_fields[$pk_field_name] = $results;
1872 1872
                         $this->_clear_cached_property($pk_field_name);
1873 1873
                         $model->add_to_entity_map($this);
1874 1874
                         $this->_update_cached_related_model_objs_fks();
@@ -1885,8 +1885,8 @@  discard block
 block discarded – undo
1885 1885
                                     'event_espresso'
1886 1886
                                 ),
1887 1887
                                 get_class($this),
1888
-                                get_class($model) . '::instance()->add_to_entity_map()',
1889
-                                get_class($model) . '::instance()->get_one_by_ID()',
1888
+                                get_class($model).'::instance()->add_to_entity_map()',
1889
+                                get_class($model).'::instance()->get_one_by_ID()',
1890 1890
                                 '<br />'
1891 1891
                             )
1892 1892
                         );
@@ -1988,27 +1988,27 @@  discard block
 block discarded – undo
1988 1988
     public function save_new_cached_related_model_objs()
1989 1989
     {
1990 1990
         // make sure this has been saved
1991
-        if (! $this->ID()) {
1991
+        if ( ! $this->ID()) {
1992 1992
             $id = $this->save();
1993 1993
         } else {
1994 1994
             $id = $this->ID();
1995 1995
         }
1996 1996
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1997 1997
         foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
-            if ($this->_model_relations[ $relationName ]) {
1998
+            if ($this->_model_relations[$relationName]) {
1999 1999
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000 2000
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001 2001
                 /* @var $related_model_obj EE_Base_Class */
2002 2002
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
2003 2003
                     // add a relation to that relation type (which saves the appropriate thing in the process)
2004 2004
                     // but ONLY if it DOES NOT exist in the DB
2005
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2005
+                    $related_model_obj = $this->_model_relations[$relationName];
2006 2006
                     // if( ! $related_model_obj->ID()){
2007 2007
                     $this->_add_relation_to($related_model_obj, $relationName);
2008 2008
                     $related_model_obj->save_new_cached_related_model_objs();
2009 2009
                     // }
2010 2010
                 } else {
2011
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2011
+                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
2012 2012
                         // add a relation to that relation type (which saves the appropriate thing in the process)
2013 2013
                         // but ONLY if it DOES NOT exist in the DB
2014 2014
                         // if( ! $related_model_obj->ID()){
@@ -2035,7 +2035,7 @@  discard block
 block discarded – undo
2035 2035
      */
2036 2036
     public function get_model()
2037 2037
     {
2038
-        if (! $this->_model) {
2038
+        if ( ! $this->_model) {
2039 2039
             $modelName = self::_get_model_classname(get_class($this));
2040 2040
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041 2041
         } else {
@@ -2061,9 +2061,9 @@  discard block
 block discarded – undo
2061 2061
         $primary_id_ref = self::_get_primary_key_name($classname);
2062 2062
         if (
2063 2063
             array_key_exists($primary_id_ref, $props_n_values)
2064
-            && ! empty($props_n_values[ $primary_id_ref ])
2064
+            && ! empty($props_n_values[$primary_id_ref])
2065 2065
         ) {
2066
-            $id = $props_n_values[ $primary_id_ref ];
2066
+            $id = $props_n_values[$primary_id_ref];
2067 2067
             return self::_get_model($classname)->get_from_entity_map($id);
2068 2068
         }
2069 2069
         return false;
@@ -2098,10 +2098,10 @@  discard block
 block discarded – undo
2098 2098
             $primary_id_ref = self::_get_primary_key_name($classname);
2099 2099
             if (
2100 2100
                 array_key_exists($primary_id_ref, $props_n_values)
2101
-                && ! empty($props_n_values[ $primary_id_ref ])
2101
+                && ! empty($props_n_values[$primary_id_ref])
2102 2102
             ) {
2103 2103
                 $existing = $model->get_one_by_ID(
2104
-                    $props_n_values[ $primary_id_ref ]
2104
+                    $props_n_values[$primary_id_ref]
2105 2105
                 );
2106 2106
             }
2107 2107
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2113,7 +2113,7 @@  discard block
 block discarded – undo
2113 2113
         }
2114 2114
         if ($existing) {
2115 2115
             // set date formats if present before setting values
2116
-            if (! empty($date_formats) && is_array($date_formats)) {
2116
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2117 2117
                 $existing->set_date_format($date_formats[0]);
2118 2118
                 $existing->set_time_format($date_formats[1]);
2119 2119
             } else {
@@ -2146,7 +2146,7 @@  discard block
 block discarded – undo
2146 2146
     protected static function _get_model($classname, $timezone = null)
2147 2147
     {
2148 2148
         // find model for this class
2149
-        if (! $classname) {
2149
+        if ( ! $classname) {
2150 2150
             throw new EE_Error(
2151 2151
                 sprintf(
2152 2152
                     esc_html__(
@@ -2195,7 +2195,7 @@  discard block
 block discarded – undo
2195 2195
         if (strpos($model_name, 'EE_') === 0) {
2196 2196
             $model_classname = str_replace('EE_', 'EEM_', $model_name);
2197 2197
         } else {
2198
-            $model_classname = 'EEM_' . $model_name;
2198
+            $model_classname = 'EEM_'.$model_name;
2199 2199
         }
2200 2200
         return $model_classname;
2201 2201
     }
@@ -2214,7 +2214,7 @@  discard block
 block discarded – undo
2214 2214
      */
2215 2215
     protected static function _get_primary_key_name($classname = null)
2216 2216
     {
2217
-        if (! $classname) {
2217
+        if ( ! $classname) {
2218 2218
             throw new EE_Error(
2219 2219
                 sprintf(
2220 2220
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2244,7 +2244,7 @@  discard block
 block discarded – undo
2244 2244
         $model = $this->get_model();
2245 2245
         // now that we know the name of the variable, use a variable variable to get its value and return its
2246 2246
         if ($model->has_primary_key_field()) {
2247
-            return $this->_fields[ $model->primary_key_name() ];
2247
+            return $this->_fields[$model->primary_key_name()];
2248 2248
         }
2249 2249
         return $model->get_index_primary_key_string($this->_fields);
2250 2250
     }
@@ -2318,7 +2318,7 @@  discard block
 block discarded – undo
2318 2318
             }
2319 2319
         } else {
2320 2320
             // this thing doesn't exist in the DB,  so just cache it
2321
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2321
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2322 2322
                 throw new EE_Error(
2323 2323
                     sprintf(
2324 2324
                         esc_html__(
@@ -2483,7 +2483,7 @@  discard block
 block discarded – undo
2483 2483
             } else {
2484 2484
                 // did we already cache the result of this query?
2485 2485
                 $cached_results = $this->get_all_from_cache($relationName);
2486
-                if (! $cached_results) {
2486
+                if ( ! $cached_results) {
2487 2487
                     $related_model_objects = $this->get_model()->get_all_related(
2488 2488
                         $this,
2489 2489
                         $relationName,
@@ -2594,7 +2594,7 @@  discard block
 block discarded – undo
2594 2594
             } else {
2595 2595
                 // first, check if we've already cached the result of this query
2596 2596
                 $cached_result = $this->get_one_from_cache($relationName);
2597
-                if (! $cached_result) {
2597
+                if ( ! $cached_result) {
2598 2598
                     $related_model_object = $model->get_first_related(
2599 2599
                         $this,
2600 2600
                         $relationName,
@@ -2618,7 +2618,7 @@  discard block
 block discarded – undo
2618 2618
             }
2619 2619
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2620 2620
             // just get what's cached on this object
2621
-            if (! $related_model_object) {
2621
+            if ( ! $related_model_object) {
2622 2622
                 $related_model_object = $this->get_one_from_cache($relationName);
2623 2623
             }
2624 2624
         }
@@ -2700,7 +2700,7 @@  discard block
 block discarded – undo
2700 2700
      */
2701 2701
     public function is_set($field_name)
2702 2702
     {
2703
-        return isset($this->_fields[ $field_name ]);
2703
+        return isset($this->_fields[$field_name]);
2704 2704
     }
2705 2705
 
2706 2706
 
@@ -2716,7 +2716,7 @@  discard block
 block discarded – undo
2716 2716
     {
2717 2717
         foreach ((array) $properties as $property_name) {
2718 2718
             // first make sure this property exists
2719
-            if (! $this->_fields[ $property_name ]) {
2719
+            if ( ! $this->_fields[$property_name]) {
2720 2720
                 throw new EE_Error(
2721 2721
                     sprintf(
2722 2722
                         esc_html__(
@@ -2748,7 +2748,7 @@  discard block
 block discarded – undo
2748 2748
         $properties = array();
2749 2749
         // remove prepended underscore
2750 2750
         foreach ($fields as $field_name => $settings) {
2751
-            $properties[ $field_name ] = $this->get($field_name);
2751
+            $properties[$field_name] = $this->get($field_name);
2752 2752
         }
2753 2753
         return $properties;
2754 2754
     }
@@ -2785,7 +2785,7 @@  discard block
 block discarded – undo
2785 2785
     {
2786 2786
         $className = get_class($this);
2787 2787
         $tagName = "FHEE__{$className}__{$methodName}";
2788
-        if (! has_filter($tagName)) {
2788
+        if ( ! has_filter($tagName)) {
2789 2789
             throw new EE_Error(
2790 2790
                 sprintf(
2791 2791
                     esc_html__(
@@ -2830,7 +2830,7 @@  discard block
 block discarded – undo
2830 2830
             $query_params[0]['EXM_value'] = $meta_value;
2831 2831
         }
2832 2832
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2833
-        if (! $existing_rows_like_that) {
2833
+        if ( ! $existing_rows_like_that) {
2834 2834
             return $this->add_extra_meta($meta_key, $meta_value);
2835 2835
         }
2836 2836
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2948,7 +2948,7 @@  discard block
 block discarded – undo
2948 2948
                 $values = array();
2949 2949
                 foreach ($results as $result) {
2950 2950
                     if ($result instanceof EE_Extra_Meta) {
2951
-                        $values[ $result->ID() ] = $result->value();
2951
+                        $values[$result->ID()] = $result->value();
2952 2952
                     }
2953 2953
                 }
2954 2954
                 return $values;
@@ -2993,17 +2993,17 @@  discard block
 block discarded – undo
2993 2993
             );
2994 2994
             foreach ($extra_meta_objs as $extra_meta_obj) {
2995 2995
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2996
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2996
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2997 2997
                 }
2998 2998
             }
2999 2999
         } else {
3000 3000
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
3001 3001
             foreach ($extra_meta_objs as $extra_meta_obj) {
3002 3002
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
3003
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
3004
-                        $return_array[ $extra_meta_obj->key() ] = array();
3003
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
3004
+                        $return_array[$extra_meta_obj->key()] = array();
3005 3005
                     }
3006
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
3006
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
3007 3007
                 }
3008 3008
             }
3009 3009
         }
@@ -3084,8 +3084,8 @@  discard block
 block discarded – undo
3084 3084
                             'event_espresso'
3085 3085
                         ),
3086 3086
                         $this->ID(),
3087
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3088
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3087
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3088
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3089 3089
                     )
3090 3090
                 );
3091 3091
             }
@@ -3118,7 +3118,7 @@  discard block
 block discarded – undo
3118 3118
     {
3119 3119
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3120 3120
         // if it wasn't even there to start off.
3121
-        if (! $this->ID()) {
3121
+        if ( ! $this->ID()) {
3122 3122
             $this->save();
3123 3123
         }
3124 3124
         global $wpdb;
@@ -3348,7 +3348,7 @@  discard block
 block discarded – undo
3348 3348
         $model = $this->get_model();
3349 3349
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3350 3350
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3351
-                $classname = 'EE_' . $model->get_this_model_name();
3351
+                $classname = 'EE_'.$model->get_this_model_name();
3352 3352
                 if (
3353 3353
                     $this->get_one_from_cache($relation_name) instanceof $classname
3354 3354
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3389,7 +3389,7 @@  discard block
 block discarded – undo
3389 3389
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3390 3390
         foreach ($this->_fields as $field => $value) {
3391 3391
             if ($value instanceof DateTime) {
3392
-                $this->_fields[ $field ] = clone $value;
3392
+                $this->_fields[$field] = clone $value;
3393 3393
             }
3394 3394
         }
3395 3395
     }
Please login to merge, or discard this patch.
Indentation   +3368 added lines, -3368 removed lines patch added patch discarded remove patch
@@ -13,3384 +13,3384 @@
 block discarded – undo
13 13
  */
14 14
 abstract class EE_Base_Class
15 15
 {
16
-    /**
17
-     * This is an array of the original properties and values provided during construction
18
-     * of this model object. (keys are model field names, values are their values).
19
-     * This list is important to remember so that when we are merging data from the db, we know
20
-     * which values to override and which to not override.
21
-     *
22
-     * @var array
23
-     */
24
-    protected $_props_n_values_provided_in_constructor;
25
-
26
-    /**
27
-     * Timezone
28
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
-     * access to it.
32
-     *
33
-     * @var string
34
-     */
35
-    protected $_timezone;
36
-
37
-    /**
38
-     * date format
39
-     * pattern or format for displaying dates
40
-     *
41
-     * @var string $_dt_frmt
42
-     */
43
-    protected $_dt_frmt;
44
-
45
-    /**
46
-     * time format
47
-     * pattern or format for displaying time
48
-     *
49
-     * @var string $_tm_frmt
50
-     */
51
-    protected $_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
-     * @var array
60
-     */
61
-    protected $_cached_properties = array();
62
-
63
-    /**
64
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
65
-     * single
66
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
-     * all others have an array)
69
-     *
70
-     * @var array
71
-     */
72
-    protected $_model_relations = array();
73
-
74
-    /**
75
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
-     *
78
-     * @var array
79
-     */
80
-    protected $_fields = array();
81
-
82
-    /**
83
-     * @var boolean indicating whether or not this model object is intended to ever be saved
84
-     * For example, we might create model objects intended to only be used for the duration
85
-     * of this request and to be thrown away, and if they were accidentally saved
86
-     * it would be a bug.
87
-     */
88
-    protected $_allow_persist = true;
89
-
90
-    /**
91
-     * @var boolean indicating whether or not this model object's properties have changed since construction
92
-     */
93
-    protected $_has_changes = false;
94
-
95
-    /**
96
-     * @var EEM_Base
97
-     */
98
-    protected $_model;
99
-
100
-    /**
101
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
-     * array as:
107
-     * array(
108
-     *  'Registration_Count' => 24
109
-     * );
110
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
-     * info)
113
-     *
114
-     * @var array
115
-     */
116
-    protected $custom_selection_results = array();
117
-
118
-
119
-    /**
120
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
-     * play nice
122
-     *
123
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
-     *                                                         TXN_amount, QST_name, etc) and values are their values
126
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
-     *                                                         corresponding db model or not.
128
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
-     *                                                         be in when instantiating a EE_Base_Class object.
130
-     * @param array   $date_formats                            An array of date formats to set on construct where first
131
-     *                                                         value is the date_format and second value is the time
132
-     *                                                         format.
133
-     * @throws InvalidArgumentException
134
-     * @throws InvalidInterfaceException
135
-     * @throws InvalidDataTypeException
136
-     * @throws EE_Error
137
-     * @throws ReflectionException
138
-     */
139
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
-    {
141
-        $className = get_class($this);
142
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
-        $model = $this->get_model();
144
-        $model_fields = $model->field_settings(false);
145
-        // ensure $fieldValues is an array
146
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
-        // verify client code has not passed any invalid field names
148
-        foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
150
-                throw new EE_Error(
151
-                    sprintf(
152
-                        esc_html__(
153
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
-                            'event_espresso'
155
-                        ),
156
-                        $field_name,
157
-                        get_class($this),
158
-                        implode(', ', array_keys($model_fields))
159
-                    )
160
-                );
161
-            }
162
-        }
163
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
165
-            [$this->_dt_frmt, $this->_tm_frmt] = $date_formats;
166
-        } else {
167
-            // set default formats for date and time
168
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
-        }
171
-        // if db model is instantiating
172
-        if ($bydb) {
173
-            // client code has indicated these field values are from the database
174
-            foreach ($model_fields as $fieldName => $field) {
175
-                $this->set_from_db(
176
-                    $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
-                );
179
-            }
180
-        } else {
181
-            // we're constructing a brand
182
-            // new instance of the model object. Generally, this means we'll need to do more field validation
183
-            foreach ($model_fields as $fieldName => $field) {
184
-                $this->set(
185
-                    $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
-                    true
188
-                );
189
-            }
190
-        }
191
-        // remember what values were passed to this constructor
192
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
193
-        // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
-            $model->add_to_entity_map($this);
196
-        }
197
-        // setup all the relations
198
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
201
-            } else {
202
-                $this->_model_relations[ $relation_name ] = array();
203
-            }
204
-        }
205
-        /**
206
-         * Action done at the end of each model object construction
207
-         *
208
-         * @param EE_Base_Class $this the model object just created
209
-         */
210
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
-    }
212
-
213
-
214
-    /**
215
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
216
-     *
217
-     * @return boolean
218
-     */
219
-    public function allow_persist()
220
-    {
221
-        return $this->_allow_persist;
222
-    }
223
-
224
-
225
-    /**
226
-     * Sets whether or not this model object should be allowed to be saved to the DB.
227
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
-     * you got new information that somehow made you change your mind.
229
-     *
230
-     * @param boolean $allow_persist
231
-     * @return boolean
232
-     */
233
-    public function set_allow_persist($allow_persist)
234
-    {
235
-        return $this->_allow_persist = $allow_persist;
236
-    }
237
-
238
-
239
-    /**
240
-     * Gets the field's original value when this object was constructed during this request.
241
-     * This can be helpful when determining if a model object has changed or not
242
-     *
243
-     * @param string $field_name
244
-     * @return mixed|null
245
-     * @throws ReflectionException
246
-     * @throws InvalidArgumentException
247
-     * @throws InvalidInterfaceException
248
-     * @throws InvalidDataTypeException
249
-     * @throws EE_Error
250
-     */
251
-    public function get_original($field_name)
252
-    {
253
-        if (
254
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
256
-        ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
-        }
259
-        return null;
260
-    }
261
-
262
-
263
-    /**
264
-     * @param EE_Base_Class $obj
265
-     * @return string
266
-     */
267
-    public function get_class($obj)
268
-    {
269
-        return get_class($obj);
270
-    }
271
-
272
-
273
-    /**
274
-     * Overrides parent because parent expects old models.
275
-     * This also doesn't do any validation, and won't work for serialized arrays
276
-     *
277
-     * @param    string $field_name
278
-     * @param    mixed  $field_value
279
-     * @param bool      $use_default
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidInterfaceException
282
-     * @throws InvalidDataTypeException
283
-     * @throws EE_Error
284
-     * @throws ReflectionException
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     */
288
-    public function set($field_name, $field_value, $use_default = false)
289
-    {
290
-        // if not using default and nothing has changed, and object has already been setup (has ID),
291
-        // then don't do anything
292
-        if (
293
-            ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
295
-            && $this->ID()
296
-        ) {
297
-            return;
298
-        }
299
-        $model = $this->get_model();
300
-        $this->_has_changes = true;
301
-        $field_obj = $model->field_settings_for($field_name);
302
-        if ($field_obj instanceof EE_Model_Field_Base) {
303
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
304
-            if ($field_obj instanceof EE_Datetime_Field) {
305
-                $field_obj->set_timezone($this->_timezone);
306
-                $field_obj->set_date_format($this->_dt_frmt);
307
-                $field_obj->set_time_format($this->_tm_frmt);
308
-            }
309
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
310
-            // should the value be null?
311
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
313
-                /**
314
-                 * To save having to refactor all the models, if a default value is used for a
315
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
-                 * object.
318
-                 *
319
-                 * @since 4.6.10+
320
-                 */
321
-                if (
322
-                    $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
325
-                ) {
326
-                    empty($this->_fields[ $field_name ])
327
-                        ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
329
-                }
330
-            } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
332
-            }
333
-            // if we're not in the constructor...
334
-            // now check if what we set was a primary key
335
-            if (
16
+	/**
17
+	 * This is an array of the original properties and values provided during construction
18
+	 * of this model object. (keys are model field names, values are their values).
19
+	 * This list is important to remember so that when we are merging data from the db, we know
20
+	 * which values to override and which to not override.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $_props_n_values_provided_in_constructor;
25
+
26
+	/**
27
+	 * Timezone
28
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
+	 * access to it.
32
+	 *
33
+	 * @var string
34
+	 */
35
+	protected $_timezone;
36
+
37
+	/**
38
+	 * date format
39
+	 * pattern or format for displaying dates
40
+	 *
41
+	 * @var string $_dt_frmt
42
+	 */
43
+	protected $_dt_frmt;
44
+
45
+	/**
46
+	 * time format
47
+	 * pattern or format for displaying time
48
+	 *
49
+	 * @var string $_tm_frmt
50
+	 */
51
+	protected $_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
+	 * @var array
60
+	 */
61
+	protected $_cached_properties = array();
62
+
63
+	/**
64
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
65
+	 * single
66
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
+	 * all others have an array)
69
+	 *
70
+	 * @var array
71
+	 */
72
+	protected $_model_relations = array();
73
+
74
+	/**
75
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
+	 *
78
+	 * @var array
79
+	 */
80
+	protected $_fields = array();
81
+
82
+	/**
83
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
84
+	 * For example, we might create model objects intended to only be used for the duration
85
+	 * of this request and to be thrown away, and if they were accidentally saved
86
+	 * it would be a bug.
87
+	 */
88
+	protected $_allow_persist = true;
89
+
90
+	/**
91
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
92
+	 */
93
+	protected $_has_changes = false;
94
+
95
+	/**
96
+	 * @var EEM_Base
97
+	 */
98
+	protected $_model;
99
+
100
+	/**
101
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
+	 * array as:
107
+	 * array(
108
+	 *  'Registration_Count' => 24
109
+	 * );
110
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
+	 * info)
113
+	 *
114
+	 * @var array
115
+	 */
116
+	protected $custom_selection_results = array();
117
+
118
+
119
+	/**
120
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
+	 * play nice
122
+	 *
123
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
126
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
+	 *                                                         corresponding db model or not.
128
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
+	 *                                                         be in when instantiating a EE_Base_Class object.
130
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
131
+	 *                                                         value is the date_format and second value is the time
132
+	 *                                                         format.
133
+	 * @throws InvalidArgumentException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws EE_Error
137
+	 * @throws ReflectionException
138
+	 */
139
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
+	{
141
+		$className = get_class($this);
142
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
+		$model = $this->get_model();
144
+		$model_fields = $model->field_settings(false);
145
+		// ensure $fieldValues is an array
146
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
+		// verify client code has not passed any invalid field names
148
+		foreach ($fieldValues as $field_name => $field_value) {
149
+			if (! isset($model_fields[ $field_name ])) {
150
+				throw new EE_Error(
151
+					sprintf(
152
+						esc_html__(
153
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
+							'event_espresso'
155
+						),
156
+						$field_name,
157
+						get_class($this),
158
+						implode(', ', array_keys($model_fields))
159
+					)
160
+				);
161
+			}
162
+		}
163
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
+		if (! empty($date_formats) && is_array($date_formats)) {
165
+			[$this->_dt_frmt, $this->_tm_frmt] = $date_formats;
166
+		} else {
167
+			// set default formats for date and time
168
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
+		}
171
+		// if db model is instantiating
172
+		if ($bydb) {
173
+			// client code has indicated these field values are from the database
174
+			foreach ($model_fields as $fieldName => $field) {
175
+				$this->set_from_db(
176
+					$fieldName,
177
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
+				);
179
+			}
180
+		} else {
181
+			// we're constructing a brand
182
+			// new instance of the model object. Generally, this means we'll need to do more field validation
183
+			foreach ($model_fields as $fieldName => $field) {
184
+				$this->set(
185
+					$fieldName,
186
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
+					true
188
+				);
189
+			}
190
+		}
191
+		// remember what values were passed to this constructor
192
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
193
+		// remember in entity mapper
194
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
+			$model->add_to_entity_map($this);
196
+		}
197
+		// setup all the relations
198
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
+				$this->_model_relations[ $relation_name ] = null;
201
+			} else {
202
+				$this->_model_relations[ $relation_name ] = array();
203
+			}
204
+		}
205
+		/**
206
+		 * Action done at the end of each model object construction
207
+		 *
208
+		 * @param EE_Base_Class $this the model object just created
209
+		 */
210
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
+	}
212
+
213
+
214
+	/**
215
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
216
+	 *
217
+	 * @return boolean
218
+	 */
219
+	public function allow_persist()
220
+	{
221
+		return $this->_allow_persist;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
227
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
+	 * you got new information that somehow made you change your mind.
229
+	 *
230
+	 * @param boolean $allow_persist
231
+	 * @return boolean
232
+	 */
233
+	public function set_allow_persist($allow_persist)
234
+	{
235
+		return $this->_allow_persist = $allow_persist;
236
+	}
237
+
238
+
239
+	/**
240
+	 * Gets the field's original value when this object was constructed during this request.
241
+	 * This can be helpful when determining if a model object has changed or not
242
+	 *
243
+	 * @param string $field_name
244
+	 * @return mixed|null
245
+	 * @throws ReflectionException
246
+	 * @throws InvalidArgumentException
247
+	 * @throws InvalidInterfaceException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws EE_Error
250
+	 */
251
+	public function get_original($field_name)
252
+	{
253
+		if (
254
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
256
+		) {
257
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
+		}
259
+		return null;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @param EE_Base_Class $obj
265
+	 * @return string
266
+	 */
267
+	public function get_class($obj)
268
+	{
269
+		return get_class($obj);
270
+	}
271
+
272
+
273
+	/**
274
+	 * Overrides parent because parent expects old models.
275
+	 * This also doesn't do any validation, and won't work for serialized arrays
276
+	 *
277
+	 * @param    string $field_name
278
+	 * @param    mixed  $field_value
279
+	 * @param bool      $use_default
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidInterfaceException
282
+	 * @throws InvalidDataTypeException
283
+	 * @throws EE_Error
284
+	 * @throws ReflectionException
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 */
288
+	public function set($field_name, $field_value, $use_default = false)
289
+	{
290
+		// if not using default and nothing has changed, and object has already been setup (has ID),
291
+		// then don't do anything
292
+		if (
293
+			! $use_default
294
+			&& $this->_fields[ $field_name ] === $field_value
295
+			&& $this->ID()
296
+		) {
297
+			return;
298
+		}
299
+		$model = $this->get_model();
300
+		$this->_has_changes = true;
301
+		$field_obj = $model->field_settings_for($field_name);
302
+		if ($field_obj instanceof EE_Model_Field_Base) {
303
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
304
+			if ($field_obj instanceof EE_Datetime_Field) {
305
+				$field_obj->set_timezone($this->_timezone);
306
+				$field_obj->set_date_format($this->_dt_frmt);
307
+				$field_obj->set_time_format($this->_tm_frmt);
308
+			}
309
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
310
+			// should the value be null?
311
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
313
+				/**
314
+				 * To save having to refactor all the models, if a default value is used for a
315
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
+				 * object.
318
+				 *
319
+				 * @since 4.6.10+
320
+				 */
321
+				if (
322
+					$field_obj instanceof EE_Datetime_Field
323
+					&& $this->_fields[ $field_name ] !== null
324
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
325
+				) {
326
+					empty($this->_fields[ $field_name ])
327
+						? $this->set($field_name, time())
328
+						: $this->set($field_name, $this->_fields[ $field_name ]);
329
+				}
330
+			} else {
331
+				$this->_fields[ $field_name ] = $holder_of_value;
332
+			}
333
+			// if we're not in the constructor...
334
+			// now check if what we set was a primary key
335
+			if (
336 336
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
337
-                $this->_props_n_values_provided_in_constructor
338
-                && $field_value
339
-                && $field_name === $model->primary_key_name()
340
-            ) {
341
-                // if so, we want all this object's fields to be filled either with
342
-                // what we've explicitly set on this model
343
-                // or what we have in the db
344
-                // echo "setting primary key!";
345
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
346
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
-                foreach ($fields_on_model as $field_obj) {
348
-                    if (
349
-                        ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
-                        && $field_obj->get_name() !== $field_name
351
-                    ) {
352
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
-                    }
354
-                }
355
-                // oh this model object has an ID? well make sure its in the entity mapper
356
-                $model->add_to_entity_map($this);
357
-            }
358
-            // let's unset any cache for this field_name from the $_cached_properties property.
359
-            $this->_clear_cached_property($field_name);
360
-        } else {
361
-            throw new EE_Error(
362
-                sprintf(
363
-                    esc_html__(
364
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
-                        'event_espresso'
366
-                    ),
367
-                    $field_name
368
-                )
369
-            );
370
-        }
371
-    }
372
-
373
-
374
-    /**
375
-     * Set custom select values for model.
376
-     *
377
-     * @param array $custom_select_values
378
-     */
379
-    public function setCustomSelectsValues(array $custom_select_values)
380
-    {
381
-        $this->custom_selection_results = $custom_select_values;
382
-    }
383
-
384
-
385
-    /**
386
-     * Returns the custom select value for the provided alias if its set.
387
-     * If not set, returns null.
388
-     *
389
-     * @param string $alias
390
-     * @return string|int|float|null
391
-     */
392
-    public function getCustomSelect($alias)
393
-    {
394
-        return isset($this->custom_selection_results[ $alias ])
395
-            ? $this->custom_selection_results[ $alias ]
396
-            : null;
397
-    }
398
-
399
-
400
-    /**
401
-     * This sets the field value on the db column if it exists for the given $column_name or
402
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
-     *
404
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
-     * @param string $field_name  Must be the exact column name.
406
-     * @param mixed  $field_value The value to set.
407
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
-     * @throws InvalidArgumentException
409
-     * @throws InvalidInterfaceException
410
-     * @throws InvalidDataTypeException
411
-     * @throws EE_Error
412
-     * @throws ReflectionException
413
-     */
414
-    public function set_field_or_extra_meta($field_name, $field_value)
415
-    {
416
-        if ($this->get_model()->has_field($field_name)) {
417
-            $this->set($field_name, $field_value);
418
-            return true;
419
-        }
420
-        // ensure this object is saved first so that extra meta can be properly related.
421
-        $this->save();
422
-        return $this->update_extra_meta($field_name, $field_value);
423
-    }
424
-
425
-
426
-    /**
427
-     * This retrieves the value of the db column set on this class or if that's not present
428
-     * it will attempt to retrieve from extra_meta if found.
429
-     * Example Usage:
430
-     * Via EE_Message child class:
431
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
434
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
-     * value for those extra fields dynamically via the EE_message object.
436
-     *
437
-     * @param  string $field_name expecting the fully qualified field name.
438
-     * @return mixed|null  value for the field if found.  null if not found.
439
-     * @throws ReflectionException
440
-     * @throws InvalidArgumentException
441
-     * @throws InvalidInterfaceException
442
-     * @throws InvalidDataTypeException
443
-     * @throws EE_Error
444
-     */
445
-    public function get_field_or_extra_meta($field_name)
446
-    {
447
-        if ($this->get_model()->has_field($field_name)) {
448
-            $column_value = $this->get($field_name);
449
-        } else {
450
-            // This isn't a column in the main table, let's see if it is in the extra meta.
451
-            $column_value = $this->get_extra_meta($field_name, true, null);
452
-        }
453
-        return $column_value;
454
-    }
455
-
456
-
457
-    /**
458
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
-     *
463
-     * @access public
464
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
-     * @return void
466
-     * @throws InvalidArgumentException
467
-     * @throws InvalidInterfaceException
468
-     * @throws InvalidDataTypeException
469
-     * @throws EE_Error
470
-     * @throws ReflectionException
471
-     */
472
-    public function set_timezone($timezone = '')
473
-    {
474
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
-        // make sure we clear all cached properties because they won't be relevant now
476
-        $this->_clear_cached_properties();
477
-        // make sure we update field settings and the date for all EE_Datetime_Fields
478
-        $model_fields = $this->get_model()->field_settings(false);
479
-        foreach ($model_fields as $field_name => $field_obj) {
480
-            if ($field_obj instanceof EE_Datetime_Field) {
481
-                $field_obj->set_timezone($this->_timezone);
482
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
-                }
485
-            }
486
-        }
487
-    }
488
-
489
-
490
-    /**
491
-     * This just returns whatever is set for the current timezone.
492
-     *
493
-     * @access public
494
-     * @return string timezone string
495
-     */
496
-    public function get_timezone()
497
-    {
498
-        return $this->_timezone;
499
-    }
500
-
501
-
502
-    /**
503
-     * This sets the internal date format to what is sent in to be used as the new default for the class
504
-     * internally instead of wp set date format options
505
-     *
506
-     * @since 4.6
507
-     * @param string $format should be a format recognizable by PHP date() functions.
508
-     */
509
-    public function set_date_format($format)
510
-    {
511
-        $this->_dt_frmt = $format;
512
-        // clear cached_properties because they won't be relevant now.
513
-        $this->_clear_cached_properties();
514
-    }
515
-
516
-
517
-    /**
518
-     * This sets the internal time format string to what is sent in to be used as the new default for the
519
-     * class internally instead of wp set time format options.
520
-     *
521
-     * @since 4.6
522
-     * @param string $format should be a format recognizable by PHP date() functions.
523
-     */
524
-    public function set_time_format($format)
525
-    {
526
-        $this->_tm_frmt = $format;
527
-        // clear cached_properties because they won't be relevant now.
528
-        $this->_clear_cached_properties();
529
-    }
530
-
531
-
532
-    /**
533
-     * This returns the current internal set format for the date and time formats.
534
-     *
535
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
-     *                             where the first value is the date format and the second value is the time format.
537
-     * @return mixed string|array
538
-     */
539
-    public function get_format($full = true)
540
-    {
541
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
-    }
543
-
544
-
545
-    /**
546
-     * cache
547
-     * stores the passed model object on the current model object.
548
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
-     *
550
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
-     *                                       'Registration' associated with this model object
552
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
-     *                                       that could be a payment or a registration)
554
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
-     *                                       items which will be stored in an array on this object
556
-     * @throws ReflectionException
557
-     * @throws InvalidArgumentException
558
-     * @throws InvalidInterfaceException
559
-     * @throws InvalidDataTypeException
560
-     * @throws EE_Error
561
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
-     *                                       related thing, no array)
563
-     */
564
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
-    {
566
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
-        if (! $object_to_cache instanceof EE_Base_Class) {
568
-            return false;
569
-        }
570
-        // also get "how" the object is related, or throw an error
571
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
-            throw new EE_Error(
573
-                sprintf(
574
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
-                    $relationName,
576
-                    get_class($this)
577
-                )
578
-            );
579
-        }
580
-        // how many things are related ?
581
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
-            // if it's a "belongs to" relationship, then there's only one related model object
583
-            // eg, if this is a registration, there's only 1 attendee for it
584
-            // so for these model objects just set it to be cached
585
-            $this->_model_relations[ $relationName ] = $object_to_cache;
586
-            $return = true;
587
-        } else {
588
-            // otherwise, this is the "many" side of a one to many relationship,
589
-            // so we'll add the object to the array of related objects for that type.
590
-            // eg: if this is an event, there are many registrations for that event,
591
-            // so we cache the registrations in an array
592
-            if (! is_array($this->_model_relations[ $relationName ])) {
593
-                // if for some reason, the cached item is a model object,
594
-                // then stick that in the array, otherwise start with an empty array
595
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
-                                                           instanceof
597
-                                                           EE_Base_Class
598
-                    ? array($this->_model_relations[ $relationName ]) : array();
599
-            }
600
-            // first check for a cache_id which is normally empty
601
-            if (! empty($cache_id)) {
602
-                // if the cache_id exists, then it means we are purposely trying to cache this
603
-                // with a known key that can then be used to retrieve the object later on
604
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
-                $return = $cache_id;
606
-            } elseif ($object_to_cache->ID()) {
607
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
608
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
-                $return = $object_to_cache->ID();
610
-            } else {
611
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
613
-                // move the internal pointer to the end of the array
614
-                end($this->_model_relations[ $relationName ]);
615
-                // and grab the key so that we can return it
616
-                $return = key($this->_model_relations[ $relationName ]);
617
-            }
618
-        }
619
-        return $return;
620
-    }
621
-
622
-
623
-    /**
624
-     * For adding an item to the cached_properties property.
625
-     *
626
-     * @access protected
627
-     * @param string      $fieldname the property item the corresponding value is for.
628
-     * @param mixed       $value     The value we are caching.
629
-     * @param string|null $cache_type
630
-     * @return void
631
-     * @throws ReflectionException
632
-     * @throws InvalidArgumentException
633
-     * @throws InvalidInterfaceException
634
-     * @throws InvalidDataTypeException
635
-     * @throws EE_Error
636
-     */
637
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
-    {
639
-        // first make sure this property exists
640
-        $this->get_model()->field_settings_for($fieldname);
641
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
-    }
644
-
645
-
646
-    /**
647
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
-     * This also SETS the cache if we return the actual property!
649
-     *
650
-     * @param string $fieldname        the name of the property we're trying to retrieve
651
-     * @param bool   $pretty
652
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
-     *                                 (in cases where the same property may be used for different outputs
654
-     *                                 - i.e. datetime, money etc.)
655
-     *                                 It can also accept certain pre-defined "schema" strings
656
-     *                                 to define how to output the property.
657
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
-     * @return mixed                   whatever the value for the property is we're retrieving
659
-     * @throws ReflectionException
660
-     * @throws InvalidArgumentException
661
-     * @throws InvalidInterfaceException
662
-     * @throws InvalidDataTypeException
663
-     * @throws EE_Error
664
-     */
665
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
-    {
667
-        // verify the field exists
668
-        $model = $this->get_model();
669
-        $model->field_settings_for($fieldname);
670
-        $cache_type = $pretty ? 'pretty' : 'standard';
671
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
-        }
675
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
-        $this->_set_cached_property($fieldname, $value, $cache_type);
677
-        return $value;
678
-    }
679
-
680
-
681
-    /**
682
-     * If the cache didn't fetch the needed item, this fetches it.
683
-     *
684
-     * @param string $fieldname
685
-     * @param bool   $pretty
686
-     * @param string $extra_cache_ref
687
-     * @return mixed
688
-     * @throws InvalidArgumentException
689
-     * @throws InvalidInterfaceException
690
-     * @throws InvalidDataTypeException
691
-     * @throws EE_Error
692
-     * @throws ReflectionException
693
-     */
694
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
-    {
696
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
697
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
-        if ($field_obj instanceof EE_Datetime_Field) {
699
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
-        }
701
-        if (! isset($this->_fields[ $fieldname ])) {
702
-            $this->_fields[ $fieldname ] = null;
703
-        }
704
-        $value = $pretty
705
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
-        return $value;
708
-    }
709
-
710
-
711
-    /**
712
-     * set timezone, formats, and output for EE_Datetime_Field objects
713
-     *
714
-     * @param \EE_Datetime_Field $datetime_field
715
-     * @param bool               $pretty
716
-     * @param null               $date_or_time
717
-     * @return void
718
-     * @throws InvalidArgumentException
719
-     * @throws InvalidInterfaceException
720
-     * @throws InvalidDataTypeException
721
-     * @throws EE_Error
722
-     */
723
-    protected function _prepare_datetime_field(
724
-        EE_Datetime_Field $datetime_field,
725
-        $pretty = false,
726
-        $date_or_time = null
727
-    ) {
728
-        $datetime_field->set_timezone($this->_timezone);
729
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
730
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
731
-        // set the output returned
732
-        switch ($date_or_time) {
733
-            case 'D':
734
-                $datetime_field->set_date_time_output('date');
735
-                break;
736
-            case 'T':
737
-                $datetime_field->set_date_time_output('time');
738
-                break;
739
-            default:
740
-                $datetime_field->set_date_time_output();
741
-        }
742
-    }
743
-
744
-
745
-    /**
746
-     * This just takes care of clearing out the cached_properties
747
-     *
748
-     * @return void
749
-     */
750
-    protected function _clear_cached_properties()
751
-    {
752
-        $this->_cached_properties = array();
753
-    }
754
-
755
-
756
-    /**
757
-     * This just clears out ONE property if it exists in the cache
758
-     *
759
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
760
-     * @return void
761
-     */
762
-    protected function _clear_cached_property($property_name)
763
-    {
764
-        if (isset($this->_cached_properties[ $property_name ])) {
765
-            unset($this->_cached_properties[ $property_name ]);
766
-        }
767
-    }
768
-
769
-
770
-    /**
771
-     * Ensures that this related thing is a model object.
772
-     *
773
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
774
-     * @param string $model_name   name of the related thing, eg 'Attendee',
775
-     * @return EE_Base_Class
776
-     * @throws ReflectionException
777
-     * @throws InvalidArgumentException
778
-     * @throws InvalidInterfaceException
779
-     * @throws InvalidDataTypeException
780
-     * @throws EE_Error
781
-     */
782
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
783
-    {
784
-        $other_model_instance = self::_get_model_instance_with_name(
785
-            self::_get_model_classname($model_name),
786
-            $this->_timezone
787
-        );
788
-        return $other_model_instance->ensure_is_obj($object_or_id);
789
-    }
790
-
791
-
792
-    /**
793
-     * Forgets the cached model of the given relation Name. So the next time we request it,
794
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
795
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
796
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
797
-     *
798
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
799
-     *                                                     Eg 'Registration'
800
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
801
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
802
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
803
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
804
-     *                                                     this is HasMany or HABTM.
805
-     * @throws ReflectionException
806
-     * @throws InvalidArgumentException
807
-     * @throws InvalidInterfaceException
808
-     * @throws InvalidDataTypeException
809
-     * @throws EE_Error
810
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
811
-     *                                                     relation from all
812
-     */
813
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
814
-    {
815
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
816
-        $index_in_cache = '';
817
-        if (! $relationship_to_model) {
818
-            throw new EE_Error(
819
-                sprintf(
820
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
821
-                    $relationName,
822
-                    get_class($this)
823
-                )
824
-            );
825
-        }
826
-        if ($clear_all) {
827
-            $obj_removed = true;
828
-            $this->_model_relations[ $relationName ] = null;
829
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
830
-            $obj_removed = $this->_model_relations[ $relationName ];
831
-            $this->_model_relations[ $relationName ] = null;
832
-        } else {
833
-            if (
834
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
835
-                && $object_to_remove_or_index_into_array->ID()
836
-            ) {
837
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
838
-                if (
839
-                    is_array($this->_model_relations[ $relationName ])
840
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
841
-                ) {
842
-                    $index_found_at = null;
843
-                    // find this object in the array even though it has a different key
844
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
845
-                        /** @noinspection TypeUnsafeComparisonInspection */
846
-                        if (
847
-                            $obj instanceof EE_Base_Class
848
-                            && (
849
-                                $obj == $object_to_remove_or_index_into_array
850
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
851
-                            )
852
-                        ) {
853
-                            $index_found_at = $index;
854
-                            break;
855
-                        }
856
-                    }
857
-                    if ($index_found_at) {
858
-                        $index_in_cache = $index_found_at;
859
-                    } else {
860
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
861
-                        // if it wasn't in it to begin with. So we're done
862
-                        return $object_to_remove_or_index_into_array;
863
-                    }
864
-                }
865
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
866
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
867
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
868
-                    /** @noinspection TypeUnsafeComparisonInspection */
869
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
870
-                        $index_in_cache = $index;
871
-                    }
872
-                }
873
-            } else {
874
-                $index_in_cache = $object_to_remove_or_index_into_array;
875
-            }
876
-            // supposedly we've found it. But it could just be that the client code
877
-            // provided a bad index/object
878
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
881
-            } else {
882
-                // that thing was never cached anyways.
883
-                $obj_removed = null;
884
-            }
885
-        }
886
-        return $obj_removed;
887
-    }
888
-
889
-
890
-    /**
891
-     * update_cache_after_object_save
892
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
893
-     * obtained after being saved to the db
894
-     *
895
-     * @param string        $relationName       - the type of object that is cached
896
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
897
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
898
-     * @return boolean TRUE on success, FALSE on fail
899
-     * @throws ReflectionException
900
-     * @throws InvalidArgumentException
901
-     * @throws InvalidInterfaceException
902
-     * @throws InvalidDataTypeException
903
-     * @throws EE_Error
904
-     */
905
-    public function update_cache_after_object_save(
906
-        $relationName,
907
-        EE_Base_Class $newly_saved_object,
908
-        $current_cache_id = ''
909
-    ) {
910
-        // verify that incoming object is of the correct type
911
-        $obj_class = 'EE_' . $relationName;
912
-        if ($newly_saved_object instanceof $obj_class) {
913
-            /* @type EE_Base_Class $newly_saved_object */
914
-            // now get the type of relation
915
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
916
-            // if this is a 1:1 relationship
917
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918
-                // then just replace the cached object with the newly saved object
919
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
920
-                return true;
921
-                // or if it's some kind of sordid feral polyamorous relationship...
922
-            }
923
-            if (
924
-                is_array($this->_model_relations[ $relationName ])
925
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
926
-            ) {
927
-                // then remove the current cached item
928
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
929
-                // and cache the newly saved object using it's new ID
930
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
931
-                return true;
932
-            }
933
-        }
934
-        return false;
935
-    }
936
-
937
-
938
-    /**
939
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
940
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
941
-     *
942
-     * @param string $relationName
943
-     * @return EE_Base_Class
944
-     */
945
-    public function get_one_from_cache($relationName)
946
-    {
947
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
948
-            ? $this->_model_relations[ $relationName ]
949
-            : 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 $relationName
962
-     * @throws ReflectionException
963
-     * @throws InvalidArgumentException
964
-     * @throws InvalidInterfaceException
965
-     * @throws InvalidDataTypeException
966
-     * @throws EE_Error
967
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
968
-     */
969
-    public function get_all_from_cache($relationName)
970
-    {
971
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
972
-        // if the result is not an array, but exists, make it an array
973
-        $objects = is_array($objects) ? $objects : array($objects);
974
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
975
-        // basically, if this model object was stored in the session, and these cached model objects
976
-        // already have IDs, let's make sure they're in their model's entity mapper
977
-        // otherwise we will have duplicates next time we call
978
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
979
-        $model = EE_Registry::instance()->load_model($relationName);
980
-        foreach ($objects as $model_object) {
981
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
982
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
983
-                if ($model_object->ID()) {
984
-                    $model->add_to_entity_map($model_object);
985
-                }
986
-            } else {
987
-                throw new EE_Error(
988
-                    sprintf(
989
-                        esc_html__(
990
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
991
-                            'event_espresso'
992
-                        ),
993
-                        $relationName,
994
-                        gettype($model_object)
995
-                    )
996
-                );
997
-            }
998
-        }
999
-        return $objects;
1000
-    }
1001
-
1002
-
1003
-    /**
1004
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1005
-     * matching the given query conditions.
1006
-     *
1007
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1008
-     * @param int   $limit              How many objects to return.
1009
-     * @param array $query_params       Any additional conditions on the query.
1010
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1011
-     *                                  you can indicate just the columns you want returned
1012
-     * @return array|EE_Base_Class[]
1013
-     * @throws ReflectionException
1014
-     * @throws InvalidArgumentException
1015
-     * @throws InvalidInterfaceException
1016
-     * @throws InvalidDataTypeException
1017
-     * @throws EE_Error
1018
-     */
1019
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1020
-    {
1021
-        $model = $this->get_model();
1022
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1023
-            ? $model->get_primary_key_field()->get_name()
1024
-            : $field_to_order_by;
1025
-        $current_value = ! empty($field) ? $this->get($field) : null;
1026
-        if (empty($field) || empty($current_value)) {
1027
-            return array();
1028
-        }
1029
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1030
-    }
1031
-
1032
-
1033
-    /**
1034
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1035
-     * matching the given query conditions.
1036
-     *
1037
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1038
-     * @param int   $limit              How many objects to return.
1039
-     * @param array $query_params       Any additional conditions on the query.
1040
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1041
-     *                                  you can indicate just the columns you want returned
1042
-     * @return array|EE_Base_Class[]
1043
-     * @throws ReflectionException
1044
-     * @throws InvalidArgumentException
1045
-     * @throws InvalidInterfaceException
1046
-     * @throws InvalidDataTypeException
1047
-     * @throws EE_Error
1048
-     */
1049
-    public function previous_x(
1050
-        $field_to_order_by = null,
1051
-        $limit = 1,
1052
-        $query_params = array(),
1053
-        $columns_to_select = null
1054
-    ) {
1055
-        $model = $this->get_model();
1056
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1057
-            ? $model->get_primary_key_field()->get_name()
1058
-            : $field_to_order_by;
1059
-        $current_value = ! empty($field) ? $this->get($field) : null;
1060
-        if (empty($field) || empty($current_value)) {
1061
-            return array();
1062
-        }
1063
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1064
-    }
1065
-
1066
-
1067
-    /**
1068
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1069
-     * matching the given query conditions.
1070
-     *
1071
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1072
-     * @param array $query_params       Any additional conditions on the query.
1073
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1074
-     *                                  you can indicate just the columns you want returned
1075
-     * @return array|EE_Base_Class
1076
-     * @throws ReflectionException
1077
-     * @throws InvalidArgumentException
1078
-     * @throws InvalidInterfaceException
1079
-     * @throws InvalidDataTypeException
1080
-     * @throws EE_Error
1081
-     */
1082
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1083
-    {
1084
-        $model = $this->get_model();
1085
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1086
-            ? $model->get_primary_key_field()->get_name()
1087
-            : $field_to_order_by;
1088
-        $current_value = ! empty($field) ? $this->get($field) : null;
1089
-        if (empty($field) || empty($current_value)) {
1090
-            return array();
1091
-        }
1092
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1093
-    }
1094
-
1095
-
1096
-    /**
1097
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1098
-     * matching the given query conditions.
1099
-     *
1100
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1101
-     * @param array $query_params       Any additional conditions on the query.
1102
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1103
-     *                                  you can indicate just the column you want returned
1104
-     * @return array|EE_Base_Class
1105
-     * @throws ReflectionException
1106
-     * @throws InvalidArgumentException
1107
-     * @throws InvalidInterfaceException
1108
-     * @throws InvalidDataTypeException
1109
-     * @throws EE_Error
1110
-     */
1111
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1112
-    {
1113
-        $model = $this->get_model();
1114
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1115
-            ? $model->get_primary_key_field()->get_name()
1116
-            : $field_to_order_by;
1117
-        $current_value = ! empty($field) ? $this->get($field) : null;
1118
-        if (empty($field) || empty($current_value)) {
1119
-            return array();
1120
-        }
1121
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1122
-    }
1123
-
1124
-
1125
-    /**
1126
-     * Overrides parent because parent expects old models.
1127
-     * This also doesn't do any validation, and won't work for serialized arrays
1128
-     *
1129
-     * @param string $field_name
1130
-     * @param mixed  $field_value_from_db
1131
-     * @throws ReflectionException
1132
-     * @throws InvalidArgumentException
1133
-     * @throws InvalidInterfaceException
1134
-     * @throws InvalidDataTypeException
1135
-     * @throws EE_Error
1136
-     */
1137
-    public function set_from_db($field_name, $field_value_from_db)
1138
-    {
1139
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1140
-        if ($field_obj instanceof EE_Model_Field_Base) {
1141
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1142
-            // eg, a CPT model object could have an entry in the posts table, but no
1143
-            // entry in the meta table. Meaning that all its columns in the meta table
1144
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1145
-            if ($field_value_from_db === null) {
1146
-                if ($field_obj->is_nullable()) {
1147
-                    // if the field allows nulls, then let it be null
1148
-                    $field_value = null;
1149
-                } else {
1150
-                    $field_value = $field_obj->get_default_value();
1151
-                }
1152
-            } else {
1153
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1154
-            }
1155
-            $this->_fields[ $field_name ] = $field_value;
1156
-            $this->_clear_cached_property($field_name);
1157
-        }
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     * verifies that the specified field is of the correct type
1163
-     *
1164
-     * @param string $field_name
1165
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1166
-     *                                (in cases where the same property may be used for different outputs
1167
-     *                                - i.e. datetime, money etc.)
1168
-     * @return mixed
1169
-     * @throws ReflectionException
1170
-     * @throws InvalidArgumentException
1171
-     * @throws InvalidInterfaceException
1172
-     * @throws InvalidDataTypeException
1173
-     * @throws EE_Error
1174
-     */
1175
-    public function get($field_name, $extra_cache_ref = null)
1176
-    {
1177
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * This method simply returns the RAW unprocessed value for the given property in this class
1183
-     *
1184
-     * @param  string $field_name A valid fieldname
1185
-     * @return mixed              Whatever the raw value stored on the property is.
1186
-     * @throws ReflectionException
1187
-     * @throws InvalidArgumentException
1188
-     * @throws InvalidInterfaceException
1189
-     * @throws InvalidDataTypeException
1190
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1191
-     */
1192
-    public function get_raw($field_name)
1193
-    {
1194
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1195
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
-            ? $this->_fields[ $field_name ]->format('U')
1197
-            : $this->_fields[ $field_name ];
1198
-    }
1199
-
1200
-
1201
-    /**
1202
-     * This is used to return the internal DateTime object used for a field that is a
1203
-     * EE_Datetime_Field.
1204
-     *
1205
-     * @param string $field_name               The field name retrieving the DateTime object.
1206
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1207
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1208
-     *                                         EE_Datetime_Field and but the field value is null, then
1209
-     *                                         just null is returned (because that indicates that likely
1210
-     *                                         this field is nullable).
1211
-     * @throws InvalidArgumentException
1212
-     * @throws InvalidDataTypeException
1213
-     * @throws InvalidInterfaceException
1214
-     * @throws ReflectionException
1215
-     */
1216
-    public function get_DateTime_object($field_name)
1217
-    {
1218
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1219
-        if (! $field_settings instanceof EE_Datetime_Field) {
1220
-            EE_Error::add_error(
1221
-                sprintf(
1222
-                    esc_html__(
1223
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1224
-                        'event_espresso'
1225
-                    ),
1226
-                    $field_name
1227
-                ),
1228
-                __FILE__,
1229
-                __FUNCTION__,
1230
-                __LINE__
1231
-            );
1232
-            return false;
1233
-        }
1234
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
-            ? clone $this->_fields[ $field_name ]
1236
-            : null;
1237
-    }
1238
-
1239
-
1240
-    /**
1241
-     * To be used in template to immediately echo out the value, and format it for output.
1242
-     * Eg, should call stripslashes and whatnot before echoing
1243
-     *
1244
-     * @param string $field_name      the name of the field as it appears in the DB
1245
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1246
-     *                                (in cases where the same property may be used for different outputs
1247
-     *                                - i.e. datetime, money etc.)
1248
-     * @return void
1249
-     * @throws ReflectionException
1250
-     * @throws InvalidArgumentException
1251
-     * @throws InvalidInterfaceException
1252
-     * @throws InvalidDataTypeException
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function e($field_name, $extra_cache_ref = null)
1256
-    {
1257
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1258
-    }
1259
-
1260
-
1261
-    /**
1262
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1263
-     * can be easily used as the value of form input.
1264
-     *
1265
-     * @param string $field_name
1266
-     * @return void
1267
-     * @throws ReflectionException
1268
-     * @throws InvalidArgumentException
1269
-     * @throws InvalidInterfaceException
1270
-     * @throws InvalidDataTypeException
1271
-     * @throws EE_Error
1272
-     */
1273
-    public function f($field_name)
1274
-    {
1275
-        $this->e($field_name, 'form_input');
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * Same as `f()` but just returns the value instead of echoing it
1281
-     *
1282
-     * @param string $field_name
1283
-     * @return string
1284
-     * @throws ReflectionException
1285
-     * @throws InvalidArgumentException
1286
-     * @throws InvalidInterfaceException
1287
-     * @throws InvalidDataTypeException
1288
-     * @throws EE_Error
1289
-     */
1290
-    public function get_f($field_name)
1291
-    {
1292
-        return (string) $this->get_pretty($field_name, 'form_input');
1293
-    }
1294
-
1295
-
1296
-    /**
1297
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1298
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1299
-     * to see what options are available.
1300
-     *
1301
-     * @param string $field_name
1302
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1303
-     *                                (in cases where the same property may be used for different outputs
1304
-     *                                - i.e. datetime, money etc.)
1305
-     * @return mixed
1306
-     * @throws ReflectionException
1307
-     * @throws InvalidArgumentException
1308
-     * @throws InvalidInterfaceException
1309
-     * @throws InvalidDataTypeException
1310
-     * @throws EE_Error
1311
-     */
1312
-    public function get_pretty($field_name, $extra_cache_ref = null)
1313
-    {
1314
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1315
-    }
1316
-
1317
-
1318
-    /**
1319
-     * This simply returns the datetime for the given field name
1320
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1321
-     * (and the equivalent e_date, e_time, e_datetime).
1322
-     *
1323
-     * @access   protected
1324
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1325
-     * @param string   $dt_frmt      valid datetime format used for date
1326
-     *                               (if '' then we just use the default on the field,
1327
-     *                               if NULL we use the last-used format)
1328
-     * @param string   $tm_frmt      Same as above except this is for time format
1329
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1330
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1331
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1332
-     *                               if field is not a valid dtt field, or void if echoing
1333
-     * @throws ReflectionException
1334
-     * @throws InvalidArgumentException
1335
-     * @throws InvalidInterfaceException
1336
-     * @throws InvalidDataTypeException
1337
-     * @throws EE_Error
1338
-     */
1339
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1340
-    {
1341
-        // clear cached property
1342
-        $this->_clear_cached_property($field_name);
1343
-        // reset format properties because they are used in get()
1344
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1345
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1346
-        if ($echo) {
1347
-            $this->e($field_name, $date_or_time);
1348
-            return '';
1349
-        }
1350
-        return $this->get($field_name, $date_or_time);
1351
-    }
1352
-
1353
-
1354
-    /**
1355
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
-     * other echoes the pretty value for dtt)
1358
-     *
1359
-     * @param  string $field_name name of model object datetime field holding the value
1360
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
-     * @return string            datetime value formatted
1362
-     * @throws ReflectionException
1363
-     * @throws InvalidArgumentException
1364
-     * @throws InvalidInterfaceException
1365
-     * @throws InvalidDataTypeException
1366
-     * @throws EE_Error
1367
-     */
1368
-    public function get_date($field_name, $format = '')
1369
-    {
1370
-        return $this->_get_datetime($field_name, $format, null, 'D');
1371
-    }
1372
-
1373
-
1374
-    /**
1375
-     * @param        $field_name
1376
-     * @param string $format
1377
-     * @throws ReflectionException
1378
-     * @throws InvalidArgumentException
1379
-     * @throws InvalidInterfaceException
1380
-     * @throws InvalidDataTypeException
1381
-     * @throws EE_Error
1382
-     */
1383
-    public function e_date($field_name, $format = '')
1384
-    {
1385
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1386
-    }
1387
-
1388
-
1389
-    /**
1390
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
-     * other echoes the pretty value for dtt)
1393
-     *
1394
-     * @param  string $field_name name of model object datetime field holding the value
1395
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
-     * @return string             datetime value formatted
1397
-     * @throws ReflectionException
1398
-     * @throws InvalidArgumentException
1399
-     * @throws InvalidInterfaceException
1400
-     * @throws InvalidDataTypeException
1401
-     * @throws EE_Error
1402
-     */
1403
-    public function get_time($field_name, $format = '')
1404
-    {
1405
-        return $this->_get_datetime($field_name, null, $format, 'T');
1406
-    }
1407
-
1408
-
1409
-    /**
1410
-     * @param        $field_name
1411
-     * @param string $format
1412
-     * @throws ReflectionException
1413
-     * @throws InvalidArgumentException
1414
-     * @throws InvalidInterfaceException
1415
-     * @throws InvalidDataTypeException
1416
-     * @throws EE_Error
1417
-     */
1418
-    public function e_time($field_name, $format = '')
1419
-    {
1420
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1421
-    }
1422
-
1423
-
1424
-    /**
1425
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
-     * other echoes the pretty value for dtt)
1428
-     *
1429
-     * @param  string $field_name name of model object datetime field holding the value
1430
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
-     * @return string             datetime value formatted
1433
-     * @throws ReflectionException
1434
-     * @throws InvalidArgumentException
1435
-     * @throws InvalidInterfaceException
1436
-     * @throws InvalidDataTypeException
1437
-     * @throws EE_Error
1438
-     */
1439
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
-    {
1441
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
-    }
1443
-
1444
-
1445
-    /**
1446
-     * @param string $field_name
1447
-     * @param string $dt_frmt
1448
-     * @param string $tm_frmt
1449
-     * @throws ReflectionException
1450
-     * @throws InvalidArgumentException
1451
-     * @throws InvalidInterfaceException
1452
-     * @throws InvalidDataTypeException
1453
-     * @throws EE_Error
1454
-     */
1455
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
-    {
1457
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
-    }
1459
-
1460
-
1461
-    /**
1462
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
-     *
1464
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
-     *                           on the object will be used.
1467
-     * @return string Date and time string in set locale or false if no field exists for the given
1468
-     * @throws ReflectionException
1469
-     * @throws InvalidArgumentException
1470
-     * @throws InvalidInterfaceException
1471
-     * @throws InvalidDataTypeException
1472
-     * @throws EE_Error
1473
-     *                           field name.
1474
-     */
1475
-    public function get_i18n_datetime($field_name, $format = '')
1476
-    {
1477
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
-        return date_i18n(
1479
-            $format,
1480
-            EEH_DTT_Helper::get_timestamp_with_offset(
1481
-                $this->get_raw($field_name),
1482
-                $this->_timezone
1483
-            )
1484
-        );
1485
-    }
1486
-
1487
-
1488
-    /**
1489
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
-     * thrown.
1492
-     *
1493
-     * @param  string $field_name The field name being checked
1494
-     * @throws ReflectionException
1495
-     * @throws InvalidArgumentException
1496
-     * @throws InvalidInterfaceException
1497
-     * @throws InvalidDataTypeException
1498
-     * @throws EE_Error
1499
-     * @return EE_Datetime_Field
1500
-     */
1501
-    protected function _get_dtt_field_settings($field_name)
1502
-    {
1503
-        $field = $this->get_model()->field_settings_for($field_name);
1504
-        // check if field is dtt
1505
-        if ($field instanceof EE_Datetime_Field) {
1506
-            return $field;
1507
-        }
1508
-        throw new EE_Error(
1509
-            sprintf(
1510
-                esc_html__(
1511
-                    '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',
1512
-                    'event_espresso'
1513
-                ),
1514
-                $field_name,
1515
-                self::_get_model_classname(get_class($this))
1516
-            )
1517
-        );
1518
-    }
1519
-
1520
-
1521
-
1522
-
1523
-    /**
1524
-     * NOTE ABOUT BELOW:
1525
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
-     * method and make sure you send the entire datetime value for setting.
1529
-     */
1530
-    /**
1531
-     * sets the time on a datetime property
1532
-     *
1533
-     * @access protected
1534
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
-     * @throws ReflectionException
1537
-     * @throws InvalidArgumentException
1538
-     * @throws InvalidInterfaceException
1539
-     * @throws InvalidDataTypeException
1540
-     * @throws EE_Error
1541
-     */
1542
-    protected function _set_time_for($time, $fieldname)
1543
-    {
1544
-        $this->_set_date_time('T', $time, $fieldname);
1545
-    }
1546
-
1547
-
1548
-    /**
1549
-     * sets the date on a datetime property
1550
-     *
1551
-     * @access protected
1552
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
-     * @throws ReflectionException
1555
-     * @throws InvalidArgumentException
1556
-     * @throws InvalidInterfaceException
1557
-     * @throws InvalidDataTypeException
1558
-     * @throws EE_Error
1559
-     */
1560
-    protected function _set_date_for($date, $fieldname)
1561
-    {
1562
-        $this->_set_date_time('D', $date, $fieldname);
1563
-    }
1564
-
1565
-
1566
-    /**
1567
-     * This takes care of setting a date or time independently on a given model object property. This method also
1568
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1569
-     *
1570
-     * @access protected
1571
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1574
-     *                                        EE_Datetime_Field property)
1575
-     * @throws ReflectionException
1576
-     * @throws InvalidArgumentException
1577
-     * @throws InvalidInterfaceException
1578
-     * @throws InvalidDataTypeException
1579
-     * @throws EE_Error
1580
-     */
1581
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1582
-    {
1583
-        $field = $this->_get_dtt_field_settings($fieldname);
1584
-        $field->set_timezone($this->_timezone);
1585
-        $field->set_date_format($this->_dt_frmt);
1586
-        $field->set_time_format($this->_tm_frmt);
1587
-        switch ($what) {
1588
-            case 'T':
1589
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1590
-                    $datetime_value,
1591
-                    $this->_fields[ $fieldname ]
1592
-                );
1593
-                $this->_has_changes = true;
1594
-                break;
1595
-            case 'D':
1596
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1597
-                    $datetime_value,
1598
-                    $this->_fields[ $fieldname ]
1599
-                );
1600
-                $this->_has_changes = true;
1601
-                break;
1602
-            case 'B':
1603
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1604
-                $this->_has_changes = true;
1605
-                break;
1606
-        }
1607
-        $this->_clear_cached_property($fieldname);
1608
-    }
1609
-
1610
-
1611
-    /**
1612
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
-     * that could lead to some unexpected results!
1616
-     *
1617
-     * @access public
1618
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
-     *                                         value being returned.
1620
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
-     * @param string $prepend                  You can include something to prepend on the timestamp
1623
-     * @param string $append                   You can include something to append on the timestamp
1624
-     * @throws ReflectionException
1625
-     * @throws InvalidArgumentException
1626
-     * @throws InvalidInterfaceException
1627
-     * @throws InvalidDataTypeException
1628
-     * @throws EE_Error
1629
-     * @return string timestamp
1630
-     */
1631
-    public function display_in_my_timezone(
1632
-        $field_name,
1633
-        $callback = 'get_datetime',
1634
-        $args = null,
1635
-        $prepend = '',
1636
-        $append = ''
1637
-    ) {
1638
-        $timezone = EEH_DTT_Helper::get_timezone();
1639
-        if ($timezone === $this->_timezone) {
1640
-            return '';
1641
-        }
1642
-        $original_timezone = $this->_timezone;
1643
-        $this->set_timezone($timezone);
1644
-        $fn = (array) $field_name;
1645
-        $args = array_merge($fn, (array) $args);
1646
-        if (! method_exists($this, $callback)) {
1647
-            throw new EE_Error(
1648
-                sprintf(
1649
-                    esc_html__(
1650
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
-                        'event_espresso'
1652
-                    ),
1653
-                    $callback
1654
-                )
1655
-            );
1656
-        }
1657
-        $args = (array) $args;
1658
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
-        $this->set_timezone($original_timezone);
1660
-        return $return;
1661
-    }
1662
-
1663
-
1664
-    /**
1665
-     * Deletes this model object.
1666
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
-     * override
1668
-     * `EE_Base_Class::_delete` NOT this class.
1669
-     *
1670
-     * @return boolean | int
1671
-     * @throws ReflectionException
1672
-     * @throws InvalidArgumentException
1673
-     * @throws InvalidInterfaceException
1674
-     * @throws InvalidDataTypeException
1675
-     * @throws EE_Error
1676
-     */
1677
-    public function delete()
1678
-    {
1679
-        /**
1680
-         * Called just before the `EE_Base_Class::_delete` method call.
1681
-         * Note:
1682
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
-         * should be aware that `_delete` may not always result in a permanent delete.
1684
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
-         * soft deletes (trash) the object and does not permanently delete it.
1686
-         *
1687
-         * @param EE_Base_Class $model_object about to be 'deleted'
1688
-         */
1689
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
-        $result = $this->_delete();
1691
-        /**
1692
-         * Called just after the `EE_Base_Class::_delete` method call.
1693
-         * Note:
1694
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
-         * should be aware that `_delete` may not always result in a permanent delete.
1696
-         * For example `EE_Soft_Base_Class::_delete`
1697
-         * soft deletes (trash) the object and does not permanently delete it.
1698
-         *
1699
-         * @param EE_Base_Class $model_object that was just 'deleted'
1700
-         * @param boolean       $result
1701
-         */
1702
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
-        return $result;
1704
-    }
1705
-
1706
-
1707
-    /**
1708
-     * Calls the specific delete method for the instantiated class.
1709
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
-     * `EE_Base_Class::delete`
1712
-     *
1713
-     * @return bool|int
1714
-     * @throws ReflectionException
1715
-     * @throws InvalidArgumentException
1716
-     * @throws InvalidInterfaceException
1717
-     * @throws InvalidDataTypeException
1718
-     * @throws EE_Error
1719
-     */
1720
-    protected function _delete()
1721
-    {
1722
-        return $this->delete_permanently();
1723
-    }
1724
-
1725
-
1726
-    /**
1727
-     * Deletes this model object permanently from db
1728
-     * (but keep in mind related models may block the delete and return an error)
1729
-     *
1730
-     * @return bool | int
1731
-     * @throws ReflectionException
1732
-     * @throws InvalidArgumentException
1733
-     * @throws InvalidInterfaceException
1734
-     * @throws InvalidDataTypeException
1735
-     * @throws EE_Error
1736
-     */
1737
-    public function delete_permanently()
1738
-    {
1739
-        /**
1740
-         * Called just before HARD deleting a model object
1741
-         *
1742
-         * @param EE_Base_Class $model_object about to be 'deleted'
1743
-         */
1744
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
-        $model = $this->get_model();
1746
-        $result = $model->delete_permanently_by_ID($this->ID());
1747
-        $this->refresh_cache_of_related_objects();
1748
-        /**
1749
-         * Called just after HARD deleting a model object
1750
-         *
1751
-         * @param EE_Base_Class $model_object that was just 'deleted'
1752
-         * @param boolean       $result
1753
-         */
1754
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
-        return $result;
1756
-    }
1757
-
1758
-
1759
-    /**
1760
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
-     * related model objects
1762
-     *
1763
-     * @throws ReflectionException
1764
-     * @throws InvalidArgumentException
1765
-     * @throws InvalidInterfaceException
1766
-     * @throws InvalidDataTypeException
1767
-     * @throws EE_Error
1768
-     */
1769
-    public function refresh_cache_of_related_objects()
1770
-    {
1771
-        $model = $this->get_model();
1772
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
-            if (! empty($this->_model_relations[ $relation_name ])) {
1774
-                $related_objects = $this->_model_relations[ $relation_name ];
1775
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
-                    // this relation only stores a single model object, not an array
1777
-                    // but let's make it consistent
1778
-                    $related_objects = array($related_objects);
1779
-                }
1780
-                foreach ($related_objects as $related_object) {
1781
-                    // only refresh their cache if they're in memory
1782
-                    if ($related_object instanceof EE_Base_Class) {
1783
-                        $related_object->clear_cache(
1784
-                            $model->get_this_model_name(),
1785
-                            $this
1786
-                        );
1787
-                    }
1788
-                }
1789
-            }
1790
-        }
1791
-    }
1792
-
1793
-
1794
-    /**
1795
-     *        Saves this object to the database. An array may be supplied to set some values on this
1796
-     * object just before saving.
1797
-     *
1798
-     * @access public
1799
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1800
-     *                                 if provided during the save() method (often client code will change the fields'
1801
-     *                                 values before calling save)
1802
-     * @return bool|int|string         1 on a successful update
1803
-     *                                 the ID of the new entry on insert
1804
-     *                                 0 on failure or if the model object isn't allowed to persist
1805
-     *                                 (as determined by EE_Base_Class::allow_persist())
1806
-     * @throws InvalidInterfaceException
1807
-     * @throws InvalidDataTypeException
1808
-     * @throws EE_Error
1809
-     * @throws InvalidArgumentException
1810
-     * @throws ReflectionException
1811
-     * @throws ReflectionException
1812
-     * @throws ReflectionException
1813
-     */
1814
-    public function save($set_cols_n_values = array())
1815
-    {
1816
-        $model = $this->get_model();
1817
-        /**
1818
-         * Filters the fields we're about to save on the model object
1819
-         *
1820
-         * @param array         $set_cols_n_values
1821
-         * @param EE_Base_Class $model_object
1822
-         */
1823
-        $set_cols_n_values = (array) apply_filters(
1824
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
-            $set_cols_n_values,
1826
-            $this
1827
-        );
1828
-        // set attributes as provided in $set_cols_n_values
1829
-        foreach ($set_cols_n_values as $column => $value) {
1830
-            $this->set($column, $value);
1831
-        }
1832
-        // no changes ? then don't do anything
1833
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
-            return 0;
1835
-        }
1836
-        /**
1837
-         * Saving a model object.
1838
-         * Before we perform a save, this action is fired.
1839
-         *
1840
-         * @param EE_Base_Class $model_object the model object about to be saved.
1841
-         */
1842
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
-        if (! $this->allow_persist()) {
1844
-            return 0;
1845
-        }
1846
-        // now get current attribute values
1847
-        $save_cols_n_values = $this->_fields;
1848
-        // if the object already has an ID, update it. Otherwise, insert it
1849
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
-        // They have been
1851
-        $old_assumption_concerning_value_preparation = $model
1852
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1853
-        $model->assume_values_already_prepared_by_model_object(true);
1854
-        // does this model have an autoincrement PK?
1855
-        if ($model->has_primary_key_field()) {
1856
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1857
-                // ok check if it's set, if so: update; if not, insert
1858
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
-                } else {
1861
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
-                    $results = $model->insert($save_cols_n_values);
1863
-                    if ($results) {
1864
-                        // if successful, set the primary key
1865
-                        // but don't use the normal SET method, because it will check if
1866
-                        // an item with the same ID exists in the mapper & db, then
1867
-                        // will find it in the db (because we just added it) and THAT object
1868
-                        // will get added to the mapper before we can add this one!
1869
-                        // but if we just avoid using the SET method, all that headache can be avoided
1870
-                        $pk_field_name = $model->primary_key_name();
1871
-                        $this->_fields[ $pk_field_name ] = $results;
1872
-                        $this->_clear_cached_property($pk_field_name);
1873
-                        $model->add_to_entity_map($this);
1874
-                        $this->_update_cached_related_model_objs_fks();
1875
-                    }
1876
-                }
1877
-            } else {// PK is NOT auto-increment
1878
-                // so check if one like it already exists in the db
1879
-                if ($model->exists_by_ID($this->ID())) {
1880
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1881
-                        throw new EE_Error(
1882
-                            sprintf(
1883
-                                esc_html__(
1884
-                                    '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',
1885
-                                    'event_espresso'
1886
-                                ),
1887
-                                get_class($this),
1888
-                                get_class($model) . '::instance()->add_to_entity_map()',
1889
-                                get_class($model) . '::instance()->get_one_by_ID()',
1890
-                                '<br />'
1891
-                            )
1892
-                        );
1893
-                    }
1894
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
-                } else {
1896
-                    $results = $model->insert($save_cols_n_values);
1897
-                    $this->_update_cached_related_model_objs_fks();
1898
-                }
1899
-            }
1900
-        } else {// there is NO primary key
1901
-            $already_in_db = false;
1902
-            foreach ($model->unique_indexes() as $index) {
1903
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
-                if ($model->exists(array($uniqueness_where_params))) {
1905
-                    $already_in_db = true;
1906
-                }
1907
-            }
1908
-            if ($already_in_db) {
1909
-                $combined_pk_fields_n_values = array_intersect_key(
1910
-                    $save_cols_n_values,
1911
-                    $model->get_combined_primary_key_fields()
1912
-                );
1913
-                $results = $model->update(
1914
-                    $save_cols_n_values,
1915
-                    $combined_pk_fields_n_values
1916
-                );
1917
-            } else {
1918
-                $results = $model->insert($save_cols_n_values);
1919
-            }
1920
-        }
1921
-        // restore the old assumption about values being prepared by the model object
1922
-        $model->assume_values_already_prepared_by_model_object(
1923
-            $old_assumption_concerning_value_preparation
1924
-        );
1925
-        /**
1926
-         * After saving the model object this action is called
1927
-         *
1928
-         * @param EE_Base_Class $model_object which was just saved
1929
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
-         */
1932
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
-        $this->_has_changes = false;
1934
-        return $results;
1935
-    }
1936
-
1937
-
1938
-    /**
1939
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
-     * 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
1944
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
-     *
1947
-     * @return void
1948
-     * @throws ReflectionException
1949
-     * @throws InvalidArgumentException
1950
-     * @throws InvalidInterfaceException
1951
-     * @throws InvalidDataTypeException
1952
-     * @throws EE_Error
1953
-     */
1954
-    protected function _update_cached_related_model_objs_fks()
1955
-    {
1956
-        $model = $this->get_model();
1957
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
-                        $model->get_this_model_name()
1962
-                    );
1963
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
-                    if ($related_model_obj_in_cache->ID()) {
1965
-                        $related_model_obj_in_cache->save();
1966
-                    }
1967
-                }
1968
-            }
1969
-        }
1970
-    }
1971
-
1972
-
1973
-    /**
1974
-     * Saves this model object and its NEW cached relations to the database.
1975
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1977
-     * because otherwise, there's a potential for infinite looping of saving
1978
-     * Saves the cached related model objects, and ensures the relation between them
1979
-     * and this object and properly setup
1980
-     *
1981
-     * @return int ID of new model object on save; 0 on failure+
1982
-     * @throws ReflectionException
1983
-     * @throws InvalidArgumentException
1984
-     * @throws InvalidInterfaceException
1985
-     * @throws InvalidDataTypeException
1986
-     * @throws EE_Error
1987
-     */
1988
-    public function save_new_cached_related_model_objs()
1989
-    {
1990
-        // make sure this has been saved
1991
-        if (! $this->ID()) {
1992
-            $id = $this->save();
1993
-        } else {
1994
-            $id = $this->ID();
1995
-        }
1996
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
-            if ($this->_model_relations[ $relationName ]) {
1999
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
-                /* @var $related_model_obj EE_Base_Class */
2002
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2004
-                    // but ONLY if it DOES NOT exist in the DB
2005
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2006
-                    // if( ! $related_model_obj->ID()){
2007
-                    $this->_add_relation_to($related_model_obj, $relationName);
2008
-                    $related_model_obj->save_new_cached_related_model_objs();
2009
-                    // }
2010
-                } else {
2011
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2013
-                        // but ONLY if it DOES NOT exist in the DB
2014
-                        // if( ! $related_model_obj->ID()){
2015
-                        $this->_add_relation_to($related_model_obj, $relationName);
2016
-                        $related_model_obj->save_new_cached_related_model_objs();
2017
-                        // }
2018
-                    }
2019
-                }
2020
-            }
2021
-        }
2022
-        return $id;
2023
-    }
2024
-
2025
-
2026
-    /**
2027
-     * for getting a model while instantiated.
2028
-     *
2029
-     * @return EEM_Base | EEM_CPT_Base
2030
-     * @throws ReflectionException
2031
-     * @throws InvalidArgumentException
2032
-     * @throws InvalidInterfaceException
2033
-     * @throws InvalidDataTypeException
2034
-     * @throws EE_Error
2035
-     */
2036
-    public function get_model()
2037
-    {
2038
-        if (! $this->_model) {
2039
-            $modelName = self::_get_model_classname(get_class($this));
2040
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
-        } else {
2042
-            $this->_model->set_timezone($this->_timezone);
2043
-        }
2044
-        return $this->_model;
2045
-    }
2046
-
2047
-
2048
-    /**
2049
-     * @param $props_n_values
2050
-     * @param $classname
2051
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
-     * @throws ReflectionException
2053
-     * @throws InvalidArgumentException
2054
-     * @throws InvalidInterfaceException
2055
-     * @throws InvalidDataTypeException
2056
-     * @throws EE_Error
2057
-     */
2058
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
-    {
2060
-        // TODO: will not work for Term_Relationships because they have no PK!
2061
-        $primary_id_ref = self::_get_primary_key_name($classname);
2062
-        if (
2063
-            array_key_exists($primary_id_ref, $props_n_values)
2064
-            && ! empty($props_n_values[ $primary_id_ref ])
2065
-        ) {
2066
-            $id = $props_n_values[ $primary_id_ref ];
2067
-            return self::_get_model($classname)->get_from_entity_map($id);
2068
-        }
2069
-        return false;
2070
-    }
2071
-
2072
-
2073
-    /**
2074
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
-     * 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
2077
-     * we return false.
2078
-     *
2079
-     * @param  array  $props_n_values   incoming array of properties and their values
2080
-     * @param  string $classname        the classname of the child class
2081
-     * @param null    $timezone
2082
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
-     *                                  date_format and the second value is the time format
2084
-     * @return mixed (EE_Base_Class|bool)
2085
-     * @throws InvalidArgumentException
2086
-     * @throws InvalidInterfaceException
2087
-     * @throws InvalidDataTypeException
2088
-     * @throws EE_Error
2089
-     * @throws ReflectionException
2090
-     * @throws ReflectionException
2091
-     * @throws ReflectionException
2092
-     */
2093
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
-    {
2095
-        $existing = null;
2096
-        $model = self::_get_model($classname, $timezone);
2097
-        if ($model->has_primary_key_field()) {
2098
-            $primary_id_ref = self::_get_primary_key_name($classname);
2099
-            if (
2100
-                array_key_exists($primary_id_ref, $props_n_values)
2101
-                && ! empty($props_n_values[ $primary_id_ref ])
2102
-            ) {
2103
-                $existing = $model->get_one_by_ID(
2104
-                    $props_n_values[ $primary_id_ref ]
2105
-                );
2106
-            }
2107
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
-            // no primary key on this model, but there's still a matching item in the DB
2109
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
-                self::_get_model($classname, $timezone)
2111
-                    ->get_index_primary_key_string($props_n_values)
2112
-            );
2113
-        }
2114
-        if ($existing) {
2115
-            // set date formats if present before setting values
2116
-            if (! empty($date_formats) && is_array($date_formats)) {
2117
-                $existing->set_date_format($date_formats[0]);
2118
-                $existing->set_time_format($date_formats[1]);
2119
-            } else {
2120
-                // set default formats for date and time
2121
-                $existing->set_date_format(get_option('date_format'));
2122
-                $existing->set_time_format(get_option('time_format'));
2123
-            }
2124
-            foreach ($props_n_values as $property => $field_value) {
2125
-                $existing->set($property, $field_value);
2126
-            }
2127
-            return $existing;
2128
-        }
2129
-        return false;
2130
-    }
2131
-
2132
-
2133
-    /**
2134
-     * Gets the EEM_*_Model for this class
2135
-     *
2136
-     * @access public now, as this is more convenient
2137
-     * @param      $classname
2138
-     * @param null $timezone
2139
-     * @throws ReflectionException
2140
-     * @throws InvalidArgumentException
2141
-     * @throws InvalidInterfaceException
2142
-     * @throws InvalidDataTypeException
2143
-     * @throws EE_Error
2144
-     * @return EEM_Base
2145
-     */
2146
-    protected static function _get_model($classname, $timezone = null)
2147
-    {
2148
-        // find model for this class
2149
-        if (! $classname) {
2150
-            throw new EE_Error(
2151
-                sprintf(
2152
-                    esc_html__(
2153
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
-                        'event_espresso'
2155
-                    ),
2156
-                    $classname
2157
-                )
2158
-            );
2159
-        }
2160
-        $modelName = self::_get_model_classname($classname);
2161
-        return self::_get_model_instance_with_name($modelName, $timezone);
2162
-    }
2163
-
2164
-
2165
-    /**
2166
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
-     *
2168
-     * @param string $model_classname
2169
-     * @param null   $timezone
2170
-     * @return EEM_Base
2171
-     * @throws ReflectionException
2172
-     * @throws InvalidArgumentException
2173
-     * @throws InvalidInterfaceException
2174
-     * @throws InvalidDataTypeException
2175
-     * @throws EE_Error
2176
-     */
2177
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
-    {
2179
-        $model_classname = str_replace('EEM_', '', $model_classname);
2180
-        $model = EE_Registry::instance()->load_model($model_classname);
2181
-        $model->set_timezone($timezone);
2182
-        return $model;
2183
-    }
2184
-
2185
-
2186
-    /**
2187
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2188
-     * Also works if a model class's classname is provided (eg EE_Registration).
2189
-     *
2190
-     * @param null $model_name
2191
-     * @return string like EEM_Attendee
2192
-     */
2193
-    private static function _get_model_classname($model_name = null)
2194
-    {
2195
-        if (strpos($model_name, 'EE_') === 0) {
2196
-            $model_classname = str_replace('EE_', 'EEM_', $model_name);
2197
-        } else {
2198
-            $model_classname = 'EEM_' . $model_name;
2199
-        }
2200
-        return $model_classname;
2201
-    }
2202
-
2203
-
2204
-    /**
2205
-     * returns the name of the primary key attribute
2206
-     *
2207
-     * @param null $classname
2208
-     * @throws ReflectionException
2209
-     * @throws InvalidArgumentException
2210
-     * @throws InvalidInterfaceException
2211
-     * @throws InvalidDataTypeException
2212
-     * @throws EE_Error
2213
-     * @return string
2214
-     */
2215
-    protected static function _get_primary_key_name($classname = null)
2216
-    {
2217
-        if (! $classname) {
2218
-            throw new EE_Error(
2219
-                sprintf(
2220
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2221
-                    $classname
2222
-                )
2223
-            );
2224
-        }
2225
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2226
-    }
2227
-
2228
-
2229
-    /**
2230
-     * Gets the value of the primary key.
2231
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2232
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2233
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2234
-     *
2235
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2236
-     * @throws ReflectionException
2237
-     * @throws InvalidArgumentException
2238
-     * @throws InvalidInterfaceException
2239
-     * @throws InvalidDataTypeException
2240
-     * @throws EE_Error
2241
-     */
2242
-    public function ID()
2243
-    {
2244
-        $model = $this->get_model();
2245
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2246
-        if ($model->has_primary_key_field()) {
2247
-            return $this->_fields[ $model->primary_key_name() ];
2248
-        }
2249
-        return $model->get_index_primary_key_string($this->_fields);
2250
-    }
2251
-
2252
-
2253
-    /**
2254
-     * @param EE_Base_Class|int|string $otherModelObjectOrID
2255
-     * @param string                   $relationName
2256
-     * @return bool
2257
-     * @throws EE_Error
2258
-     * @throws ReflectionException
2259
-     * @since   $VID:$
2260
-     */
2261
-    public function hasRelation($otherModelObjectOrID, string $relationName): bool
2262
-    {
2263
-        $other_model = self::_get_model_instance_with_name(
2264
-            self::_get_model_classname($relationName),
2265
-            $this->_timezone
2266
-        );
2267
-        $primary_key = $other_model->primary_key_name();
2268
-        /** @var EE_Base_Class $otherModelObject */
2269
-        $otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2270
-        return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2271
-    }
2272
-
2273
-
2274
-    /**
2275
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2276
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2277
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2278
-     *
2279
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2280
-     * @param string $relationName                     eg 'Events','Question',etc.
2281
-     *                                                 an attendee to a group, you also want to specify which role they
2282
-     *                                                 will have in that group. So you would use this parameter to
2283
-     *                                                 specify array('role-column-name'=>'role-id')
2284
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2285
-     *                                                 allow you to further constrict the relation to being added.
2286
-     *                                                 However, keep in mind that the columns (keys) given must match a
2287
-     *                                                 column on the JOIN table and currently only the HABTM models
2288
-     *                                                 accept these additional conditions.  Also remember that if an
2289
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2290
-     *                                                 NEW row is created in the join table.
2291
-     * @param null   $cache_id
2292
-     * @throws ReflectionException
2293
-     * @throws InvalidArgumentException
2294
-     * @throws InvalidInterfaceException
2295
-     * @throws InvalidDataTypeException
2296
-     * @throws EE_Error
2297
-     * @return EE_Base_Class the object the relation was added to
2298
-     */
2299
-    public function _add_relation_to(
2300
-        $otherObjectModelObjectOrID,
2301
-        $relationName,
2302
-        $extra_join_model_fields_n_values = array(),
2303
-        $cache_id = null
2304
-    ) {
2305
-        $model = $this->get_model();
2306
-        // if this thing exists in the DB, save the relation to the DB
2307
-        if ($this->ID()) {
2308
-            $otherObject = $model->add_relationship_to(
2309
-                $this,
2310
-                $otherObjectModelObjectOrID,
2311
-                $relationName,
2312
-                $extra_join_model_fields_n_values
2313
-            );
2314
-            // clear cache so future get_many_related and get_first_related() return new results.
2315
-            $this->clear_cache($relationName, $otherObject, true);
2316
-            if ($otherObject instanceof EE_Base_Class) {
2317
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2318
-            }
2319
-        } else {
2320
-            // this thing doesn't exist in the DB,  so just cache it
2321
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2322
-                throw new EE_Error(
2323
-                    sprintf(
2324
-                        esc_html__(
2325
-                            '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',
2326
-                            'event_espresso'
2327
-                        ),
2328
-                        $otherObjectModelObjectOrID,
2329
-                        get_class($this)
2330
-                    )
2331
-                );
2332
-            }
2333
-            $otherObject = $otherObjectModelObjectOrID;
2334
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2335
-        }
2336
-        if ($otherObject instanceof EE_Base_Class) {
2337
-            // fix the reciprocal relation too
2338
-            if ($otherObject->ID()) {
2339
-                // its saved so assumed relations exist in the DB, so we can just
2340
-                // clear the cache so future queries use the updated info in the DB
2341
-                $otherObject->clear_cache(
2342
-                    $model->get_this_model_name(),
2343
-                    null,
2344
-                    true
2345
-                );
2346
-            } else {
2347
-                // it's not saved, so it caches relations like this
2348
-                $otherObject->cache($model->get_this_model_name(), $this);
2349
-            }
2350
-        }
2351
-        return $otherObject;
2352
-    }
2353
-
2354
-
2355
-    /**
2356
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2357
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2358
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2359
-     * from the cache
2360
-     *
2361
-     * @param mixed  $otherObjectModelObjectOrID
2362
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2363
-     *                to the DB yet
2364
-     * @param string $relationName
2365
-     * @param array  $where_query
2366
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2367
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2368
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2369
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2370
-     *                deleted.
2371
-     * @return EE_Base_Class the relation was removed from
2372
-     * @throws ReflectionException
2373
-     * @throws InvalidArgumentException
2374
-     * @throws InvalidInterfaceException
2375
-     * @throws InvalidDataTypeException
2376
-     * @throws EE_Error
2377
-     */
2378
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2379
-    {
2380
-        if ($this->ID()) {
2381
-            // if this exists in the DB, save the relation change to the DB too
2382
-            $otherObject = $this->get_model()->remove_relationship_to(
2383
-                $this,
2384
-                $otherObjectModelObjectOrID,
2385
-                $relationName,
2386
-                $where_query
2387
-            );
2388
-            $this->clear_cache(
2389
-                $relationName,
2390
-                $otherObject
2391
-            );
2392
-        } else {
2393
-            // this doesn't exist in the DB, just remove it from the cache
2394
-            $otherObject = $this->clear_cache(
2395
-                $relationName,
2396
-                $otherObjectModelObjectOrID
2397
-            );
2398
-        }
2399
-        if ($otherObject instanceof EE_Base_Class) {
2400
-            $otherObject->clear_cache(
2401
-                $this->get_model()->get_this_model_name(),
2402
-                $this
2403
-            );
2404
-        }
2405
-        return $otherObject;
2406
-    }
2407
-
2408
-
2409
-    /**
2410
-     * Removes ALL the related things for the $relationName.
2411
-     *
2412
-     * @param string $relationName
2413
-     * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2414
-     * @return EE_Base_Class
2415
-     * @throws ReflectionException
2416
-     * @throws InvalidArgumentException
2417
-     * @throws InvalidInterfaceException
2418
-     * @throws InvalidDataTypeException
2419
-     * @throws EE_Error
2420
-     */
2421
-    public function _remove_relations($relationName, $where_query_params = array())
2422
-    {
2423
-        if ($this->ID()) {
2424
-            // if this exists in the DB, save the relation change to the DB too
2425
-            $otherObjects = $this->get_model()->remove_relations(
2426
-                $this,
2427
-                $relationName,
2428
-                $where_query_params
2429
-            );
2430
-            $this->clear_cache(
2431
-                $relationName,
2432
-                null,
2433
-                true
2434
-            );
2435
-        } else {
2436
-            // this doesn't exist in the DB, just remove it from the cache
2437
-            $otherObjects = $this->clear_cache(
2438
-                $relationName,
2439
-                null,
2440
-                true
2441
-            );
2442
-        }
2443
-        if (is_array($otherObjects)) {
2444
-            foreach ($otherObjects as $otherObject) {
2445
-                $otherObject->clear_cache(
2446
-                    $this->get_model()->get_this_model_name(),
2447
-                    $this
2448
-                );
2449
-            }
2450
-        }
2451
-        return $otherObjects;
2452
-    }
2453
-
2454
-
2455
-    /**
2456
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2457
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2458
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2459
-     * because we want to get even deleted items etc.
2460
-     *
2461
-     * @param string $relationName key in the model's _model_relations array
2462
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2463
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2464
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2465
-     *                             results if you want IDs
2466
-     * @throws ReflectionException
2467
-     * @throws InvalidArgumentException
2468
-     * @throws InvalidInterfaceException
2469
-     * @throws InvalidDataTypeException
2470
-     * @throws EE_Error
2471
-     */
2472
-    public function get_many_related($relationName, $query_params = array())
2473
-    {
2474
-        if ($this->ID()) {
2475
-            // this exists in the DB, so get the related things from either the cache or the DB
2476
-            // if there are query parameters, forget about caching the related model objects.
2477
-            if ($query_params) {
2478
-                $related_model_objects = $this->get_model()->get_all_related(
2479
-                    $this,
2480
-                    $relationName,
2481
-                    $query_params
2482
-                );
2483
-            } else {
2484
-                // did we already cache the result of this query?
2485
-                $cached_results = $this->get_all_from_cache($relationName);
2486
-                if (! $cached_results) {
2487
-                    $related_model_objects = $this->get_model()->get_all_related(
2488
-                        $this,
2489
-                        $relationName,
2490
-                        $query_params
2491
-                    );
2492
-                    // if no query parameters were passed, then we got all the related model objects
2493
-                    // for that relation. We can cache them then.
2494
-                    foreach ($related_model_objects as $related_model_object) {
2495
-                        $this->cache($relationName, $related_model_object);
2496
-                    }
2497
-                } else {
2498
-                    $related_model_objects = $cached_results;
2499
-                }
2500
-            }
2501
-        } else {
2502
-            // this doesn't exist in the DB, so just get the related things from the cache
2503
-            $related_model_objects = $this->get_all_from_cache($relationName);
2504
-        }
2505
-        return $related_model_objects;
2506
-    }
2507
-
2508
-
2509
-    /**
2510
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2511
-     * unless otherwise specified in the $query_params
2512
-     *
2513
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2514
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2515
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2516
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2517
-     *                               that by the setting $distinct to TRUE;
2518
-     * @return int
2519
-     * @throws ReflectionException
2520
-     * @throws InvalidArgumentException
2521
-     * @throws InvalidInterfaceException
2522
-     * @throws InvalidDataTypeException
2523
-     * @throws EE_Error
2524
-     */
2525
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2526
-    {
2527
-        return $this->get_model()->count_related(
2528
-            $this,
2529
-            $relation_name,
2530
-            $query_params,
2531
-            $field_to_count,
2532
-            $distinct
2533
-        );
2534
-    }
2535
-
2536
-
2537
-    /**
2538
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2539
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2540
-     *
2541
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2542
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2543
-     * @param string $field_to_sum  name of field to count by.
2544
-     *                              By default, uses primary key
2545
-     *                              (which doesn't make much sense, so you should probably change it)
2546
-     * @return int
2547
-     * @throws ReflectionException
2548
-     * @throws InvalidArgumentException
2549
-     * @throws InvalidInterfaceException
2550
-     * @throws InvalidDataTypeException
2551
-     * @throws EE_Error
2552
-     */
2553
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2554
-    {
2555
-        return $this->get_model()->sum_related(
2556
-            $this,
2557
-            $relation_name,
2558
-            $query_params,
2559
-            $field_to_sum
2560
-        );
2561
-    }
2562
-
2563
-
2564
-    /**
2565
-     * Gets the first (ie, one) related model object of the specified type.
2566
-     *
2567
-     * @param string $relationName key in the model's _model_relations array
2568
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2569
-     * @return EE_Base_Class (not an array, a single object)
2570
-     * @throws ReflectionException
2571
-     * @throws InvalidArgumentException
2572
-     * @throws InvalidInterfaceException
2573
-     * @throws InvalidDataTypeException
2574
-     * @throws EE_Error
2575
-     */
2576
-    public function get_first_related($relationName, $query_params = array())
2577
-    {
2578
-        $model = $this->get_model();
2579
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2580
-            // if they've provided some query parameters, don't bother trying to cache the result
2581
-            // also make sure we're not caching the result of get_first_related
2582
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2583
-            if (
2584
-                $query_params
2585
-                || ! $model->related_settings_for($relationName)
2586
-                     instanceof
2587
-                     EE_Belongs_To_Relation
2588
-            ) {
2589
-                $related_model_object = $model->get_first_related(
2590
-                    $this,
2591
-                    $relationName,
2592
-                    $query_params
2593
-                );
2594
-            } else {
2595
-                // first, check if we've already cached the result of this query
2596
-                $cached_result = $this->get_one_from_cache($relationName);
2597
-                if (! $cached_result) {
2598
-                    $related_model_object = $model->get_first_related(
2599
-                        $this,
2600
-                        $relationName,
2601
-                        $query_params
2602
-                    );
2603
-                    $this->cache($relationName, $related_model_object);
2604
-                } else {
2605
-                    $related_model_object = $cached_result;
2606
-                }
2607
-            }
2608
-        } else {
2609
-            $related_model_object = null;
2610
-            // this doesn't exist in the Db,
2611
-            // but maybe the relation is of type belongs to, and so the related thing might
2612
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2613
-                $related_model_object = $model->get_first_related(
2614
-                    $this,
2615
-                    $relationName,
2616
-                    $query_params
2617
-                );
2618
-            }
2619
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2620
-            // just get what's cached on this object
2621
-            if (! $related_model_object) {
2622
-                $related_model_object = $this->get_one_from_cache($relationName);
2623
-            }
2624
-        }
2625
-        return $related_model_object;
2626
-    }
2627
-
2628
-
2629
-    /**
2630
-     * Does a delete on all related objects of type $relationName and removes
2631
-     * the current model object's relation to them. If they can't be deleted (because
2632
-     * of blocking related model objects) does nothing. If the related model objects are
2633
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2634
-     * If this model object doesn't exist yet in the DB, just removes its related things
2635
-     *
2636
-     * @param string $relationName
2637
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2638
-     * @return int how many deleted
2639
-     * @throws ReflectionException
2640
-     * @throws InvalidArgumentException
2641
-     * @throws InvalidInterfaceException
2642
-     * @throws InvalidDataTypeException
2643
-     * @throws EE_Error
2644
-     */
2645
-    public function delete_related($relationName, $query_params = array())
2646
-    {
2647
-        if ($this->ID()) {
2648
-            $count = $this->get_model()->delete_related(
2649
-                $this,
2650
-                $relationName,
2651
-                $query_params
2652
-            );
2653
-        } else {
2654
-            $count = count($this->get_all_from_cache($relationName));
2655
-            $this->clear_cache($relationName, null, true);
2656
-        }
2657
-        return $count;
2658
-    }
2659
-
2660
-
2661
-    /**
2662
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2663
-     * the current model object's relation to them. If they can't be deleted (because
2664
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2665
-     * If the related thing isn't a soft-deletable model object, this function is identical
2666
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2667
-     *
2668
-     * @param string $relationName
2669
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2670
-     * @return int how many deleted (including those soft deleted)
2671
-     * @throws ReflectionException
2672
-     * @throws InvalidArgumentException
2673
-     * @throws InvalidInterfaceException
2674
-     * @throws InvalidDataTypeException
2675
-     * @throws EE_Error
2676
-     */
2677
-    public function delete_related_permanently($relationName, $query_params = array())
2678
-    {
2679
-        if ($this->ID()) {
2680
-            $count = $this->get_model()->delete_related_permanently(
2681
-                $this,
2682
-                $relationName,
2683
-                $query_params
2684
-            );
2685
-        } else {
2686
-            $count = count($this->get_all_from_cache($relationName));
2687
-        }
2688
-        $this->clear_cache($relationName, null, true);
2689
-        return $count;
2690
-    }
2691
-
2692
-
2693
-    /**
2694
-     * is_set
2695
-     * Just a simple utility function children can use for checking if property exists
2696
-     *
2697
-     * @access  public
2698
-     * @param  string $field_name property to check
2699
-     * @return bool                              TRUE if existing,FALSE if not.
2700
-     */
2701
-    public function is_set($field_name)
2702
-    {
2703
-        return isset($this->_fields[ $field_name ]);
2704
-    }
2705
-
2706
-
2707
-    /**
2708
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2709
-     * EE_Error exception if they don't
2710
-     *
2711
-     * @param  mixed (string|array) $properties properties to check
2712
-     * @throws EE_Error
2713
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2714
-     */
2715
-    protected function _property_exists($properties)
2716
-    {
2717
-        foreach ((array) $properties as $property_name) {
2718
-            // first make sure this property exists
2719
-            if (! $this->_fields[ $property_name ]) {
2720
-                throw new EE_Error(
2721
-                    sprintf(
2722
-                        esc_html__(
2723
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2724
-                            'event_espresso'
2725
-                        ),
2726
-                        $property_name
2727
-                    )
2728
-                );
2729
-            }
2730
-        }
2731
-        return true;
2732
-    }
2733
-
2734
-
2735
-    /**
2736
-     * This simply returns an array of model fields for this object
2737
-     *
2738
-     * @return array
2739
-     * @throws ReflectionException
2740
-     * @throws InvalidArgumentException
2741
-     * @throws InvalidInterfaceException
2742
-     * @throws InvalidDataTypeException
2743
-     * @throws EE_Error
2744
-     */
2745
-    public function model_field_array()
2746
-    {
2747
-        $fields = $this->get_model()->field_settings(false);
2748
-        $properties = array();
2749
-        // remove prepended underscore
2750
-        foreach ($fields as $field_name => $settings) {
2751
-            $properties[ $field_name ] = $this->get($field_name);
2752
-        }
2753
-        return $properties;
2754
-    }
2755
-
2756
-
2757
-    /**
2758
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2759
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2760
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2761
-     * Instead of requiring a plugin to extend the EE_Base_Class
2762
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2763
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2764
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2765
-     * and accepts 2 arguments: the object on which the function was called,
2766
-     * and an array of the original arguments passed to the function.
2767
-     * Whatever their callback function returns will be returned by this function.
2768
-     * Example: in functions.php (or in a plugin):
2769
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2770
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2771
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2772
-     *          return $previousReturnValue.$returnString;
2773
-     *      }
2774
-     * require('EE_Answer.class.php');
2775
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2776
-     * echo $answer->my_callback('monkeys',100);
2777
-     * //will output "you called my_callback! and passed args:monkeys,100"
2778
-     *
2779
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2780
-     * @param array  $args       array of original arguments passed to the function
2781
-     * @throws EE_Error
2782
-     * @return mixed whatever the plugin which calls add_filter decides
2783
-     */
2784
-    public function __call($methodName, $args)
2785
-    {
2786
-        $className = get_class($this);
2787
-        $tagName = "FHEE__{$className}__{$methodName}";
2788
-        if (! has_filter($tagName)) {
2789
-            throw new EE_Error(
2790
-                sprintf(
2791
-                    esc_html__(
2792
-                        "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;}",
2793
-                        'event_espresso'
2794
-                    ),
2795
-                    $methodName,
2796
-                    $className,
2797
-                    $tagName
2798
-                )
2799
-            );
2800
-        }
2801
-        return apply_filters($tagName, null, $this, $args);
2802
-    }
2803
-
2804
-
2805
-    /**
2806
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2807
-     * A $previous_value can be specified in case there are many meta rows with the same key
2808
-     *
2809
-     * @param string $meta_key
2810
-     * @param mixed  $meta_value
2811
-     * @param mixed  $previous_value
2812
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2813
-     *                  NOTE: if the values haven't changed, returns 0
2814
-     * @throws InvalidArgumentException
2815
-     * @throws InvalidInterfaceException
2816
-     * @throws InvalidDataTypeException
2817
-     * @throws EE_Error
2818
-     * @throws ReflectionException
2819
-     */
2820
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2821
-    {
2822
-        $query_params = array(
2823
-            array(
2824
-                'EXM_key'  => $meta_key,
2825
-                'OBJ_ID'   => $this->ID(),
2826
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2827
-            ),
2828
-        );
2829
-        if ($previous_value !== null) {
2830
-            $query_params[0]['EXM_value'] = $meta_value;
2831
-        }
2832
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2833
-        if (! $existing_rows_like_that) {
2834
-            return $this->add_extra_meta($meta_key, $meta_value);
2835
-        }
2836
-        foreach ($existing_rows_like_that as $existing_row) {
2837
-            $existing_row->save(array('EXM_value' => $meta_value));
2838
-        }
2839
-        return count($existing_rows_like_that);
2840
-    }
2841
-
2842
-
2843
-    /**
2844
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2845
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2846
-     * extra meta row was entered, false if not
2847
-     *
2848
-     * @param string  $meta_key
2849
-     * @param mixed   $meta_value
2850
-     * @param boolean $unique
2851
-     * @return boolean
2852
-     * @throws InvalidArgumentException
2853
-     * @throws InvalidInterfaceException
2854
-     * @throws InvalidDataTypeException
2855
-     * @throws EE_Error
2856
-     * @throws ReflectionException
2857
-     * @throws ReflectionException
2858
-     */
2859
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2860
-    {
2861
-        if ($unique) {
2862
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2863
-                array(
2864
-                    array(
2865
-                        'EXM_key'  => $meta_key,
2866
-                        'OBJ_ID'   => $this->ID(),
2867
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2868
-                    ),
2869
-                )
2870
-            );
2871
-            if ($existing_extra_meta) {
2872
-                return false;
2873
-            }
2874
-        }
2875
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2876
-            array(
2877
-                'EXM_key'   => $meta_key,
2878
-                'EXM_value' => $meta_value,
2879
-                'OBJ_ID'    => $this->ID(),
2880
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2881
-            )
2882
-        );
2883
-        $new_extra_meta->save();
2884
-        return true;
2885
-    }
2886
-
2887
-
2888
-    /**
2889
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2890
-     * is specified, only deletes extra meta records with that value.
2891
-     *
2892
-     * @param string $meta_key
2893
-     * @param mixed  $meta_value
2894
-     * @return int number of extra meta rows deleted
2895
-     * @throws InvalidArgumentException
2896
-     * @throws InvalidInterfaceException
2897
-     * @throws InvalidDataTypeException
2898
-     * @throws EE_Error
2899
-     * @throws ReflectionException
2900
-     */
2901
-    public function delete_extra_meta($meta_key, $meta_value = null)
2902
-    {
2903
-        $query_params = array(
2904
-            array(
2905
-                'EXM_key'  => $meta_key,
2906
-                'OBJ_ID'   => $this->ID(),
2907
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2908
-            ),
2909
-        );
2910
-        if ($meta_value !== null) {
2911
-            $query_params[0]['EXM_value'] = $meta_value;
2912
-        }
2913
-        return EEM_Extra_Meta::instance()->delete($query_params);
2914
-    }
2915
-
2916
-
2917
-    /**
2918
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2919
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2920
-     * You can specify $default is case you haven't found the extra meta
2921
-     *
2922
-     * @param string  $meta_key
2923
-     * @param boolean $single
2924
-     * @param mixed   $default if we don't find anything, what should we return?
2925
-     * @return mixed single value if $single; array if ! $single
2926
-     * @throws ReflectionException
2927
-     * @throws InvalidArgumentException
2928
-     * @throws InvalidInterfaceException
2929
-     * @throws InvalidDataTypeException
2930
-     * @throws EE_Error
2931
-     */
2932
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2933
-    {
2934
-        if ($single) {
2935
-            $result = $this->get_first_related(
2936
-                'Extra_Meta',
2937
-                array(array('EXM_key' => $meta_key))
2938
-            );
2939
-            if ($result instanceof EE_Extra_Meta) {
2940
-                return $result->value();
2941
-            }
2942
-        } else {
2943
-            $results = $this->get_many_related(
2944
-                'Extra_Meta',
2945
-                array(array('EXM_key' => $meta_key))
2946
-            );
2947
-            if ($results) {
2948
-                $values = array();
2949
-                foreach ($results as $result) {
2950
-                    if ($result instanceof EE_Extra_Meta) {
2951
-                        $values[ $result->ID() ] = $result->value();
2952
-                    }
2953
-                }
2954
-                return $values;
2955
-            }
2956
-        }
2957
-        // if nothing discovered yet return default.
2958
-        return apply_filters(
2959
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2960
-            $default,
2961
-            $meta_key,
2962
-            $single,
2963
-            $this
2964
-        );
2965
-    }
2966
-
2967
-
2968
-    /**
2969
-     * Returns a simple array of all the extra meta associated with this model object.
2970
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2971
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2972
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2973
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2974
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2975
-     * finally the extra meta's value as each sub-value. (eg
2976
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2977
-     *
2978
-     * @param boolean $one_of_each_key
2979
-     * @return array
2980
-     * @throws ReflectionException
2981
-     * @throws InvalidArgumentException
2982
-     * @throws InvalidInterfaceException
2983
-     * @throws InvalidDataTypeException
2984
-     * @throws EE_Error
2985
-     */
2986
-    public function all_extra_meta_array($one_of_each_key = true)
2987
-    {
2988
-        $return_array = array();
2989
-        if ($one_of_each_key) {
2990
-            $extra_meta_objs = $this->get_many_related(
2991
-                'Extra_Meta',
2992
-                array('group_by' => 'EXM_key')
2993
-            );
2994
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2995
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2996
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2997
-                }
2998
-            }
2999
-        } else {
3000
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
3001
-            foreach ($extra_meta_objs as $extra_meta_obj) {
3002
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
3003
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
3004
-                        $return_array[ $extra_meta_obj->key() ] = array();
3005
-                    }
3006
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
3007
-                }
3008
-            }
3009
-        }
3010
-        return $return_array;
3011
-    }
3012
-
3013
-
3014
-    /**
3015
-     * Gets a pretty nice displayable nice for this model object. Often overridden
3016
-     *
3017
-     * @return string
3018
-     * @throws ReflectionException
3019
-     * @throws InvalidArgumentException
3020
-     * @throws InvalidInterfaceException
3021
-     * @throws InvalidDataTypeException
3022
-     * @throws EE_Error
3023
-     */
3024
-    public function name()
3025
-    {
3026
-        // find a field that's not a text field
3027
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3028
-        if ($field_we_can_use) {
3029
-            return $this->get($field_we_can_use->get_name());
3030
-        }
3031
-        $first_few_properties = $this->model_field_array();
3032
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3033
-        $name_parts = array();
3034
-        foreach ($first_few_properties as $name => $value) {
3035
-            $name_parts[] = "$name:$value";
3036
-        }
3037
-        return implode(',', $name_parts);
3038
-    }
3039
-
3040
-
3041
-    /**
3042
-     * in_entity_map
3043
-     * Checks if this model object has been proven to already be in the entity map
3044
-     *
3045
-     * @return boolean
3046
-     * @throws ReflectionException
3047
-     * @throws InvalidArgumentException
3048
-     * @throws InvalidInterfaceException
3049
-     * @throws InvalidDataTypeException
3050
-     * @throws EE_Error
3051
-     */
3052
-    public function in_entity_map()
3053
-    {
3054
-        // well, if we looked, did we find it in the entity map?
3055
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3056
-    }
3057
-
3058
-
3059
-    /**
3060
-     * refresh_from_db
3061
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3062
-     *
3063
-     * @throws ReflectionException
3064
-     * @throws InvalidArgumentException
3065
-     * @throws InvalidInterfaceException
3066
-     * @throws InvalidDataTypeException
3067
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3068
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3069
-     */
3070
-    public function refresh_from_db()
3071
-    {
3072
-        if ($this->ID() && $this->in_entity_map()) {
3073
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3074
-        } else {
3075
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3076
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3077
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3078
-            // absolutely nothing in it for this ID
3079
-            if (WP_DEBUG) {
3080
-                throw new EE_Error(
3081
-                    sprintf(
3082
-                        esc_html__(
3083
-                            '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.',
3084
-                            'event_espresso'
3085
-                        ),
3086
-                        $this->ID(),
3087
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3088
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3089
-                    )
3090
-                );
3091
-            }
3092
-        }
3093
-    }
3094
-
3095
-
3096
-    /**
3097
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3098
-     *
3099
-     * @since 4.9.80.p
3100
-     * @param EE_Model_Field_Base[] $fields
3101
-     * @param string $new_value_sql
3102
-     *      example: 'column_name=123',
3103
-     *      or 'column_name=column_name+1',
3104
-     *      or 'column_name= CASE
3105
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3106
-     *          THEN `column_name` + 5
3107
-     *          ELSE `column_name`
3108
-     *      END'
3109
-     *      Also updates $field on this model object with the latest value from the database.
3110
-     * @return bool
3111
-     * @throws EE_Error
3112
-     * @throws InvalidArgumentException
3113
-     * @throws InvalidDataTypeException
3114
-     * @throws InvalidInterfaceException
3115
-     * @throws ReflectionException
3116
-     */
3117
-    protected function updateFieldsInDB($fields, $new_value_sql)
3118
-    {
3119
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3120
-        // if it wasn't even there to start off.
3121
-        if (! $this->ID()) {
3122
-            $this->save();
3123
-        }
3124
-        global $wpdb;
3125
-        if (empty($fields)) {
3126
-            throw new InvalidArgumentException(
3127
-                esc_html__(
3128
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3129
-                    'event_espresso'
3130
-                )
3131
-            );
3132
-        }
3133
-        $first_field = reset($fields);
3134
-        $table_alias = $first_field->get_table_alias();
3135
-        foreach ($fields as $field) {
3136
-            if ($table_alias !== $field->get_table_alias()) {
3137
-                throw new InvalidArgumentException(
3138
-                    sprintf(
3139
-                        esc_html__(
3140
-                            // @codingStandardsIgnoreStart
3141
-                            '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.',
3142
-                            // @codingStandardsIgnoreEnd
3143
-                            'event_espresso'
3144
-                        ),
3145
-                        $table_alias,
3146
-                        $field->get_table_alias()
3147
-                    )
3148
-                );
3149
-            }
3150
-        }
3151
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3152
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3153
-        $table_pk_value = $this->ID();
3154
-        $table_name = $table_obj->get_table_name();
3155
-        if ($table_obj instanceof EE_Secondary_Table) {
3156
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3157
-        } else {
3158
-            $table_pk_field_name = $table_obj->get_pk_column();
3159
-        }
3160
-
3161
-        $query =
3162
-            "UPDATE `{$table_name}`
337
+				$this->_props_n_values_provided_in_constructor
338
+				&& $field_value
339
+				&& $field_name === $model->primary_key_name()
340
+			) {
341
+				// if so, we want all this object's fields to be filled either with
342
+				// what we've explicitly set on this model
343
+				// or what we have in the db
344
+				// echo "setting primary key!";
345
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
346
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
+				foreach ($fields_on_model as $field_obj) {
348
+					if (
349
+						! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
+						&& $field_obj->get_name() !== $field_name
351
+					) {
352
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
+					}
354
+				}
355
+				// oh this model object has an ID? well make sure its in the entity mapper
356
+				$model->add_to_entity_map($this);
357
+			}
358
+			// let's unset any cache for this field_name from the $_cached_properties property.
359
+			$this->_clear_cached_property($field_name);
360
+		} else {
361
+			throw new EE_Error(
362
+				sprintf(
363
+					esc_html__(
364
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
+						'event_espresso'
366
+					),
367
+					$field_name
368
+				)
369
+			);
370
+		}
371
+	}
372
+
373
+
374
+	/**
375
+	 * Set custom select values for model.
376
+	 *
377
+	 * @param array $custom_select_values
378
+	 */
379
+	public function setCustomSelectsValues(array $custom_select_values)
380
+	{
381
+		$this->custom_selection_results = $custom_select_values;
382
+	}
383
+
384
+
385
+	/**
386
+	 * Returns the custom select value for the provided alias if its set.
387
+	 * If not set, returns null.
388
+	 *
389
+	 * @param string $alias
390
+	 * @return string|int|float|null
391
+	 */
392
+	public function getCustomSelect($alias)
393
+	{
394
+		return isset($this->custom_selection_results[ $alias ])
395
+			? $this->custom_selection_results[ $alias ]
396
+			: null;
397
+	}
398
+
399
+
400
+	/**
401
+	 * This sets the field value on the db column if it exists for the given $column_name or
402
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
+	 *
404
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
+	 * @param string $field_name  Must be the exact column name.
406
+	 * @param mixed  $field_value The value to set.
407
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
+	 * @throws InvalidArgumentException
409
+	 * @throws InvalidInterfaceException
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws EE_Error
412
+	 * @throws ReflectionException
413
+	 */
414
+	public function set_field_or_extra_meta($field_name, $field_value)
415
+	{
416
+		if ($this->get_model()->has_field($field_name)) {
417
+			$this->set($field_name, $field_value);
418
+			return true;
419
+		}
420
+		// ensure this object is saved first so that extra meta can be properly related.
421
+		$this->save();
422
+		return $this->update_extra_meta($field_name, $field_value);
423
+	}
424
+
425
+
426
+	/**
427
+	 * This retrieves the value of the db column set on this class or if that's not present
428
+	 * it will attempt to retrieve from extra_meta if found.
429
+	 * Example Usage:
430
+	 * Via EE_Message child class:
431
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
434
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
+	 * value for those extra fields dynamically via the EE_message object.
436
+	 *
437
+	 * @param  string $field_name expecting the fully qualified field name.
438
+	 * @return mixed|null  value for the field if found.  null if not found.
439
+	 * @throws ReflectionException
440
+	 * @throws InvalidArgumentException
441
+	 * @throws InvalidInterfaceException
442
+	 * @throws InvalidDataTypeException
443
+	 * @throws EE_Error
444
+	 */
445
+	public function get_field_or_extra_meta($field_name)
446
+	{
447
+		if ($this->get_model()->has_field($field_name)) {
448
+			$column_value = $this->get($field_name);
449
+		} else {
450
+			// This isn't a column in the main table, let's see if it is in the extra meta.
451
+			$column_value = $this->get_extra_meta($field_name, true, null);
452
+		}
453
+		return $column_value;
454
+	}
455
+
456
+
457
+	/**
458
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
+	 *
463
+	 * @access public
464
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
+	 * @return void
466
+	 * @throws InvalidArgumentException
467
+	 * @throws InvalidInterfaceException
468
+	 * @throws InvalidDataTypeException
469
+	 * @throws EE_Error
470
+	 * @throws ReflectionException
471
+	 */
472
+	public function set_timezone($timezone = '')
473
+	{
474
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
+		// make sure we clear all cached properties because they won't be relevant now
476
+		$this->_clear_cached_properties();
477
+		// make sure we update field settings and the date for all EE_Datetime_Fields
478
+		$model_fields = $this->get_model()->field_settings(false);
479
+		foreach ($model_fields as $field_name => $field_obj) {
480
+			if ($field_obj instanceof EE_Datetime_Field) {
481
+				$field_obj->set_timezone($this->_timezone);
482
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
+				}
485
+			}
486
+		}
487
+	}
488
+
489
+
490
+	/**
491
+	 * This just returns whatever is set for the current timezone.
492
+	 *
493
+	 * @access public
494
+	 * @return string timezone string
495
+	 */
496
+	public function get_timezone()
497
+	{
498
+		return $this->_timezone;
499
+	}
500
+
501
+
502
+	/**
503
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
504
+	 * internally instead of wp set date format options
505
+	 *
506
+	 * @since 4.6
507
+	 * @param string $format should be a format recognizable by PHP date() functions.
508
+	 */
509
+	public function set_date_format($format)
510
+	{
511
+		$this->_dt_frmt = $format;
512
+		// clear cached_properties because they won't be relevant now.
513
+		$this->_clear_cached_properties();
514
+	}
515
+
516
+
517
+	/**
518
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
519
+	 * class internally instead of wp set time format options.
520
+	 *
521
+	 * @since 4.6
522
+	 * @param string $format should be a format recognizable by PHP date() functions.
523
+	 */
524
+	public function set_time_format($format)
525
+	{
526
+		$this->_tm_frmt = $format;
527
+		// clear cached_properties because they won't be relevant now.
528
+		$this->_clear_cached_properties();
529
+	}
530
+
531
+
532
+	/**
533
+	 * This returns the current internal set format for the date and time formats.
534
+	 *
535
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
+	 *                             where the first value is the date format and the second value is the time format.
537
+	 * @return mixed string|array
538
+	 */
539
+	public function get_format($full = true)
540
+	{
541
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
+	}
543
+
544
+
545
+	/**
546
+	 * cache
547
+	 * stores the passed model object on the current model object.
548
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
+	 *
550
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
+	 *                                       'Registration' associated with this model object
552
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
+	 *                                       that could be a payment or a registration)
554
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
+	 *                                       items which will be stored in an array on this object
556
+	 * @throws ReflectionException
557
+	 * @throws InvalidArgumentException
558
+	 * @throws InvalidInterfaceException
559
+	 * @throws InvalidDataTypeException
560
+	 * @throws EE_Error
561
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
+	 *                                       related thing, no array)
563
+	 */
564
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
+	{
566
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
+		if (! $object_to_cache instanceof EE_Base_Class) {
568
+			return false;
569
+		}
570
+		// also get "how" the object is related, or throw an error
571
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
+			throw new EE_Error(
573
+				sprintf(
574
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
+					$relationName,
576
+					get_class($this)
577
+				)
578
+			);
579
+		}
580
+		// how many things are related ?
581
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
+			// if it's a "belongs to" relationship, then there's only one related model object
583
+			// eg, if this is a registration, there's only 1 attendee for it
584
+			// so for these model objects just set it to be cached
585
+			$this->_model_relations[ $relationName ] = $object_to_cache;
586
+			$return = true;
587
+		} else {
588
+			// otherwise, this is the "many" side of a one to many relationship,
589
+			// so we'll add the object to the array of related objects for that type.
590
+			// eg: if this is an event, there are many registrations for that event,
591
+			// so we cache the registrations in an array
592
+			if (! is_array($this->_model_relations[ $relationName ])) {
593
+				// if for some reason, the cached item is a model object,
594
+				// then stick that in the array, otherwise start with an empty array
595
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
+														   instanceof
597
+														   EE_Base_Class
598
+					? array($this->_model_relations[ $relationName ]) : array();
599
+			}
600
+			// first check for a cache_id which is normally empty
601
+			if (! empty($cache_id)) {
602
+				// if the cache_id exists, then it means we are purposely trying to cache this
603
+				// with a known key that can then be used to retrieve the object later on
604
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
+				$return = $cache_id;
606
+			} elseif ($object_to_cache->ID()) {
607
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
608
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
+				$return = $object_to_cache->ID();
610
+			} else {
611
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
613
+				// move the internal pointer to the end of the array
614
+				end($this->_model_relations[ $relationName ]);
615
+				// and grab the key so that we can return it
616
+				$return = key($this->_model_relations[ $relationName ]);
617
+			}
618
+		}
619
+		return $return;
620
+	}
621
+
622
+
623
+	/**
624
+	 * For adding an item to the cached_properties property.
625
+	 *
626
+	 * @access protected
627
+	 * @param string      $fieldname the property item the corresponding value is for.
628
+	 * @param mixed       $value     The value we are caching.
629
+	 * @param string|null $cache_type
630
+	 * @return void
631
+	 * @throws ReflectionException
632
+	 * @throws InvalidArgumentException
633
+	 * @throws InvalidInterfaceException
634
+	 * @throws InvalidDataTypeException
635
+	 * @throws EE_Error
636
+	 */
637
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
+	{
639
+		// first make sure this property exists
640
+		$this->get_model()->field_settings_for($fieldname);
641
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
+	}
644
+
645
+
646
+	/**
647
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
+	 * This also SETS the cache if we return the actual property!
649
+	 *
650
+	 * @param string $fieldname        the name of the property we're trying to retrieve
651
+	 * @param bool   $pretty
652
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
+	 *                                 (in cases where the same property may be used for different outputs
654
+	 *                                 - i.e. datetime, money etc.)
655
+	 *                                 It can also accept certain pre-defined "schema" strings
656
+	 *                                 to define how to output the property.
657
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
+	 * @return mixed                   whatever the value for the property is we're retrieving
659
+	 * @throws ReflectionException
660
+	 * @throws InvalidArgumentException
661
+	 * @throws InvalidInterfaceException
662
+	 * @throws InvalidDataTypeException
663
+	 * @throws EE_Error
664
+	 */
665
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
+	{
667
+		// verify the field exists
668
+		$model = $this->get_model();
669
+		$model->field_settings_for($fieldname);
670
+		$cache_type = $pretty ? 'pretty' : 'standard';
671
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
+		}
675
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
+		$this->_set_cached_property($fieldname, $value, $cache_type);
677
+		return $value;
678
+	}
679
+
680
+
681
+	/**
682
+	 * If the cache didn't fetch the needed item, this fetches it.
683
+	 *
684
+	 * @param string $fieldname
685
+	 * @param bool   $pretty
686
+	 * @param string $extra_cache_ref
687
+	 * @return mixed
688
+	 * @throws InvalidArgumentException
689
+	 * @throws InvalidInterfaceException
690
+	 * @throws InvalidDataTypeException
691
+	 * @throws EE_Error
692
+	 * @throws ReflectionException
693
+	 */
694
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
+	{
696
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
697
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
+		if ($field_obj instanceof EE_Datetime_Field) {
699
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
+		}
701
+		if (! isset($this->_fields[ $fieldname ])) {
702
+			$this->_fields[ $fieldname ] = null;
703
+		}
704
+		$value = $pretty
705
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
+		return $value;
708
+	}
709
+
710
+
711
+	/**
712
+	 * set timezone, formats, and output for EE_Datetime_Field objects
713
+	 *
714
+	 * @param \EE_Datetime_Field $datetime_field
715
+	 * @param bool               $pretty
716
+	 * @param null               $date_or_time
717
+	 * @return void
718
+	 * @throws InvalidArgumentException
719
+	 * @throws InvalidInterfaceException
720
+	 * @throws InvalidDataTypeException
721
+	 * @throws EE_Error
722
+	 */
723
+	protected function _prepare_datetime_field(
724
+		EE_Datetime_Field $datetime_field,
725
+		$pretty = false,
726
+		$date_or_time = null
727
+	) {
728
+		$datetime_field->set_timezone($this->_timezone);
729
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
730
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
731
+		// set the output returned
732
+		switch ($date_or_time) {
733
+			case 'D':
734
+				$datetime_field->set_date_time_output('date');
735
+				break;
736
+			case 'T':
737
+				$datetime_field->set_date_time_output('time');
738
+				break;
739
+			default:
740
+				$datetime_field->set_date_time_output();
741
+		}
742
+	}
743
+
744
+
745
+	/**
746
+	 * This just takes care of clearing out the cached_properties
747
+	 *
748
+	 * @return void
749
+	 */
750
+	protected function _clear_cached_properties()
751
+	{
752
+		$this->_cached_properties = array();
753
+	}
754
+
755
+
756
+	/**
757
+	 * This just clears out ONE property if it exists in the cache
758
+	 *
759
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
760
+	 * @return void
761
+	 */
762
+	protected function _clear_cached_property($property_name)
763
+	{
764
+		if (isset($this->_cached_properties[ $property_name ])) {
765
+			unset($this->_cached_properties[ $property_name ]);
766
+		}
767
+	}
768
+
769
+
770
+	/**
771
+	 * Ensures that this related thing is a model object.
772
+	 *
773
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
774
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
775
+	 * @return EE_Base_Class
776
+	 * @throws ReflectionException
777
+	 * @throws InvalidArgumentException
778
+	 * @throws InvalidInterfaceException
779
+	 * @throws InvalidDataTypeException
780
+	 * @throws EE_Error
781
+	 */
782
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
783
+	{
784
+		$other_model_instance = self::_get_model_instance_with_name(
785
+			self::_get_model_classname($model_name),
786
+			$this->_timezone
787
+		);
788
+		return $other_model_instance->ensure_is_obj($object_or_id);
789
+	}
790
+
791
+
792
+	/**
793
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
794
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
795
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
796
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
797
+	 *
798
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
799
+	 *                                                     Eg 'Registration'
800
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
801
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
802
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
803
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
804
+	 *                                                     this is HasMany or HABTM.
805
+	 * @throws ReflectionException
806
+	 * @throws InvalidArgumentException
807
+	 * @throws InvalidInterfaceException
808
+	 * @throws InvalidDataTypeException
809
+	 * @throws EE_Error
810
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
811
+	 *                                                     relation from all
812
+	 */
813
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
814
+	{
815
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
816
+		$index_in_cache = '';
817
+		if (! $relationship_to_model) {
818
+			throw new EE_Error(
819
+				sprintf(
820
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
821
+					$relationName,
822
+					get_class($this)
823
+				)
824
+			);
825
+		}
826
+		if ($clear_all) {
827
+			$obj_removed = true;
828
+			$this->_model_relations[ $relationName ] = null;
829
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
830
+			$obj_removed = $this->_model_relations[ $relationName ];
831
+			$this->_model_relations[ $relationName ] = null;
832
+		} else {
833
+			if (
834
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
835
+				&& $object_to_remove_or_index_into_array->ID()
836
+			) {
837
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
838
+				if (
839
+					is_array($this->_model_relations[ $relationName ])
840
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
841
+				) {
842
+					$index_found_at = null;
843
+					// find this object in the array even though it has a different key
844
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
845
+						/** @noinspection TypeUnsafeComparisonInspection */
846
+						if (
847
+							$obj instanceof EE_Base_Class
848
+							&& (
849
+								$obj == $object_to_remove_or_index_into_array
850
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
851
+							)
852
+						) {
853
+							$index_found_at = $index;
854
+							break;
855
+						}
856
+					}
857
+					if ($index_found_at) {
858
+						$index_in_cache = $index_found_at;
859
+					} else {
860
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
861
+						// if it wasn't in it to begin with. So we're done
862
+						return $object_to_remove_or_index_into_array;
863
+					}
864
+				}
865
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
866
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
867
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
868
+					/** @noinspection TypeUnsafeComparisonInspection */
869
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
870
+						$index_in_cache = $index;
871
+					}
872
+				}
873
+			} else {
874
+				$index_in_cache = $object_to_remove_or_index_into_array;
875
+			}
876
+			// supposedly we've found it. But it could just be that the client code
877
+			// provided a bad index/object
878
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
881
+			} else {
882
+				// that thing was never cached anyways.
883
+				$obj_removed = null;
884
+			}
885
+		}
886
+		return $obj_removed;
887
+	}
888
+
889
+
890
+	/**
891
+	 * update_cache_after_object_save
892
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
893
+	 * obtained after being saved to the db
894
+	 *
895
+	 * @param string        $relationName       - the type of object that is cached
896
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
897
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
898
+	 * @return boolean TRUE on success, FALSE on fail
899
+	 * @throws ReflectionException
900
+	 * @throws InvalidArgumentException
901
+	 * @throws InvalidInterfaceException
902
+	 * @throws InvalidDataTypeException
903
+	 * @throws EE_Error
904
+	 */
905
+	public function update_cache_after_object_save(
906
+		$relationName,
907
+		EE_Base_Class $newly_saved_object,
908
+		$current_cache_id = ''
909
+	) {
910
+		// verify that incoming object is of the correct type
911
+		$obj_class = 'EE_' . $relationName;
912
+		if ($newly_saved_object instanceof $obj_class) {
913
+			/* @type EE_Base_Class $newly_saved_object */
914
+			// now get the type of relation
915
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
916
+			// if this is a 1:1 relationship
917
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918
+				// then just replace the cached object with the newly saved object
919
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
920
+				return true;
921
+				// or if it's some kind of sordid feral polyamorous relationship...
922
+			}
923
+			if (
924
+				is_array($this->_model_relations[ $relationName ])
925
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
926
+			) {
927
+				// then remove the current cached item
928
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
929
+				// and cache the newly saved object using it's new ID
930
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
931
+				return true;
932
+			}
933
+		}
934
+		return false;
935
+	}
936
+
937
+
938
+	/**
939
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
940
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
941
+	 *
942
+	 * @param string $relationName
943
+	 * @return EE_Base_Class
944
+	 */
945
+	public function get_one_from_cache($relationName)
946
+	{
947
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
948
+			? $this->_model_relations[ $relationName ]
949
+			: 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 $relationName
962
+	 * @throws ReflectionException
963
+	 * @throws InvalidArgumentException
964
+	 * @throws InvalidInterfaceException
965
+	 * @throws InvalidDataTypeException
966
+	 * @throws EE_Error
967
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
968
+	 */
969
+	public function get_all_from_cache($relationName)
970
+	{
971
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
972
+		// if the result is not an array, but exists, make it an array
973
+		$objects = is_array($objects) ? $objects : array($objects);
974
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
975
+		// basically, if this model object was stored in the session, and these cached model objects
976
+		// already have IDs, let's make sure they're in their model's entity mapper
977
+		// otherwise we will have duplicates next time we call
978
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
979
+		$model = EE_Registry::instance()->load_model($relationName);
980
+		foreach ($objects as $model_object) {
981
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
982
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
983
+				if ($model_object->ID()) {
984
+					$model->add_to_entity_map($model_object);
985
+				}
986
+			} else {
987
+				throw new EE_Error(
988
+					sprintf(
989
+						esc_html__(
990
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
991
+							'event_espresso'
992
+						),
993
+						$relationName,
994
+						gettype($model_object)
995
+					)
996
+				);
997
+			}
998
+		}
999
+		return $objects;
1000
+	}
1001
+
1002
+
1003
+	/**
1004
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1005
+	 * matching the given query conditions.
1006
+	 *
1007
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1008
+	 * @param int   $limit              How many objects to return.
1009
+	 * @param array $query_params       Any additional conditions on the query.
1010
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1011
+	 *                                  you can indicate just the columns you want returned
1012
+	 * @return array|EE_Base_Class[]
1013
+	 * @throws ReflectionException
1014
+	 * @throws InvalidArgumentException
1015
+	 * @throws InvalidInterfaceException
1016
+	 * @throws InvalidDataTypeException
1017
+	 * @throws EE_Error
1018
+	 */
1019
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1020
+	{
1021
+		$model = $this->get_model();
1022
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1023
+			? $model->get_primary_key_field()->get_name()
1024
+			: $field_to_order_by;
1025
+		$current_value = ! empty($field) ? $this->get($field) : null;
1026
+		if (empty($field) || empty($current_value)) {
1027
+			return array();
1028
+		}
1029
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1030
+	}
1031
+
1032
+
1033
+	/**
1034
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1035
+	 * matching the given query conditions.
1036
+	 *
1037
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1038
+	 * @param int   $limit              How many objects to return.
1039
+	 * @param array $query_params       Any additional conditions on the query.
1040
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1041
+	 *                                  you can indicate just the columns you want returned
1042
+	 * @return array|EE_Base_Class[]
1043
+	 * @throws ReflectionException
1044
+	 * @throws InvalidArgumentException
1045
+	 * @throws InvalidInterfaceException
1046
+	 * @throws InvalidDataTypeException
1047
+	 * @throws EE_Error
1048
+	 */
1049
+	public function previous_x(
1050
+		$field_to_order_by = null,
1051
+		$limit = 1,
1052
+		$query_params = array(),
1053
+		$columns_to_select = null
1054
+	) {
1055
+		$model = $this->get_model();
1056
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1057
+			? $model->get_primary_key_field()->get_name()
1058
+			: $field_to_order_by;
1059
+		$current_value = ! empty($field) ? $this->get($field) : null;
1060
+		if (empty($field) || empty($current_value)) {
1061
+			return array();
1062
+		}
1063
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1064
+	}
1065
+
1066
+
1067
+	/**
1068
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1069
+	 * matching the given query conditions.
1070
+	 *
1071
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1072
+	 * @param array $query_params       Any additional conditions on the query.
1073
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1074
+	 *                                  you can indicate just the columns you want returned
1075
+	 * @return array|EE_Base_Class
1076
+	 * @throws ReflectionException
1077
+	 * @throws InvalidArgumentException
1078
+	 * @throws InvalidInterfaceException
1079
+	 * @throws InvalidDataTypeException
1080
+	 * @throws EE_Error
1081
+	 */
1082
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1083
+	{
1084
+		$model = $this->get_model();
1085
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1086
+			? $model->get_primary_key_field()->get_name()
1087
+			: $field_to_order_by;
1088
+		$current_value = ! empty($field) ? $this->get($field) : null;
1089
+		if (empty($field) || empty($current_value)) {
1090
+			return array();
1091
+		}
1092
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1093
+	}
1094
+
1095
+
1096
+	/**
1097
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1098
+	 * matching the given query conditions.
1099
+	 *
1100
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1101
+	 * @param array $query_params       Any additional conditions on the query.
1102
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1103
+	 *                                  you can indicate just the column you want returned
1104
+	 * @return array|EE_Base_Class
1105
+	 * @throws ReflectionException
1106
+	 * @throws InvalidArgumentException
1107
+	 * @throws InvalidInterfaceException
1108
+	 * @throws InvalidDataTypeException
1109
+	 * @throws EE_Error
1110
+	 */
1111
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1112
+	{
1113
+		$model = $this->get_model();
1114
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1115
+			? $model->get_primary_key_field()->get_name()
1116
+			: $field_to_order_by;
1117
+		$current_value = ! empty($field) ? $this->get($field) : null;
1118
+		if (empty($field) || empty($current_value)) {
1119
+			return array();
1120
+		}
1121
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1122
+	}
1123
+
1124
+
1125
+	/**
1126
+	 * Overrides parent because parent expects old models.
1127
+	 * This also doesn't do any validation, and won't work for serialized arrays
1128
+	 *
1129
+	 * @param string $field_name
1130
+	 * @param mixed  $field_value_from_db
1131
+	 * @throws ReflectionException
1132
+	 * @throws InvalidArgumentException
1133
+	 * @throws InvalidInterfaceException
1134
+	 * @throws InvalidDataTypeException
1135
+	 * @throws EE_Error
1136
+	 */
1137
+	public function set_from_db($field_name, $field_value_from_db)
1138
+	{
1139
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1140
+		if ($field_obj instanceof EE_Model_Field_Base) {
1141
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1142
+			// eg, a CPT model object could have an entry in the posts table, but no
1143
+			// entry in the meta table. Meaning that all its columns in the meta table
1144
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1145
+			if ($field_value_from_db === null) {
1146
+				if ($field_obj->is_nullable()) {
1147
+					// if the field allows nulls, then let it be null
1148
+					$field_value = null;
1149
+				} else {
1150
+					$field_value = $field_obj->get_default_value();
1151
+				}
1152
+			} else {
1153
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1154
+			}
1155
+			$this->_fields[ $field_name ] = $field_value;
1156
+			$this->_clear_cached_property($field_name);
1157
+		}
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 * verifies that the specified field is of the correct type
1163
+	 *
1164
+	 * @param string $field_name
1165
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1166
+	 *                                (in cases where the same property may be used for different outputs
1167
+	 *                                - i.e. datetime, money etc.)
1168
+	 * @return mixed
1169
+	 * @throws ReflectionException
1170
+	 * @throws InvalidArgumentException
1171
+	 * @throws InvalidInterfaceException
1172
+	 * @throws InvalidDataTypeException
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	public function get($field_name, $extra_cache_ref = null)
1176
+	{
1177
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1183
+	 *
1184
+	 * @param  string $field_name A valid fieldname
1185
+	 * @return mixed              Whatever the raw value stored on the property is.
1186
+	 * @throws ReflectionException
1187
+	 * @throws InvalidArgumentException
1188
+	 * @throws InvalidInterfaceException
1189
+	 * @throws InvalidDataTypeException
1190
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1191
+	 */
1192
+	public function get_raw($field_name)
1193
+	{
1194
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1195
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
+			? $this->_fields[ $field_name ]->format('U')
1197
+			: $this->_fields[ $field_name ];
1198
+	}
1199
+
1200
+
1201
+	/**
1202
+	 * This is used to return the internal DateTime object used for a field that is a
1203
+	 * EE_Datetime_Field.
1204
+	 *
1205
+	 * @param string $field_name               The field name retrieving the DateTime object.
1206
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1207
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1208
+	 *                                         EE_Datetime_Field and but the field value is null, then
1209
+	 *                                         just null is returned (because that indicates that likely
1210
+	 *                                         this field is nullable).
1211
+	 * @throws InvalidArgumentException
1212
+	 * @throws InvalidDataTypeException
1213
+	 * @throws InvalidInterfaceException
1214
+	 * @throws ReflectionException
1215
+	 */
1216
+	public function get_DateTime_object($field_name)
1217
+	{
1218
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1219
+		if (! $field_settings instanceof EE_Datetime_Field) {
1220
+			EE_Error::add_error(
1221
+				sprintf(
1222
+					esc_html__(
1223
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1224
+						'event_espresso'
1225
+					),
1226
+					$field_name
1227
+				),
1228
+				__FILE__,
1229
+				__FUNCTION__,
1230
+				__LINE__
1231
+			);
1232
+			return false;
1233
+		}
1234
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
+			? clone $this->_fields[ $field_name ]
1236
+			: null;
1237
+	}
1238
+
1239
+
1240
+	/**
1241
+	 * To be used in template to immediately echo out the value, and format it for output.
1242
+	 * Eg, should call stripslashes and whatnot before echoing
1243
+	 *
1244
+	 * @param string $field_name      the name of the field as it appears in the DB
1245
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1246
+	 *                                (in cases where the same property may be used for different outputs
1247
+	 *                                - i.e. datetime, money etc.)
1248
+	 * @return void
1249
+	 * @throws ReflectionException
1250
+	 * @throws InvalidArgumentException
1251
+	 * @throws InvalidInterfaceException
1252
+	 * @throws InvalidDataTypeException
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function e($field_name, $extra_cache_ref = null)
1256
+	{
1257
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1258
+	}
1259
+
1260
+
1261
+	/**
1262
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1263
+	 * can be easily used as the value of form input.
1264
+	 *
1265
+	 * @param string $field_name
1266
+	 * @return void
1267
+	 * @throws ReflectionException
1268
+	 * @throws InvalidArgumentException
1269
+	 * @throws InvalidInterfaceException
1270
+	 * @throws InvalidDataTypeException
1271
+	 * @throws EE_Error
1272
+	 */
1273
+	public function f($field_name)
1274
+	{
1275
+		$this->e($field_name, 'form_input');
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * Same as `f()` but just returns the value instead of echoing it
1281
+	 *
1282
+	 * @param string $field_name
1283
+	 * @return string
1284
+	 * @throws ReflectionException
1285
+	 * @throws InvalidArgumentException
1286
+	 * @throws InvalidInterfaceException
1287
+	 * @throws InvalidDataTypeException
1288
+	 * @throws EE_Error
1289
+	 */
1290
+	public function get_f($field_name)
1291
+	{
1292
+		return (string) $this->get_pretty($field_name, 'form_input');
1293
+	}
1294
+
1295
+
1296
+	/**
1297
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1298
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1299
+	 * to see what options are available.
1300
+	 *
1301
+	 * @param string $field_name
1302
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1303
+	 *                                (in cases where the same property may be used for different outputs
1304
+	 *                                - i.e. datetime, money etc.)
1305
+	 * @return mixed
1306
+	 * @throws ReflectionException
1307
+	 * @throws InvalidArgumentException
1308
+	 * @throws InvalidInterfaceException
1309
+	 * @throws InvalidDataTypeException
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	public function get_pretty($field_name, $extra_cache_ref = null)
1313
+	{
1314
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1315
+	}
1316
+
1317
+
1318
+	/**
1319
+	 * This simply returns the datetime for the given field name
1320
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1321
+	 * (and the equivalent e_date, e_time, e_datetime).
1322
+	 *
1323
+	 * @access   protected
1324
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1325
+	 * @param string   $dt_frmt      valid datetime format used for date
1326
+	 *                               (if '' then we just use the default on the field,
1327
+	 *                               if NULL we use the last-used format)
1328
+	 * @param string   $tm_frmt      Same as above except this is for time format
1329
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1330
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1331
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1332
+	 *                               if field is not a valid dtt field, or void if echoing
1333
+	 * @throws ReflectionException
1334
+	 * @throws InvalidArgumentException
1335
+	 * @throws InvalidInterfaceException
1336
+	 * @throws InvalidDataTypeException
1337
+	 * @throws EE_Error
1338
+	 */
1339
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1340
+	{
1341
+		// clear cached property
1342
+		$this->_clear_cached_property($field_name);
1343
+		// reset format properties because they are used in get()
1344
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1345
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1346
+		if ($echo) {
1347
+			$this->e($field_name, $date_or_time);
1348
+			return '';
1349
+		}
1350
+		return $this->get($field_name, $date_or_time);
1351
+	}
1352
+
1353
+
1354
+	/**
1355
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
+	 * other echoes the pretty value for dtt)
1358
+	 *
1359
+	 * @param  string $field_name name of model object datetime field holding the value
1360
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
+	 * @return string            datetime value formatted
1362
+	 * @throws ReflectionException
1363
+	 * @throws InvalidArgumentException
1364
+	 * @throws InvalidInterfaceException
1365
+	 * @throws InvalidDataTypeException
1366
+	 * @throws EE_Error
1367
+	 */
1368
+	public function get_date($field_name, $format = '')
1369
+	{
1370
+		return $this->_get_datetime($field_name, $format, null, 'D');
1371
+	}
1372
+
1373
+
1374
+	/**
1375
+	 * @param        $field_name
1376
+	 * @param string $format
1377
+	 * @throws ReflectionException
1378
+	 * @throws InvalidArgumentException
1379
+	 * @throws InvalidInterfaceException
1380
+	 * @throws InvalidDataTypeException
1381
+	 * @throws EE_Error
1382
+	 */
1383
+	public function e_date($field_name, $format = '')
1384
+	{
1385
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1386
+	}
1387
+
1388
+
1389
+	/**
1390
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
+	 * other echoes the pretty value for dtt)
1393
+	 *
1394
+	 * @param  string $field_name name of model object datetime field holding the value
1395
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
+	 * @return string             datetime value formatted
1397
+	 * @throws ReflectionException
1398
+	 * @throws InvalidArgumentException
1399
+	 * @throws InvalidInterfaceException
1400
+	 * @throws InvalidDataTypeException
1401
+	 * @throws EE_Error
1402
+	 */
1403
+	public function get_time($field_name, $format = '')
1404
+	{
1405
+		return $this->_get_datetime($field_name, null, $format, 'T');
1406
+	}
1407
+
1408
+
1409
+	/**
1410
+	 * @param        $field_name
1411
+	 * @param string $format
1412
+	 * @throws ReflectionException
1413
+	 * @throws InvalidArgumentException
1414
+	 * @throws InvalidInterfaceException
1415
+	 * @throws InvalidDataTypeException
1416
+	 * @throws EE_Error
1417
+	 */
1418
+	public function e_time($field_name, $format = '')
1419
+	{
1420
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1421
+	}
1422
+
1423
+
1424
+	/**
1425
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
+	 * other echoes the pretty value for dtt)
1428
+	 *
1429
+	 * @param  string $field_name name of model object datetime field holding the value
1430
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
+	 * @return string             datetime value formatted
1433
+	 * @throws ReflectionException
1434
+	 * @throws InvalidArgumentException
1435
+	 * @throws InvalidInterfaceException
1436
+	 * @throws InvalidDataTypeException
1437
+	 * @throws EE_Error
1438
+	 */
1439
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
+	{
1441
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
+	}
1443
+
1444
+
1445
+	/**
1446
+	 * @param string $field_name
1447
+	 * @param string $dt_frmt
1448
+	 * @param string $tm_frmt
1449
+	 * @throws ReflectionException
1450
+	 * @throws InvalidArgumentException
1451
+	 * @throws InvalidInterfaceException
1452
+	 * @throws InvalidDataTypeException
1453
+	 * @throws EE_Error
1454
+	 */
1455
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
+	{
1457
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
+	}
1459
+
1460
+
1461
+	/**
1462
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
+	 *
1464
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
+	 *                           on the object will be used.
1467
+	 * @return string Date and time string in set locale or false if no field exists for the given
1468
+	 * @throws ReflectionException
1469
+	 * @throws InvalidArgumentException
1470
+	 * @throws InvalidInterfaceException
1471
+	 * @throws InvalidDataTypeException
1472
+	 * @throws EE_Error
1473
+	 *                           field name.
1474
+	 */
1475
+	public function get_i18n_datetime($field_name, $format = '')
1476
+	{
1477
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
+		return date_i18n(
1479
+			$format,
1480
+			EEH_DTT_Helper::get_timestamp_with_offset(
1481
+				$this->get_raw($field_name),
1482
+				$this->_timezone
1483
+			)
1484
+		);
1485
+	}
1486
+
1487
+
1488
+	/**
1489
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
+	 * thrown.
1492
+	 *
1493
+	 * @param  string $field_name The field name being checked
1494
+	 * @throws ReflectionException
1495
+	 * @throws InvalidArgumentException
1496
+	 * @throws InvalidInterfaceException
1497
+	 * @throws InvalidDataTypeException
1498
+	 * @throws EE_Error
1499
+	 * @return EE_Datetime_Field
1500
+	 */
1501
+	protected function _get_dtt_field_settings($field_name)
1502
+	{
1503
+		$field = $this->get_model()->field_settings_for($field_name);
1504
+		// check if field is dtt
1505
+		if ($field instanceof EE_Datetime_Field) {
1506
+			return $field;
1507
+		}
1508
+		throw new EE_Error(
1509
+			sprintf(
1510
+				esc_html__(
1511
+					'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',
1512
+					'event_espresso'
1513
+				),
1514
+				$field_name,
1515
+				self::_get_model_classname(get_class($this))
1516
+			)
1517
+		);
1518
+	}
1519
+
1520
+
1521
+
1522
+
1523
+	/**
1524
+	 * NOTE ABOUT BELOW:
1525
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
+	 * method and make sure you send the entire datetime value for setting.
1529
+	 */
1530
+	/**
1531
+	 * sets the time on a datetime property
1532
+	 *
1533
+	 * @access protected
1534
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
+	 * @throws ReflectionException
1537
+	 * @throws InvalidArgumentException
1538
+	 * @throws InvalidInterfaceException
1539
+	 * @throws InvalidDataTypeException
1540
+	 * @throws EE_Error
1541
+	 */
1542
+	protected function _set_time_for($time, $fieldname)
1543
+	{
1544
+		$this->_set_date_time('T', $time, $fieldname);
1545
+	}
1546
+
1547
+
1548
+	/**
1549
+	 * sets the date on a datetime property
1550
+	 *
1551
+	 * @access protected
1552
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
+	 * @throws ReflectionException
1555
+	 * @throws InvalidArgumentException
1556
+	 * @throws InvalidInterfaceException
1557
+	 * @throws InvalidDataTypeException
1558
+	 * @throws EE_Error
1559
+	 */
1560
+	protected function _set_date_for($date, $fieldname)
1561
+	{
1562
+		$this->_set_date_time('D', $date, $fieldname);
1563
+	}
1564
+
1565
+
1566
+	/**
1567
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1568
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1569
+	 *
1570
+	 * @access protected
1571
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1574
+	 *                                        EE_Datetime_Field property)
1575
+	 * @throws ReflectionException
1576
+	 * @throws InvalidArgumentException
1577
+	 * @throws InvalidInterfaceException
1578
+	 * @throws InvalidDataTypeException
1579
+	 * @throws EE_Error
1580
+	 */
1581
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1582
+	{
1583
+		$field = $this->_get_dtt_field_settings($fieldname);
1584
+		$field->set_timezone($this->_timezone);
1585
+		$field->set_date_format($this->_dt_frmt);
1586
+		$field->set_time_format($this->_tm_frmt);
1587
+		switch ($what) {
1588
+			case 'T':
1589
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1590
+					$datetime_value,
1591
+					$this->_fields[ $fieldname ]
1592
+				);
1593
+				$this->_has_changes = true;
1594
+				break;
1595
+			case 'D':
1596
+				$this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1597
+					$datetime_value,
1598
+					$this->_fields[ $fieldname ]
1599
+				);
1600
+				$this->_has_changes = true;
1601
+				break;
1602
+			case 'B':
1603
+				$this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1604
+				$this->_has_changes = true;
1605
+				break;
1606
+		}
1607
+		$this->_clear_cached_property($fieldname);
1608
+	}
1609
+
1610
+
1611
+	/**
1612
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
+	 * that could lead to some unexpected results!
1616
+	 *
1617
+	 * @access public
1618
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
+	 *                                         value being returned.
1620
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1623
+	 * @param string $append                   You can include something to append on the timestamp
1624
+	 * @throws ReflectionException
1625
+	 * @throws InvalidArgumentException
1626
+	 * @throws InvalidInterfaceException
1627
+	 * @throws InvalidDataTypeException
1628
+	 * @throws EE_Error
1629
+	 * @return string timestamp
1630
+	 */
1631
+	public function display_in_my_timezone(
1632
+		$field_name,
1633
+		$callback = 'get_datetime',
1634
+		$args = null,
1635
+		$prepend = '',
1636
+		$append = ''
1637
+	) {
1638
+		$timezone = EEH_DTT_Helper::get_timezone();
1639
+		if ($timezone === $this->_timezone) {
1640
+			return '';
1641
+		}
1642
+		$original_timezone = $this->_timezone;
1643
+		$this->set_timezone($timezone);
1644
+		$fn = (array) $field_name;
1645
+		$args = array_merge($fn, (array) $args);
1646
+		if (! method_exists($this, $callback)) {
1647
+			throw new EE_Error(
1648
+				sprintf(
1649
+					esc_html__(
1650
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
+						'event_espresso'
1652
+					),
1653
+					$callback
1654
+				)
1655
+			);
1656
+		}
1657
+		$args = (array) $args;
1658
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
+		$this->set_timezone($original_timezone);
1660
+		return $return;
1661
+	}
1662
+
1663
+
1664
+	/**
1665
+	 * Deletes this model object.
1666
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
+	 * override
1668
+	 * `EE_Base_Class::_delete` NOT this class.
1669
+	 *
1670
+	 * @return boolean | int
1671
+	 * @throws ReflectionException
1672
+	 * @throws InvalidArgumentException
1673
+	 * @throws InvalidInterfaceException
1674
+	 * @throws InvalidDataTypeException
1675
+	 * @throws EE_Error
1676
+	 */
1677
+	public function delete()
1678
+	{
1679
+		/**
1680
+		 * Called just before the `EE_Base_Class::_delete` method call.
1681
+		 * Note:
1682
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
+		 * should be aware that `_delete` may not always result in a permanent delete.
1684
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
+		 * soft deletes (trash) the object and does not permanently delete it.
1686
+		 *
1687
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1688
+		 */
1689
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
+		$result = $this->_delete();
1691
+		/**
1692
+		 * Called just after the `EE_Base_Class::_delete` method call.
1693
+		 * Note:
1694
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
+		 * should be aware that `_delete` may not always result in a permanent delete.
1696
+		 * For example `EE_Soft_Base_Class::_delete`
1697
+		 * soft deletes (trash) the object and does not permanently delete it.
1698
+		 *
1699
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1700
+		 * @param boolean       $result
1701
+		 */
1702
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
+		return $result;
1704
+	}
1705
+
1706
+
1707
+	/**
1708
+	 * Calls the specific delete method for the instantiated class.
1709
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
+	 * `EE_Base_Class::delete`
1712
+	 *
1713
+	 * @return bool|int
1714
+	 * @throws ReflectionException
1715
+	 * @throws InvalidArgumentException
1716
+	 * @throws InvalidInterfaceException
1717
+	 * @throws InvalidDataTypeException
1718
+	 * @throws EE_Error
1719
+	 */
1720
+	protected function _delete()
1721
+	{
1722
+		return $this->delete_permanently();
1723
+	}
1724
+
1725
+
1726
+	/**
1727
+	 * Deletes this model object permanently from db
1728
+	 * (but keep in mind related models may block the delete and return an error)
1729
+	 *
1730
+	 * @return bool | int
1731
+	 * @throws ReflectionException
1732
+	 * @throws InvalidArgumentException
1733
+	 * @throws InvalidInterfaceException
1734
+	 * @throws InvalidDataTypeException
1735
+	 * @throws EE_Error
1736
+	 */
1737
+	public function delete_permanently()
1738
+	{
1739
+		/**
1740
+		 * Called just before HARD deleting a model object
1741
+		 *
1742
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1743
+		 */
1744
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
+		$model = $this->get_model();
1746
+		$result = $model->delete_permanently_by_ID($this->ID());
1747
+		$this->refresh_cache_of_related_objects();
1748
+		/**
1749
+		 * Called just after HARD deleting a model object
1750
+		 *
1751
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1752
+		 * @param boolean       $result
1753
+		 */
1754
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
+		return $result;
1756
+	}
1757
+
1758
+
1759
+	/**
1760
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
+	 * related model objects
1762
+	 *
1763
+	 * @throws ReflectionException
1764
+	 * @throws InvalidArgumentException
1765
+	 * @throws InvalidInterfaceException
1766
+	 * @throws InvalidDataTypeException
1767
+	 * @throws EE_Error
1768
+	 */
1769
+	public function refresh_cache_of_related_objects()
1770
+	{
1771
+		$model = $this->get_model();
1772
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
+			if (! empty($this->_model_relations[ $relation_name ])) {
1774
+				$related_objects = $this->_model_relations[ $relation_name ];
1775
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
+					// this relation only stores a single model object, not an array
1777
+					// but let's make it consistent
1778
+					$related_objects = array($related_objects);
1779
+				}
1780
+				foreach ($related_objects as $related_object) {
1781
+					// only refresh their cache if they're in memory
1782
+					if ($related_object instanceof EE_Base_Class) {
1783
+						$related_object->clear_cache(
1784
+							$model->get_this_model_name(),
1785
+							$this
1786
+						);
1787
+					}
1788
+				}
1789
+			}
1790
+		}
1791
+	}
1792
+
1793
+
1794
+	/**
1795
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1796
+	 * object just before saving.
1797
+	 *
1798
+	 * @access public
1799
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1800
+	 *                                 if provided during the save() method (often client code will change the fields'
1801
+	 *                                 values before calling save)
1802
+	 * @return bool|int|string         1 on a successful update
1803
+	 *                                 the ID of the new entry on insert
1804
+	 *                                 0 on failure or if the model object isn't allowed to persist
1805
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1806
+	 * @throws InvalidInterfaceException
1807
+	 * @throws InvalidDataTypeException
1808
+	 * @throws EE_Error
1809
+	 * @throws InvalidArgumentException
1810
+	 * @throws ReflectionException
1811
+	 * @throws ReflectionException
1812
+	 * @throws ReflectionException
1813
+	 */
1814
+	public function save($set_cols_n_values = array())
1815
+	{
1816
+		$model = $this->get_model();
1817
+		/**
1818
+		 * Filters the fields we're about to save on the model object
1819
+		 *
1820
+		 * @param array         $set_cols_n_values
1821
+		 * @param EE_Base_Class $model_object
1822
+		 */
1823
+		$set_cols_n_values = (array) apply_filters(
1824
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
+			$set_cols_n_values,
1826
+			$this
1827
+		);
1828
+		// set attributes as provided in $set_cols_n_values
1829
+		foreach ($set_cols_n_values as $column => $value) {
1830
+			$this->set($column, $value);
1831
+		}
1832
+		// no changes ? then don't do anything
1833
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
+			return 0;
1835
+		}
1836
+		/**
1837
+		 * Saving a model object.
1838
+		 * Before we perform a save, this action is fired.
1839
+		 *
1840
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1841
+		 */
1842
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
+		if (! $this->allow_persist()) {
1844
+			return 0;
1845
+		}
1846
+		// now get current attribute values
1847
+		$save_cols_n_values = $this->_fields;
1848
+		// if the object already has an ID, update it. Otherwise, insert it
1849
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
+		// They have been
1851
+		$old_assumption_concerning_value_preparation = $model
1852
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1853
+		$model->assume_values_already_prepared_by_model_object(true);
1854
+		// does this model have an autoincrement PK?
1855
+		if ($model->has_primary_key_field()) {
1856
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1857
+				// ok check if it's set, if so: update; if not, insert
1858
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
+				} else {
1861
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
+					$results = $model->insert($save_cols_n_values);
1863
+					if ($results) {
1864
+						// if successful, set the primary key
1865
+						// but don't use the normal SET method, because it will check if
1866
+						// an item with the same ID exists in the mapper & db, then
1867
+						// will find it in the db (because we just added it) and THAT object
1868
+						// will get added to the mapper before we can add this one!
1869
+						// but if we just avoid using the SET method, all that headache can be avoided
1870
+						$pk_field_name = $model->primary_key_name();
1871
+						$this->_fields[ $pk_field_name ] = $results;
1872
+						$this->_clear_cached_property($pk_field_name);
1873
+						$model->add_to_entity_map($this);
1874
+						$this->_update_cached_related_model_objs_fks();
1875
+					}
1876
+				}
1877
+			} else {// PK is NOT auto-increment
1878
+				// so check if one like it already exists in the db
1879
+				if ($model->exists_by_ID($this->ID())) {
1880
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1881
+						throw new EE_Error(
1882
+							sprintf(
1883
+								esc_html__(
1884
+									'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',
1885
+									'event_espresso'
1886
+								),
1887
+								get_class($this),
1888
+								get_class($model) . '::instance()->add_to_entity_map()',
1889
+								get_class($model) . '::instance()->get_one_by_ID()',
1890
+								'<br />'
1891
+							)
1892
+						);
1893
+					}
1894
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
+				} else {
1896
+					$results = $model->insert($save_cols_n_values);
1897
+					$this->_update_cached_related_model_objs_fks();
1898
+				}
1899
+			}
1900
+		} else {// there is NO primary key
1901
+			$already_in_db = false;
1902
+			foreach ($model->unique_indexes() as $index) {
1903
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
+				if ($model->exists(array($uniqueness_where_params))) {
1905
+					$already_in_db = true;
1906
+				}
1907
+			}
1908
+			if ($already_in_db) {
1909
+				$combined_pk_fields_n_values = array_intersect_key(
1910
+					$save_cols_n_values,
1911
+					$model->get_combined_primary_key_fields()
1912
+				);
1913
+				$results = $model->update(
1914
+					$save_cols_n_values,
1915
+					$combined_pk_fields_n_values
1916
+				);
1917
+			} else {
1918
+				$results = $model->insert($save_cols_n_values);
1919
+			}
1920
+		}
1921
+		// restore the old assumption about values being prepared by the model object
1922
+		$model->assume_values_already_prepared_by_model_object(
1923
+			$old_assumption_concerning_value_preparation
1924
+		);
1925
+		/**
1926
+		 * After saving the model object this action is called
1927
+		 *
1928
+		 * @param EE_Base_Class $model_object which was just saved
1929
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
+		 */
1932
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
+		$this->_has_changes = false;
1934
+		return $results;
1935
+	}
1936
+
1937
+
1938
+	/**
1939
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
+	 * 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
1944
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
+	 *
1947
+	 * @return void
1948
+	 * @throws ReflectionException
1949
+	 * @throws InvalidArgumentException
1950
+	 * @throws InvalidInterfaceException
1951
+	 * @throws InvalidDataTypeException
1952
+	 * @throws EE_Error
1953
+	 */
1954
+	protected function _update_cached_related_model_objs_fks()
1955
+	{
1956
+		$model = $this->get_model();
1957
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
+						$model->get_this_model_name()
1962
+					);
1963
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
+					if ($related_model_obj_in_cache->ID()) {
1965
+						$related_model_obj_in_cache->save();
1966
+					}
1967
+				}
1968
+			}
1969
+		}
1970
+	}
1971
+
1972
+
1973
+	/**
1974
+	 * Saves this model object and its NEW cached relations to the database.
1975
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1977
+	 * because otherwise, there's a potential for infinite looping of saving
1978
+	 * Saves the cached related model objects, and ensures the relation between them
1979
+	 * and this object and properly setup
1980
+	 *
1981
+	 * @return int ID of new model object on save; 0 on failure+
1982
+	 * @throws ReflectionException
1983
+	 * @throws InvalidArgumentException
1984
+	 * @throws InvalidInterfaceException
1985
+	 * @throws InvalidDataTypeException
1986
+	 * @throws EE_Error
1987
+	 */
1988
+	public function save_new_cached_related_model_objs()
1989
+	{
1990
+		// make sure this has been saved
1991
+		if (! $this->ID()) {
1992
+			$id = $this->save();
1993
+		} else {
1994
+			$id = $this->ID();
1995
+		}
1996
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
+			if ($this->_model_relations[ $relationName ]) {
1999
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
+				/* @var $related_model_obj EE_Base_Class */
2002
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2004
+					// but ONLY if it DOES NOT exist in the DB
2005
+					$related_model_obj = $this->_model_relations[ $relationName ];
2006
+					// if( ! $related_model_obj->ID()){
2007
+					$this->_add_relation_to($related_model_obj, $relationName);
2008
+					$related_model_obj->save_new_cached_related_model_objs();
2009
+					// }
2010
+				} else {
2011
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2013
+						// but ONLY if it DOES NOT exist in the DB
2014
+						// if( ! $related_model_obj->ID()){
2015
+						$this->_add_relation_to($related_model_obj, $relationName);
2016
+						$related_model_obj->save_new_cached_related_model_objs();
2017
+						// }
2018
+					}
2019
+				}
2020
+			}
2021
+		}
2022
+		return $id;
2023
+	}
2024
+
2025
+
2026
+	/**
2027
+	 * for getting a model while instantiated.
2028
+	 *
2029
+	 * @return EEM_Base | EEM_CPT_Base
2030
+	 * @throws ReflectionException
2031
+	 * @throws InvalidArgumentException
2032
+	 * @throws InvalidInterfaceException
2033
+	 * @throws InvalidDataTypeException
2034
+	 * @throws EE_Error
2035
+	 */
2036
+	public function get_model()
2037
+	{
2038
+		if (! $this->_model) {
2039
+			$modelName = self::_get_model_classname(get_class($this));
2040
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
+		} else {
2042
+			$this->_model->set_timezone($this->_timezone);
2043
+		}
2044
+		return $this->_model;
2045
+	}
2046
+
2047
+
2048
+	/**
2049
+	 * @param $props_n_values
2050
+	 * @param $classname
2051
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
+	 * @throws ReflectionException
2053
+	 * @throws InvalidArgumentException
2054
+	 * @throws InvalidInterfaceException
2055
+	 * @throws InvalidDataTypeException
2056
+	 * @throws EE_Error
2057
+	 */
2058
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
+	{
2060
+		// TODO: will not work for Term_Relationships because they have no PK!
2061
+		$primary_id_ref = self::_get_primary_key_name($classname);
2062
+		if (
2063
+			array_key_exists($primary_id_ref, $props_n_values)
2064
+			&& ! empty($props_n_values[ $primary_id_ref ])
2065
+		) {
2066
+			$id = $props_n_values[ $primary_id_ref ];
2067
+			return self::_get_model($classname)->get_from_entity_map($id);
2068
+		}
2069
+		return false;
2070
+	}
2071
+
2072
+
2073
+	/**
2074
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
+	 * 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
2077
+	 * we return false.
2078
+	 *
2079
+	 * @param  array  $props_n_values   incoming array of properties and their values
2080
+	 * @param  string $classname        the classname of the child class
2081
+	 * @param null    $timezone
2082
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
+	 *                                  date_format and the second value is the time format
2084
+	 * @return mixed (EE_Base_Class|bool)
2085
+	 * @throws InvalidArgumentException
2086
+	 * @throws InvalidInterfaceException
2087
+	 * @throws InvalidDataTypeException
2088
+	 * @throws EE_Error
2089
+	 * @throws ReflectionException
2090
+	 * @throws ReflectionException
2091
+	 * @throws ReflectionException
2092
+	 */
2093
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
+	{
2095
+		$existing = null;
2096
+		$model = self::_get_model($classname, $timezone);
2097
+		if ($model->has_primary_key_field()) {
2098
+			$primary_id_ref = self::_get_primary_key_name($classname);
2099
+			if (
2100
+				array_key_exists($primary_id_ref, $props_n_values)
2101
+				&& ! empty($props_n_values[ $primary_id_ref ])
2102
+			) {
2103
+				$existing = $model->get_one_by_ID(
2104
+					$props_n_values[ $primary_id_ref ]
2105
+				);
2106
+			}
2107
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
+			// no primary key on this model, but there's still a matching item in the DB
2109
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
+				self::_get_model($classname, $timezone)
2111
+					->get_index_primary_key_string($props_n_values)
2112
+			);
2113
+		}
2114
+		if ($existing) {
2115
+			// set date formats if present before setting values
2116
+			if (! empty($date_formats) && is_array($date_formats)) {
2117
+				$existing->set_date_format($date_formats[0]);
2118
+				$existing->set_time_format($date_formats[1]);
2119
+			} else {
2120
+				// set default formats for date and time
2121
+				$existing->set_date_format(get_option('date_format'));
2122
+				$existing->set_time_format(get_option('time_format'));
2123
+			}
2124
+			foreach ($props_n_values as $property => $field_value) {
2125
+				$existing->set($property, $field_value);
2126
+			}
2127
+			return $existing;
2128
+		}
2129
+		return false;
2130
+	}
2131
+
2132
+
2133
+	/**
2134
+	 * Gets the EEM_*_Model for this class
2135
+	 *
2136
+	 * @access public now, as this is more convenient
2137
+	 * @param      $classname
2138
+	 * @param null $timezone
2139
+	 * @throws ReflectionException
2140
+	 * @throws InvalidArgumentException
2141
+	 * @throws InvalidInterfaceException
2142
+	 * @throws InvalidDataTypeException
2143
+	 * @throws EE_Error
2144
+	 * @return EEM_Base
2145
+	 */
2146
+	protected static function _get_model($classname, $timezone = null)
2147
+	{
2148
+		// find model for this class
2149
+		if (! $classname) {
2150
+			throw new EE_Error(
2151
+				sprintf(
2152
+					esc_html__(
2153
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
+						'event_espresso'
2155
+					),
2156
+					$classname
2157
+				)
2158
+			);
2159
+		}
2160
+		$modelName = self::_get_model_classname($classname);
2161
+		return self::_get_model_instance_with_name($modelName, $timezone);
2162
+	}
2163
+
2164
+
2165
+	/**
2166
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
+	 *
2168
+	 * @param string $model_classname
2169
+	 * @param null   $timezone
2170
+	 * @return EEM_Base
2171
+	 * @throws ReflectionException
2172
+	 * @throws InvalidArgumentException
2173
+	 * @throws InvalidInterfaceException
2174
+	 * @throws InvalidDataTypeException
2175
+	 * @throws EE_Error
2176
+	 */
2177
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
+	{
2179
+		$model_classname = str_replace('EEM_', '', $model_classname);
2180
+		$model = EE_Registry::instance()->load_model($model_classname);
2181
+		$model->set_timezone($timezone);
2182
+		return $model;
2183
+	}
2184
+
2185
+
2186
+	/**
2187
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2188
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2189
+	 *
2190
+	 * @param null $model_name
2191
+	 * @return string like EEM_Attendee
2192
+	 */
2193
+	private static function _get_model_classname($model_name = null)
2194
+	{
2195
+		if (strpos($model_name, 'EE_') === 0) {
2196
+			$model_classname = str_replace('EE_', 'EEM_', $model_name);
2197
+		} else {
2198
+			$model_classname = 'EEM_' . $model_name;
2199
+		}
2200
+		return $model_classname;
2201
+	}
2202
+
2203
+
2204
+	/**
2205
+	 * returns the name of the primary key attribute
2206
+	 *
2207
+	 * @param null $classname
2208
+	 * @throws ReflectionException
2209
+	 * @throws InvalidArgumentException
2210
+	 * @throws InvalidInterfaceException
2211
+	 * @throws InvalidDataTypeException
2212
+	 * @throws EE_Error
2213
+	 * @return string
2214
+	 */
2215
+	protected static function _get_primary_key_name($classname = null)
2216
+	{
2217
+		if (! $classname) {
2218
+			throw new EE_Error(
2219
+				sprintf(
2220
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2221
+					$classname
2222
+				)
2223
+			);
2224
+		}
2225
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2226
+	}
2227
+
2228
+
2229
+	/**
2230
+	 * Gets the value of the primary key.
2231
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2232
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2233
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2234
+	 *
2235
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2236
+	 * @throws ReflectionException
2237
+	 * @throws InvalidArgumentException
2238
+	 * @throws InvalidInterfaceException
2239
+	 * @throws InvalidDataTypeException
2240
+	 * @throws EE_Error
2241
+	 */
2242
+	public function ID()
2243
+	{
2244
+		$model = $this->get_model();
2245
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2246
+		if ($model->has_primary_key_field()) {
2247
+			return $this->_fields[ $model->primary_key_name() ];
2248
+		}
2249
+		return $model->get_index_primary_key_string($this->_fields);
2250
+	}
2251
+
2252
+
2253
+	/**
2254
+	 * @param EE_Base_Class|int|string $otherModelObjectOrID
2255
+	 * @param string                   $relationName
2256
+	 * @return bool
2257
+	 * @throws EE_Error
2258
+	 * @throws ReflectionException
2259
+	 * @since   $VID:$
2260
+	 */
2261
+	public function hasRelation($otherModelObjectOrID, string $relationName): bool
2262
+	{
2263
+		$other_model = self::_get_model_instance_with_name(
2264
+			self::_get_model_classname($relationName),
2265
+			$this->_timezone
2266
+		);
2267
+		$primary_key = $other_model->primary_key_name();
2268
+		/** @var EE_Base_Class $otherModelObject */
2269
+		$otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2270
+		return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2271
+	}
2272
+
2273
+
2274
+	/**
2275
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2276
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2277
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2278
+	 *
2279
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2280
+	 * @param string $relationName                     eg 'Events','Question',etc.
2281
+	 *                                                 an attendee to a group, you also want to specify which role they
2282
+	 *                                                 will have in that group. So you would use this parameter to
2283
+	 *                                                 specify array('role-column-name'=>'role-id')
2284
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2285
+	 *                                                 allow you to further constrict the relation to being added.
2286
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2287
+	 *                                                 column on the JOIN table and currently only the HABTM models
2288
+	 *                                                 accept these additional conditions.  Also remember that if an
2289
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2290
+	 *                                                 NEW row is created in the join table.
2291
+	 * @param null   $cache_id
2292
+	 * @throws ReflectionException
2293
+	 * @throws InvalidArgumentException
2294
+	 * @throws InvalidInterfaceException
2295
+	 * @throws InvalidDataTypeException
2296
+	 * @throws EE_Error
2297
+	 * @return EE_Base_Class the object the relation was added to
2298
+	 */
2299
+	public function _add_relation_to(
2300
+		$otherObjectModelObjectOrID,
2301
+		$relationName,
2302
+		$extra_join_model_fields_n_values = array(),
2303
+		$cache_id = null
2304
+	) {
2305
+		$model = $this->get_model();
2306
+		// if this thing exists in the DB, save the relation to the DB
2307
+		if ($this->ID()) {
2308
+			$otherObject = $model->add_relationship_to(
2309
+				$this,
2310
+				$otherObjectModelObjectOrID,
2311
+				$relationName,
2312
+				$extra_join_model_fields_n_values
2313
+			);
2314
+			// clear cache so future get_many_related and get_first_related() return new results.
2315
+			$this->clear_cache($relationName, $otherObject, true);
2316
+			if ($otherObject instanceof EE_Base_Class) {
2317
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2318
+			}
2319
+		} else {
2320
+			// this thing doesn't exist in the DB,  so just cache it
2321
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2322
+				throw new EE_Error(
2323
+					sprintf(
2324
+						esc_html__(
2325
+							'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',
2326
+							'event_espresso'
2327
+						),
2328
+						$otherObjectModelObjectOrID,
2329
+						get_class($this)
2330
+					)
2331
+				);
2332
+			}
2333
+			$otherObject = $otherObjectModelObjectOrID;
2334
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2335
+		}
2336
+		if ($otherObject instanceof EE_Base_Class) {
2337
+			// fix the reciprocal relation too
2338
+			if ($otherObject->ID()) {
2339
+				// its saved so assumed relations exist in the DB, so we can just
2340
+				// clear the cache so future queries use the updated info in the DB
2341
+				$otherObject->clear_cache(
2342
+					$model->get_this_model_name(),
2343
+					null,
2344
+					true
2345
+				);
2346
+			} else {
2347
+				// it's not saved, so it caches relations like this
2348
+				$otherObject->cache($model->get_this_model_name(), $this);
2349
+			}
2350
+		}
2351
+		return $otherObject;
2352
+	}
2353
+
2354
+
2355
+	/**
2356
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2357
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2358
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2359
+	 * from the cache
2360
+	 *
2361
+	 * @param mixed  $otherObjectModelObjectOrID
2362
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2363
+	 *                to the DB yet
2364
+	 * @param string $relationName
2365
+	 * @param array  $where_query
2366
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2367
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2368
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2369
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2370
+	 *                deleted.
2371
+	 * @return EE_Base_Class the relation was removed from
2372
+	 * @throws ReflectionException
2373
+	 * @throws InvalidArgumentException
2374
+	 * @throws InvalidInterfaceException
2375
+	 * @throws InvalidDataTypeException
2376
+	 * @throws EE_Error
2377
+	 */
2378
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2379
+	{
2380
+		if ($this->ID()) {
2381
+			// if this exists in the DB, save the relation change to the DB too
2382
+			$otherObject = $this->get_model()->remove_relationship_to(
2383
+				$this,
2384
+				$otherObjectModelObjectOrID,
2385
+				$relationName,
2386
+				$where_query
2387
+			);
2388
+			$this->clear_cache(
2389
+				$relationName,
2390
+				$otherObject
2391
+			);
2392
+		} else {
2393
+			// this doesn't exist in the DB, just remove it from the cache
2394
+			$otherObject = $this->clear_cache(
2395
+				$relationName,
2396
+				$otherObjectModelObjectOrID
2397
+			);
2398
+		}
2399
+		if ($otherObject instanceof EE_Base_Class) {
2400
+			$otherObject->clear_cache(
2401
+				$this->get_model()->get_this_model_name(),
2402
+				$this
2403
+			);
2404
+		}
2405
+		return $otherObject;
2406
+	}
2407
+
2408
+
2409
+	/**
2410
+	 * Removes ALL the related things for the $relationName.
2411
+	 *
2412
+	 * @param string $relationName
2413
+	 * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2414
+	 * @return EE_Base_Class
2415
+	 * @throws ReflectionException
2416
+	 * @throws InvalidArgumentException
2417
+	 * @throws InvalidInterfaceException
2418
+	 * @throws InvalidDataTypeException
2419
+	 * @throws EE_Error
2420
+	 */
2421
+	public function _remove_relations($relationName, $where_query_params = array())
2422
+	{
2423
+		if ($this->ID()) {
2424
+			// if this exists in the DB, save the relation change to the DB too
2425
+			$otherObjects = $this->get_model()->remove_relations(
2426
+				$this,
2427
+				$relationName,
2428
+				$where_query_params
2429
+			);
2430
+			$this->clear_cache(
2431
+				$relationName,
2432
+				null,
2433
+				true
2434
+			);
2435
+		} else {
2436
+			// this doesn't exist in the DB, just remove it from the cache
2437
+			$otherObjects = $this->clear_cache(
2438
+				$relationName,
2439
+				null,
2440
+				true
2441
+			);
2442
+		}
2443
+		if (is_array($otherObjects)) {
2444
+			foreach ($otherObjects as $otherObject) {
2445
+				$otherObject->clear_cache(
2446
+					$this->get_model()->get_this_model_name(),
2447
+					$this
2448
+				);
2449
+			}
2450
+		}
2451
+		return $otherObjects;
2452
+	}
2453
+
2454
+
2455
+	/**
2456
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2457
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2458
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2459
+	 * because we want to get even deleted items etc.
2460
+	 *
2461
+	 * @param string $relationName key in the model's _model_relations array
2462
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2463
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2464
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2465
+	 *                             results if you want IDs
2466
+	 * @throws ReflectionException
2467
+	 * @throws InvalidArgumentException
2468
+	 * @throws InvalidInterfaceException
2469
+	 * @throws InvalidDataTypeException
2470
+	 * @throws EE_Error
2471
+	 */
2472
+	public function get_many_related($relationName, $query_params = array())
2473
+	{
2474
+		if ($this->ID()) {
2475
+			// this exists in the DB, so get the related things from either the cache or the DB
2476
+			// if there are query parameters, forget about caching the related model objects.
2477
+			if ($query_params) {
2478
+				$related_model_objects = $this->get_model()->get_all_related(
2479
+					$this,
2480
+					$relationName,
2481
+					$query_params
2482
+				);
2483
+			} else {
2484
+				// did we already cache the result of this query?
2485
+				$cached_results = $this->get_all_from_cache($relationName);
2486
+				if (! $cached_results) {
2487
+					$related_model_objects = $this->get_model()->get_all_related(
2488
+						$this,
2489
+						$relationName,
2490
+						$query_params
2491
+					);
2492
+					// if no query parameters were passed, then we got all the related model objects
2493
+					// for that relation. We can cache them then.
2494
+					foreach ($related_model_objects as $related_model_object) {
2495
+						$this->cache($relationName, $related_model_object);
2496
+					}
2497
+				} else {
2498
+					$related_model_objects = $cached_results;
2499
+				}
2500
+			}
2501
+		} else {
2502
+			// this doesn't exist in the DB, so just get the related things from the cache
2503
+			$related_model_objects = $this->get_all_from_cache($relationName);
2504
+		}
2505
+		return $related_model_objects;
2506
+	}
2507
+
2508
+
2509
+	/**
2510
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2511
+	 * unless otherwise specified in the $query_params
2512
+	 *
2513
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2514
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2515
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2516
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2517
+	 *                               that by the setting $distinct to TRUE;
2518
+	 * @return int
2519
+	 * @throws ReflectionException
2520
+	 * @throws InvalidArgumentException
2521
+	 * @throws InvalidInterfaceException
2522
+	 * @throws InvalidDataTypeException
2523
+	 * @throws EE_Error
2524
+	 */
2525
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2526
+	{
2527
+		return $this->get_model()->count_related(
2528
+			$this,
2529
+			$relation_name,
2530
+			$query_params,
2531
+			$field_to_count,
2532
+			$distinct
2533
+		);
2534
+	}
2535
+
2536
+
2537
+	/**
2538
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2539
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2540
+	 *
2541
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2542
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2543
+	 * @param string $field_to_sum  name of field to count by.
2544
+	 *                              By default, uses primary key
2545
+	 *                              (which doesn't make much sense, so you should probably change it)
2546
+	 * @return int
2547
+	 * @throws ReflectionException
2548
+	 * @throws InvalidArgumentException
2549
+	 * @throws InvalidInterfaceException
2550
+	 * @throws InvalidDataTypeException
2551
+	 * @throws EE_Error
2552
+	 */
2553
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2554
+	{
2555
+		return $this->get_model()->sum_related(
2556
+			$this,
2557
+			$relation_name,
2558
+			$query_params,
2559
+			$field_to_sum
2560
+		);
2561
+	}
2562
+
2563
+
2564
+	/**
2565
+	 * Gets the first (ie, one) related model object of the specified type.
2566
+	 *
2567
+	 * @param string $relationName key in the model's _model_relations array
2568
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2569
+	 * @return EE_Base_Class (not an array, a single object)
2570
+	 * @throws ReflectionException
2571
+	 * @throws InvalidArgumentException
2572
+	 * @throws InvalidInterfaceException
2573
+	 * @throws InvalidDataTypeException
2574
+	 * @throws EE_Error
2575
+	 */
2576
+	public function get_first_related($relationName, $query_params = array())
2577
+	{
2578
+		$model = $this->get_model();
2579
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2580
+			// if they've provided some query parameters, don't bother trying to cache the result
2581
+			// also make sure we're not caching the result of get_first_related
2582
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2583
+			if (
2584
+				$query_params
2585
+				|| ! $model->related_settings_for($relationName)
2586
+					 instanceof
2587
+					 EE_Belongs_To_Relation
2588
+			) {
2589
+				$related_model_object = $model->get_first_related(
2590
+					$this,
2591
+					$relationName,
2592
+					$query_params
2593
+				);
2594
+			} else {
2595
+				// first, check if we've already cached the result of this query
2596
+				$cached_result = $this->get_one_from_cache($relationName);
2597
+				if (! $cached_result) {
2598
+					$related_model_object = $model->get_first_related(
2599
+						$this,
2600
+						$relationName,
2601
+						$query_params
2602
+					);
2603
+					$this->cache($relationName, $related_model_object);
2604
+				} else {
2605
+					$related_model_object = $cached_result;
2606
+				}
2607
+			}
2608
+		} else {
2609
+			$related_model_object = null;
2610
+			// this doesn't exist in the Db,
2611
+			// but maybe the relation is of type belongs to, and so the related thing might
2612
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2613
+				$related_model_object = $model->get_first_related(
2614
+					$this,
2615
+					$relationName,
2616
+					$query_params
2617
+				);
2618
+			}
2619
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2620
+			// just get what's cached on this object
2621
+			if (! $related_model_object) {
2622
+				$related_model_object = $this->get_one_from_cache($relationName);
2623
+			}
2624
+		}
2625
+		return $related_model_object;
2626
+	}
2627
+
2628
+
2629
+	/**
2630
+	 * Does a delete on all related objects of type $relationName and removes
2631
+	 * the current model object's relation to them. If they can't be deleted (because
2632
+	 * of blocking related model objects) does nothing. If the related model objects are
2633
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2634
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2635
+	 *
2636
+	 * @param string $relationName
2637
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2638
+	 * @return int how many deleted
2639
+	 * @throws ReflectionException
2640
+	 * @throws InvalidArgumentException
2641
+	 * @throws InvalidInterfaceException
2642
+	 * @throws InvalidDataTypeException
2643
+	 * @throws EE_Error
2644
+	 */
2645
+	public function delete_related($relationName, $query_params = array())
2646
+	{
2647
+		if ($this->ID()) {
2648
+			$count = $this->get_model()->delete_related(
2649
+				$this,
2650
+				$relationName,
2651
+				$query_params
2652
+			);
2653
+		} else {
2654
+			$count = count($this->get_all_from_cache($relationName));
2655
+			$this->clear_cache($relationName, null, true);
2656
+		}
2657
+		return $count;
2658
+	}
2659
+
2660
+
2661
+	/**
2662
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2663
+	 * the current model object's relation to them. If they can't be deleted (because
2664
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2665
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2666
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2667
+	 *
2668
+	 * @param string $relationName
2669
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2670
+	 * @return int how many deleted (including those soft deleted)
2671
+	 * @throws ReflectionException
2672
+	 * @throws InvalidArgumentException
2673
+	 * @throws InvalidInterfaceException
2674
+	 * @throws InvalidDataTypeException
2675
+	 * @throws EE_Error
2676
+	 */
2677
+	public function delete_related_permanently($relationName, $query_params = array())
2678
+	{
2679
+		if ($this->ID()) {
2680
+			$count = $this->get_model()->delete_related_permanently(
2681
+				$this,
2682
+				$relationName,
2683
+				$query_params
2684
+			);
2685
+		} else {
2686
+			$count = count($this->get_all_from_cache($relationName));
2687
+		}
2688
+		$this->clear_cache($relationName, null, true);
2689
+		return $count;
2690
+	}
2691
+
2692
+
2693
+	/**
2694
+	 * is_set
2695
+	 * Just a simple utility function children can use for checking if property exists
2696
+	 *
2697
+	 * @access  public
2698
+	 * @param  string $field_name property to check
2699
+	 * @return bool                              TRUE if existing,FALSE if not.
2700
+	 */
2701
+	public function is_set($field_name)
2702
+	{
2703
+		return isset($this->_fields[ $field_name ]);
2704
+	}
2705
+
2706
+
2707
+	/**
2708
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2709
+	 * EE_Error exception if they don't
2710
+	 *
2711
+	 * @param  mixed (string|array) $properties properties to check
2712
+	 * @throws EE_Error
2713
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2714
+	 */
2715
+	protected function _property_exists($properties)
2716
+	{
2717
+		foreach ((array) $properties as $property_name) {
2718
+			// first make sure this property exists
2719
+			if (! $this->_fields[ $property_name ]) {
2720
+				throw new EE_Error(
2721
+					sprintf(
2722
+						esc_html__(
2723
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2724
+							'event_espresso'
2725
+						),
2726
+						$property_name
2727
+					)
2728
+				);
2729
+			}
2730
+		}
2731
+		return true;
2732
+	}
2733
+
2734
+
2735
+	/**
2736
+	 * This simply returns an array of model fields for this object
2737
+	 *
2738
+	 * @return array
2739
+	 * @throws ReflectionException
2740
+	 * @throws InvalidArgumentException
2741
+	 * @throws InvalidInterfaceException
2742
+	 * @throws InvalidDataTypeException
2743
+	 * @throws EE_Error
2744
+	 */
2745
+	public function model_field_array()
2746
+	{
2747
+		$fields = $this->get_model()->field_settings(false);
2748
+		$properties = array();
2749
+		// remove prepended underscore
2750
+		foreach ($fields as $field_name => $settings) {
2751
+			$properties[ $field_name ] = $this->get($field_name);
2752
+		}
2753
+		return $properties;
2754
+	}
2755
+
2756
+
2757
+	/**
2758
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2759
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2760
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2761
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2762
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2763
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2764
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2765
+	 * and accepts 2 arguments: the object on which the function was called,
2766
+	 * and an array of the original arguments passed to the function.
2767
+	 * Whatever their callback function returns will be returned by this function.
2768
+	 * Example: in functions.php (or in a plugin):
2769
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2770
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2771
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2772
+	 *          return $previousReturnValue.$returnString;
2773
+	 *      }
2774
+	 * require('EE_Answer.class.php');
2775
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2776
+	 * echo $answer->my_callback('monkeys',100);
2777
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2778
+	 *
2779
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2780
+	 * @param array  $args       array of original arguments passed to the function
2781
+	 * @throws EE_Error
2782
+	 * @return mixed whatever the plugin which calls add_filter decides
2783
+	 */
2784
+	public function __call($methodName, $args)
2785
+	{
2786
+		$className = get_class($this);
2787
+		$tagName = "FHEE__{$className}__{$methodName}";
2788
+		if (! has_filter($tagName)) {
2789
+			throw new EE_Error(
2790
+				sprintf(
2791
+					esc_html__(
2792
+						"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;}",
2793
+						'event_espresso'
2794
+					),
2795
+					$methodName,
2796
+					$className,
2797
+					$tagName
2798
+				)
2799
+			);
2800
+		}
2801
+		return apply_filters($tagName, null, $this, $args);
2802
+	}
2803
+
2804
+
2805
+	/**
2806
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2807
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2808
+	 *
2809
+	 * @param string $meta_key
2810
+	 * @param mixed  $meta_value
2811
+	 * @param mixed  $previous_value
2812
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2813
+	 *                  NOTE: if the values haven't changed, returns 0
2814
+	 * @throws InvalidArgumentException
2815
+	 * @throws InvalidInterfaceException
2816
+	 * @throws InvalidDataTypeException
2817
+	 * @throws EE_Error
2818
+	 * @throws ReflectionException
2819
+	 */
2820
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2821
+	{
2822
+		$query_params = array(
2823
+			array(
2824
+				'EXM_key'  => $meta_key,
2825
+				'OBJ_ID'   => $this->ID(),
2826
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2827
+			),
2828
+		);
2829
+		if ($previous_value !== null) {
2830
+			$query_params[0]['EXM_value'] = $meta_value;
2831
+		}
2832
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2833
+		if (! $existing_rows_like_that) {
2834
+			return $this->add_extra_meta($meta_key, $meta_value);
2835
+		}
2836
+		foreach ($existing_rows_like_that as $existing_row) {
2837
+			$existing_row->save(array('EXM_value' => $meta_value));
2838
+		}
2839
+		return count($existing_rows_like_that);
2840
+	}
2841
+
2842
+
2843
+	/**
2844
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2845
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2846
+	 * extra meta row was entered, false if not
2847
+	 *
2848
+	 * @param string  $meta_key
2849
+	 * @param mixed   $meta_value
2850
+	 * @param boolean $unique
2851
+	 * @return boolean
2852
+	 * @throws InvalidArgumentException
2853
+	 * @throws InvalidInterfaceException
2854
+	 * @throws InvalidDataTypeException
2855
+	 * @throws EE_Error
2856
+	 * @throws ReflectionException
2857
+	 * @throws ReflectionException
2858
+	 */
2859
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2860
+	{
2861
+		if ($unique) {
2862
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2863
+				array(
2864
+					array(
2865
+						'EXM_key'  => $meta_key,
2866
+						'OBJ_ID'   => $this->ID(),
2867
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2868
+					),
2869
+				)
2870
+			);
2871
+			if ($existing_extra_meta) {
2872
+				return false;
2873
+			}
2874
+		}
2875
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2876
+			array(
2877
+				'EXM_key'   => $meta_key,
2878
+				'EXM_value' => $meta_value,
2879
+				'OBJ_ID'    => $this->ID(),
2880
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2881
+			)
2882
+		);
2883
+		$new_extra_meta->save();
2884
+		return true;
2885
+	}
2886
+
2887
+
2888
+	/**
2889
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2890
+	 * is specified, only deletes extra meta records with that value.
2891
+	 *
2892
+	 * @param string $meta_key
2893
+	 * @param mixed  $meta_value
2894
+	 * @return int number of extra meta rows deleted
2895
+	 * @throws InvalidArgumentException
2896
+	 * @throws InvalidInterfaceException
2897
+	 * @throws InvalidDataTypeException
2898
+	 * @throws EE_Error
2899
+	 * @throws ReflectionException
2900
+	 */
2901
+	public function delete_extra_meta($meta_key, $meta_value = null)
2902
+	{
2903
+		$query_params = array(
2904
+			array(
2905
+				'EXM_key'  => $meta_key,
2906
+				'OBJ_ID'   => $this->ID(),
2907
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2908
+			),
2909
+		);
2910
+		if ($meta_value !== null) {
2911
+			$query_params[0]['EXM_value'] = $meta_value;
2912
+		}
2913
+		return EEM_Extra_Meta::instance()->delete($query_params);
2914
+	}
2915
+
2916
+
2917
+	/**
2918
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2919
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2920
+	 * You can specify $default is case you haven't found the extra meta
2921
+	 *
2922
+	 * @param string  $meta_key
2923
+	 * @param boolean $single
2924
+	 * @param mixed   $default if we don't find anything, what should we return?
2925
+	 * @return mixed single value if $single; array if ! $single
2926
+	 * @throws ReflectionException
2927
+	 * @throws InvalidArgumentException
2928
+	 * @throws InvalidInterfaceException
2929
+	 * @throws InvalidDataTypeException
2930
+	 * @throws EE_Error
2931
+	 */
2932
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2933
+	{
2934
+		if ($single) {
2935
+			$result = $this->get_first_related(
2936
+				'Extra_Meta',
2937
+				array(array('EXM_key' => $meta_key))
2938
+			);
2939
+			if ($result instanceof EE_Extra_Meta) {
2940
+				return $result->value();
2941
+			}
2942
+		} else {
2943
+			$results = $this->get_many_related(
2944
+				'Extra_Meta',
2945
+				array(array('EXM_key' => $meta_key))
2946
+			);
2947
+			if ($results) {
2948
+				$values = array();
2949
+				foreach ($results as $result) {
2950
+					if ($result instanceof EE_Extra_Meta) {
2951
+						$values[ $result->ID() ] = $result->value();
2952
+					}
2953
+				}
2954
+				return $values;
2955
+			}
2956
+		}
2957
+		// if nothing discovered yet return default.
2958
+		return apply_filters(
2959
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2960
+			$default,
2961
+			$meta_key,
2962
+			$single,
2963
+			$this
2964
+		);
2965
+	}
2966
+
2967
+
2968
+	/**
2969
+	 * Returns a simple array of all the extra meta associated with this model object.
2970
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2971
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2972
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2973
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2974
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2975
+	 * finally the extra meta's value as each sub-value. (eg
2976
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2977
+	 *
2978
+	 * @param boolean $one_of_each_key
2979
+	 * @return array
2980
+	 * @throws ReflectionException
2981
+	 * @throws InvalidArgumentException
2982
+	 * @throws InvalidInterfaceException
2983
+	 * @throws InvalidDataTypeException
2984
+	 * @throws EE_Error
2985
+	 */
2986
+	public function all_extra_meta_array($one_of_each_key = true)
2987
+	{
2988
+		$return_array = array();
2989
+		if ($one_of_each_key) {
2990
+			$extra_meta_objs = $this->get_many_related(
2991
+				'Extra_Meta',
2992
+				array('group_by' => 'EXM_key')
2993
+			);
2994
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2995
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2996
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2997
+				}
2998
+			}
2999
+		} else {
3000
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
3001
+			foreach ($extra_meta_objs as $extra_meta_obj) {
3002
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
3003
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
3004
+						$return_array[ $extra_meta_obj->key() ] = array();
3005
+					}
3006
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
3007
+				}
3008
+			}
3009
+		}
3010
+		return $return_array;
3011
+	}
3012
+
3013
+
3014
+	/**
3015
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
3016
+	 *
3017
+	 * @return string
3018
+	 * @throws ReflectionException
3019
+	 * @throws InvalidArgumentException
3020
+	 * @throws InvalidInterfaceException
3021
+	 * @throws InvalidDataTypeException
3022
+	 * @throws EE_Error
3023
+	 */
3024
+	public function name()
3025
+	{
3026
+		// find a field that's not a text field
3027
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3028
+		if ($field_we_can_use) {
3029
+			return $this->get($field_we_can_use->get_name());
3030
+		}
3031
+		$first_few_properties = $this->model_field_array();
3032
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3033
+		$name_parts = array();
3034
+		foreach ($first_few_properties as $name => $value) {
3035
+			$name_parts[] = "$name:$value";
3036
+		}
3037
+		return implode(',', $name_parts);
3038
+	}
3039
+
3040
+
3041
+	/**
3042
+	 * in_entity_map
3043
+	 * Checks if this model object has been proven to already be in the entity map
3044
+	 *
3045
+	 * @return boolean
3046
+	 * @throws ReflectionException
3047
+	 * @throws InvalidArgumentException
3048
+	 * @throws InvalidInterfaceException
3049
+	 * @throws InvalidDataTypeException
3050
+	 * @throws EE_Error
3051
+	 */
3052
+	public function in_entity_map()
3053
+	{
3054
+		// well, if we looked, did we find it in the entity map?
3055
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3056
+	}
3057
+
3058
+
3059
+	/**
3060
+	 * refresh_from_db
3061
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3062
+	 *
3063
+	 * @throws ReflectionException
3064
+	 * @throws InvalidArgumentException
3065
+	 * @throws InvalidInterfaceException
3066
+	 * @throws InvalidDataTypeException
3067
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3068
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3069
+	 */
3070
+	public function refresh_from_db()
3071
+	{
3072
+		if ($this->ID() && $this->in_entity_map()) {
3073
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3074
+		} else {
3075
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3076
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3077
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3078
+			// absolutely nothing in it for this ID
3079
+			if (WP_DEBUG) {
3080
+				throw new EE_Error(
3081
+					sprintf(
3082
+						esc_html__(
3083
+							'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.',
3084
+							'event_espresso'
3085
+						),
3086
+						$this->ID(),
3087
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3088
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3089
+					)
3090
+				);
3091
+			}
3092
+		}
3093
+	}
3094
+
3095
+
3096
+	/**
3097
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3098
+	 *
3099
+	 * @since 4.9.80.p
3100
+	 * @param EE_Model_Field_Base[] $fields
3101
+	 * @param string $new_value_sql
3102
+	 *      example: 'column_name=123',
3103
+	 *      or 'column_name=column_name+1',
3104
+	 *      or 'column_name= CASE
3105
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3106
+	 *          THEN `column_name` + 5
3107
+	 *          ELSE `column_name`
3108
+	 *      END'
3109
+	 *      Also updates $field on this model object with the latest value from the database.
3110
+	 * @return bool
3111
+	 * @throws EE_Error
3112
+	 * @throws InvalidArgumentException
3113
+	 * @throws InvalidDataTypeException
3114
+	 * @throws InvalidInterfaceException
3115
+	 * @throws ReflectionException
3116
+	 */
3117
+	protected function updateFieldsInDB($fields, $new_value_sql)
3118
+	{
3119
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3120
+		// if it wasn't even there to start off.
3121
+		if (! $this->ID()) {
3122
+			$this->save();
3123
+		}
3124
+		global $wpdb;
3125
+		if (empty($fields)) {
3126
+			throw new InvalidArgumentException(
3127
+				esc_html__(
3128
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3129
+					'event_espresso'
3130
+				)
3131
+			);
3132
+		}
3133
+		$first_field = reset($fields);
3134
+		$table_alias = $first_field->get_table_alias();
3135
+		foreach ($fields as $field) {
3136
+			if ($table_alias !== $field->get_table_alias()) {
3137
+				throw new InvalidArgumentException(
3138
+					sprintf(
3139
+						esc_html__(
3140
+							// @codingStandardsIgnoreStart
3141
+							'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.',
3142
+							// @codingStandardsIgnoreEnd
3143
+							'event_espresso'
3144
+						),
3145
+						$table_alias,
3146
+						$field->get_table_alias()
3147
+					)
3148
+				);
3149
+			}
3150
+		}
3151
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3152
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3153
+		$table_pk_value = $this->ID();
3154
+		$table_name = $table_obj->get_table_name();
3155
+		if ($table_obj instanceof EE_Secondary_Table) {
3156
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3157
+		} else {
3158
+			$table_pk_field_name = $table_obj->get_pk_column();
3159
+		}
3160
+
3161
+		$query =
3162
+			"UPDATE `{$table_name}`
3163 3163
             SET "
3164
-            . $new_value_sql
3165
-            . $wpdb->prepare(
3166
-                "
3164
+			. $new_value_sql
3165
+			. $wpdb->prepare(
3166
+				"
3167 3167
             WHERE `{$table_pk_field_name}` = %d;",
3168
-                $table_pk_value
3169
-            );
3170
-        $result = $wpdb->query($query);
3171
-        foreach ($fields as $field) {
3172
-            // If it was successful, we'd like to know the new value.
3173
-            // If it failed, we'd also like to know the new value.
3174
-            $new_value = $this->get_model()->get_var(
3175
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3176
-                    $this->get_model()->get_index_primary_key_string(
3177
-                        $this->model_field_array()
3178
-                    ),
3179
-                    array(
3180
-                        'default_where_conditions' => 'minimum',
3181
-                    )
3182
-                ),
3183
-                $field->get_name()
3184
-            );
3185
-            $this->set_from_db(
3186
-                $field->get_name(),
3187
-                $new_value
3188
-            );
3189
-        }
3190
-        return (bool) $result;
3191
-    }
3192
-
3193
-
3194
-    /**
3195
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3196
-     * Does not allow negative values, however.
3197
-     *
3198
-     * @since 4.9.80.p
3199
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3200
-     *                                   (positive or negative). One important gotcha: all these values must be
3201
-     *                                   on the same table (eg don't pass in one field for the posts table and
3202
-     *                                   another for the event meta table.)
3203
-     * @return bool
3204
-     * @throws EE_Error
3205
-     * @throws InvalidArgumentException
3206
-     * @throws InvalidDataTypeException
3207
-     * @throws InvalidInterfaceException
3208
-     * @throws ReflectionException
3209
-     */
3210
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3211
-    {
3212
-        global $wpdb;
3213
-        if (empty($fields_n_quantities)) {
3214
-            // No fields to update? Well sure, we updated them to that value just fine.
3215
-            return true;
3216
-        }
3217
-        $fields = [];
3218
-        $set_sql_statements = [];
3219
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3220
-            $field = $this->get_model()->field_settings_for($field_name, true);
3221
-            $fields[] = $field;
3222
-            $column_name = $field->get_table_column();
3223
-
3224
-            $abs_qty = absint($quantity);
3225
-            if ($quantity > 0) {
3226
-                // don't let the value be negative as often these fields are unsigned
3227
-                $set_sql_statements[] = $wpdb->prepare(
3228
-                    "`{$column_name}` = `{$column_name}` + %d",
3229
-                    $abs_qty
3230
-                );
3231
-            } else {
3232
-                $set_sql_statements[] = $wpdb->prepare(
3233
-                    "`{$column_name}` = CASE
3168
+				$table_pk_value
3169
+			);
3170
+		$result = $wpdb->query($query);
3171
+		foreach ($fields as $field) {
3172
+			// If it was successful, we'd like to know the new value.
3173
+			// If it failed, we'd also like to know the new value.
3174
+			$new_value = $this->get_model()->get_var(
3175
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3176
+					$this->get_model()->get_index_primary_key_string(
3177
+						$this->model_field_array()
3178
+					),
3179
+					array(
3180
+						'default_where_conditions' => 'minimum',
3181
+					)
3182
+				),
3183
+				$field->get_name()
3184
+			);
3185
+			$this->set_from_db(
3186
+				$field->get_name(),
3187
+				$new_value
3188
+			);
3189
+		}
3190
+		return (bool) $result;
3191
+	}
3192
+
3193
+
3194
+	/**
3195
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3196
+	 * Does not allow negative values, however.
3197
+	 *
3198
+	 * @since 4.9.80.p
3199
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3200
+	 *                                   (positive or negative). One important gotcha: all these values must be
3201
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3202
+	 *                                   another for the event meta table.)
3203
+	 * @return bool
3204
+	 * @throws EE_Error
3205
+	 * @throws InvalidArgumentException
3206
+	 * @throws InvalidDataTypeException
3207
+	 * @throws InvalidInterfaceException
3208
+	 * @throws ReflectionException
3209
+	 */
3210
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3211
+	{
3212
+		global $wpdb;
3213
+		if (empty($fields_n_quantities)) {
3214
+			// No fields to update? Well sure, we updated them to that value just fine.
3215
+			return true;
3216
+		}
3217
+		$fields = [];
3218
+		$set_sql_statements = [];
3219
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3220
+			$field = $this->get_model()->field_settings_for($field_name, true);
3221
+			$fields[] = $field;
3222
+			$column_name = $field->get_table_column();
3223
+
3224
+			$abs_qty = absint($quantity);
3225
+			if ($quantity > 0) {
3226
+				// don't let the value be negative as often these fields are unsigned
3227
+				$set_sql_statements[] = $wpdb->prepare(
3228
+					"`{$column_name}` = `{$column_name}` + %d",
3229
+					$abs_qty
3230
+				);
3231
+			} else {
3232
+				$set_sql_statements[] = $wpdb->prepare(
3233
+					"`{$column_name}` = CASE
3234 3234
                        WHEN (`{$column_name}` >= %d)
3235 3235
                        THEN `{$column_name}` - %d
3236 3236
                        ELSE 0
3237 3237
                     END",
3238
-                    $abs_qty,
3239
-                    $abs_qty
3240
-                );
3241
-            }
3242
-        }
3243
-        return $this->updateFieldsInDB(
3244
-            $fields,
3245
-            implode(', ', $set_sql_statements)
3246
-        );
3247
-    }
3248
-
3249
-
3250
-    /**
3251
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3252
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3253
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3254
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3255
-     * Otherwise returns false.
3256
-     *
3257
-     * @since 4.9.80.p
3258
-     * @param string $field_name_to_bump
3259
-     * @param string $field_name_affecting_total
3260
-     * @param string $limit_field_name
3261
-     * @param int    $quantity
3262
-     * @return bool
3263
-     * @throws EE_Error
3264
-     * @throws InvalidArgumentException
3265
-     * @throws InvalidDataTypeException
3266
-     * @throws InvalidInterfaceException
3267
-     * @throws ReflectionException
3268
-     */
3269
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3270
-    {
3271
-        global $wpdb;
3272
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3273
-        $column_name = $field->get_table_column();
3274
-
3275
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3276
-        $column_affecting_total = $field_affecting_total->get_table_column();
3277
-
3278
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3279
-        $limiting_column = $limiting_field->get_table_column();
3280
-        return $this->updateFieldsInDB(
3281
-            [$field],
3282
-            $wpdb->prepare(
3283
-                "`{$column_name}` =
3238
+					$abs_qty,
3239
+					$abs_qty
3240
+				);
3241
+			}
3242
+		}
3243
+		return $this->updateFieldsInDB(
3244
+			$fields,
3245
+			implode(', ', $set_sql_statements)
3246
+		);
3247
+	}
3248
+
3249
+
3250
+	/**
3251
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3252
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3253
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3254
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3255
+	 * Otherwise returns false.
3256
+	 *
3257
+	 * @since 4.9.80.p
3258
+	 * @param string $field_name_to_bump
3259
+	 * @param string $field_name_affecting_total
3260
+	 * @param string $limit_field_name
3261
+	 * @param int    $quantity
3262
+	 * @return bool
3263
+	 * @throws EE_Error
3264
+	 * @throws InvalidArgumentException
3265
+	 * @throws InvalidDataTypeException
3266
+	 * @throws InvalidInterfaceException
3267
+	 * @throws ReflectionException
3268
+	 */
3269
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3270
+	{
3271
+		global $wpdb;
3272
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3273
+		$column_name = $field->get_table_column();
3274
+
3275
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3276
+		$column_affecting_total = $field_affecting_total->get_table_column();
3277
+
3278
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3279
+		$limiting_column = $limiting_field->get_table_column();
3280
+		return $this->updateFieldsInDB(
3281
+			[$field],
3282
+			$wpdb->prepare(
3283
+				"`{$column_name}` =
3284 3284
             CASE
3285 3285
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3286 3286
                THEN `{$column_name}` + %d
3287 3287
                ELSE `{$column_name}`
3288 3288
             END",
3289
-                $quantity,
3290
-                EE_INF_IN_DB,
3291
-                $quantity
3292
-            )
3293
-        );
3294
-    }
3295
-
3296
-
3297
-    /**
3298
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3299
-     * (probably a bad assumption they have made, oh well)
3300
-     *
3301
-     * @return string
3302
-     */
3303
-    public function __toString()
3304
-    {
3305
-        try {
3306
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3307
-        } catch (Exception $e) {
3308
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3309
-            return '';
3310
-        }
3311
-    }
3312
-
3313
-
3314
-    /**
3315
-     * Clear related model objects if they're already in the DB, because otherwise when we
3316
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3317
-     * This means if we have made changes to those related model objects, and want to unserialize
3318
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3319
-     * Instead, those related model objects should be directly serialized and stored.
3320
-     * Eg, the following won't work:
3321
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3322
-     * $att = $reg->attendee();
3323
-     * $att->set( 'ATT_fname', 'Dirk' );
3324
-     * update_option( 'my_option', serialize( $reg ) );
3325
-     * //END REQUEST
3326
-     * //START NEXT REQUEST
3327
-     * $reg = get_option( 'my_option' );
3328
-     * $reg->attendee()->save();
3329
-     * And would need to be replace with:
3330
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3331
-     * $att = $reg->attendee();
3332
-     * $att->set( 'ATT_fname', 'Dirk' );
3333
-     * update_option( 'my_option', serialize( $reg ) );
3334
-     * //END REQUEST
3335
-     * //START NEXT REQUEST
3336
-     * $att = get_option( 'my_option' );
3337
-     * $att->save();
3338
-     *
3339
-     * @return array
3340
-     * @throws ReflectionException
3341
-     * @throws InvalidArgumentException
3342
-     * @throws InvalidInterfaceException
3343
-     * @throws InvalidDataTypeException
3344
-     * @throws EE_Error
3345
-     */
3346
-    public function __sleep()
3347
-    {
3348
-        $model = $this->get_model();
3349
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3350
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3351
-                $classname = 'EE_' . $model->get_this_model_name();
3352
-                if (
3353
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3354
-                    && $this->get_one_from_cache($relation_name)->ID()
3355
-                ) {
3356
-                    $this->clear_cache(
3357
-                        $relation_name,
3358
-                        $this->get_one_from_cache($relation_name)->ID()
3359
-                    );
3360
-                }
3361
-            }
3362
-        }
3363
-        $this->_props_n_values_provided_in_constructor = array();
3364
-        $properties_to_serialize = get_object_vars($this);
3365
-        // don't serialize the model. It's big and that risks recursion
3366
-        unset($properties_to_serialize['_model']);
3367
-        return array_keys($properties_to_serialize);
3368
-    }
3369
-
3370
-
3371
-    /**
3372
-     * restore _props_n_values_provided_in_constructor
3373
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3374
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3375
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3376
-     */
3377
-    public function __wakeup()
3378
-    {
3379
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3380
-    }
3381
-
3382
-
3383
-    /**
3384
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3385
-     * distinct with the clone host instance are also cloned.
3386
-     */
3387
-    public function __clone()
3388
-    {
3389
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3390
-        foreach ($this->_fields as $field => $value) {
3391
-            if ($value instanceof DateTime) {
3392
-                $this->_fields[ $field ] = clone $value;
3393
-            }
3394
-        }
3395
-    }
3289
+				$quantity,
3290
+				EE_INF_IN_DB,
3291
+				$quantity
3292
+			)
3293
+		);
3294
+	}
3295
+
3296
+
3297
+	/**
3298
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3299
+	 * (probably a bad assumption they have made, oh well)
3300
+	 *
3301
+	 * @return string
3302
+	 */
3303
+	public function __toString()
3304
+	{
3305
+		try {
3306
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3307
+		} catch (Exception $e) {
3308
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3309
+			return '';
3310
+		}
3311
+	}
3312
+
3313
+
3314
+	/**
3315
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3316
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3317
+	 * This means if we have made changes to those related model objects, and want to unserialize
3318
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3319
+	 * Instead, those related model objects should be directly serialized and stored.
3320
+	 * Eg, the following won't work:
3321
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3322
+	 * $att = $reg->attendee();
3323
+	 * $att->set( 'ATT_fname', 'Dirk' );
3324
+	 * update_option( 'my_option', serialize( $reg ) );
3325
+	 * //END REQUEST
3326
+	 * //START NEXT REQUEST
3327
+	 * $reg = get_option( 'my_option' );
3328
+	 * $reg->attendee()->save();
3329
+	 * And would need to be replace with:
3330
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3331
+	 * $att = $reg->attendee();
3332
+	 * $att->set( 'ATT_fname', 'Dirk' );
3333
+	 * update_option( 'my_option', serialize( $reg ) );
3334
+	 * //END REQUEST
3335
+	 * //START NEXT REQUEST
3336
+	 * $att = get_option( 'my_option' );
3337
+	 * $att->save();
3338
+	 *
3339
+	 * @return array
3340
+	 * @throws ReflectionException
3341
+	 * @throws InvalidArgumentException
3342
+	 * @throws InvalidInterfaceException
3343
+	 * @throws InvalidDataTypeException
3344
+	 * @throws EE_Error
3345
+	 */
3346
+	public function __sleep()
3347
+	{
3348
+		$model = $this->get_model();
3349
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3350
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3351
+				$classname = 'EE_' . $model->get_this_model_name();
3352
+				if (
3353
+					$this->get_one_from_cache($relation_name) instanceof $classname
3354
+					&& $this->get_one_from_cache($relation_name)->ID()
3355
+				) {
3356
+					$this->clear_cache(
3357
+						$relation_name,
3358
+						$this->get_one_from_cache($relation_name)->ID()
3359
+					);
3360
+				}
3361
+			}
3362
+		}
3363
+		$this->_props_n_values_provided_in_constructor = array();
3364
+		$properties_to_serialize = get_object_vars($this);
3365
+		// don't serialize the model. It's big and that risks recursion
3366
+		unset($properties_to_serialize['_model']);
3367
+		return array_keys($properties_to_serialize);
3368
+	}
3369
+
3370
+
3371
+	/**
3372
+	 * restore _props_n_values_provided_in_constructor
3373
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3374
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3375
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3376
+	 */
3377
+	public function __wakeup()
3378
+	{
3379
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3380
+	}
3381
+
3382
+
3383
+	/**
3384
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3385
+	 * distinct with the clone host instance are also cloned.
3386
+	 */
3387
+	public function __clone()
3388
+	{
3389
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3390
+		foreach ($this->_fields as $field => $value) {
3391
+			if ($value instanceof DateTime) {
3392
+				$this->_fields[ $field ] = clone $value;
3393
+			}
3394
+		}
3395
+	}
3396 3396
 }
Please login to merge, or discard this patch.
core/domain/services/graphql/types/RootQuery.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
     {
51 51
         return [
52 52
             new GraphQLOutputField(
53
-                lcfirst($this->namespace) . 'EventRelations',
53
+                lcfirst($this->namespace).'EventRelations',
54 54
                 'String',
55 55
                 null,
56 56
                 esc_html__('JSON encoded relational data of the models', 'event_espresso'),
@@ -65,8 +65,8 @@  discard block
 block discarded – undo
65 65
                 ]
66 66
             ),
67 67
             new GraphQLOutputField(
68
-                lcfirst($this->namespace) . 'Datetime',
69
-                $this->namespace . 'Datetime',
68
+                lcfirst($this->namespace).'Datetime',
69
+                $this->namespace.'Datetime',
70 70
                 null,
71 71
                 esc_html__('A datetime', 'event_espresso'),
72 72
                 null,
@@ -82,8 +82,8 @@  discard block
 block discarded – undo
82 82
                 ]
83 83
             ),
84 84
             new GraphQLOutputField(
85
-                lcfirst($this->namespace) . 'Ticket',
86
-                $this->namespace . 'Ticket',
85
+                lcfirst($this->namespace).'Ticket',
86
+                $this->namespace.'Ticket',
87 87
                 null,
88 88
                 esc_html__('A ticket', 'event_espresso'),
89 89
                 null,
Please login to merge, or discard this patch.
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -31,171 +31,171 @@
 block discarded – undo
31 31
  */
32 32
 class RootQuery extends TypeBase
33 33
 {
34
-    /**
35
-     * RootQuery constructor.
36
-     */
37
-    public function __construct()
38
-    {
39
-        $this->setName('RootQuery');
40
-        $this->setIsCustomPostType(true);
41
-        parent::__construct();
42
-    }
43
-
44
-
45
-    /**
46
-     * @return GraphQLFieldInterface[]
47
-     */
48
-    public function getFields(): array
49
-    {
50
-        return [
51
-            new GraphQLOutputField(
52
-                lcfirst($this->namespace) . 'EventRelations',
53
-                'String',
54
-                null,
55
-                esc_html__('JSON encoded relational data of the models', 'event_espresso'),
56
-                null,
57
-                [$this, 'getEventRelationalData'],
58
-                [],
59
-                [
60
-                    'eventId' => [
61
-                        'type'        => ['non_null' => 'Int'],
62
-                        'description' => esc_html__('The event ID to get the relational data for.', 'event_espresso'),
63
-                    ],
64
-                ]
65
-            ),
66
-            new GraphQLOutputField(
67
-                lcfirst($this->namespace) . 'Datetime',
68
-                $this->namespace . 'Datetime',
69
-                null,
70
-                esc_html__('A datetime', 'event_espresso'),
71
-                null,
72
-                [$this, 'getDatetime'],
73
-                [],
74
-                [
75
-                    'id' => [
76
-                        'type'        => [
77
-                            'non_null' => 'ID',
78
-                        ],
79
-                        'description' => esc_html__('The globally unique identifier of the datetime.', 'event_espresso'),
80
-                    ],
81
-                ]
82
-            ),
83
-            new GraphQLOutputField(
84
-                lcfirst($this->namespace) . 'Ticket',
85
-                $this->namespace . 'Ticket',
86
-                null,
87
-                esc_html__('A ticket', 'event_espresso'),
88
-                null,
89
-                [$this, 'getTicket'],
90
-                [],
91
-                [
92
-                    'id' => [
93
-                        'type'        => [
94
-                            'non_null' => 'ID',
95
-                        ],
96
-                        'description' => esc_html__('The globally unique identifier of the ticket.', 'event_espresso'),
97
-                    ],
98
-                ]
99
-            ),
100
-        ];
101
-    }
102
-
103
-
104
-    /**
105
-     * @param mixed       $source  The source that's passed down the GraphQL queries
106
-     * @param array       $args    The inputArgs on the field
107
-     * @param AppContext  $context The AppContext passed down the GraphQL tree
108
-     * @param ResolveInfo $info    The ResolveInfo passed down the GraphQL tree
109
-     * @return string
110
-     * @throws Exception
111
-     * @throws InvalidArgumentException
112
-     * @throws InvalidDataTypeException
113
-     * @throws InvalidInterfaceException
114
-     * @throws UserError
115
-     * @throws UnexpectedEntityException
116
-     * @since $VID:$
117
-     */
118
-    public function getEventRelationalData($source, array $args, AppContext $context, ResolveInfo $info): string
119
-    {
120
-        /**
121
-         * Throw an exception if there's no event ID
122
-         */
123
-        if (empty($args['eventId']) || ! absint($args['eventId'])) {
124
-            throw new UserError(esc_html__(
125
-                'No event ID was provided to get the relational data for',
126
-                'event_espresso'
127
-            ));
128
-        }
129
-
130
-        $eventId = absint($args['eventId']);
131
-        /** @var EventEntityRelations $event_entity_relations */
132
-        $event_entity_relations = LoaderFactory::getLoader()->getShared(
133
-            'EventEspresso\core\domain\services\admin\events\editor\EventEntityRelations'
134
-        );
135
-        return json_encode($event_entity_relations->getData($eventId));
136
-    }
137
-
138
-
139
-    /**
140
-     * @param mixed       $source  The source that's passed down the GraphQL queries
141
-     * @param array       $args    The inputArgs on the field
142
-     * @param AppContext  $context The AppContext passed down the GraphQL tree
143
-     * @param ResolveInfo $info    The ResolveInfo passed down the GraphQL tree
144
-     * @return string
145
-     * @throws Exception
146
-     * @throws InvalidArgumentException
147
-     * @throws InvalidDataTypeException
148
-     * @throws InvalidInterfaceException
149
-     * @throws UserError
150
-     * @throws UnexpectedEntityException
151
-     * @since $VID:$
152
-     */
153
-    public function getDatetime($source, array $args, AppContext $context, ResolveInfo $info): EE_Datetime
154
-    {
155
-        $parts = Relay::fromGlobalId(sanitize_text_field($args['id']));
156
-
157
-        /**
158
-         * Throw an exception if there's no ID
159
-         */
160
-        if (empty($parts['id'])) {
161
-            throw new UserError(esc_html__(
162
-                'A missing or invalid ID was received.',
163
-                'event_espresso'
164
-            ));
165
-        }
166
-
167
-        return EEM_Datetime::instance()->get_one_by_ID(absint($parts['id']));
168
-    }
169
-
170
-
171
-    /**
172
-     * @param mixed       $source  The source that's passed down the GraphQL queries
173
-     * @param array       $args    The inputArgs on the field
174
-     * @param AppContext  $context The AppContext passed down the GraphQL tree
175
-     * @param ResolveInfo $info    The ResolveInfo passed down the GraphQL tree
176
-     * @return string
177
-     * @throws Exception
178
-     * @throws InvalidArgumentException
179
-     * @throws InvalidDataTypeException
180
-     * @throws InvalidInterfaceException
181
-     * @throws UserError
182
-     * @throws UnexpectedEntityException
183
-     * @since $VID:$
184
-     */
185
-    public function getTicket($source, array $args, AppContext $context, ResolveInfo $info): EE_Ticket
186
-    {
187
-        $parts = Relay::fromGlobalId(sanitize_text_field($args['id']));
188
-
189
-        /**
190
-         * Throw an exception if there's no ID
191
-         */
192
-        if (empty($parts['id'])) {
193
-            throw new UserError(esc_html__(
194
-                'A missing or invalid ID was received.',
195
-                'event_espresso'
196
-            ));
197
-        }
198
-
199
-        return EEM_Ticket::instance()->get_one_by_ID(absint($parts['id']));
200
-    }
34
+	/**
35
+	 * RootQuery constructor.
36
+	 */
37
+	public function __construct()
38
+	{
39
+		$this->setName('RootQuery');
40
+		$this->setIsCustomPostType(true);
41
+		parent::__construct();
42
+	}
43
+
44
+
45
+	/**
46
+	 * @return GraphQLFieldInterface[]
47
+	 */
48
+	public function getFields(): array
49
+	{
50
+		return [
51
+			new GraphQLOutputField(
52
+				lcfirst($this->namespace) . 'EventRelations',
53
+				'String',
54
+				null,
55
+				esc_html__('JSON encoded relational data of the models', 'event_espresso'),
56
+				null,
57
+				[$this, 'getEventRelationalData'],
58
+				[],
59
+				[
60
+					'eventId' => [
61
+						'type'        => ['non_null' => 'Int'],
62
+						'description' => esc_html__('The event ID to get the relational data for.', 'event_espresso'),
63
+					],
64
+				]
65
+			),
66
+			new GraphQLOutputField(
67
+				lcfirst($this->namespace) . 'Datetime',
68
+				$this->namespace . 'Datetime',
69
+				null,
70
+				esc_html__('A datetime', 'event_espresso'),
71
+				null,
72
+				[$this, 'getDatetime'],
73
+				[],
74
+				[
75
+					'id' => [
76
+						'type'        => [
77
+							'non_null' => 'ID',
78
+						],
79
+						'description' => esc_html__('The globally unique identifier of the datetime.', 'event_espresso'),
80
+					],
81
+				]
82
+			),
83
+			new GraphQLOutputField(
84
+				lcfirst($this->namespace) . 'Ticket',
85
+				$this->namespace . 'Ticket',
86
+				null,
87
+				esc_html__('A ticket', 'event_espresso'),
88
+				null,
89
+				[$this, 'getTicket'],
90
+				[],
91
+				[
92
+					'id' => [
93
+						'type'        => [
94
+							'non_null' => 'ID',
95
+						],
96
+						'description' => esc_html__('The globally unique identifier of the ticket.', 'event_espresso'),
97
+					],
98
+				]
99
+			),
100
+		];
101
+	}
102
+
103
+
104
+	/**
105
+	 * @param mixed       $source  The source that's passed down the GraphQL queries
106
+	 * @param array       $args    The inputArgs on the field
107
+	 * @param AppContext  $context The AppContext passed down the GraphQL tree
108
+	 * @param ResolveInfo $info    The ResolveInfo passed down the GraphQL tree
109
+	 * @return string
110
+	 * @throws Exception
111
+	 * @throws InvalidArgumentException
112
+	 * @throws InvalidDataTypeException
113
+	 * @throws InvalidInterfaceException
114
+	 * @throws UserError
115
+	 * @throws UnexpectedEntityException
116
+	 * @since $VID:$
117
+	 */
118
+	public function getEventRelationalData($source, array $args, AppContext $context, ResolveInfo $info): string
119
+	{
120
+		/**
121
+		 * Throw an exception if there's no event ID
122
+		 */
123
+		if (empty($args['eventId']) || ! absint($args['eventId'])) {
124
+			throw new UserError(esc_html__(
125
+				'No event ID was provided to get the relational data for',
126
+				'event_espresso'
127
+			));
128
+		}
129
+
130
+		$eventId = absint($args['eventId']);
131
+		/** @var EventEntityRelations $event_entity_relations */
132
+		$event_entity_relations = LoaderFactory::getLoader()->getShared(
133
+			'EventEspresso\core\domain\services\admin\events\editor\EventEntityRelations'
134
+		);
135
+		return json_encode($event_entity_relations->getData($eventId));
136
+	}
137
+
138
+
139
+	/**
140
+	 * @param mixed       $source  The source that's passed down the GraphQL queries
141
+	 * @param array       $args    The inputArgs on the field
142
+	 * @param AppContext  $context The AppContext passed down the GraphQL tree
143
+	 * @param ResolveInfo $info    The ResolveInfo passed down the GraphQL tree
144
+	 * @return string
145
+	 * @throws Exception
146
+	 * @throws InvalidArgumentException
147
+	 * @throws InvalidDataTypeException
148
+	 * @throws InvalidInterfaceException
149
+	 * @throws UserError
150
+	 * @throws UnexpectedEntityException
151
+	 * @since $VID:$
152
+	 */
153
+	public function getDatetime($source, array $args, AppContext $context, ResolveInfo $info): EE_Datetime
154
+	{
155
+		$parts = Relay::fromGlobalId(sanitize_text_field($args['id']));
156
+
157
+		/**
158
+		 * Throw an exception if there's no ID
159
+		 */
160
+		if (empty($parts['id'])) {
161
+			throw new UserError(esc_html__(
162
+				'A missing or invalid ID was received.',
163
+				'event_espresso'
164
+			));
165
+		}
166
+
167
+		return EEM_Datetime::instance()->get_one_by_ID(absint($parts['id']));
168
+	}
169
+
170
+
171
+	/**
172
+	 * @param mixed       $source  The source that's passed down the GraphQL queries
173
+	 * @param array       $args    The inputArgs on the field
174
+	 * @param AppContext  $context The AppContext passed down the GraphQL tree
175
+	 * @param ResolveInfo $info    The ResolveInfo passed down the GraphQL tree
176
+	 * @return string
177
+	 * @throws Exception
178
+	 * @throws InvalidArgumentException
179
+	 * @throws InvalidDataTypeException
180
+	 * @throws InvalidInterfaceException
181
+	 * @throws UserError
182
+	 * @throws UnexpectedEntityException
183
+	 * @since $VID:$
184
+	 */
185
+	public function getTicket($source, array $args, AppContext $context, ResolveInfo $info): EE_Ticket
186
+	{
187
+		$parts = Relay::fromGlobalId(sanitize_text_field($args['id']));
188
+
189
+		/**
190
+		 * Throw an exception if there's no ID
191
+		 */
192
+		if (empty($parts['id'])) {
193
+			throw new UserError(esc_html__(
194
+				'A missing or invalid ID was received.',
195
+				'event_espresso'
196
+			));
197
+		}
198
+
199
+		return EEM_Ticket::instance()->get_one_by_ID(absint($parts['id']));
200
+	}
201 201
 }
Please login to merge, or discard this patch.
core/templates/json_linked_data_for_event.template.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -25,7 +25,7 @@  discard block
 block discarded – undo
25 25
   "endDate": "<?php echo esc_html($event_end); ?>",
26 26
   "description": <?php echo wp_json_encode($event_description); ?>,
27 27
   "url": "<?php echo esc_url_raw($event_permalink); ?>",
28
-  "eventAttendanceMode": "<?php echo esc_url_raw('https://schema.org/' . $event_attendance_mode); ?>",
28
+  "eventAttendanceMode": "<?php echo esc_url_raw('https://schema.org/'.$event_attendance_mode); ?>",
29 29
   "eventStatus": [ "<?php echo esc_url_raw($event_status); ?>" ],
30 30
   "offers": [
31 31
     <?php
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
       "price": "<?php echo esc_html($ticket['price']); ?>",
40 40
       "priceCurrency": "<?php echo esc_html($currency); ?>"
41 41
         <?php if (isset($ticket['availability'])) {
42
-            ?>,"availability": "<?php echo esc_url_raw('https://schema.org/' . $ticket['availability']); ?>"
42
+            ?>,"availability": "<?php echo esc_url_raw('https://schema.org/'.$ticket['availability']); ?>"
43 43
         <?php } ?>
44 44
     }<?php
45 45
     $i++;
Please login to merge, or discard this patch.
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -29,8 +29,8 @@  discard block
 block discarded – undo
29 29
   "eventStatus": [ "<?php echo esc_url_raw($event_status); ?>" ],
30 30
   "offers": [
31 31
     <?php
32
-    $i = 0;
33
-    foreach ($event_tickets as $ticket) {?>
32
+	$i = 0;
33
+	foreach ($event_tickets as $ticket) {?>
34 34
     {
35 35
       "@type": "Offer",
36 36
       "url": "<?php echo esc_url_raw($event_permalink); ?>",
@@ -39,18 +39,18 @@  discard block
 block discarded – undo
39 39
       "price": "<?php echo esc_html($ticket['price']); ?>",
40 40
       "priceCurrency": "<?php echo esc_html($currency); ?>"
41 41
         <?php if (isset($ticket['availability'])) {
42
-            ?>,"availability": "<?php echo esc_url_raw('https://schema.org/' . $ticket['availability']); ?>"
42
+			?>,"availability": "<?php echo esc_url_raw('https://schema.org/' . $ticket['availability']); ?>"
43 43
         <?php } ?>
44 44
     }<?php
45
-    $i++;
46
-    if ($i < count($event_tickets)) {
47
-        echo ',';
48
-    }
49
-    }
50
-    ?>
45
+	$i++;
46
+	if ($i < count($event_tickets)) {
47
+		echo ',';
48
+	}
49
+	}
50
+	?>
51 51
     ]<?php
52
-    if ($venue_name) {
53
-        ?>,
52
+	if ($venue_name) {
53
+		?>,
54 54
   "location": {
55 55
     "@type": "Place",
56 56
     "name": <?php echo wp_json_encode($venue_name); ?>,
@@ -63,13 +63,13 @@  discard block
 block discarded – undo
63 63
     }
64 64
   }
65 65
         <?php
66
-    } ?>
66
+	} ?>
67 67
     <?php
68
-    if ($event_image) {
69
-        ?>,
68
+	if ($event_image) {
69
+		?>,
70 70
   "image": "<?php echo esc_url_raw($event_image); ?>"
71 71
         <?php
72
-    } ?>
72
+	} ?>
73 73
     <?php do_action('AHEE__json_linked_data_for_event__template'); ?>
74 74
 }
75 75
 
Please login to merge, or discard this patch.
core/services/request/sanitizers/RequestSanitizer.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -25,7 +25,7 @@
 block discarded – undo
25 25
         if ($is_array) {
26 26
             $values = [];
27 27
             foreach ((array) $param as $key => $value) {
28
-                $values[ $key ] = $this->clean($value, $type, is_array($value), $delimiter);
28
+                $values[$key] = $this->clean($value, $type, is_array($value), $delimiter);
29 29
             }
30 30
             return $values;
31 31
         }
Please login to merge, or discard this patch.
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -6,67 +6,67 @@
 block discarded – undo
6 6
 
7 7
 class RequestSanitizer
8 8
 {
9
-    /**
10
-     * Will sanitize the supplied request parameter based on the specified data type
11
-     *
12
-     * @param mixed  $param     the supplied request parameter
13
-     * @param string $type      the specified data type (default: "string")
14
-     *                          valid values: "bool", "float", "int", "key", "url", or "string"
15
-     * @param bool   $is_array  if true, then $param will be treated as an array of $type
16
-     * @param string $delimiter if $param is a CSV like value (ex: 1,2,3,4,5...) then this is the value separator
17
-     * @return array|bool|float|int|string
18
-     * @since 4.10.14.p
19
-     */
20
-    public function clean($param, $type = DataType::STRING, $is_array = false, $delimiter = '')
21
-    {
22
-        if ($delimiter !== '' && is_string($param)) {
23
-            $param = explode($delimiter, $param);
24
-            $is_array = is_array($param);
25
-            // unset the delimiter else this function will recurse forever when we loop over the array of results
26
-            $delimiter = '';
27
-        }
28
-        // check if we are getting an improperly typed array and correct
29
-        $is_array = $is_array && is_array($param);
30
-        if ($is_array) {
31
-            $values = [];
32
-            foreach ((array) $param as $key => $value) {
33
-                $values[ $key ] = $this->clean($value, $type, is_array($value), $delimiter);
34
-            }
35
-            return $values;
36
-        }
37
-        return $this->sanitizeParam($param, $type);
38
-    }
9
+	/**
10
+	 * Will sanitize the supplied request parameter based on the specified data type
11
+	 *
12
+	 * @param mixed  $param     the supplied request parameter
13
+	 * @param string $type      the specified data type (default: "string")
14
+	 *                          valid values: "bool", "float", "int", "key", "url", or "string"
15
+	 * @param bool   $is_array  if true, then $param will be treated as an array of $type
16
+	 * @param string $delimiter if $param is a CSV like value (ex: 1,2,3,4,5...) then this is the value separator
17
+	 * @return array|bool|float|int|string
18
+	 * @since 4.10.14.p
19
+	 */
20
+	public function clean($param, $type = DataType::STRING, $is_array = false, $delimiter = '')
21
+	{
22
+		if ($delimiter !== '' && is_string($param)) {
23
+			$param = explode($delimiter, $param);
24
+			$is_array = is_array($param);
25
+			// unset the delimiter else this function will recurse forever when we loop over the array of results
26
+			$delimiter = '';
27
+		}
28
+		// check if we are getting an improperly typed array and correct
29
+		$is_array = $is_array && is_array($param);
30
+		if ($is_array) {
31
+			$values = [];
32
+			foreach ((array) $param as $key => $value) {
33
+				$values[ $key ] = $this->clean($value, $type, is_array($value), $delimiter);
34
+			}
35
+			return $values;
36
+		}
37
+		return $this->sanitizeParam($param, $type);
38
+	}
39 39
 
40 40
 
41
-    /**
42
-     * @param mixed  $param
43
-     * @param string $type
44
-     * @return array|float|int|mixed|string|string[]|null
45
-     * @since   4.10.20.p
46
-     */
47
-    public function sanitizeParam($param, $type = DataType::STRING)
48
-    {
49
-        switch ($type) {
50
-            case DataType::BOOL:
51
-                return filter_var($param, FILTER_VALIDATE_BOOLEAN);
52
-            case DataType::FLOAT:
53
-                return (float) $param;
54
-            case DataType::FQCN:
55
-                return preg_replace('[^\\\w\d]', '', $param);
56
-            case DataType::HTML:
57
-                $allowed_tags = AllowedTags::getAllowedTags();
58
-                return wp_kses($param, $allowed_tags);
59
-            case DataType::INT:
60
-                return (int) $param;
61
-            case DataType::KEY:
62
-                return sanitize_key($param);
63
-            case DataType::TITLE:
64
-                return sanitize_title($param);
65
-            case DataType::URL:
66
-                return esc_url_raw($param);
67
-            case DataType::STRING:
68
-            default:
69
-                return sanitize_text_field($param);
70
-        }
71
-    }
41
+	/**
42
+	 * @param mixed  $param
43
+	 * @param string $type
44
+	 * @return array|float|int|mixed|string|string[]|null
45
+	 * @since   4.10.20.p
46
+	 */
47
+	public function sanitizeParam($param, $type = DataType::STRING)
48
+	{
49
+		switch ($type) {
50
+			case DataType::BOOL:
51
+				return filter_var($param, FILTER_VALIDATE_BOOLEAN);
52
+			case DataType::FLOAT:
53
+				return (float) $param;
54
+			case DataType::FQCN:
55
+				return preg_replace('[^\\\w\d]', '', $param);
56
+			case DataType::HTML:
57
+				$allowed_tags = AllowedTags::getAllowedTags();
58
+				return wp_kses($param, $allowed_tags);
59
+			case DataType::INT:
60
+				return (int) $param;
61
+			case DataType::KEY:
62
+				return sanitize_key($param);
63
+			case DataType::TITLE:
64
+				return sanitize_title($param);
65
+			case DataType::URL:
66
+				return esc_url_raw($param);
67
+			case DataType::STRING:
68
+			default:
69
+				return sanitize_text_field($param);
70
+		}
71
+	}
72 72
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Schema.helper.php 2 patches
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@  discard block
 block discarded – undo
21 21
     public static function add_json_linked_data_for_event(EE_Event $event)
22 22
     {
23 23
         // Check we have a valid datetime for the event
24
-        if (! $event->primary_datetime() instanceof EE_Datetime) {
24
+        if ( ! $event->primary_datetime() instanceof EE_Datetime) {
25 25
             return;
26 26
         }
27 27
 
@@ -61,15 +61,15 @@  discard block
 block discarded – undo
61 61
                 $event_status = 'EventScheduled';
62 62
         }
63 63
         $template_args['event_attendance_mode'] = 'OfflineEventAttendanceMode';
64
-        $template_args['event_status'] = 'https://schema.org/' . $event_status;
64
+        $template_args['event_status'] = 'https://schema.org/'.$event_status;
65 65
         $template_args['currency'] = EE_Registry::instance()->CFG->currency->code;
66 66
         foreach ($event->tickets() as $original_ticket) {
67 67
             // clone tickets so that date formats don't override those for the original ticket
68 68
             $ticket = clone $original_ticket;
69 69
             $ID = $ticket->ID();
70
-            $template_args['event_tickets'][ $ID ]['start_date'] = $ticket->start_date(DateTime::ATOM, null);
71
-            $template_args['event_tickets'][ $ID ]['end_date'] = $ticket->end_date(DateTime::ATOM, null);
72
-            $template_args['event_tickets'][ $ID ]['price'] = number_format(
70
+            $template_args['event_tickets'][$ID]['start_date'] = $ticket->start_date(DateTime::ATOM, null);
71
+            $template_args['event_tickets'][$ID]['end_date'] = $ticket->end_date(DateTime::ATOM, null);
72
+            $template_args['event_tickets'][$ID]['price'] = number_format(
73 73
                 $ticket->price(),
74 74
                 EE_Registry::instance()->CFG->currency->dec_plc,
75 75
                 EE_Registry::instance()->CFG->currency->dec_mrk,
@@ -86,11 +86,11 @@  discard block
 block discarded – undo
86 86
                     $availability = null;
87 87
                     break;
88 88
             }
89
-            $template_args['event_tickets'][ $ID ]['availability'] = $availability;
89
+            $template_args['event_tickets'][$ID]['availability'] = $availability;
90 90
             unset($ticket);
91 91
         }
92 92
         $VNU_ID = espresso_venue_id();
93
-        if (! empty($VNU_ID) && ! espresso_is_venue_private($VNU_ID)) {
93
+        if ( ! empty($VNU_ID) && ! espresso_is_venue_private($VNU_ID)) {
94 94
             $venue = EEH_Venue_View::get_venue($VNU_ID);
95 95
             $template_args['venue_name'] = get_the_title($VNU_ID);
96 96
             $template_args['venue_url'] = get_permalink($VNU_ID);
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
             $VNU_ID
113 113
         );
114 114
         extract($template_args, EXTR_OVERWRITE);
115
-        include EE_TEMPLATES . 'json_linked_data_for_event.template.php';
115
+        include EE_TEMPLATES.'json_linked_data_for_event.template.php';
116 116
     }
117 117
 
118 118
 
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
      */
145 145
     public static function name($name = null)
146 146
     {
147
-        return ! empty($name) ? '<span itemprop="name">' . $name . '</span>' : '';
147
+        return ! empty($name) ? '<span itemprop="name">'.$name.'</span>' : '';
148 148
     }
149 149
 
150 150
 
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
     public static function streetAddress(EEI_Address $obj_with_address = null)
161 161
     {
162 162
         return $obj_with_address->address() !== null && $obj_with_address->address() !== ''
163
-            ? '<span itemprop="streetAddress">' . $obj_with_address->address() . '</span>' : '';
163
+            ? '<span itemprop="streetAddress">'.$obj_with_address->address().'</span>' : '';
164 164
     }
165 165
 
166 166
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
             )
184 184
         ) {
185 185
             return $obj_with_address->address2() !== null && $obj_with_address->address2() !== ''
186
-                ? '<span itemprop="postOfficeBoxNumber">' . $obj_with_address->address2() . '</span>' : '';
186
+                ? '<span itemprop="postOfficeBoxNumber">'.$obj_with_address->address2().'</span>' : '';
187 187
         } else {
188 188
             return $obj_with_address->address2();
189 189
         }
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
     public static function addressLocality(EEI_Address $obj_with_address = null)
203 203
     {
204 204
         return $obj_with_address->city() !== null && $obj_with_address->city() !== ''
205
-            ? '<span itemprop="addressLocality">' . $obj_with_address->city() . '</span>' : '';
205
+            ? '<span itemprop="addressLocality">'.$obj_with_address->city().'</span>' : '';
206 206
     }
207 207
 
208 208
 
@@ -218,8 +218,8 @@  discard block
 block discarded – undo
218 218
     public static function addressRegion(EEI_Address $obj_with_address = null)
219 219
     {
220 220
         $state = $obj_with_address->state_name();
221
-        if (! empty($state)) {
222
-            return '<span itemprop="addressRegion">' . $state . '</span>';
221
+        if ( ! empty($state)) {
222
+            return '<span itemprop="addressRegion">'.$state.'</span>';
223 223
         } else {
224 224
             return '';
225 225
         }
@@ -238,8 +238,8 @@  discard block
 block discarded – undo
238 238
     public static function addressCountry(EEI_Address $obj_with_address = null)
239 239
     {
240 240
         $country = $obj_with_address->country_name();
241
-        if (! empty($country)) {
242
-            return '<span itemprop="addressCountry">' . $country . '</span>';
241
+        if ( ! empty($country)) {
242
+            return '<span itemprop="addressCountry">'.$country.'</span>';
243 243
         } else {
244 244
             return '';
245 245
         }
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
      */
275 275
     public static function telephone($phone_nmbr = null)
276 276
     {
277
-        return $phone_nmbr !== null && $phone_nmbr !== '' ? '<span itemprop="telephone">' . $phone_nmbr . '</span>'
277
+        return $phone_nmbr !== null && $phone_nmbr !== '' ? '<span itemprop="telephone">'.$phone_nmbr.'</span>'
278 278
             : '';
279 279
     }
280 280
 
@@ -295,15 +295,15 @@  discard block
 block discarded – undo
295 295
         // Check the URL includes a scheme
296 296
         $parsed_url = parse_url($url);
297 297
         if (empty($parsed_url['scheme'])) {
298
-            $url = 'https://' . ltrim($url, '/');
298
+            $url = 'https://'.ltrim($url, '/');
299 299
         }
300 300
         $atts = '';
301 301
         foreach ($attributes as $attribute => $value) {
302
-            $atts .= ' ' . $attribute . '="' . $value . '"';
302
+            $atts .= ' '.$attribute.'="'.$value.'"';
303 303
         }
304 304
         $text = $text !== null && $text !== '' ? $text : esc_url($url);
305 305
         return ! empty($url)
306
-            ? '<a itemprop="url" href="' . esc_url_raw($url) . '"' . $atts . '>' . $text . '</a>'
306
+            ? '<a itemprop="url" href="'.esc_url_raw($url).'"'.$atts.'>'.$text.'</a>'
307 307
             : '';
308 308
     }
309 309
 }
Please login to merge, or discard this patch.
Indentation   +264 added lines, -264 removed lines patch added patch discarded remove patch
@@ -10,298 +10,298 @@
 block discarded – undo
10 10
  */
11 11
 class EEH_Schema
12 12
 {
13
-    /**
14
-     * generates JSON-based linked data for an event
15
-     *
16
-     * @param EE_Event $event
17
-     * @throws EE_Error
18
-     */
19
-    public static function add_json_linked_data_for_event(EE_Event $event)
20
-    {
21
-        // Check we have a valid datetime for the event
22
-        if (! $event->primary_datetime() instanceof EE_Datetime) {
23
-            return;
24
-        }
13
+	/**
14
+	 * generates JSON-based linked data for an event
15
+	 *
16
+	 * @param EE_Event $event
17
+	 * @throws EE_Error
18
+	 */
19
+	public static function add_json_linked_data_for_event(EE_Event $event)
20
+	{
21
+		// Check we have a valid datetime for the event
22
+		if (! $event->primary_datetime() instanceof EE_Datetime) {
23
+			return;
24
+		}
25 25
 
26
-        $template_args = array(
27
-            'event_permalink' => '',
28
-            'event_name' => '',
29
-            'event_description' => '',
30
-            'event_start' => '',
31
-            'event_end' => '',
32
-            'event_attendance_mode' => '',
33
-            'event_status' => '',
34
-            'currency' => '',
35
-            'event_tickets' => array(),
36
-            'venue_name' => '',
37
-            'venue_url' => '',
38
-            'venue_locality' => '',
39
-            'venue_region' => '',
40
-            'venue_address' => '',
41
-            'event_image' => '',
42
-        );
43
-        $template_args['event_permalink'] = $event->get_permalink();
44
-        $template_args['event_name'] = $event->name();
45
-        $template_args['event_description'] = wp_strip_all_tags($event->short_description(200));
46
-        // clone datetime so that date formats don't override those for the original datetime
47
-        $primary_datetime = clone $event->primary_datetime();
48
-        $template_args['event_start'] = $primary_datetime->start_date(DateTime::ATOM);
49
-        $template_args['event_end'] = $primary_datetime->end_date(DateTime::ATOM);
50
-        unset($primary_datetime);
51
-        switch ($event->status()) {
52
-            case EEM_Event::cancelled:
53
-                $event_status = 'EventCancelled';
54
-                break;
55
-            case EEM_Event::postponed:
56
-                $event_status = 'EventPostponed';
57
-                break;
58
-            default:
59
-                $event_status = 'EventScheduled';
60
-        }
61
-        $template_args['event_attendance_mode'] = 'OfflineEventAttendanceMode';
62
-        $template_args['event_status'] = 'https://schema.org/' . $event_status;
63
-        $template_args['currency'] = EE_Registry::instance()->CFG->currency->code;
64
-        foreach ($event->tickets() as $original_ticket) {
65
-            // clone tickets so that date formats don't override those for the original ticket
66
-            $ticket = clone $original_ticket;
67
-            $ID = $ticket->ID();
68
-            $template_args['event_tickets'][ $ID ]['start_date'] = $ticket->start_date(DateTime::ATOM, null);
69
-            $template_args['event_tickets'][ $ID ]['end_date'] = $ticket->end_date(DateTime::ATOM, null);
70
-            $template_args['event_tickets'][ $ID ]['price'] = number_format(
71
-                $ticket->price(),
72
-                EE_Registry::instance()->CFG->currency->dec_plc,
73
-                EE_Registry::instance()->CFG->currency->dec_mrk,
74
-                ''
75
-            );
76
-            switch ($ticket->ticket_status()) {
77
-                case 'TKO':
78
-                    $availability = 'InStock';
79
-                    break;
80
-                case 'TKS':
81
-                    $availability = 'SoldOut';
82
-                    break;
83
-                default:
84
-                    $availability = null;
85
-                    break;
86
-            }
87
-            $template_args['event_tickets'][ $ID ]['availability'] = $availability;
88
-            unset($ticket);
89
-        }
90
-        $VNU_ID = espresso_venue_id();
91
-        if (! empty($VNU_ID) && ! espresso_is_venue_private($VNU_ID)) {
92
-            $venue = EEH_Venue_View::get_venue($VNU_ID);
93
-            $template_args['venue_name'] = get_the_title($VNU_ID);
94
-            $template_args['venue_url'] = get_permalink($VNU_ID);
95
-            $template_args['venue_locality'] = $venue->city();
96
-            $template_args['venue_region'] = $venue->state_name();
97
-            $template_args['venue_address'] = $venue->address();
98
-            if ($venue->virtual_url() !== '') {
99
-                $template_args['event_attendance_mode'] = 'OnlineEventAttendanceMode';
100
-            }
101
-            if ($venue->virtual_url() !== '' && $venue->address() !== '') {
102
-                $template_args['event_attendance_mode'] = 'MixedEventAttendanceMode';
103
-            }
104
-        }
105
-        $template_args['event_image'] = $event->feature_image_url();
106
-        $template_args = apply_filters(
107
-            'FHEE__EEH_Schema__add_json_linked_data_for_event__template_args',
108
-            $template_args,
109
-            $event,
110
-            $VNU_ID
111
-        );
112
-        extract($template_args, EXTR_OVERWRITE);
113
-        include EE_TEMPLATES . 'json_linked_data_for_event.template.php';
114
-    }
26
+		$template_args = array(
27
+			'event_permalink' => '',
28
+			'event_name' => '',
29
+			'event_description' => '',
30
+			'event_start' => '',
31
+			'event_end' => '',
32
+			'event_attendance_mode' => '',
33
+			'event_status' => '',
34
+			'currency' => '',
35
+			'event_tickets' => array(),
36
+			'venue_name' => '',
37
+			'venue_url' => '',
38
+			'venue_locality' => '',
39
+			'venue_region' => '',
40
+			'venue_address' => '',
41
+			'event_image' => '',
42
+		);
43
+		$template_args['event_permalink'] = $event->get_permalink();
44
+		$template_args['event_name'] = $event->name();
45
+		$template_args['event_description'] = wp_strip_all_tags($event->short_description(200));
46
+		// clone datetime so that date formats don't override those for the original datetime
47
+		$primary_datetime = clone $event->primary_datetime();
48
+		$template_args['event_start'] = $primary_datetime->start_date(DateTime::ATOM);
49
+		$template_args['event_end'] = $primary_datetime->end_date(DateTime::ATOM);
50
+		unset($primary_datetime);
51
+		switch ($event->status()) {
52
+			case EEM_Event::cancelled:
53
+				$event_status = 'EventCancelled';
54
+				break;
55
+			case EEM_Event::postponed:
56
+				$event_status = 'EventPostponed';
57
+				break;
58
+			default:
59
+				$event_status = 'EventScheduled';
60
+		}
61
+		$template_args['event_attendance_mode'] = 'OfflineEventAttendanceMode';
62
+		$template_args['event_status'] = 'https://schema.org/' . $event_status;
63
+		$template_args['currency'] = EE_Registry::instance()->CFG->currency->code;
64
+		foreach ($event->tickets() as $original_ticket) {
65
+			// clone tickets so that date formats don't override those for the original ticket
66
+			$ticket = clone $original_ticket;
67
+			$ID = $ticket->ID();
68
+			$template_args['event_tickets'][ $ID ]['start_date'] = $ticket->start_date(DateTime::ATOM, null);
69
+			$template_args['event_tickets'][ $ID ]['end_date'] = $ticket->end_date(DateTime::ATOM, null);
70
+			$template_args['event_tickets'][ $ID ]['price'] = number_format(
71
+				$ticket->price(),
72
+				EE_Registry::instance()->CFG->currency->dec_plc,
73
+				EE_Registry::instance()->CFG->currency->dec_mrk,
74
+				''
75
+			);
76
+			switch ($ticket->ticket_status()) {
77
+				case 'TKO':
78
+					$availability = 'InStock';
79
+					break;
80
+				case 'TKS':
81
+					$availability = 'SoldOut';
82
+					break;
83
+				default:
84
+					$availability = null;
85
+					break;
86
+			}
87
+			$template_args['event_tickets'][ $ID ]['availability'] = $availability;
88
+			unset($ticket);
89
+		}
90
+		$VNU_ID = espresso_venue_id();
91
+		if (! empty($VNU_ID) && ! espresso_is_venue_private($VNU_ID)) {
92
+			$venue = EEH_Venue_View::get_venue($VNU_ID);
93
+			$template_args['venue_name'] = get_the_title($VNU_ID);
94
+			$template_args['venue_url'] = get_permalink($VNU_ID);
95
+			$template_args['venue_locality'] = $venue->city();
96
+			$template_args['venue_region'] = $venue->state_name();
97
+			$template_args['venue_address'] = $venue->address();
98
+			if ($venue->virtual_url() !== '') {
99
+				$template_args['event_attendance_mode'] = 'OnlineEventAttendanceMode';
100
+			}
101
+			if ($venue->virtual_url() !== '' && $venue->address() !== '') {
102
+				$template_args['event_attendance_mode'] = 'MixedEventAttendanceMode';
103
+			}
104
+		}
105
+		$template_args['event_image'] = $event->feature_image_url();
106
+		$template_args = apply_filters(
107
+			'FHEE__EEH_Schema__add_json_linked_data_for_event__template_args',
108
+			$template_args,
109
+			$event,
110
+			$VNU_ID
111
+		);
112
+		extract($template_args, EXTR_OVERWRITE);
113
+		include EE_TEMPLATES . 'json_linked_data_for_event.template.php';
114
+	}
115 115
 
116 116
 
117
-    /**
118
-     *    location
119
-     *    The location of the event, organization or action.
120
-     *    Should include the Venue name AND schema formatted address info
121
-     *
122
-     * @access public
123
-     * @param string $location
124
-     * @return string
125
-     */
126
-    public static function location($location = null)
127
-    {
128
-        return ! empty($location) ? '<div itemprop="location" itemscope itemtype="http://schema.org/Place">'
129
-                                      . $location
130
-                                      . '</div>' : '';
131
-    }
117
+	/**
118
+	 *    location
119
+	 *    The location of the event, organization or action.
120
+	 *    Should include the Venue name AND schema formatted address info
121
+	 *
122
+	 * @access public
123
+	 * @param string $location
124
+	 * @return string
125
+	 */
126
+	public static function location($location = null)
127
+	{
128
+		return ! empty($location) ? '<div itemprop="location" itemscope itemtype="http://schema.org/Place">'
129
+									  . $location
130
+									  . '</div>' : '';
131
+	}
132 132
 
133 133
 
134 134
 
135
-    /**
136
-     *    name
137
-     *    The name of the Event or Venue.
138
-     *
139
-     * @access public
140
-     * @param string $name
141
-     * @return string
142
-     */
143
-    public static function name($name = null)
144
-    {
145
-        return ! empty($name) ? '<span itemprop="name">' . $name . '</span>' : '';
146
-    }
135
+	/**
136
+	 *    name
137
+	 *    The name of the Event or Venue.
138
+	 *
139
+	 * @access public
140
+	 * @param string $name
141
+	 * @return string
142
+	 */
143
+	public static function name($name = null)
144
+	{
145
+		return ! empty($name) ? '<span itemprop="name">' . $name . '</span>' : '';
146
+	}
147 147
 
148 148
 
149 149
 
150
-    /**
151
-     *    streetAddress
152
-     *    The street address. For example, 1600 Amphitheatre Pkwy.
153
-     *
154
-     * @access public
155
-     * @param EEI_Address $obj_with_address
156
-     * @return string
157
-     */
158
-    public static function streetAddress(EEI_Address $obj_with_address = null)
159
-    {
160
-        return $obj_with_address->address() !== null && $obj_with_address->address() !== ''
161
-            ? '<span itemprop="streetAddress">' . $obj_with_address->address() . '</span>' : '';
162
-    }
150
+	/**
151
+	 *    streetAddress
152
+	 *    The street address. For example, 1600 Amphitheatre Pkwy.
153
+	 *
154
+	 * @access public
155
+	 * @param EEI_Address $obj_with_address
156
+	 * @return string
157
+	 */
158
+	public static function streetAddress(EEI_Address $obj_with_address = null)
159
+	{
160
+		return $obj_with_address->address() !== null && $obj_with_address->address() !== ''
161
+			? '<span itemprop="streetAddress">' . $obj_with_address->address() . '</span>' : '';
162
+	}
163 163
 
164 164
 
165 165
 
166
-    /**
167
-     *    postOfficeBoxNumber
168
-     *    The post office box number for PO box addresses.
169
-     *
170
-     * @access public
171
-     * @param EEI_Address $obj_with_address
172
-     * @return string
173
-     */
174
-    public static function postOfficeBoxNumber(EEI_Address $obj_with_address = null)
175
-    {
176
-        // regex check for some form of PO Box or P.O. Box, etc, etc, etc
177
-        if (
178
-            preg_match(
179
-                "/^\s*((P(OST)?.?\s*(O(FF(ICE)?)?)?.?\s+(B(IN|OX))?)|B(IN|OX))/i",
180
-                $obj_with_address->address2()
181
-            )
182
-        ) {
183
-            return $obj_with_address->address2() !== null && $obj_with_address->address2() !== ''
184
-                ? '<span itemprop="postOfficeBoxNumber">' . $obj_with_address->address2() . '</span>' : '';
185
-        } else {
186
-            return $obj_with_address->address2();
187
-        }
188
-    }
166
+	/**
167
+	 *    postOfficeBoxNumber
168
+	 *    The post office box number for PO box addresses.
169
+	 *
170
+	 * @access public
171
+	 * @param EEI_Address $obj_with_address
172
+	 * @return string
173
+	 */
174
+	public static function postOfficeBoxNumber(EEI_Address $obj_with_address = null)
175
+	{
176
+		// regex check for some form of PO Box or P.O. Box, etc, etc, etc
177
+		if (
178
+			preg_match(
179
+				"/^\s*((P(OST)?.?\s*(O(FF(ICE)?)?)?.?\s+(B(IN|OX))?)|B(IN|OX))/i",
180
+				$obj_with_address->address2()
181
+			)
182
+		) {
183
+			return $obj_with_address->address2() !== null && $obj_with_address->address2() !== ''
184
+				? '<span itemprop="postOfficeBoxNumber">' . $obj_with_address->address2() . '</span>' : '';
185
+		} else {
186
+			return $obj_with_address->address2();
187
+		}
188
+	}
189 189
 
190 190
 
191 191
 
192
-    /**
193
-     *    addressLocality
194
-     *    The locality (city, town, etc). For example, Mountain View.
195
-     *
196
-     * @access public
197
-     * @param EEI_Address $obj_with_address
198
-     * @return string
199
-     */
200
-    public static function addressLocality(EEI_Address $obj_with_address = null)
201
-    {
202
-        return $obj_with_address->city() !== null && $obj_with_address->city() !== ''
203
-            ? '<span itemprop="addressLocality">' . $obj_with_address->city() . '</span>' : '';
204
-    }
192
+	/**
193
+	 *    addressLocality
194
+	 *    The locality (city, town, etc). For example, Mountain View.
195
+	 *
196
+	 * @access public
197
+	 * @param EEI_Address $obj_with_address
198
+	 * @return string
199
+	 */
200
+	public static function addressLocality(EEI_Address $obj_with_address = null)
201
+	{
202
+		return $obj_with_address->city() !== null && $obj_with_address->city() !== ''
203
+			? '<span itemprop="addressLocality">' . $obj_with_address->city() . '</span>' : '';
204
+	}
205 205
 
206 206
 
207 207
 
208
-    /**
209
-     *    addressRegion
210
-     *    The region (state, province, etc). For example, CA.
211
-     *
212
-     * @access public
213
-     * @param EEI_Address $obj_with_address
214
-     * @return string
215
-     */
216
-    public static function addressRegion(EEI_Address $obj_with_address = null)
217
-    {
218
-        $state = $obj_with_address->state_name();
219
-        if (! empty($state)) {
220
-            return '<span itemprop="addressRegion">' . $state . '</span>';
221
-        } else {
222
-            return '';
223
-        }
224
-    }
208
+	/**
209
+	 *    addressRegion
210
+	 *    The region (state, province, etc). For example, CA.
211
+	 *
212
+	 * @access public
213
+	 * @param EEI_Address $obj_with_address
214
+	 * @return string
215
+	 */
216
+	public static function addressRegion(EEI_Address $obj_with_address = null)
217
+	{
218
+		$state = $obj_with_address->state_name();
219
+		if (! empty($state)) {
220
+			return '<span itemprop="addressRegion">' . $state . '</span>';
221
+		} else {
222
+			return '';
223
+		}
224
+	}
225 225
 
226 226
 
227 227
 
228
-    /**
229
-     *    addressCountry
230
-     *    The country. For example, USA. You can also provide the two-letter ISO 3166-1 alpha-2 country code.
231
-     *
232
-     * @access public
233
-     * @param EEI_Address $obj_with_address
234
-     * @return string
235
-     */
236
-    public static function addressCountry(EEI_Address $obj_with_address = null)
237
-    {
238
-        $country = $obj_with_address->country_name();
239
-        if (! empty($country)) {
240
-            return '<span itemprop="addressCountry">' . $country . '</span>';
241
-        } else {
242
-            return '';
243
-        }
244
-    }
228
+	/**
229
+	 *    addressCountry
230
+	 *    The country. For example, USA. You can also provide the two-letter ISO 3166-1 alpha-2 country code.
231
+	 *
232
+	 * @access public
233
+	 * @param EEI_Address $obj_with_address
234
+	 * @return string
235
+	 */
236
+	public static function addressCountry(EEI_Address $obj_with_address = null)
237
+	{
238
+		$country = $obj_with_address->country_name();
239
+		if (! empty($country)) {
240
+			return '<span itemprop="addressCountry">' . $country . '</span>';
241
+		} else {
242
+			return '';
243
+		}
244
+	}
245 245
 
246 246
 
247 247
 
248
-    /**
249
-     *    postalCode
250
-     *    The postal code. For example, 94043.
251
-     *
252
-     * @access public
253
-     * @param EEI_Address $obj_with_address
254
-     * @return string
255
-     */
256
-    public static function postalCode(EEI_Address $obj_with_address = null)
257
-    {
258
-        return $obj_with_address->zip() !== null && $obj_with_address->zip() !== '' ? '<span itemprop="postalCode">'
259
-                                                                                      . $obj_with_address->zip()
260
-                                                                                      . '</span>' : '';
261
-    }
248
+	/**
249
+	 *    postalCode
250
+	 *    The postal code. For example, 94043.
251
+	 *
252
+	 * @access public
253
+	 * @param EEI_Address $obj_with_address
254
+	 * @return string
255
+	 */
256
+	public static function postalCode(EEI_Address $obj_with_address = null)
257
+	{
258
+		return $obj_with_address->zip() !== null && $obj_with_address->zip() !== '' ? '<span itemprop="postalCode">'
259
+																					  . $obj_with_address->zip()
260
+																					  . '</span>' : '';
261
+	}
262 262
 
263 263
 
264 264
 
265
-    /**
266
-     *    telephone
267
-     *    The telephone number.
268
-     *
269
-     * @access public
270
-     * @param string $phone_nmbr
271
-     * @return string
272
-     */
273
-    public static function telephone($phone_nmbr = null)
274
-    {
275
-        return $phone_nmbr !== null && $phone_nmbr !== '' ? '<span itemprop="telephone">' . $phone_nmbr . '</span>'
276
-            : '';
277
-    }
265
+	/**
266
+	 *    telephone
267
+	 *    The telephone number.
268
+	 *
269
+	 * @access public
270
+	 * @param string $phone_nmbr
271
+	 * @return string
272
+	 */
273
+	public static function telephone($phone_nmbr = null)
274
+	{
275
+		return $phone_nmbr !== null && $phone_nmbr !== '' ? '<span itemprop="telephone">' . $phone_nmbr . '</span>'
276
+			: '';
277
+	}
278 278
 
279 279
 
280 280
 
281
-    /**
282
-     *    URL
283
-     *    URL of the item as a clickable link
284
-     *
285
-     * @access public
286
-     * @param string $url        - the URL that the link will resolve to
287
-     * @param string $text       - the text that will be used for the visible link
288
-     * @param array  $attributes - array of additional link attributes in  attribute_name => value pairs. ie: array( 'title' => 'click here', 'class' => 'link-class' )
289
-     * @return string (link)
290
-     */
291
-    public static function url($url = null, $text = null, $attributes = array())
292
-    {
293
-        // Check the URL includes a scheme
294
-        $parsed_url = parse_url($url);
295
-        if (empty($parsed_url['scheme'])) {
296
-            $url = 'https://' . ltrim($url, '/');
297
-        }
298
-        $atts = '';
299
-        foreach ($attributes as $attribute => $value) {
300
-            $atts .= ' ' . $attribute . '="' . $value . '"';
301
-        }
302
-        $text = $text !== null && $text !== '' ? $text : esc_url($url);
303
-        return ! empty($url)
304
-            ? '<a itemprop="url" href="' . esc_url_raw($url) . '"' . $atts . '>' . $text . '</a>'
305
-            : '';
306
-    }
281
+	/**
282
+	 *    URL
283
+	 *    URL of the item as a clickable link
284
+	 *
285
+	 * @access public
286
+	 * @param string $url        - the URL that the link will resolve to
287
+	 * @param string $text       - the text that will be used for the visible link
288
+	 * @param array  $attributes - array of additional link attributes in  attribute_name => value pairs. ie: array( 'title' => 'click here', 'class' => 'link-class' )
289
+	 * @return string (link)
290
+	 */
291
+	public static function url($url = null, $text = null, $attributes = array())
292
+	{
293
+		// Check the URL includes a scheme
294
+		$parsed_url = parse_url($url);
295
+		if (empty($parsed_url['scheme'])) {
296
+			$url = 'https://' . ltrim($url, '/');
297
+		}
298
+		$atts = '';
299
+		foreach ($attributes as $attribute => $value) {
300
+			$atts .= ' ' . $attribute . '="' . $value . '"';
301
+		}
302
+		$text = $text !== null && $text !== '' ? $text : esc_url($url);
303
+		return ! empty($url)
304
+			? '<a itemprop="url" href="' . esc_url_raw($url) . '"' . $atts . '>' . $text . '</a>'
305
+			: '';
306
+	}
307 307
 }
Please login to merge, or discard this patch.
core/EE_Request_Handler.core.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@
 block discarded – undo
73 73
 
74 74
     private function getCurrentPage()
75 75
     {
76
-        if (! $this->current_page instanceof CurrentPage) {
76
+        if ( ! $this->current_page instanceof CurrentPage) {
77 77
             $this->current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
78 78
         }
79 79
         return $this->current_page;
Please login to merge, or discard this patch.
Indentation   +269 added lines, -269 removed lines patch added patch discarded remove patch
@@ -16,273 +16,273 @@
 block discarded – undo
16 16
  */
17 17
 final class EE_Request_Handler implements InterminableInterface
18 18
 {
19
-    /**
20
-     * @var CurrentPage
21
-     */
22
-    private $current_page;
23
-
24
-    /**
25
-     * @var RequestInterface
26
-     */
27
-    private $request;
28
-
29
-    /**
30
-     * @var ResponseInterface
31
-     */
32
-    private $response;
33
-
34
-    /**
35
-     * whether current request is via AJAX
36
-     *
37
-     * @var boolean
38
-     */
39
-    public $ajax = false;
40
-
41
-    /**
42
-     * whether current request is via AJAX from the frontend of the site
43
-     *
44
-     * @var boolean
45
-     */
46
-    public $front_ajax = false;
47
-
48
-
49
-    /**
50
-     * @param RequestInterface  $request
51
-     * @param ResponseInterface $response
52
-     */
53
-    public function __construct(RequestInterface $request, ResponseInterface $response)
54
-    {
55
-        $this->request      = $request;
56
-        $this->response     = $response;
57
-        $this->ajax         = $this->request->isAjax();
58
-        $this->front_ajax   = $this->request->isFrontAjax();
59
-        do_action('AHEE__EE_Request_Handler__construct__complete');
60
-    }
61
-
62
-
63
-    /**
64
-     * @param WP $WP
65
-     * @return void
66
-     * @deprecated  4.10.14.p
67
-     */
68
-    public function parse_request($WP = null)
69
-    {
70
-    }
71
-
72
-
73
-    private function getCurrentPage()
74
-    {
75
-        if (! $this->current_page instanceof CurrentPage) {
76
-            $this->current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
77
-        }
78
-        return $this->current_page;
79
-    }
80
-
81
-
82
-    /**
83
-     * @param WP $WP
84
-     * @return void
85
-     * @deprecated  4.10.14.p
86
-     */
87
-    public function set_request_vars($WP = null)
88
-    {
89
-        $this->getCurrentPage()->parseQueryVars($WP);
90
-    }
91
-
92
-
93
-    /**
94
-     * @param WP $WP
95
-     * @return int
96
-     * @deprecated  4.10.14.p
97
-     */
98
-    public function get_post_id_from_request($WP = null)
99
-    {
100
-        return $this->getCurrentPage()->postId();
101
-    }
102
-
103
-
104
-    /**
105
-     * @param WP $WP
106
-     * @return string
107
-     * @deprecated  4.10.14.p
108
-     */
109
-    public function get_post_name_from_request($WP = null)
110
-    {
111
-        return $this->getCurrentPage()->postName();
112
-    }
113
-
114
-
115
-    /**
116
-     * @param WP $WP
117
-     * @return array
118
-     * @deprecated  4.10.14.p
119
-     */
120
-    public function get_post_type_from_request($WP = null)
121
-    {
122
-        return $this->getCurrentPage()->postType();
123
-    }
124
-
125
-
126
-    /**
127
-     * Just a helper method for getting the url for the displayed page.
128
-     *
129
-     * @param WP $WP
130
-     * @return string
131
-     * @deprecated  4.10.14.p
132
-     */
133
-    public function get_current_page_permalink($WP = null)
134
-    {
135
-        return $this->getCurrentPage()->getPermalink($WP);
136
-    }
137
-
138
-
139
-    /**
140
-     * @return bool
141
-     * @deprecated  4.10.14.p
142
-     */
143
-    public function test_for_espresso_page()
144
-    {
145
-        return $this->getCurrentPage()->isEspressoPage();
146
-    }
147
-
148
-
149
-    /**
150
-     * @param $key
151
-     * @param $value
152
-     * @return void
153
-     * @deprecated  4.10.14.p
154
-     */
155
-    public function set_notice($key, $value)
156
-    {
157
-        $this->response->setNotice($key, $value);
158
-    }
159
-
160
-
161
-    /**
162
-     * @param $key
163
-     * @return mixed
164
-     * @deprecated  4.10.14.p
165
-     */
166
-    public function get_notice($key)
167
-    {
168
-        return $this->response->getNotice($key);
169
-    }
170
-
171
-
172
-    /**
173
-     * @param $string
174
-     * @return void
175
-     * @deprecated  4.10.14.p
176
-     */
177
-    public function add_output($string)
178
-    {
179
-        $this->response->addOutput($string);
180
-    }
181
-
182
-
183
-    /**
184
-     * @return string
185
-     * @deprecated  4.10.14.p
186
-     */
187
-    public function get_output()
188
-    {
189
-        return $this->response->getOutput();
190
-    }
191
-
192
-
193
-    /**
194
-     * @param $item
195
-     * @param $key
196
-     * @deprecated  4.10.14.p
197
-     */
198
-    public function sanitize_text_field_for_array_walk(&$item, &$key)
199
-    {
200
-        $item = strpos($item, 'email') !== false
201
-            ? sanitize_email($item)
202
-            : sanitize_text_field($item);
203
-    }
204
-
205
-
206
-    /**
207
-     * @param null|bool $value
208
-     * @return void
209
-     * @deprecated  4.10.14.p
210
-     */
211
-    public function set_espresso_page($value = null)
212
-    {
213
-        $this->getCurrentPage()->setEspressoPage($value);
214
-    }
215
-
216
-
217
-    /**
218
-     * @return bool
219
-     * @deprecated  4.10.14.p
220
-     */
221
-    public function is_espresso_page()
222
-    {
223
-        return $this->getCurrentPage()->isEspressoPage();
224
-    }
225
-
226
-
227
-    /**
228
-     * returns sanitized contents of $_REQUEST
229
-     *
230
-     * @return array
231
-     * @deprecated  4.10.14.p
232
-     */
233
-    public function params()
234
-    {
235
-        return $this->request->requestParams();
236
-    }
237
-
238
-
239
-    /**
240
-     * @param      $key
241
-     * @param      $value
242
-     * @param bool $override_ee
243
-     * @return    void
244
-     * @deprecated  4.10.14.p
245
-     */
246
-    public function set($key, $value, $override_ee = false)
247
-    {
248
-        $this->request->setRequestParam($key, $value, $override_ee);
249
-    }
250
-
251
-
252
-    /**
253
-     * @param      $key
254
-     * @param null $default
255
-     * @return    mixed
256
-     * @deprecated  4.10.14.p
257
-     */
258
-    public function get($key, $default = null)
259
-    {
260
-        return $this->request->getRequestParam($key, $default);
261
-    }
262
-
263
-
264
-    /**
265
-     * check if param exists
266
-     *
267
-     * @param $key
268
-     * @return    boolean
269
-     * @deprecated  4.10.14.p
270
-     */
271
-    public function is_set($key)
272
-    {
273
-        return $this->request->requestParamIsSet($key);
274
-    }
275
-
276
-
277
-    /**
278
-     * remove param
279
-     *
280
-     * @param $key
281
-     * @return    void
282
-     * @deprecated  4.10.14.p
283
-     */
284
-    public function un_set($key)
285
-    {
286
-        $this->request->unSetRequestParam($key);
287
-    }
19
+	/**
20
+	 * @var CurrentPage
21
+	 */
22
+	private $current_page;
23
+
24
+	/**
25
+	 * @var RequestInterface
26
+	 */
27
+	private $request;
28
+
29
+	/**
30
+	 * @var ResponseInterface
31
+	 */
32
+	private $response;
33
+
34
+	/**
35
+	 * whether current request is via AJAX
36
+	 *
37
+	 * @var boolean
38
+	 */
39
+	public $ajax = false;
40
+
41
+	/**
42
+	 * whether current request is via AJAX from the frontend of the site
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	public $front_ajax = false;
47
+
48
+
49
+	/**
50
+	 * @param RequestInterface  $request
51
+	 * @param ResponseInterface $response
52
+	 */
53
+	public function __construct(RequestInterface $request, ResponseInterface $response)
54
+	{
55
+		$this->request      = $request;
56
+		$this->response     = $response;
57
+		$this->ajax         = $this->request->isAjax();
58
+		$this->front_ajax   = $this->request->isFrontAjax();
59
+		do_action('AHEE__EE_Request_Handler__construct__complete');
60
+	}
61
+
62
+
63
+	/**
64
+	 * @param WP $WP
65
+	 * @return void
66
+	 * @deprecated  4.10.14.p
67
+	 */
68
+	public function parse_request($WP = null)
69
+	{
70
+	}
71
+
72
+
73
+	private function getCurrentPage()
74
+	{
75
+		if (! $this->current_page instanceof CurrentPage) {
76
+			$this->current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
77
+		}
78
+		return $this->current_page;
79
+	}
80
+
81
+
82
+	/**
83
+	 * @param WP $WP
84
+	 * @return void
85
+	 * @deprecated  4.10.14.p
86
+	 */
87
+	public function set_request_vars($WP = null)
88
+	{
89
+		$this->getCurrentPage()->parseQueryVars($WP);
90
+	}
91
+
92
+
93
+	/**
94
+	 * @param WP $WP
95
+	 * @return int
96
+	 * @deprecated  4.10.14.p
97
+	 */
98
+	public function get_post_id_from_request($WP = null)
99
+	{
100
+		return $this->getCurrentPage()->postId();
101
+	}
102
+
103
+
104
+	/**
105
+	 * @param WP $WP
106
+	 * @return string
107
+	 * @deprecated  4.10.14.p
108
+	 */
109
+	public function get_post_name_from_request($WP = null)
110
+	{
111
+		return $this->getCurrentPage()->postName();
112
+	}
113
+
114
+
115
+	/**
116
+	 * @param WP $WP
117
+	 * @return array
118
+	 * @deprecated  4.10.14.p
119
+	 */
120
+	public function get_post_type_from_request($WP = null)
121
+	{
122
+		return $this->getCurrentPage()->postType();
123
+	}
124
+
125
+
126
+	/**
127
+	 * Just a helper method for getting the url for the displayed page.
128
+	 *
129
+	 * @param WP $WP
130
+	 * @return string
131
+	 * @deprecated  4.10.14.p
132
+	 */
133
+	public function get_current_page_permalink($WP = null)
134
+	{
135
+		return $this->getCurrentPage()->getPermalink($WP);
136
+	}
137
+
138
+
139
+	/**
140
+	 * @return bool
141
+	 * @deprecated  4.10.14.p
142
+	 */
143
+	public function test_for_espresso_page()
144
+	{
145
+		return $this->getCurrentPage()->isEspressoPage();
146
+	}
147
+
148
+
149
+	/**
150
+	 * @param $key
151
+	 * @param $value
152
+	 * @return void
153
+	 * @deprecated  4.10.14.p
154
+	 */
155
+	public function set_notice($key, $value)
156
+	{
157
+		$this->response->setNotice($key, $value);
158
+	}
159
+
160
+
161
+	/**
162
+	 * @param $key
163
+	 * @return mixed
164
+	 * @deprecated  4.10.14.p
165
+	 */
166
+	public function get_notice($key)
167
+	{
168
+		return $this->response->getNotice($key);
169
+	}
170
+
171
+
172
+	/**
173
+	 * @param $string
174
+	 * @return void
175
+	 * @deprecated  4.10.14.p
176
+	 */
177
+	public function add_output($string)
178
+	{
179
+		$this->response->addOutput($string);
180
+	}
181
+
182
+
183
+	/**
184
+	 * @return string
185
+	 * @deprecated  4.10.14.p
186
+	 */
187
+	public function get_output()
188
+	{
189
+		return $this->response->getOutput();
190
+	}
191
+
192
+
193
+	/**
194
+	 * @param $item
195
+	 * @param $key
196
+	 * @deprecated  4.10.14.p
197
+	 */
198
+	public function sanitize_text_field_for_array_walk(&$item, &$key)
199
+	{
200
+		$item = strpos($item, 'email') !== false
201
+			? sanitize_email($item)
202
+			: sanitize_text_field($item);
203
+	}
204
+
205
+
206
+	/**
207
+	 * @param null|bool $value
208
+	 * @return void
209
+	 * @deprecated  4.10.14.p
210
+	 */
211
+	public function set_espresso_page($value = null)
212
+	{
213
+		$this->getCurrentPage()->setEspressoPage($value);
214
+	}
215
+
216
+
217
+	/**
218
+	 * @return bool
219
+	 * @deprecated  4.10.14.p
220
+	 */
221
+	public function is_espresso_page()
222
+	{
223
+		return $this->getCurrentPage()->isEspressoPage();
224
+	}
225
+
226
+
227
+	/**
228
+	 * returns sanitized contents of $_REQUEST
229
+	 *
230
+	 * @return array
231
+	 * @deprecated  4.10.14.p
232
+	 */
233
+	public function params()
234
+	{
235
+		return $this->request->requestParams();
236
+	}
237
+
238
+
239
+	/**
240
+	 * @param      $key
241
+	 * @param      $value
242
+	 * @param bool $override_ee
243
+	 * @return    void
244
+	 * @deprecated  4.10.14.p
245
+	 */
246
+	public function set($key, $value, $override_ee = false)
247
+	{
248
+		$this->request->setRequestParam($key, $value, $override_ee);
249
+	}
250
+
251
+
252
+	/**
253
+	 * @param      $key
254
+	 * @param null $default
255
+	 * @return    mixed
256
+	 * @deprecated  4.10.14.p
257
+	 */
258
+	public function get($key, $default = null)
259
+	{
260
+		return $this->request->getRequestParam($key, $default);
261
+	}
262
+
263
+
264
+	/**
265
+	 * check if param exists
266
+	 *
267
+	 * @param $key
268
+	 * @return    boolean
269
+	 * @deprecated  4.10.14.p
270
+	 */
271
+	public function is_set($key)
272
+	{
273
+		return $this->request->requestParamIsSet($key);
274
+	}
275
+
276
+
277
+	/**
278
+	 * remove param
279
+	 *
280
+	 * @param $key
281
+	 * @return    void
282
+	 * @deprecated  4.10.14.p
283
+	 */
284
+	public function un_set($key)
285
+	{
286
+		$this->request->unSetRequestParam($key);
287
+	}
288 288
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Country.model.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
             'Country' => new EE_Primary_Table('esp_country', 'CNT_ISO'),
47 47
         ];
48 48
 
49
-        $this->_fields          = [
49
+        $this->_fields = [
50 50
             'Country' => [
51 51
                 'CNT_active'      => new EE_Boolean_Field(
52 52
                     'CNT_active',
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
             'Venue'    => new EE_Has_Many_Relation(),
142 142
         ];
143 143
         // only anyone to view, but only those with the default role can do anything
144
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
144
+        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
145 145
 
146 146
         parent::__construct($timezone);
147 147
     }
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
      */
154 154
     public function get_all_countries()
155 155
     {
156
-        if (! self::$_all_countries) {
156
+        if ( ! self::$_all_countries) {
157 157
             self::$_all_countries = $this->get_all(['order_by' => ['CNT_name' => 'ASC'], 'limit' => [0, 99999]]);
158 158
         }
159 159
         return self::$_all_countries;
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
      */
170 170
     public function get_all_active_countries()
171 171
     {
172
-        if (! self::$_active_countries) {
172
+        if ( ! self::$_active_countries) {
173 173
             self::$_active_countries =
174 174
                 $this->get_all([['CNT_active' => true], 'order_by' => ['CNT_name' => 'ASC'], 'limit' => [0, 99999]]);
175 175
         }
@@ -187,8 +187,8 @@  discard block
 block discarded – undo
187 187
     public function get_country_name_by_ISO($country_ISO)
188 188
     {
189 189
         $countries = $this->get_all_countries();
190
-        if (isset($countries[ $country_ISO ]) && $countries[ $country_ISO ] instanceof EE_Country) {
191
-            return $countries[ $country_ISO ]->name();
190
+        if (isset($countries[$country_ISO]) && $countries[$country_ISO] instanceof EE_Country) {
191
+            return $countries[$country_ISO]->name();
192 192
         }
193 193
         $names = $this->get_col([['CNT_ISO' => $country_ISO], 'limit' => 1], 'CNT_name');
194 194
         if (is_array($names) && ! empty($names)) {
Please login to merge, or discard this patch.
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -10,209 +10,209 @@
 block discarded – undo
10 10
  */
11 11
 class EEM_Country extends EEM_Base
12 12
 {
13
-    // private instance of the Attendee object
14
-    protected static $_instance = null;
15
-
16
-    // array of all countries
17
-    private static $_all_countries = false;
18
-
19
-    // array of all active countries
20
-    private static $_active_countries = false;
21
-
22
-
23
-    /**
24
-     * Resets the country
25
-     *
26
-     * @param string $timezone
27
-     * @return EEM_Country|EEM_Base|null
28
-     * @throws EE_Error
29
-     * @throws ReflectionException
30
-     */
31
-    public static function reset($timezone = null)
32
-    {
33
-        self::$_active_countries = null;
34
-        self::$_all_countries    = null;
35
-        return parent::reset($timezone);
36
-    }
37
-
38
-
39
-    protected function __construct($timezone = '')
40
-    {
41
-        $this->singular_item = esc_html__('Country', 'event_espresso');
42
-        $this->plural_item   = esc_html__('Countries', 'event_espresso');
43
-
44
-        $this->_tables = [
45
-            'Country' => new EE_Primary_Table('esp_country', 'CNT_ISO'),
46
-        ];
47
-
48
-        $this->_fields          = [
49
-            'Country' => [
50
-                'CNT_active'      => new EE_Boolean_Field(
51
-                    'CNT_active',
52
-                    esc_html__('Country Appears in Dropdown Select Lists', 'event_espresso'),
53
-                    false,
54
-                    true
55
-                ),
56
-                'CNT_ISO'         => new EE_Primary_Key_String_Field(
57
-                    'CNT_ISO',
58
-                    esc_html__('Country ISO Code', 'event_espresso')
59
-                ),
60
-                'CNT_ISO3'        => new EE_All_Caps_Text_Field(
61
-                    'CNT_ISO3',
62
-                    esc_html__('Country ISO3 Code', 'event_espresso'),
63
-                    false,
64
-                    ''
65
-                ),
66
-                'RGN_ID'          => new EE_Integer_Field(
67
-                    'RGN_ID',
68
-                    esc_html__('Region ID', 'event_espresso'),
69
-                    false,
70
-                    0
71
-                ),
72
-                // should be a foreign key, but no region table exists yet
73
-                'CNT_name'        => new EE_Plain_Text_Field(
74
-                    'CNT_name',
75
-                    esc_html__('Country Name', 'event_espresso'),
76
-                    false,
77
-                    ''
78
-                ),
79
-                'CNT_cur_code'    => new EE_All_Caps_Text_Field(
80
-                    'CNT_cur_code',
81
-                    esc_html__('Country Currency Code', 'event_espresso'),
82
-                    false
83
-                ),
84
-                'CNT_cur_single'  => new EE_Plain_Text_Field(
85
-                    'CNT_cur_single',
86
-                    esc_html__('Currency Name Singular', 'event_espresso'),
87
-                    false
88
-                ),
89
-                'CNT_cur_plural'  => new EE_Plain_Text_Field(
90
-                    'CNT_cur_plural',
91
-                    esc_html__('Currency Name Plural', 'event_espresso'),
92
-                    false
93
-                ),
94
-                'CNT_cur_sign'    => new EE_Plain_Text_Field(
95
-                    'CNT_cur_sign',
96
-                    esc_html__('Currency Sign', 'event_espresso'),
97
-                    false
98
-                ),
99
-                'CNT_cur_sign_b4' => new EE_Boolean_Field(
100
-                    'CNT_cur_sign_b4',
101
-                    esc_html__('Currency Sign Before Number', 'event_espresso'),
102
-                    false,
103
-                    true
104
-                ),
105
-                'CNT_cur_dec_plc' => new EE_Integer_Field(
106
-                    'CNT_cur_dec_plc',
107
-                    esc_html__('Currency Decimal Places', 'event_espresso'),
108
-                    false,
109
-                    2
110
-                ),
111
-                'CNT_cur_dec_mrk' => new EE_Plain_Text_Field(
112
-                    'CNT_cur_dec_mrk',
113
-                    esc_html__('Currency Decimal Mark', 'event_espresso'),
114
-                    false,
115
-                    '.'
116
-                ),
117
-                'CNT_cur_thsnds'  => new EE_Plain_Text_Field(
118
-                    'CNT_cur_thsnds',
119
-                    esc_html__('Currency Thousands Separator', 'event_espresso'),
120
-                    false,
121
-                    ','
122
-                ),
123
-                'CNT_tel_code'    => new EE_Plain_Text_Field(
124
-                    'CNT_tel_code',
125
-                    esc_html__('Country Telephone Code', 'event_espresso'),
126
-                    false,
127
-                    ''
128
-                ),
129
-                'CNT_is_EU'       => new EE_Boolean_Field(
130
-                    'CNT_is_EU',
131
-                    esc_html__('Country is Member of EU', 'event_espresso'),
132
-                    false,
133
-                    false
134
-                ),
135
-            ],
136
-        ];
137
-        $this->_model_relations = [
138
-            'Attendee' => new EE_Has_Many_Relation(),
139
-            'State'    => new EE_Has_Many_Relation(),
140
-            'Venue'    => new EE_Has_Many_Relation(),
141
-        ];
142
-        // only anyone to view, but only those with the default role can do anything
143
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
144
-
145
-        parent::__construct($timezone);
146
-    }
147
-
148
-
149
-    /**
150
-     * @return EE_Country[]
151
-     * @throws EE_Error
152
-     */
153
-    public function get_all_countries()
154
-    {
155
-        if (! self::$_all_countries) {
156
-            self::$_all_countries = $this->get_all(['order_by' => ['CNT_name' => 'ASC'], 'limit' => [0, 99999]]);
157
-        }
158
-        return self::$_all_countries;
159
-    }
160
-
161
-
162
-    /**
163
-     * Gets and caches the list of active countries. If you know the list of active countries
164
-     * has changed during this request, first use EEM_Country::reset() to flush the cache
165
-     *
166
-     * @return EE_Country[]
167
-     * @throws EE_Error
168
-     */
169
-    public function get_all_active_countries()
170
-    {
171
-        if (! self::$_active_countries) {
172
-            self::$_active_countries =
173
-                $this->get_all([['CNT_active' => true], 'order_by' => ['CNT_name' => 'ASC'], 'limit' => [0, 99999]]);
174
-        }
175
-        return self::$_active_countries;
176
-    }
177
-
178
-
179
-    /**
180
-     * Gets the country's name by its ISO
181
-     *
182
-     * @param string $country_ISO
183
-     * @return string
184
-     * @throws EE_Error
185
-     */
186
-    public function get_country_name_by_ISO($country_ISO)
187
-    {
188
-        $countries = $this->get_all_countries();
189
-        if (isset($countries[ $country_ISO ]) && $countries[ $country_ISO ] instanceof EE_Country) {
190
-            return $countries[ $country_ISO ]->name();
191
-        }
192
-        $names = $this->get_col([['CNT_ISO' => $country_ISO], 'limit' => 1], 'CNT_name');
193
-        if (is_array($names) && ! empty($names)) {
194
-            return reset($names);
195
-        } else {
196
-            return '';
197
-        }
198
-    }
199
-
200
-
201
-    /**
202
-     * Gets the country's name by its name
203
-     *
204
-     * @param string $country_name
205
-     * @return EE_Country|null
206
-     * @throws EE_Error
207
-     */
208
-    public function getCountryByName($country_name)
209
-    {
210
-        $countries = $this->get_all_countries();
211
-        foreach ($countries as $country) {
212
-            if ($country instanceof EE_Country && $country->name() === $country_name) {
213
-                return $country;
214
-            }
215
-        }
216
-        return $this->get_one([['CNT_name' => $country_name]]);
217
-    }
13
+	// private instance of the Attendee object
14
+	protected static $_instance = null;
15
+
16
+	// array of all countries
17
+	private static $_all_countries = false;
18
+
19
+	// array of all active countries
20
+	private static $_active_countries = false;
21
+
22
+
23
+	/**
24
+	 * Resets the country
25
+	 *
26
+	 * @param string $timezone
27
+	 * @return EEM_Country|EEM_Base|null
28
+	 * @throws EE_Error
29
+	 * @throws ReflectionException
30
+	 */
31
+	public static function reset($timezone = null)
32
+	{
33
+		self::$_active_countries = null;
34
+		self::$_all_countries    = null;
35
+		return parent::reset($timezone);
36
+	}
37
+
38
+
39
+	protected function __construct($timezone = '')
40
+	{
41
+		$this->singular_item = esc_html__('Country', 'event_espresso');
42
+		$this->plural_item   = esc_html__('Countries', 'event_espresso');
43
+
44
+		$this->_tables = [
45
+			'Country' => new EE_Primary_Table('esp_country', 'CNT_ISO'),
46
+		];
47
+
48
+		$this->_fields          = [
49
+			'Country' => [
50
+				'CNT_active'      => new EE_Boolean_Field(
51
+					'CNT_active',
52
+					esc_html__('Country Appears in Dropdown Select Lists', 'event_espresso'),
53
+					false,
54
+					true
55
+				),
56
+				'CNT_ISO'         => new EE_Primary_Key_String_Field(
57
+					'CNT_ISO',
58
+					esc_html__('Country ISO Code', 'event_espresso')
59
+				),
60
+				'CNT_ISO3'        => new EE_All_Caps_Text_Field(
61
+					'CNT_ISO3',
62
+					esc_html__('Country ISO3 Code', 'event_espresso'),
63
+					false,
64
+					''
65
+				),
66
+				'RGN_ID'          => new EE_Integer_Field(
67
+					'RGN_ID',
68
+					esc_html__('Region ID', 'event_espresso'),
69
+					false,
70
+					0
71
+				),
72
+				// should be a foreign key, but no region table exists yet
73
+				'CNT_name'        => new EE_Plain_Text_Field(
74
+					'CNT_name',
75
+					esc_html__('Country Name', 'event_espresso'),
76
+					false,
77
+					''
78
+				),
79
+				'CNT_cur_code'    => new EE_All_Caps_Text_Field(
80
+					'CNT_cur_code',
81
+					esc_html__('Country Currency Code', 'event_espresso'),
82
+					false
83
+				),
84
+				'CNT_cur_single'  => new EE_Plain_Text_Field(
85
+					'CNT_cur_single',
86
+					esc_html__('Currency Name Singular', 'event_espresso'),
87
+					false
88
+				),
89
+				'CNT_cur_plural'  => new EE_Plain_Text_Field(
90
+					'CNT_cur_plural',
91
+					esc_html__('Currency Name Plural', 'event_espresso'),
92
+					false
93
+				),
94
+				'CNT_cur_sign'    => new EE_Plain_Text_Field(
95
+					'CNT_cur_sign',
96
+					esc_html__('Currency Sign', 'event_espresso'),
97
+					false
98
+				),
99
+				'CNT_cur_sign_b4' => new EE_Boolean_Field(
100
+					'CNT_cur_sign_b4',
101
+					esc_html__('Currency Sign Before Number', 'event_espresso'),
102
+					false,
103
+					true
104
+				),
105
+				'CNT_cur_dec_plc' => new EE_Integer_Field(
106
+					'CNT_cur_dec_plc',
107
+					esc_html__('Currency Decimal Places', 'event_espresso'),
108
+					false,
109
+					2
110
+				),
111
+				'CNT_cur_dec_mrk' => new EE_Plain_Text_Field(
112
+					'CNT_cur_dec_mrk',
113
+					esc_html__('Currency Decimal Mark', 'event_espresso'),
114
+					false,
115
+					'.'
116
+				),
117
+				'CNT_cur_thsnds'  => new EE_Plain_Text_Field(
118
+					'CNT_cur_thsnds',
119
+					esc_html__('Currency Thousands Separator', 'event_espresso'),
120
+					false,
121
+					','
122
+				),
123
+				'CNT_tel_code'    => new EE_Plain_Text_Field(
124
+					'CNT_tel_code',
125
+					esc_html__('Country Telephone Code', 'event_espresso'),
126
+					false,
127
+					''
128
+				),
129
+				'CNT_is_EU'       => new EE_Boolean_Field(
130
+					'CNT_is_EU',
131
+					esc_html__('Country is Member of EU', 'event_espresso'),
132
+					false,
133
+					false
134
+				),
135
+			],
136
+		];
137
+		$this->_model_relations = [
138
+			'Attendee' => new EE_Has_Many_Relation(),
139
+			'State'    => new EE_Has_Many_Relation(),
140
+			'Venue'    => new EE_Has_Many_Relation(),
141
+		];
142
+		// only anyone to view, but only those with the default role can do anything
143
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
144
+
145
+		parent::__construct($timezone);
146
+	}
147
+
148
+
149
+	/**
150
+	 * @return EE_Country[]
151
+	 * @throws EE_Error
152
+	 */
153
+	public function get_all_countries()
154
+	{
155
+		if (! self::$_all_countries) {
156
+			self::$_all_countries = $this->get_all(['order_by' => ['CNT_name' => 'ASC'], 'limit' => [0, 99999]]);
157
+		}
158
+		return self::$_all_countries;
159
+	}
160
+
161
+
162
+	/**
163
+	 * Gets and caches the list of active countries. If you know the list of active countries
164
+	 * has changed during this request, first use EEM_Country::reset() to flush the cache
165
+	 *
166
+	 * @return EE_Country[]
167
+	 * @throws EE_Error
168
+	 */
169
+	public function get_all_active_countries()
170
+	{
171
+		if (! self::$_active_countries) {
172
+			self::$_active_countries =
173
+				$this->get_all([['CNT_active' => true], 'order_by' => ['CNT_name' => 'ASC'], 'limit' => [0, 99999]]);
174
+		}
175
+		return self::$_active_countries;
176
+	}
177
+
178
+
179
+	/**
180
+	 * Gets the country's name by its ISO
181
+	 *
182
+	 * @param string $country_ISO
183
+	 * @return string
184
+	 * @throws EE_Error
185
+	 */
186
+	public function get_country_name_by_ISO($country_ISO)
187
+	{
188
+		$countries = $this->get_all_countries();
189
+		if (isset($countries[ $country_ISO ]) && $countries[ $country_ISO ] instanceof EE_Country) {
190
+			return $countries[ $country_ISO ]->name();
191
+		}
192
+		$names = $this->get_col([['CNT_ISO' => $country_ISO], 'limit' => 1], 'CNT_name');
193
+		if (is_array($names) && ! empty($names)) {
194
+			return reset($names);
195
+		} else {
196
+			return '';
197
+		}
198
+	}
199
+
200
+
201
+	/**
202
+	 * Gets the country's name by its name
203
+	 *
204
+	 * @param string $country_name
205
+	 * @return EE_Country|null
206
+	 * @throws EE_Error
207
+	 */
208
+	public function getCountryByName($country_name)
209
+	{
210
+		$countries = $this->get_all_countries();
211
+		foreach ($countries as $country) {
212
+			if ($country instanceof EE_Country && $country->name() === $country_name) {
213
+				return $country;
214
+			}
215
+		}
216
+		return $this->get_one([['CNT_name' => $country_name]]);
217
+	}
218 218
 }
Please login to merge, or discard this patch.
core/services/calculators/LineItemCalculator.php 2 patches
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
         // for the actual pre-tax sub total line item, we want to save the pretax value for everything
161 161
         if ($line_item->is_sub_total() && $line_item->name() === esc_html__('Pre-Tax Subtotal', 'event_espresso')) {
162 162
             $this->updateTotal($line_item, $pretax_total, true);
163
-        } elseif (! $line_item->is_total()) {
163
+        } elseif ( ! $line_item->is_total()) {
164 164
             // we don't update the total for the total line item, because that will need to include taxes
165 165
             $total = $this->updateTotal($line_item, $total, true);
166 166
         }
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
         } else {
188 188
             // recursively loop through children and recalculate their totals
189 189
             $children = $line_item->children($this->default_query_params);
190
-            if (! empty($children)) {
190
+            if ( ! empty($children)) {
191 191
                 // reset the total and pretax total to zero since we are recalculating them
192 192
                 $total = $pretax_total = 0;
193 193
                 foreach ($children as $child_line_item) {
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
                 $pretax_total = $total = $this->calculateTotalForQuantity($line_item);
206 206
             }
207 207
         }
208
-        $total  = $this->updateTotal($line_item, $total, true);
208
+        $total = $this->updateTotal($line_item, $total, true);
209 209
         $pretax_total = $this->updatePreTaxTotal($line_item, $pretax_total, true);
210 210
 
211 211
         // need to also adjust unit price too if the pretax total or quantity has been updated
@@ -489,7 +489,7 @@  discard block
 block discarded – undo
489 489
         $taxable_total = $this->taxableAmountForGlobalTaxes($total_line_item);
490 490
         $global_taxes     = $this->applyGlobalTaxes($total_line_item, $taxable_total);
491 491
         $non_global_taxes = $this->calculateNonGlobalTaxes($total_line_item);
492
-        $all_tax_total        = $this->applyNonGlobalTaxes($total_line_item, $global_taxes, $non_global_taxes);
492
+        $all_tax_total = $this->applyNonGlobalTaxes($total_line_item, $global_taxes, $non_global_taxes);
493 493
         $this->recalculateTaxSubTotal($total_line_item);
494 494
         return $all_tax_total;
495 495
     }
@@ -582,9 +582,9 @@  discard block
 block discarded – undo
582 582
                         $line_item->pretaxTotal()
583 583
                     );
584 584
                 } elseif ($line_item->isSubTax()) {
585
-                    $tax_ID = $line_item->name() . '_' . $line_item->percent();
586
-                    if (! isset($non_global_taxes[ $tax_ID ])) {
587
-                        $non_global_taxes[ $tax_ID ] = [
585
+                    $tax_ID = $line_item->name().'_'.$line_item->percent();
586
+                    if ( ! isset($non_global_taxes[$tax_ID])) {
587
+                        $non_global_taxes[$tax_ID] = [
588 588
                             'name'  => $line_item->name(),
589 589
                             'rate'  => $line_item->percent(),
590 590
                             'total' => 0,
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
                         ];
594 594
                     }
595 595
                     $tax = $this->calculatePercentage($line_item_total, $line_item->percent());
596
-                    $non_global_taxes[ $tax_ID ]['total'] += $tax;
596
+                    $non_global_taxes[$tax_ID]['total'] += $tax;
597 597
                 }
598 598
             }
599 599
         }
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
                     $tax_total += $non_global_tax['total'];
633 633
                 }
634 634
             }
635
-            if (! $found) {
635
+            if ( ! $found) {
636 636
                 // add a new line item for this non global tax
637 637
                 $taxes_subtotal->add_child_line_item(
638 638
                     EE_Line_Item::new_instance(
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
      */
691 691
     public function taxableAmountForGlobalTaxes(?EE_Line_Item $line_item): float
692 692
     {
693
-        $total      = 0;
693
+        $total = 0;
694 694
         $child_line_items = $line_item->children($this->default_query_params);
695 695
         foreach ($child_line_items as $child_line_item) {
696 696
             $this->validateLineItemAndType($child_line_item);
@@ -721,7 +721,7 @@  discard block
 block discarded – undo
721 721
      */
722 722
     private function validateLineItemAndType(?EE_Line_Item $line_item, ?string $type = null): bool
723 723
     {
724
-        if (! $line_item instanceof EE_Line_Item) {
724
+        if ( ! $line_item instanceof EE_Line_Item) {
725 725
             throw new DomainException(
726 726
                 esc_html__('Invalid or missing Line Item supplied .', 'event_espresso')
727 727
             );
Please login to merge, or discard this patch.
Indentation   +719 added lines, -719 removed lines patch added patch discarded remove patch
@@ -20,723 +20,723 @@
 block discarded – undo
20 20
  */
21 21
 class LineItemCalculator
22 22
 {
23
-    /**
24
-     * @var DecimalValues
25
-     */
26
-    protected $decimal_values;
27
-
28
-    /**
29
-     * @var array
30
-     */
31
-    protected $default_query_params = [
32
-        ['LIN_type' => ['!=', EEM_Line_Item::type_cancellation]]
33
-    ];
34
-
35
-
36
-    /**
37
-     * @param DecimalValues $decimal_values
38
-     */
39
-    public function __construct(DecimalValues $decimal_values)
40
-    {
41
-        $this->decimal_values = $decimal_values;
42
-    }
43
-
44
-
45
-    /**
46
-     * Gets the final total on this item, taking taxes into account.
47
-     * Has the side-effect of setting the sub-total as it was just calculated.
48
-     * If this is used on a grand-total line item, also updates the transaction's
49
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
50
-     * want to change a persistable transaction with info from a non-persistent line item)
51
-     *
52
-     * @param EE_Line_Item $line_item
53
-     * @param bool         $update_txn_status
54
-     * @return float
55
-     * @throws EE_Error
56
-     * @throws ReflectionException
57
-     */
58
-    public function recalculateTotalIncludingTaxes(EE_Line_Item $line_item, bool $update_txn_status = false): float
59
-    {
60
-        $this->validateLineItemAndType($line_item, EEM_Line_Item::type_total);
61
-        $ticket_line_items = EEH_Line_Item::get_ticket_line_items($line_item);
62
-        if (empty($ticket_line_items)) {
63
-            return 0;
64
-        }
65
-        [, $pretax_total] = $this->recalculateLineItemTotals($line_item);
66
-        // EEH_Line_Item::visualize($line_item);
67
-        $total_tax = $this->recalculateTaxesAndTaxTotal($line_item);
68
-        // no negative totals plz
69
-        $grand_total  = max($pretax_total + $total_tax, 0);
70
-        $this->updatePreTaxTotal($line_item, $pretax_total, true);
71
-        $grand_total  = $this->updateTotal($line_item, $grand_total, true);
72
-        $this->updateTransaction($line_item, $grand_total, $update_txn_status);
73
-        return $grand_total;
74
-    }
75
-
76
-
77
-    /**
78
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
79
-     * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
80
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
81
-     * when this is called on the grand total
82
-     *
83
-     * @param EE_Line_Item $line_item
84
-     * @param float        $total
85
-     * @param float        $pretax_total
86
-     * @return array
87
-     * @throws EE_Error
88
-     * @throws ReflectionException
89
-     */
90
-    public function recalculateLineItemTotals(
91
-        EE_Line_Item $line_item,
92
-        float $total = 0,
93
-        float $pretax_total = 0
94
-    ): array {
95
-        switch ($line_item->type()) {
96
-            case EEM_Line_Item::type_total:
97
-            case EEM_Line_Item::type_sub_total:
98
-                [$total, $pretax_total] = $this->recalculateSubTotal($line_item);
99
-                break;
100
-
101
-            case EEM_Line_Item::type_line_item:
102
-                [$total, $pretax_total] = $this->recalculateLineItem($line_item, $total, $pretax_total);
103
-                break;
104
-
105
-            case EEM_Line_Item::type_sub_line_item:
106
-                // sub line items operate on the total and update both the total AND the pre-tax total
107
-                [$total, $pretax_total] = $this->recalculateSubLineItem($line_item, $total, $pretax_total);
108
-                break;
109
-
110
-            case EEM_Line_Item::type_sub_tax:
111
-                // sub line item taxes ONLY operate on the pre-tax total and ONLY update the total
112
-                [$total, $pretax_total] = $this->recalculateSubTax($line_item, $pretax_total);
113
-                break;
114
-
115
-            case EEM_Line_Item::type_tax_sub_total:
116
-            case EEM_Line_Item::type_tax:
117
-            case EEM_Line_Item::type_cancellation:
118
-                // completely ignore tax totals, tax sub-totals, and cancelled line items
119
-                // when calculating the pre-tax-total
120
-                $total = $pretax_total = 0;
121
-                break;
122
-        }
123
-        return [$total, $pretax_total];
124
-    }
125
-
126
-
127
-    /**
128
-     * @param EE_Line_Item $line_item
129
-     * @return array
130
-     * @throws EE_Error
131
-     * @throws ReflectionException
132
-     */
133
-    private function recalculateSubTotal(EE_Line_Item $line_item): array
134
-    {
135
-        // reset the total and pretax total to zero since we are recalculating them
136
-        $total = $pretax_total = 0;
137
-        if ($line_item->is_total()) {
138
-            // if this is the grand total line item
139
-            // then first update ALL of the line item quantities (if need be)
140
-            $this->updateLineItemQuantities($line_item);
141
-        }
142
-        // recursively loop through children and recalculate their totals
143
-        $children = $line_item->children($this->default_query_params);
144
-        if (empty($children)) {
145
-            return [$total, $pretax_total];
146
-        }
147
-        foreach ($children as $child_line_item) {
148
-            [$child_total, $child_pretax_total] = $this->recalculateLineItemTotals(
149
-                $child_line_item,
150
-                $total,
151
-                $pretax_total
152
-            );
153
-            $total += $child_total;
154
-            $pretax_total += $child_pretax_total;
155
-        }
156
-        // update the unit price and pretax total
157
-        $this->updateUnitPrice($line_item, $pretax_total);
158
-        $pretax_total = $this->updatePreTaxTotal($line_item, $pretax_total, true);
159
-        // for the actual pre-tax sub total line item, we want to save the pretax value for everything
160
-        if ($line_item->is_sub_total() && $line_item->name() === esc_html__('Pre-Tax Subtotal', 'event_espresso')) {
161
-            $this->updateTotal($line_item, $pretax_total, true);
162
-        } elseif (! $line_item->is_total()) {
163
-            // we don't update the total for the total line item, because that will need to include taxes
164
-            $total = $this->updateTotal($line_item, $total, true);
165
-        }
166
-        return [$total, $pretax_total];
167
-    }
168
-
169
-
170
-    /**
171
-     * @param EE_Line_Item $line_item
172
-     * @param float        $total
173
-     * @param float        $pretax_total
174
-     * @return array
175
-     * @throws EE_Error
176
-     * @throws ReflectionException
177
-     */
178
-    private function recalculateLineItem(
179
-        EE_Line_Item $line_item,
180
-        float $total = 0,
181
-        float $pretax_total = 0
182
-    ): array {
183
-        if ($line_item->is_percent()) {
184
-            $total = $this->calculatePercentage($total, $line_item->percent());
185
-            $pretax_total = $this->calculatePercentage($pretax_total, $line_item->percent());
186
-        } else {
187
-            // recursively loop through children and recalculate their totals
188
-            $children = $line_item->children($this->default_query_params);
189
-            if (! empty($children)) {
190
-                // reset the total and pretax total to zero since we are recalculating them
191
-                $total = $pretax_total = 0;
192
-                foreach ($children as $child_line_item) {
193
-                    [$child_total, $child_pretax_total] = $this->recalculateLineItemTotals(
194
-                        $child_line_item,
195
-                        $total,
196
-                        $pretax_total
197
-                    );
198
-                    $total        += $child_total;
199
-                    $pretax_total += $child_pretax_total;
200
-                }
201
-            } else {
202
-                // no child line items, so recalculate the total from the unit price and quantity
203
-                // and set the pretax total to match since their are obviously no sub-taxes
204
-                $pretax_total = $total = $this->calculateTotalForQuantity($line_item);
205
-            }
206
-        }
207
-        $total  = $this->updateTotal($line_item, $total, true);
208
-        $pretax_total = $this->updatePreTaxTotal($line_item, $pretax_total, true);
209
-
210
-        // need to also adjust unit price too if the pretax total or quantity has been updated
211
-        $this->updateUnitPrice($line_item, $pretax_total);
212
-        return [$total, $pretax_total];
213
-    }
214
-
215
-
216
-    /**
217
-     * @param EE_Line_Item $sub_line_item
218
-     * @param float|int    $total
219
-     * @param float|int    $pretax_total
220
-     * @return float[]
221
-     * @throws EE_Error
222
-     * @throws ReflectionException
223
-     */
224
-    private function recalculateSubLineItem(EE_Line_Item $sub_line_item, float $total = 0, float $pretax_total = 0): array
225
-    {
226
-        if ($sub_line_item->is_percent()) {
227
-            $new_total = $this->calculatePercentage($total, $sub_line_item->percent());
228
-            $new_pretax_total = $this->calculatePercentage($pretax_total, $sub_line_item->percent());
229
-        } else {
230
-            $new_total = $new_pretax_total = $this->calculateTotalForQuantity($sub_line_item);
231
-        }
232
-        $total = $this->updateTotal($sub_line_item, $new_total);
233
-        $pretax_total = $this->updatePreTaxTotal($sub_line_item, $new_pretax_total);
234
-        // need to also adjust unit price too if the pretax total or quantity has been updated
235
-        $this->updateUnitPrice($sub_line_item, $pretax_total);
236
-        return [$total, $pretax_total];
237
-    }
238
-
239
-
240
-    /**
241
-     * @param EE_Line_Item $sub_line_item
242
-     * @param float|int    $pretax_total
243
-     * @return float[]
244
-     * @throws EE_Error
245
-     * @throws ReflectionException
246
-     */
247
-    private function recalculateSubTax(EE_Line_Item $sub_line_item, float $pretax_total = 0): array
248
-    {
249
-        $total_tax = $this->calculatePercentage($pretax_total, $sub_line_item->percent());
250
-        $total_tax = $this->updateTotal($sub_line_item, $total_tax);
251
-        return [$total_tax, 0];
252
-    }
253
-
254
-
255
-    /**
256
-     * recursively loops through the entire line item tree updating line item quantities accordingly.
257
-     * this needs to be done prior to running any other calculations for reasons that are hopefully obvious :p
258
-     *
259
-     * @param EE_Line_Item $line_item
260
-     * @param int          $quantity
261
-     * @return int
262
-     * @throws EE_Error
263
-     * @throws ReflectionException
264
-     */
265
-    private function updateLineItemQuantities(EE_Line_Item $line_item, int $quantity = 1): int
266
-    {
267
-        switch ($line_item->type()) {
268
-            case EEM_Line_Item::type_total:
269
-            case EEM_Line_Item::type_sub_total:
270
-            case EEM_Line_Item::type_tax_sub_total:
271
-                // first, loop through children and set their quantities
272
-                $count = 0;
273
-                $children = $line_item->children($this->default_query_params);
274
-                foreach ($children as $child_line_item) {
275
-                    $count += $this->updateLineItemQuantities($child_line_item);
276
-                }
277
-                // totals and subtotals should have a quantity of 1
278
-                // unless their children have all been removed, in which case we can set them to 0
279
-                $quantity = $count > 0 ? 1 : 0;
280
-                $this->updateQuantity($line_item, $quantity);
281
-                return $quantity;
282
-
283
-            case EEM_Line_Item::type_line_item:
284
-                // line items should ALREADY have accurate quantities set, if not, then somebody done goofed!
285
-                // but if this is a percentage based line item, then ensure its quantity is 1
286
-                if ($line_item->is_percent()) {
287
-                    $this->updateQuantity($line_item, 1);
288
-                }
289
-                // and we also need to loop through all of the sub items and ensure those quantities match this parent.
290
-                $children = $line_item->children($this->default_query_params);
291
-                $quantity = $line_item->quantity();
292
-                foreach ($children as $child_line_item) {
293
-                    $this->updateLineItemQuantities($child_line_item, $quantity);
294
-                }
295
-                // percentage line items should not increment their parent's count, so they return 0
296
-                return ! $line_item->is_percent() ? $quantity : 0;
297
-
298
-            case EEM_Line_Item::type_sub_line_item:
299
-                // percentage based items need their quantity set to 1,
300
-                // all others use the incoming value from the parent line item
301
-                $quantity = $line_item->is_percent() ? 1 : $quantity;
302
-                $this->updateQuantity($line_item, $quantity);
303
-                // percentage line items should not increment their parent's count, so they return 0
304
-                return ! $line_item->is_percent() ? $quantity : 0;
305
-
306
-            case EEM_Line_Item::type_tax:
307
-            case EEM_Line_Item::type_sub_tax:
308
-                // taxes should have a quantity of 1
309
-                $this->updateQuantity($line_item, 1);
310
-                return 1;
311
-
312
-            case EEM_Line_Item::type_cancellation:
313
-                // cancellations will be ignored for all calculations
314
-                // because their parent quantities should have already been adjusted when they were added
315
-                // so assume that things are already set correctly
316
-                return 0;
317
-        }
318
-        return 0;
319
-    }
320
-
321
-
322
-    /**
323
-     * @param float $total
324
-     * @param float $percent
325
-     * @param bool  $round
326
-     * @return float
327
-     */
328
-    private function calculatePercentage(float $total, float $percent, bool $round = false): float
329
-    {
330
-        $amount = $total * $percent / 100;
331
-        return $this->decimal_values->roundDecimalValue($amount, $round);
332
-    }
333
-
334
-
335
-    /**
336
-     * @param EE_Line_Item $line_item
337
-     * @return float
338
-     * @throws EE_Error
339
-     * @throws ReflectionException
340
-     */
341
-    private function calculateTotalForQuantity(EE_Line_Item $line_item): float
342
-    {
343
-        $total = $line_item->unit_price() * $line_item->quantity();
344
-        return $this->decimal_values->roundDecimalValue($total);
345
-    }
346
-
347
-
348
-    /**
349
-     * @param EE_Line_Item $line_item
350
-     * @param float        $percent
351
-     * @throws EE_Error
352
-     * @throws ReflectionException
353
-     */
354
-    private function updatePercent(EE_Line_Item $line_item, float $percent)
355
-    {
356
-        // update and save new percent only if incoming value does not match existing value
357
-        if ($line_item->percent() !== $percent) {
358
-            $line_item->set_percent($percent);
359
-            $line_item->maybe_save();
360
-        }
361
-    }
362
-
363
-
364
-    /**
365
-     * @param EE_Line_Item $line_item
366
-     * @param float        $pretax_total
367
-     * @param bool         $round
368
-     * @return float
369
-     * @throws EE_Error
370
-     * @throws ReflectionException
371
-     */
372
-    private function updatePreTaxTotal(EE_Line_Item $line_item, float $pretax_total, bool $round = false): float
373
-    {
374
-        $pretax_total = $this->decimal_values->roundDecimalValue($pretax_total, $round);
375
-        // update and save new total only if incoming value does not match existing value
376
-        if ($line_item->preTaxTotal() !== $pretax_total) {
377
-            $line_item->setPreTaxTotal($pretax_total);
378
-            $line_item->maybe_save();
379
-        }
380
-        return $pretax_total;
381
-    }
382
-
383
-
384
-    /**
385
-     * @param EE_Line_Item $line_item
386
-     * @param int          $quantity
387
-     * @throws EE_Error
388
-     * @throws ReflectionException
389
-     */
390
-    private function updateQuantity(EE_Line_Item $line_item, int $quantity)
391
-    {
392
-        // update and save new quantity only if incoming value does not match existing value
393
-        if ($line_item->quantity() !== $quantity) {
394
-            $line_item->set_quantity($quantity);
395
-            $line_item->maybe_save();
396
-        }
397
-    }
398
-
399
-
400
-    /**
401
-     * @param EE_Line_Item $line_item
402
-     * @param float        $total
403
-     * @param bool         $round
404
-     * @return float
405
-     * @throws EE_Error
406
-     * @throws ReflectionException
407
-     */
408
-    private function updateTotal(EE_Line_Item $line_item, float $total, bool $round = false): float
409
-    {
410
-        $total = $this->decimal_values->roundDecimalValue($total, $round);
411
-        // update and save new total only if incoming value does not match existing value
412
-        if ($line_item->total() !== $total) {
413
-            $line_item->set_total($total);
414
-            $line_item->maybe_save();
415
-        }
416
-        return $total;
417
-    }
418
-
419
-
420
-    /**
421
-     * @param EE_Line_Item $line_item
422
-     * @param float        $total
423
-     * @param bool         $update_status
424
-     * @return void
425
-     * @throws EE_Error
426
-     * @throws ReflectionException
427
-     */
428
-    private function updateTransaction(EE_Line_Item $line_item, float $total, bool $update_status)
429
-    {
430
-        // only update the related transaction's total
431
-        // if we intend to save this line item and its a grand total
432
-        if ($line_item->allow_persist()) {
433
-            $transaction = $line_item->transaction();
434
-            if ($transaction instanceof EE_Transaction) {
435
-                $transaction->set_total($total);
436
-                if ($update_status) {
437
-                    // don't save the TXN because that will be done below
438
-                    // and the following method only saves if the status changes
439
-                    $transaction->update_status_based_on_total_paid(false);
440
-                }
441
-                if ($transaction->ID()) {
442
-                    $transaction->save();
443
-                }
444
-            }
445
-        }
446
-    }
447
-
448
-
449
-    /**
450
-     * @param EE_Line_Item $line_item
451
-     * @param float        $pretax_total
452
-     * @return void
453
-     * @throws EE_Error
454
-     * @throws ReflectionException
455
-     */
456
-    private function updateUnitPrice(EE_Line_Item $line_item, float $pretax_total)
457
-    {
458
-        $quantity = $line_item->quantity();
459
-        // don't divide by zero else you'll create a singularity and implode the interweb
460
-        // we also don't set unit prices for percentage based line items
461
-        if ($quantity === 0 || $line_item->is_percent()) {
462
-            return;
463
-        }
464
-        $new_unit_price = $pretax_total / $quantity;
465
-        $new_unit_price = $this->decimal_values->roundDecimalValue($new_unit_price);
466
-        // update and save new total only if incoming value does not match existing value
467
-        if ($line_item->unit_price() !== $new_unit_price) {
468
-            $line_item->set_unit_price($new_unit_price);
469
-            $line_item->maybe_save();
470
-        }
471
-    }
472
-
473
-
474
-    /**
475
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
476
-     * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
477
-     * and tax sub-total if already in the DB
478
-     *
479
-     * @param EE_Line_Item $total_line_item
480
-     * @return float
481
-     * @throws EE_Error
482
-     * @throws ReflectionException
483
-     */
484
-    public function recalculateTaxesAndTaxTotal(EE_Line_Item $total_line_item): float
485
-    {
486
-        $this->validateLineItemAndType($total_line_item, EEM_Line_Item::type_total);
487
-        // calculate the total taxable amount for globally applied taxes
488
-        $taxable_total = $this->taxableAmountForGlobalTaxes($total_line_item);
489
-        $global_taxes     = $this->applyGlobalTaxes($total_line_item, $taxable_total);
490
-        $non_global_taxes = $this->calculateNonGlobalTaxes($total_line_item);
491
-        $all_tax_total        = $this->applyNonGlobalTaxes($total_line_item, $global_taxes, $non_global_taxes);
492
-        $this->recalculateTaxSubTotal($total_line_item);
493
-        return $all_tax_total;
494
-    }
495
-
496
-
497
-    /**
498
-     * @param EE_Line_Item $total_line_item
499
-     * @param float        $taxable_total
500
-     * @return float
501
-     * @throws EE_Error
502
-     * @throws ReflectionException
503
-     */
504
-    private function applyGlobalTaxes(EE_Line_Item $total_line_item, float $taxable_total): float
505
-    {
506
-        $this->validateLineItemAndType($total_line_item, EEM_Line_Item::type_total);
507
-        $total_tax = 0;
508
-        // loop through all global taxes all taxes
509
-        $global_taxes = $total_line_item->tax_descendants();
510
-        foreach ($global_taxes as $tax) {
511
-            $tax_total = $this->calculatePercentage($taxable_total, $tax->percent());
512
-            $tax_total = $this->updateTotal($tax, $tax_total, true);
513
-            $total_tax += $tax_total;
514
-        }
515
-        return $this->decimal_values->roundDecimalValue($total_tax, true);
516
-    }
517
-
518
-
519
-    /**
520
-     * Simply forces all the tax-sub-totals to recalculate. Assumes the taxes have been calculated
521
-     *
522
-     * @param EE_Line_Item $line_item
523
-     * @return void
524
-     * @throws EE_Error
525
-     * @throws ReflectionException
526
-     */
527
-    private function recalculateTaxSubTotal(EE_Line_Item $line_item)
528
-    {
529
-        $this->validateLineItemAndType($line_item, EEM_Line_Item::type_total);
530
-        foreach ($line_item->children() as $maybe_tax_subtotal) {
531
-            if (
532
-                $this->validateLineItemAndType($maybe_tax_subtotal)
533
-                && $maybe_tax_subtotal->is_tax_sub_total()
534
-            ) {
535
-                $total         = 0;
536
-                $total_percent = 0;
537
-                // simply loop through all its children (which should be taxes) and sum their total
538
-                foreach ($maybe_tax_subtotal->children() as $child_tax) {
539
-                    if ($this->validateLineItemAndType($child_tax) && $child_tax->isGlobalTax()) {
540
-                        $total         += $child_tax->total();
541
-                        $total_percent += $child_tax->percent();
542
-                    }
543
-                }
544
-                $this->updateTotal($maybe_tax_subtotal, $total, true);
545
-                $this->updatePercent($maybe_tax_subtotal, $total_percent);
546
-            }
547
-        }
548
-    }
549
-
550
-
551
-    /**
552
-     * returns an array of tax details like:
553
-     *  [
554
-     *      'GST_7' => [
555
-     *          'name'  => 'GST',
556
-     *          'rate'  => float(7),
557
-     *          'total' => float(4.9),
558
-     *      ]
559
-     *  ]
560
-     *
561
-     * @param EE_Line_Item $total_line_item
562
-     * @param array        $non_global_taxes
563
-     * @param float        $line_item_total
564
-     * @return array
565
-     * @throws EE_Error
566
-     * @throws ReflectionException
567
-     */
568
-    private function calculateNonGlobalTaxes(
569
-        EE_Line_Item $total_line_item,
570
-        array $non_global_taxes = [],
571
-        float $line_item_total = 0
572
-    ): array {
573
-        foreach ($total_line_item->children() as $line_item) {
574
-            if ($this->validateLineItemAndType($line_item)) {
575
-                if ($line_item->is_sub_total()) {
576
-                    $non_global_taxes = $this->calculateNonGlobalTaxes($line_item, $non_global_taxes);
577
-                } elseif ($line_item->is_line_item()) {
578
-                    $non_global_taxes = $this->calculateNonGlobalTaxes(
579
-                        $line_item,
580
-                        $non_global_taxes,
581
-                        $line_item->pretaxTotal()
582
-                    );
583
-                } elseif ($line_item->isSubTax()) {
584
-                    $tax_ID = $line_item->name() . '_' . $line_item->percent();
585
-                    if (! isset($non_global_taxes[ $tax_ID ])) {
586
-                        $non_global_taxes[ $tax_ID ] = [
587
-                            'name'  => $line_item->name(),
588
-                            'rate'  => $line_item->percent(),
589
-                            'total' => 0,
590
-                            'obj'   => $line_item->OBJ_type(),
591
-                            'objID' => $line_item->OBJ_ID(),
592
-                        ];
593
-                    }
594
-                    $tax = $this->calculatePercentage($line_item_total, $line_item->percent());
595
-                    $non_global_taxes[ $tax_ID ]['total'] += $tax;
596
-                }
597
-            }
598
-        }
599
-        return $non_global_taxes;
600
-    }
601
-
602
-
603
-    /**
604
-     * @param EE_Line_Item $total_line_item
605
-     * @param float        $tax_total
606
-     * @param array        $non_global_taxes array of tax details generated by calculateNonGlobalTaxes()
607
-     * @return float
608
-     * @throws EE_Error
609
-     * @throws ReflectionException
610
-     */
611
-    private function applyNonGlobalTaxes(
612
-        EE_Line_Item $total_line_item,
613
-        float $tax_total,
614
-        array $non_global_taxes
615
-    ): float {
616
-        $global_taxes   = $total_line_item->tax_descendants();
617
-        $taxes_subtotal = EEH_Line_Item::get_taxes_subtotal($total_line_item);
618
-        foreach ($non_global_taxes as $non_global_tax) {
619
-            $found = false;
620
-            foreach ($global_taxes as $global_tax) {
621
-                if (
622
-                    $this->validateLineItemAndType($global_tax)
623
-                    && $non_global_tax['obj'] === $global_tax->OBJ_type()
624
-                    && $non_global_tax['objID'] === $global_tax->OBJ_ID()
625
-                ) {
626
-                    $found = true;
627
-                    $new_total = $global_tax->total() + $non_global_tax['total'];
628
-                    // add non global tax to matching global tax AND the tax total
629
-                    $global_tax->set_total($new_total);
630
-                    $global_tax->maybe_save();
631
-                    $tax_total += $non_global_tax['total'];
632
-                }
633
-            }
634
-            if (! $found) {
635
-                // add a new line item for this non global tax
636
-                $taxes_subtotal->add_child_line_item(
637
-                    EE_Line_Item::new_instance(
638
-                        [
639
-                            'LIN_name'       => $non_global_tax['name'],
640
-                            'LIN_percent'    => $non_global_tax['rate'],
641
-                            'LIN_is_taxable' => false,
642
-                            'LIN_total'      => $non_global_tax['total'],
643
-                            'LIN_type'       => EEM_Line_Item::type_tax,
644
-                            'OBJ_type'       => $non_global_tax['obj'],
645
-                            'OBJ_ID'         => $non_global_tax['objID'],
646
-                        ]
647
-                    )
648
-                );
649
-                $tax_total += $non_global_tax['total'];
650
-            }
651
-        }
652
-        return $this->decimal_values->roundDecimalValue($tax_total, true);
653
-    }
654
-
655
-
656
-    /**
657
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
658
-     * recalculate_taxes_and_total
659
-     *
660
-     * @param EE_Line_Item $line_item
661
-     * @return float
662
-     * @throws EE_Error
663
-     * @throws ReflectionException
664
-     */
665
-    public function getTotalTax(EE_Line_Item $line_item): float
666
-    {
667
-        $this->validateLineItemAndType($line_item, EEM_Line_Item::type_total);
668
-        $this->recalculateTaxSubTotal($line_item);
669
-        $total = 0;
670
-        foreach ($line_item->tax_descendants() as $tax_line_item) {
671
-            if ($this->validateLineItemAndType($tax_line_item)) {
672
-                $total += $tax_line_item->total();
673
-            }
674
-        }
675
-        return $this->decimal_values->roundDecimalValue($total, true);
676
-    }
677
-
678
-
679
-    /**
680
-     * Returns the amount taxable among this line item's children (or if it has no children,
681
-     * how much of it is taxable). Does not recalculate totals or subtotals.
682
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
683
-     * but there is a "Taxable" discount), returns 0.
684
-     *
685
-     * @param EE_Line_Item|null $line_item
686
-     * @return float
687
-     * @throws EE_Error
688
-     * @throws ReflectionException
689
-     */
690
-    public function taxableAmountForGlobalTaxes(?EE_Line_Item $line_item): float
691
-    {
692
-        $total      = 0;
693
-        $child_line_items = $line_item->children($this->default_query_params);
694
-        foreach ($child_line_items as $child_line_item) {
695
-            $this->validateLineItemAndType($child_line_item);
696
-            if ($child_line_item->is_sub_total()) {
697
-                $total += $this->taxableAmountForGlobalTaxes($child_line_item);
698
-            } elseif ($child_line_item->is_line_item() && $child_line_item->is_taxable()) {
699
-                // if it's a percent item, only take into account
700
-                // the percentage that's taxable (the taxable total so far)
701
-                if ($child_line_item->is_percent()) {
702
-                    $total += $this->calculatePercentage($total, $child_line_item->percent(), true);
703
-                } else {
704
-                    // pretax total will be equal to the total for line items with globally applied taxes
705
-                    $pretax_total = $this->calculateTotalForQuantity($child_line_item);
706
-                    $total += $this->updatePreTaxTotal($child_line_item, $pretax_total);
707
-                }
708
-            }
709
-        }
710
-        return max($total, 0);
711
-    }
712
-
713
-
714
-    /**
715
-     * @param EE_Line_Item|null $line_item
716
-     * @param string|null       $type
717
-     * @return bool
718
-     * @throws EE_Error
719
-     * @throws ReflectionException
720
-     */
721
-    private function validateLineItemAndType(?EE_Line_Item $line_item, ?string $type = null): bool
722
-    {
723
-        if (! $line_item instanceof EE_Line_Item) {
724
-            throw new DomainException(
725
-                esc_html__('Invalid or missing Line Item supplied .', 'event_espresso')
726
-            );
727
-        }
728
-        if ($type && $line_item->type() !== $type) {
729
-            throw new DomainException(
730
-                sprintf(
731
-                    esc_html__(
732
-                        'Invalid Line Item type supplied. Received "%1$s" but expected "%2$s".',
733
-                        'event_espresso'
734
-                    ),
735
-                    $line_item->type(),
736
-                    $type
737
-                )
738
-            );
739
-        }
740
-        return true;
741
-    }
23
+	/**
24
+	 * @var DecimalValues
25
+	 */
26
+	protected $decimal_values;
27
+
28
+	/**
29
+	 * @var array
30
+	 */
31
+	protected $default_query_params = [
32
+		['LIN_type' => ['!=', EEM_Line_Item::type_cancellation]]
33
+	];
34
+
35
+
36
+	/**
37
+	 * @param DecimalValues $decimal_values
38
+	 */
39
+	public function __construct(DecimalValues $decimal_values)
40
+	{
41
+		$this->decimal_values = $decimal_values;
42
+	}
43
+
44
+
45
+	/**
46
+	 * Gets the final total on this item, taking taxes into account.
47
+	 * Has the side-effect of setting the sub-total as it was just calculated.
48
+	 * If this is used on a grand-total line item, also updates the transaction's
49
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
50
+	 * want to change a persistable transaction with info from a non-persistent line item)
51
+	 *
52
+	 * @param EE_Line_Item $line_item
53
+	 * @param bool         $update_txn_status
54
+	 * @return float
55
+	 * @throws EE_Error
56
+	 * @throws ReflectionException
57
+	 */
58
+	public function recalculateTotalIncludingTaxes(EE_Line_Item $line_item, bool $update_txn_status = false): float
59
+	{
60
+		$this->validateLineItemAndType($line_item, EEM_Line_Item::type_total);
61
+		$ticket_line_items = EEH_Line_Item::get_ticket_line_items($line_item);
62
+		if (empty($ticket_line_items)) {
63
+			return 0;
64
+		}
65
+		[, $pretax_total] = $this->recalculateLineItemTotals($line_item);
66
+		// EEH_Line_Item::visualize($line_item);
67
+		$total_tax = $this->recalculateTaxesAndTaxTotal($line_item);
68
+		// no negative totals plz
69
+		$grand_total  = max($pretax_total + $total_tax, 0);
70
+		$this->updatePreTaxTotal($line_item, $pretax_total, true);
71
+		$grand_total  = $this->updateTotal($line_item, $grand_total, true);
72
+		$this->updateTransaction($line_item, $grand_total, $update_txn_status);
73
+		return $grand_total;
74
+	}
75
+
76
+
77
+	/**
78
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
79
+	 * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
80
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
81
+	 * when this is called on the grand total
82
+	 *
83
+	 * @param EE_Line_Item $line_item
84
+	 * @param float        $total
85
+	 * @param float        $pretax_total
86
+	 * @return array
87
+	 * @throws EE_Error
88
+	 * @throws ReflectionException
89
+	 */
90
+	public function recalculateLineItemTotals(
91
+		EE_Line_Item $line_item,
92
+		float $total = 0,
93
+		float $pretax_total = 0
94
+	): array {
95
+		switch ($line_item->type()) {
96
+			case EEM_Line_Item::type_total:
97
+			case EEM_Line_Item::type_sub_total:
98
+				[$total, $pretax_total] = $this->recalculateSubTotal($line_item);
99
+				break;
100
+
101
+			case EEM_Line_Item::type_line_item:
102
+				[$total, $pretax_total] = $this->recalculateLineItem($line_item, $total, $pretax_total);
103
+				break;
104
+
105
+			case EEM_Line_Item::type_sub_line_item:
106
+				// sub line items operate on the total and update both the total AND the pre-tax total
107
+				[$total, $pretax_total] = $this->recalculateSubLineItem($line_item, $total, $pretax_total);
108
+				break;
109
+
110
+			case EEM_Line_Item::type_sub_tax:
111
+				// sub line item taxes ONLY operate on the pre-tax total and ONLY update the total
112
+				[$total, $pretax_total] = $this->recalculateSubTax($line_item, $pretax_total);
113
+				break;
114
+
115
+			case EEM_Line_Item::type_tax_sub_total:
116
+			case EEM_Line_Item::type_tax:
117
+			case EEM_Line_Item::type_cancellation:
118
+				// completely ignore tax totals, tax sub-totals, and cancelled line items
119
+				// when calculating the pre-tax-total
120
+				$total = $pretax_total = 0;
121
+				break;
122
+		}
123
+		return [$total, $pretax_total];
124
+	}
125
+
126
+
127
+	/**
128
+	 * @param EE_Line_Item $line_item
129
+	 * @return array
130
+	 * @throws EE_Error
131
+	 * @throws ReflectionException
132
+	 */
133
+	private function recalculateSubTotal(EE_Line_Item $line_item): array
134
+	{
135
+		// reset the total and pretax total to zero since we are recalculating them
136
+		$total = $pretax_total = 0;
137
+		if ($line_item->is_total()) {
138
+			// if this is the grand total line item
139
+			// then first update ALL of the line item quantities (if need be)
140
+			$this->updateLineItemQuantities($line_item);
141
+		}
142
+		// recursively loop through children and recalculate their totals
143
+		$children = $line_item->children($this->default_query_params);
144
+		if (empty($children)) {
145
+			return [$total, $pretax_total];
146
+		}
147
+		foreach ($children as $child_line_item) {
148
+			[$child_total, $child_pretax_total] = $this->recalculateLineItemTotals(
149
+				$child_line_item,
150
+				$total,
151
+				$pretax_total
152
+			);
153
+			$total += $child_total;
154
+			$pretax_total += $child_pretax_total;
155
+		}
156
+		// update the unit price and pretax total
157
+		$this->updateUnitPrice($line_item, $pretax_total);
158
+		$pretax_total = $this->updatePreTaxTotal($line_item, $pretax_total, true);
159
+		// for the actual pre-tax sub total line item, we want to save the pretax value for everything
160
+		if ($line_item->is_sub_total() && $line_item->name() === esc_html__('Pre-Tax Subtotal', 'event_espresso')) {
161
+			$this->updateTotal($line_item, $pretax_total, true);
162
+		} elseif (! $line_item->is_total()) {
163
+			// we don't update the total for the total line item, because that will need to include taxes
164
+			$total = $this->updateTotal($line_item, $total, true);
165
+		}
166
+		return [$total, $pretax_total];
167
+	}
168
+
169
+
170
+	/**
171
+	 * @param EE_Line_Item $line_item
172
+	 * @param float        $total
173
+	 * @param float        $pretax_total
174
+	 * @return array
175
+	 * @throws EE_Error
176
+	 * @throws ReflectionException
177
+	 */
178
+	private function recalculateLineItem(
179
+		EE_Line_Item $line_item,
180
+		float $total = 0,
181
+		float $pretax_total = 0
182
+	): array {
183
+		if ($line_item->is_percent()) {
184
+			$total = $this->calculatePercentage($total, $line_item->percent());
185
+			$pretax_total = $this->calculatePercentage($pretax_total, $line_item->percent());
186
+		} else {
187
+			// recursively loop through children and recalculate their totals
188
+			$children = $line_item->children($this->default_query_params);
189
+			if (! empty($children)) {
190
+				// reset the total and pretax total to zero since we are recalculating them
191
+				$total = $pretax_total = 0;
192
+				foreach ($children as $child_line_item) {
193
+					[$child_total, $child_pretax_total] = $this->recalculateLineItemTotals(
194
+						$child_line_item,
195
+						$total,
196
+						$pretax_total
197
+					);
198
+					$total        += $child_total;
199
+					$pretax_total += $child_pretax_total;
200
+				}
201
+			} else {
202
+				// no child line items, so recalculate the total from the unit price and quantity
203
+				// and set the pretax total to match since their are obviously no sub-taxes
204
+				$pretax_total = $total = $this->calculateTotalForQuantity($line_item);
205
+			}
206
+		}
207
+		$total  = $this->updateTotal($line_item, $total, true);
208
+		$pretax_total = $this->updatePreTaxTotal($line_item, $pretax_total, true);
209
+
210
+		// need to also adjust unit price too if the pretax total or quantity has been updated
211
+		$this->updateUnitPrice($line_item, $pretax_total);
212
+		return [$total, $pretax_total];
213
+	}
214
+
215
+
216
+	/**
217
+	 * @param EE_Line_Item $sub_line_item
218
+	 * @param float|int    $total
219
+	 * @param float|int    $pretax_total
220
+	 * @return float[]
221
+	 * @throws EE_Error
222
+	 * @throws ReflectionException
223
+	 */
224
+	private function recalculateSubLineItem(EE_Line_Item $sub_line_item, float $total = 0, float $pretax_total = 0): array
225
+	{
226
+		if ($sub_line_item->is_percent()) {
227
+			$new_total = $this->calculatePercentage($total, $sub_line_item->percent());
228
+			$new_pretax_total = $this->calculatePercentage($pretax_total, $sub_line_item->percent());
229
+		} else {
230
+			$new_total = $new_pretax_total = $this->calculateTotalForQuantity($sub_line_item);
231
+		}
232
+		$total = $this->updateTotal($sub_line_item, $new_total);
233
+		$pretax_total = $this->updatePreTaxTotal($sub_line_item, $new_pretax_total);
234
+		// need to also adjust unit price too if the pretax total or quantity has been updated
235
+		$this->updateUnitPrice($sub_line_item, $pretax_total);
236
+		return [$total, $pretax_total];
237
+	}
238
+
239
+
240
+	/**
241
+	 * @param EE_Line_Item $sub_line_item
242
+	 * @param float|int    $pretax_total
243
+	 * @return float[]
244
+	 * @throws EE_Error
245
+	 * @throws ReflectionException
246
+	 */
247
+	private function recalculateSubTax(EE_Line_Item $sub_line_item, float $pretax_total = 0): array
248
+	{
249
+		$total_tax = $this->calculatePercentage($pretax_total, $sub_line_item->percent());
250
+		$total_tax = $this->updateTotal($sub_line_item, $total_tax);
251
+		return [$total_tax, 0];
252
+	}
253
+
254
+
255
+	/**
256
+	 * recursively loops through the entire line item tree updating line item quantities accordingly.
257
+	 * this needs to be done prior to running any other calculations for reasons that are hopefully obvious :p
258
+	 *
259
+	 * @param EE_Line_Item $line_item
260
+	 * @param int          $quantity
261
+	 * @return int
262
+	 * @throws EE_Error
263
+	 * @throws ReflectionException
264
+	 */
265
+	private function updateLineItemQuantities(EE_Line_Item $line_item, int $quantity = 1): int
266
+	{
267
+		switch ($line_item->type()) {
268
+			case EEM_Line_Item::type_total:
269
+			case EEM_Line_Item::type_sub_total:
270
+			case EEM_Line_Item::type_tax_sub_total:
271
+				// first, loop through children and set their quantities
272
+				$count = 0;
273
+				$children = $line_item->children($this->default_query_params);
274
+				foreach ($children as $child_line_item) {
275
+					$count += $this->updateLineItemQuantities($child_line_item);
276
+				}
277
+				// totals and subtotals should have a quantity of 1
278
+				// unless their children have all been removed, in which case we can set them to 0
279
+				$quantity = $count > 0 ? 1 : 0;
280
+				$this->updateQuantity($line_item, $quantity);
281
+				return $quantity;
282
+
283
+			case EEM_Line_Item::type_line_item:
284
+				// line items should ALREADY have accurate quantities set, if not, then somebody done goofed!
285
+				// but if this is a percentage based line item, then ensure its quantity is 1
286
+				if ($line_item->is_percent()) {
287
+					$this->updateQuantity($line_item, 1);
288
+				}
289
+				// and we also need to loop through all of the sub items and ensure those quantities match this parent.
290
+				$children = $line_item->children($this->default_query_params);
291
+				$quantity = $line_item->quantity();
292
+				foreach ($children as $child_line_item) {
293
+					$this->updateLineItemQuantities($child_line_item, $quantity);
294
+				}
295
+				// percentage line items should not increment their parent's count, so they return 0
296
+				return ! $line_item->is_percent() ? $quantity : 0;
297
+
298
+			case EEM_Line_Item::type_sub_line_item:
299
+				// percentage based items need their quantity set to 1,
300
+				// all others use the incoming value from the parent line item
301
+				$quantity = $line_item->is_percent() ? 1 : $quantity;
302
+				$this->updateQuantity($line_item, $quantity);
303
+				// percentage line items should not increment their parent's count, so they return 0
304
+				return ! $line_item->is_percent() ? $quantity : 0;
305
+
306
+			case EEM_Line_Item::type_tax:
307
+			case EEM_Line_Item::type_sub_tax:
308
+				// taxes should have a quantity of 1
309
+				$this->updateQuantity($line_item, 1);
310
+				return 1;
311
+
312
+			case EEM_Line_Item::type_cancellation:
313
+				// cancellations will be ignored for all calculations
314
+				// because their parent quantities should have already been adjusted when they were added
315
+				// so assume that things are already set correctly
316
+				return 0;
317
+		}
318
+		return 0;
319
+	}
320
+
321
+
322
+	/**
323
+	 * @param float $total
324
+	 * @param float $percent
325
+	 * @param bool  $round
326
+	 * @return float
327
+	 */
328
+	private function calculatePercentage(float $total, float $percent, bool $round = false): float
329
+	{
330
+		$amount = $total * $percent / 100;
331
+		return $this->decimal_values->roundDecimalValue($amount, $round);
332
+	}
333
+
334
+
335
+	/**
336
+	 * @param EE_Line_Item $line_item
337
+	 * @return float
338
+	 * @throws EE_Error
339
+	 * @throws ReflectionException
340
+	 */
341
+	private function calculateTotalForQuantity(EE_Line_Item $line_item): float
342
+	{
343
+		$total = $line_item->unit_price() * $line_item->quantity();
344
+		return $this->decimal_values->roundDecimalValue($total);
345
+	}
346
+
347
+
348
+	/**
349
+	 * @param EE_Line_Item $line_item
350
+	 * @param float        $percent
351
+	 * @throws EE_Error
352
+	 * @throws ReflectionException
353
+	 */
354
+	private function updatePercent(EE_Line_Item $line_item, float $percent)
355
+	{
356
+		// update and save new percent only if incoming value does not match existing value
357
+		if ($line_item->percent() !== $percent) {
358
+			$line_item->set_percent($percent);
359
+			$line_item->maybe_save();
360
+		}
361
+	}
362
+
363
+
364
+	/**
365
+	 * @param EE_Line_Item $line_item
366
+	 * @param float        $pretax_total
367
+	 * @param bool         $round
368
+	 * @return float
369
+	 * @throws EE_Error
370
+	 * @throws ReflectionException
371
+	 */
372
+	private function updatePreTaxTotal(EE_Line_Item $line_item, float $pretax_total, bool $round = false): float
373
+	{
374
+		$pretax_total = $this->decimal_values->roundDecimalValue($pretax_total, $round);
375
+		// update and save new total only if incoming value does not match existing value
376
+		if ($line_item->preTaxTotal() !== $pretax_total) {
377
+			$line_item->setPreTaxTotal($pretax_total);
378
+			$line_item->maybe_save();
379
+		}
380
+		return $pretax_total;
381
+	}
382
+
383
+
384
+	/**
385
+	 * @param EE_Line_Item $line_item
386
+	 * @param int          $quantity
387
+	 * @throws EE_Error
388
+	 * @throws ReflectionException
389
+	 */
390
+	private function updateQuantity(EE_Line_Item $line_item, int $quantity)
391
+	{
392
+		// update and save new quantity only if incoming value does not match existing value
393
+		if ($line_item->quantity() !== $quantity) {
394
+			$line_item->set_quantity($quantity);
395
+			$line_item->maybe_save();
396
+		}
397
+	}
398
+
399
+
400
+	/**
401
+	 * @param EE_Line_Item $line_item
402
+	 * @param float        $total
403
+	 * @param bool         $round
404
+	 * @return float
405
+	 * @throws EE_Error
406
+	 * @throws ReflectionException
407
+	 */
408
+	private function updateTotal(EE_Line_Item $line_item, float $total, bool $round = false): float
409
+	{
410
+		$total = $this->decimal_values->roundDecimalValue($total, $round);
411
+		// update and save new total only if incoming value does not match existing value
412
+		if ($line_item->total() !== $total) {
413
+			$line_item->set_total($total);
414
+			$line_item->maybe_save();
415
+		}
416
+		return $total;
417
+	}
418
+
419
+
420
+	/**
421
+	 * @param EE_Line_Item $line_item
422
+	 * @param float        $total
423
+	 * @param bool         $update_status
424
+	 * @return void
425
+	 * @throws EE_Error
426
+	 * @throws ReflectionException
427
+	 */
428
+	private function updateTransaction(EE_Line_Item $line_item, float $total, bool $update_status)
429
+	{
430
+		// only update the related transaction's total
431
+		// if we intend to save this line item and its a grand total
432
+		if ($line_item->allow_persist()) {
433
+			$transaction = $line_item->transaction();
434
+			if ($transaction instanceof EE_Transaction) {
435
+				$transaction->set_total($total);
436
+				if ($update_status) {
437
+					// don't save the TXN because that will be done below
438
+					// and the following method only saves if the status changes
439
+					$transaction->update_status_based_on_total_paid(false);
440
+				}
441
+				if ($transaction->ID()) {
442
+					$transaction->save();
443
+				}
444
+			}
445
+		}
446
+	}
447
+
448
+
449
+	/**
450
+	 * @param EE_Line_Item $line_item
451
+	 * @param float        $pretax_total
452
+	 * @return void
453
+	 * @throws EE_Error
454
+	 * @throws ReflectionException
455
+	 */
456
+	private function updateUnitPrice(EE_Line_Item $line_item, float $pretax_total)
457
+	{
458
+		$quantity = $line_item->quantity();
459
+		// don't divide by zero else you'll create a singularity and implode the interweb
460
+		// we also don't set unit prices for percentage based line items
461
+		if ($quantity === 0 || $line_item->is_percent()) {
462
+			return;
463
+		}
464
+		$new_unit_price = $pretax_total / $quantity;
465
+		$new_unit_price = $this->decimal_values->roundDecimalValue($new_unit_price);
466
+		// update and save new total only if incoming value does not match existing value
467
+		if ($line_item->unit_price() !== $new_unit_price) {
468
+			$line_item->set_unit_price($new_unit_price);
469
+			$line_item->maybe_save();
470
+		}
471
+	}
472
+
473
+
474
+	/**
475
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
476
+	 * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
477
+	 * and tax sub-total if already in the DB
478
+	 *
479
+	 * @param EE_Line_Item $total_line_item
480
+	 * @return float
481
+	 * @throws EE_Error
482
+	 * @throws ReflectionException
483
+	 */
484
+	public function recalculateTaxesAndTaxTotal(EE_Line_Item $total_line_item): float
485
+	{
486
+		$this->validateLineItemAndType($total_line_item, EEM_Line_Item::type_total);
487
+		// calculate the total taxable amount for globally applied taxes
488
+		$taxable_total = $this->taxableAmountForGlobalTaxes($total_line_item);
489
+		$global_taxes     = $this->applyGlobalTaxes($total_line_item, $taxable_total);
490
+		$non_global_taxes = $this->calculateNonGlobalTaxes($total_line_item);
491
+		$all_tax_total        = $this->applyNonGlobalTaxes($total_line_item, $global_taxes, $non_global_taxes);
492
+		$this->recalculateTaxSubTotal($total_line_item);
493
+		return $all_tax_total;
494
+	}
495
+
496
+
497
+	/**
498
+	 * @param EE_Line_Item $total_line_item
499
+	 * @param float        $taxable_total
500
+	 * @return float
501
+	 * @throws EE_Error
502
+	 * @throws ReflectionException
503
+	 */
504
+	private function applyGlobalTaxes(EE_Line_Item $total_line_item, float $taxable_total): float
505
+	{
506
+		$this->validateLineItemAndType($total_line_item, EEM_Line_Item::type_total);
507
+		$total_tax = 0;
508
+		// loop through all global taxes all taxes
509
+		$global_taxes = $total_line_item->tax_descendants();
510
+		foreach ($global_taxes as $tax) {
511
+			$tax_total = $this->calculatePercentage($taxable_total, $tax->percent());
512
+			$tax_total = $this->updateTotal($tax, $tax_total, true);
513
+			$total_tax += $tax_total;
514
+		}
515
+		return $this->decimal_values->roundDecimalValue($total_tax, true);
516
+	}
517
+
518
+
519
+	/**
520
+	 * Simply forces all the tax-sub-totals to recalculate. Assumes the taxes have been calculated
521
+	 *
522
+	 * @param EE_Line_Item $line_item
523
+	 * @return void
524
+	 * @throws EE_Error
525
+	 * @throws ReflectionException
526
+	 */
527
+	private function recalculateTaxSubTotal(EE_Line_Item $line_item)
528
+	{
529
+		$this->validateLineItemAndType($line_item, EEM_Line_Item::type_total);
530
+		foreach ($line_item->children() as $maybe_tax_subtotal) {
531
+			if (
532
+				$this->validateLineItemAndType($maybe_tax_subtotal)
533
+				&& $maybe_tax_subtotal->is_tax_sub_total()
534
+			) {
535
+				$total         = 0;
536
+				$total_percent = 0;
537
+				// simply loop through all its children (which should be taxes) and sum their total
538
+				foreach ($maybe_tax_subtotal->children() as $child_tax) {
539
+					if ($this->validateLineItemAndType($child_tax) && $child_tax->isGlobalTax()) {
540
+						$total         += $child_tax->total();
541
+						$total_percent += $child_tax->percent();
542
+					}
543
+				}
544
+				$this->updateTotal($maybe_tax_subtotal, $total, true);
545
+				$this->updatePercent($maybe_tax_subtotal, $total_percent);
546
+			}
547
+		}
548
+	}
549
+
550
+
551
+	/**
552
+	 * returns an array of tax details like:
553
+	 *  [
554
+	 *      'GST_7' => [
555
+	 *          'name'  => 'GST',
556
+	 *          'rate'  => float(7),
557
+	 *          'total' => float(4.9),
558
+	 *      ]
559
+	 *  ]
560
+	 *
561
+	 * @param EE_Line_Item $total_line_item
562
+	 * @param array        $non_global_taxes
563
+	 * @param float        $line_item_total
564
+	 * @return array
565
+	 * @throws EE_Error
566
+	 * @throws ReflectionException
567
+	 */
568
+	private function calculateNonGlobalTaxes(
569
+		EE_Line_Item $total_line_item,
570
+		array $non_global_taxes = [],
571
+		float $line_item_total = 0
572
+	): array {
573
+		foreach ($total_line_item->children() as $line_item) {
574
+			if ($this->validateLineItemAndType($line_item)) {
575
+				if ($line_item->is_sub_total()) {
576
+					$non_global_taxes = $this->calculateNonGlobalTaxes($line_item, $non_global_taxes);
577
+				} elseif ($line_item->is_line_item()) {
578
+					$non_global_taxes = $this->calculateNonGlobalTaxes(
579
+						$line_item,
580
+						$non_global_taxes,
581
+						$line_item->pretaxTotal()
582
+					);
583
+				} elseif ($line_item->isSubTax()) {
584
+					$tax_ID = $line_item->name() . '_' . $line_item->percent();
585
+					if (! isset($non_global_taxes[ $tax_ID ])) {
586
+						$non_global_taxes[ $tax_ID ] = [
587
+							'name'  => $line_item->name(),
588
+							'rate'  => $line_item->percent(),
589
+							'total' => 0,
590
+							'obj'   => $line_item->OBJ_type(),
591
+							'objID' => $line_item->OBJ_ID(),
592
+						];
593
+					}
594
+					$tax = $this->calculatePercentage($line_item_total, $line_item->percent());
595
+					$non_global_taxes[ $tax_ID ]['total'] += $tax;
596
+				}
597
+			}
598
+		}
599
+		return $non_global_taxes;
600
+	}
601
+
602
+
603
+	/**
604
+	 * @param EE_Line_Item $total_line_item
605
+	 * @param float        $tax_total
606
+	 * @param array        $non_global_taxes array of tax details generated by calculateNonGlobalTaxes()
607
+	 * @return float
608
+	 * @throws EE_Error
609
+	 * @throws ReflectionException
610
+	 */
611
+	private function applyNonGlobalTaxes(
612
+		EE_Line_Item $total_line_item,
613
+		float $tax_total,
614
+		array $non_global_taxes
615
+	): float {
616
+		$global_taxes   = $total_line_item->tax_descendants();
617
+		$taxes_subtotal = EEH_Line_Item::get_taxes_subtotal($total_line_item);
618
+		foreach ($non_global_taxes as $non_global_tax) {
619
+			$found = false;
620
+			foreach ($global_taxes as $global_tax) {
621
+				if (
622
+					$this->validateLineItemAndType($global_tax)
623
+					&& $non_global_tax['obj'] === $global_tax->OBJ_type()
624
+					&& $non_global_tax['objID'] === $global_tax->OBJ_ID()
625
+				) {
626
+					$found = true;
627
+					$new_total = $global_tax->total() + $non_global_tax['total'];
628
+					// add non global tax to matching global tax AND the tax total
629
+					$global_tax->set_total($new_total);
630
+					$global_tax->maybe_save();
631
+					$tax_total += $non_global_tax['total'];
632
+				}
633
+			}
634
+			if (! $found) {
635
+				// add a new line item for this non global tax
636
+				$taxes_subtotal->add_child_line_item(
637
+					EE_Line_Item::new_instance(
638
+						[
639
+							'LIN_name'       => $non_global_tax['name'],
640
+							'LIN_percent'    => $non_global_tax['rate'],
641
+							'LIN_is_taxable' => false,
642
+							'LIN_total'      => $non_global_tax['total'],
643
+							'LIN_type'       => EEM_Line_Item::type_tax,
644
+							'OBJ_type'       => $non_global_tax['obj'],
645
+							'OBJ_ID'         => $non_global_tax['objID'],
646
+						]
647
+					)
648
+				);
649
+				$tax_total += $non_global_tax['total'];
650
+			}
651
+		}
652
+		return $this->decimal_values->roundDecimalValue($tax_total, true);
653
+	}
654
+
655
+
656
+	/**
657
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
658
+	 * recalculate_taxes_and_total
659
+	 *
660
+	 * @param EE_Line_Item $line_item
661
+	 * @return float
662
+	 * @throws EE_Error
663
+	 * @throws ReflectionException
664
+	 */
665
+	public function getTotalTax(EE_Line_Item $line_item): float
666
+	{
667
+		$this->validateLineItemAndType($line_item, EEM_Line_Item::type_total);
668
+		$this->recalculateTaxSubTotal($line_item);
669
+		$total = 0;
670
+		foreach ($line_item->tax_descendants() as $tax_line_item) {
671
+			if ($this->validateLineItemAndType($tax_line_item)) {
672
+				$total += $tax_line_item->total();
673
+			}
674
+		}
675
+		return $this->decimal_values->roundDecimalValue($total, true);
676
+	}
677
+
678
+
679
+	/**
680
+	 * Returns the amount taxable among this line item's children (or if it has no children,
681
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
682
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
683
+	 * but there is a "Taxable" discount), returns 0.
684
+	 *
685
+	 * @param EE_Line_Item|null $line_item
686
+	 * @return float
687
+	 * @throws EE_Error
688
+	 * @throws ReflectionException
689
+	 */
690
+	public function taxableAmountForGlobalTaxes(?EE_Line_Item $line_item): float
691
+	{
692
+		$total      = 0;
693
+		$child_line_items = $line_item->children($this->default_query_params);
694
+		foreach ($child_line_items as $child_line_item) {
695
+			$this->validateLineItemAndType($child_line_item);
696
+			if ($child_line_item->is_sub_total()) {
697
+				$total += $this->taxableAmountForGlobalTaxes($child_line_item);
698
+			} elseif ($child_line_item->is_line_item() && $child_line_item->is_taxable()) {
699
+				// if it's a percent item, only take into account
700
+				// the percentage that's taxable (the taxable total so far)
701
+				if ($child_line_item->is_percent()) {
702
+					$total += $this->calculatePercentage($total, $child_line_item->percent(), true);
703
+				} else {
704
+					// pretax total will be equal to the total for line items with globally applied taxes
705
+					$pretax_total = $this->calculateTotalForQuantity($child_line_item);
706
+					$total += $this->updatePreTaxTotal($child_line_item, $pretax_total);
707
+				}
708
+			}
709
+		}
710
+		return max($total, 0);
711
+	}
712
+
713
+
714
+	/**
715
+	 * @param EE_Line_Item|null $line_item
716
+	 * @param string|null       $type
717
+	 * @return bool
718
+	 * @throws EE_Error
719
+	 * @throws ReflectionException
720
+	 */
721
+	private function validateLineItemAndType(?EE_Line_Item $line_item, ?string $type = null): bool
722
+	{
723
+		if (! $line_item instanceof EE_Line_Item) {
724
+			throw new DomainException(
725
+				esc_html__('Invalid or missing Line Item supplied .', 'event_espresso')
726
+			);
727
+		}
728
+		if ($type && $line_item->type() !== $type) {
729
+			throw new DomainException(
730
+				sprintf(
731
+					esc_html__(
732
+						'Invalid Line Item type supplied. Received "%1$s" but expected "%2$s".',
733
+						'event_espresso'
734
+					),
735
+					$line_item->type(),
736
+					$type
737
+				)
738
+			);
739
+		}
740
+		return true;
741
+	}
742 742
 }
Please login to merge, or discard this patch.