Completed
Branch master (44537d)
by
unknown
14:30 queued 10:03
created
core/db_classes/EE_Event.class.php 1 patch
Indentation   +1634 added lines, -1634 removed lines patch added patch discarded remove patch
@@ -16,1641 +16,1641 @@
 block discarded – undo
16 16
  */
17 17
 class EE_Event extends EE_CPT_Base implements EEI_Line_Item_Object, EEI_Admin_Links, EEI_Has_Icon, EEI_Event
18 18
 {
19
-    /**
20
-     * cached value for the the logical active status for the event
21
-     *
22
-     * @see get_active_status()
23
-     * @var string
24
-     */
25
-    protected $_active_status = '';
26
-
27
-    /**
28
-     * This is just used for caching the Primary Datetime for the Event on initial retrieval
29
-     *
30
-     * @var EE_Datetime
31
-     */
32
-    protected $_Primary_Datetime;
33
-
34
-    /**
35
-     * @var EventSpacesCalculator $available_spaces_calculator
36
-     */
37
-    protected $available_spaces_calculator;
38
-
39
-
40
-    /**
41
-     * @param array  $props_n_values          incoming values
42
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
43
-     *                                        used.)
44
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
45
-     *                                        date_format and the second value is the time format
46
-     * @return EE_Event
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = []): EE_Event
51
-    {
52
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
53
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
54
-    }
55
-
56
-
57
-    /**
58
-     * @param array  $props_n_values  incoming values from the database
59
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
60
-     *                                the website will be used.
61
-     * @return EE_Event
62
-     * @throws EE_Error
63
-     * @throws ReflectionException
64
-     */
65
-    public static function new_instance_from_db($props_n_values = [], $timezone = ''): EE_Event
66
-    {
67
-        return new self($props_n_values, true, $timezone);
68
-    }
69
-
70
-
71
-    /**
72
-     * @return EventSpacesCalculator
73
-     * @throws EE_Error
74
-     * @throws ReflectionException
75
-     */
76
-    public function getAvailableSpacesCalculator(): EventSpacesCalculator
77
-    {
78
-        if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79
-            $this->available_spaces_calculator = new EventSpacesCalculator($this);
80
-        }
81
-        return $this->available_spaces_calculator;
82
-    }
83
-
84
-
85
-    /**
86
-     * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
87
-     *
88
-     * @param string $field_name
89
-     * @param mixed  $field_value
90
-     * @param bool   $use_default
91
-     * @throws EE_Error
92
-     * @throws ReflectionException
93
-     */
94
-    public function set($field_name, $field_value, $use_default = false)
95
-    {
96
-        switch ($field_name) {
97
-            case 'status':
98
-                $this->set_status($field_value, $use_default);
99
-                break;
100
-            default:
101
-                parent::set($field_name, $field_value, $use_default);
102
-        }
103
-    }
104
-
105
-
106
-    /**
107
-     *    set_status
108
-     * Checks if event status is being changed to SOLD OUT
109
-     * and updates event meta data with previous event status
110
-     * so that we can revert things if/when the event is no longer sold out
111
-     *
112
-     * @param string $status
113
-     * @param bool   $use_default
114
-     * @return void
115
-     * @throws EE_Error
116
-     * @throws ReflectionException
117
-     */
118
-    public function set_status($status = '', $use_default = false)
119
-    {
120
-        // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($status) && ! $use_default) {
122
-            return;
123
-        }
124
-        // get current Event status
125
-        $old_status = $this->status();
126
-        // if status has changed
127
-        if ($old_status !== $status) {
128
-            // TO sold_out
129
-            if ($status === EEM_Event::sold_out) {
130
-                // save the previous event status so that we can revert if the event is no longer sold out
131
-                $this->add_post_meta('_previous_event_status', $old_status);
132
-                do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $status);
133
-                // OR FROM  sold_out
134
-            } elseif ($old_status === EEM_Event::sold_out) {
135
-                $this->delete_post_meta('_previous_event_status');
136
-                do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $status);
137
-            }
138
-            // clear out the active status so that it gets reset the next time it is requested
139
-            $this->_active_status = null;
140
-            // update status
141
-            parent::set('status', $status, $use_default);
142
-            do_action('AHEE__EE_Event__set_status__after_update', $this);
143
-            return;
144
-        }
145
-        // even though the old value matches the new value, it's still good to
146
-        // allow the parent set method to have a say
147
-        parent::set('status', $status, $use_default);
148
-    }
149
-
150
-
151
-    /**
152
-     * Gets all the datetimes for this event
153
-     *
154
-     * @param array|null $query_params
155
-     * @return EE_Base_Class[]|EE_Datetime[]
156
-     * @throws EE_Error
157
-     * @throws ReflectionException
158
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
159
-     */
160
-    public function datetimes(?array $query_params = []): array
161
-    {
162
-        return $this->get_many_related('Datetime', $query_params);
163
-    }
164
-
165
-
166
-    /**
167
-     * Gets all the datetimes for this event that are currently ACTIVE,
168
-     * meaning the datetime has started and has not yet ended.
169
-     *
170
-     * @param int|null   $start_date   timestamp to use for event date start time, defaults to NOW unless set to 0
171
-     * @param array|null $query_params will recursively replace default values
172
-     * @throws EE_Error
173
-     * @throws ReflectionException
174
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
175
-     */
176
-    public function activeDatetimes(?int $start_date, ?array $query_params = []): array
177
-    {
178
-        // if start date is null, then use current time
179
-        $start_date = $start_date ?? time();
180
-        $where      = [];
181
-        if ($start_date) {
182
-            $where['DTT_EVT_start'] = ['<', $start_date];
183
-            $where['DTT_EVT_end']   = ['>', time()];
184
-        }
185
-        $query_params = array_replace_recursive(
186
-            [
187
-                $where,
188
-                'order_by' => ['DTT_EVT_start' => 'ASC'],
189
-            ],
190
-            $query_params
191
-        );
192
-        return $this->get_many_related('Datetime', $query_params);
193
-    }
194
-
195
-
196
-    /**
197
-     * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
198
-     *
199
-     * @return EE_Base_Class[]|EE_Datetime[]
200
-     * @throws EE_Error
201
-     * @throws ReflectionException
202
-     */
203
-    public function datetimes_in_chronological_order(): array
204
-    {
205
-        return $this->get_many_related('Datetime', ['order_by' => ['DTT_EVT_start' => 'ASC']]);
206
-    }
207
-
208
-
209
-    /**
210
-     * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
211
-     * @darren, we should probably UNSET timezone on the EEM_Datetime model
212
-     * after running our query, so that this timezone isn't set for EVERY query
213
-     * on EEM_Datetime for the rest of the request, no?
214
-     *
215
-     * @param bool     $show_expired whether or not to include expired events
216
-     * @param bool     $show_deleted whether or not to include deleted events
217
-     * @param int|null $limit
218
-     * @return EE_Datetime[]
219
-     * @throws EE_Error
220
-     * @throws ReflectionException
221
-     */
222
-    public function datetimes_ordered(bool $show_expired = true, bool $show_deleted = false, ?int $limit = null): array
223
-    {
224
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
225
-            $this->ID(),
226
-            $show_expired,
227
-            $show_deleted,
228
-            $limit
229
-        );
230
-    }
231
-
232
-
233
-    /**
234
-     * Returns one related datetime. Mostly only used by some legacy code.
235
-     *
236
-     * @return EE_Base_Class|EE_Datetime
237
-     * @throws EE_Error
238
-     * @throws ReflectionException
239
-     */
240
-    public function first_datetime(): EE_Datetime
241
-    {
242
-        return $this->get_first_related('Datetime');
243
-    }
244
-
245
-
246
-    /**
247
-     * Returns the 'primary' datetime for the event
248
-     *
249
-     * @param bool $try_to_exclude_expired
250
-     * @param bool $try_to_exclude_deleted
251
-     * @return EE_Datetime|null
252
-     * @throws EE_Error
253
-     * @throws ReflectionException
254
-     */
255
-    public function primary_datetime(
256
-        bool $try_to_exclude_expired = true,
257
-        bool $try_to_exclude_deleted = true
258
-    ): ?EE_Datetime {
259
-        if (! empty($this->_Primary_Datetime)) {
260
-            return $this->_Primary_Datetime;
261
-        }
262
-        $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
263
-            $this->ID(),
264
-            $try_to_exclude_expired,
265
-            $try_to_exclude_deleted
266
-        );
267
-        return $this->_Primary_Datetime;
268
-    }
269
-
270
-
271
-    /**
272
-     * Gets all the tickets available for purchase of this event
273
-     *
274
-     * @param array|null $query_params
275
-     * @return EE_Base_Class[]|EE_Ticket[]
276
-     * @throws EE_Error
277
-     * @throws ReflectionException
278
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
279
-     */
280
-    public function tickets(?array $query_params = []): array
281
-    {
282
-        // first get all datetimes
283
-        $datetimes = $this->datetimes_ordered();
284
-        if (! $datetimes) {
285
-            return [];
286
-        }
287
-        $datetime_ids = [];
288
-        foreach ($datetimes as $datetime) {
289
-            $datetime_ids[] = $datetime->ID();
290
-        }
291
-        $where_params = ['Datetime.DTT_ID' => ['IN', $datetime_ids]];
292
-        // if incoming $query_params has where conditions let's merge but not override existing.
293
-        if (is_array($query_params) && isset($query_params[0])) {
294
-            $where_params = array_merge($query_params[0], $where_params);
295
-            unset($query_params[0]);
296
-        }
297
-        // now add $where_params to $query_params
298
-        $query_params[0] = $where_params;
299
-        return EEM_Ticket::instance()->get_all($query_params);
300
-    }
301
-
302
-
303
-    /**
304
-     * get all unexpired not-trashed tickets
305
-     *
306
-     * @return EE_Ticket[]
307
-     * @throws EE_Error
308
-     * @throws ReflectionException
309
-     */
310
-    public function active_tickets(): array
311
-    {
312
-        return $this->tickets(
313
-            [
314
-                [
315
-                    'TKT_end_date' => ['>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')],
316
-                    'TKT_deleted'  => false,
317
-                ],
318
-            ]
319
-        );
320
-    }
321
-
322
-
323
-    /**
324
-     * @return int
325
-     * @throws EE_Error
326
-     * @throws ReflectionException
327
-     */
328
-    public function additional_limit(): int
329
-    {
330
-        return $this->get('EVT_additional_limit');
331
-    }
332
-
333
-
334
-    /**
335
-     * @return bool
336
-     * @throws EE_Error
337
-     * @throws ReflectionException
338
-     */
339
-    public function allow_overflow(): bool
340
-    {
341
-        return $this->get('EVT_allow_overflow');
342
-    }
343
-
344
-
345
-    /**
346
-     * @return string
347
-     * @throws EE_Error
348
-     * @throws ReflectionException
349
-     */
350
-    public function created(): string
351
-    {
352
-        return $this->get('EVT_created');
353
-    }
354
-
355
-
356
-    /**
357
-     * @return string
358
-     * @throws EE_Error
359
-     * @throws ReflectionException
360
-     */
361
-    public function description(): string
362
-    {
363
-        return $this->get('EVT_desc');
364
-    }
365
-
366
-
367
-    /**
368
-     * Runs do_shortcode and wpautop on the description
369
-     *
370
-     * @return string of html
371
-     * @throws EE_Error
372
-     * @throws ReflectionException
373
-     */
374
-    public function description_filtered(): string
375
-    {
376
-        return $this->get_pretty('EVT_desc');
377
-    }
378
-
379
-
380
-    /**
381
-     * @return bool
382
-     * @throws EE_Error
383
-     * @throws ReflectionException
384
-     */
385
-    public function display_description(): bool
386
-    {
387
-        return $this->get('EVT_display_desc');
388
-    }
389
-
390
-
391
-    /**
392
-     * @return bool
393
-     * @throws EE_Error
394
-     * @throws ReflectionException
395
-     */
396
-    public function display_ticket_selector(): bool
397
-    {
398
-        return (bool) $this->get('EVT_display_ticket_selector');
399
-    }
400
-
401
-
402
-    /**
403
-     * @return string
404
-     * @throws EE_Error
405
-     * @throws ReflectionException
406
-     */
407
-    public function external_url(): ?string
408
-    {
409
-        return $this->get('EVT_external_URL') ?? '';
410
-    }
411
-
412
-
413
-    /**
414
-     * @return bool
415
-     * @throws EE_Error
416
-     * @throws ReflectionException
417
-     */
418
-    public function member_only(): bool
419
-    {
420
-        return $this->get('EVT_member_only');
421
-    }
422
-
423
-
424
-    /**
425
-     * @return string
426
-     * @throws EE_Error
427
-     * @throws ReflectionException
428
-     */
429
-    public function phone(): string
430
-    {
431
-        return $this->get('EVT_phone');
432
-    }
433
-
434
-
435
-    /**
436
-     * @return string
437
-     * @throws EE_Error
438
-     * @throws ReflectionException
439
-     */
440
-    public function modified(): string
441
-    {
442
-        return $this->get('EVT_modified');
443
-    }
444
-
445
-
446
-    /**
447
-     * @return string
448
-     * @throws EE_Error
449
-     * @throws ReflectionException
450
-     */
451
-    public function name(): string
452
-    {
453
-        return $this->get('EVT_name');
454
-    }
455
-
456
-
457
-    /**
458
-     * @return int
459
-     * @throws EE_Error
460
-     * @throws ReflectionException
461
-     */
462
-    public function order(): int
463
-    {
464
-        return $this->get('EVT_order');
465
-    }
466
-
467
-
468
-    /**
469
-     * @return string
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     */
473
-    public function default_registration_status(): string
474
-    {
475
-        $event_default_registration_status = $this->get('EVT_default_registration_status');
476
-        return ! empty($event_default_registration_status)
477
-            ? $event_default_registration_status
478
-            : EE_Registry::instance()->CFG->registration->default_STS_ID;
479
-    }
480
-
481
-
482
-    /**
483
-     * @param int|null    $num_words
484
-     * @param string|null $more
485
-     * @param bool        $not_full_desc
486
-     * @return string
487
-     * @throws EE_Error
488
-     * @throws ReflectionException
489
-     */
490
-    public function short_description(?int $num_words = 55, string $more = null, bool $not_full_desc = false): string
491
-    {
492
-        $short_desc = $this->get('EVT_short_desc');
493
-        if (! empty($short_desc) || $not_full_desc) {
494
-            return $short_desc;
495
-        }
496
-        $full_desc = $this->get('EVT_desc');
497
-        return wp_trim_words($full_desc, $num_words, $more);
498
-    }
499
-
500
-
501
-    /**
502
-     * @return string
503
-     * @throws EE_Error
504
-     * @throws ReflectionException
505
-     */
506
-    public function slug(): string
507
-    {
508
-        return $this->get('EVT_slug');
509
-    }
510
-
511
-
512
-    /**
513
-     * @return string
514
-     * @throws EE_Error
515
-     * @throws ReflectionException
516
-     */
517
-    public function timezone_string(): string
518
-    {
519
-        return $this->get('EVT_timezone_string');
520
-    }
521
-
522
-
523
-    /**
524
-     * @return string
525
-     * @throws EE_Error
526
-     * @throws ReflectionException
527
-     * @deprecated
528
-     */
529
-    public function visible_on(): string
530
-    {
531
-        EE_Error::doing_it_wrong(
532
-            __METHOD__,
533
-            esc_html__(
534
-                'This method has been deprecated and there is no replacement for it.',
535
-                'event_espresso'
536
-            ),
537
-            '5.0.0.rc.002'
538
-        );
539
-        return $this->get('EVT_visible_on');
540
-    }
541
-
542
-
543
-    /**
544
-     * @return int
545
-     * @throws EE_Error
546
-     * @throws ReflectionException
547
-     */
548
-    public function wp_user(): int
549
-    {
550
-        return $this->get('EVT_wp_user');
551
-    }
552
-
553
-
554
-    /**
555
-     * @return bool
556
-     * @throws EE_Error
557
-     * @throws ReflectionException
558
-     */
559
-    public function donations(): bool
560
-    {
561
-        return $this->get('EVT_donations');
562
-    }
563
-
564
-
565
-    /**
566
-     * @param int $limit
567
-     * @throws EE_Error
568
-     * @throws ReflectionException
569
-     */
570
-    public function set_additional_limit(int $limit)
571
-    {
572
-        $this->set('EVT_additional_limit', $limit);
573
-    }
574
-
575
-
576
-    /**
577
-     * @param $created
578
-     * @throws EE_Error
579
-     * @throws ReflectionException
580
-     */
581
-    public function set_created($created)
582
-    {
583
-        $this->set('EVT_created', $created);
584
-    }
585
-
586
-
587
-    /**
588
-     * @param $desc
589
-     * @throws EE_Error
590
-     * @throws ReflectionException
591
-     */
592
-    public function set_description($desc)
593
-    {
594
-        $this->set('EVT_desc', $desc);
595
-    }
596
-
597
-
598
-    /**
599
-     * @param $display_desc
600
-     * @throws EE_Error
601
-     * @throws ReflectionException
602
-     */
603
-    public function set_display_description($display_desc)
604
-    {
605
-        $this->set('EVT_display_desc', $display_desc);
606
-    }
607
-
608
-
609
-    /**
610
-     * @param $display_ticket_selector
611
-     * @throws EE_Error
612
-     * @throws ReflectionException
613
-     */
614
-    public function set_display_ticket_selector($display_ticket_selector)
615
-    {
616
-        $this->set('EVT_display_ticket_selector', $display_ticket_selector);
617
-    }
618
-
619
-
620
-    /**
621
-     * @param $external_url
622
-     * @throws EE_Error
623
-     * @throws ReflectionException
624
-     */
625
-    public function set_external_url($external_url)
626
-    {
627
-        $this->set('EVT_external_URL', $external_url);
628
-    }
629
-
630
-
631
-    /**
632
-     * @param $member_only
633
-     * @throws EE_Error
634
-     * @throws ReflectionException
635
-     */
636
-    public function set_member_only($member_only)
637
-    {
638
-        $this->set('EVT_member_only', $member_only);
639
-    }
640
-
641
-
642
-    /**
643
-     * @param $event_phone
644
-     * @throws EE_Error
645
-     * @throws ReflectionException
646
-     */
647
-    public function set_event_phone($event_phone)
648
-    {
649
-        $this->set('EVT_phone', $event_phone);
650
-    }
651
-
652
-
653
-    /**
654
-     * @param $modified
655
-     * @throws EE_Error
656
-     * @throws ReflectionException
657
-     */
658
-    public function set_modified($modified)
659
-    {
660
-        $this->set('EVT_modified', $modified);
661
-    }
662
-
663
-
664
-    /**
665
-     * @param $name
666
-     * @throws EE_Error
667
-     * @throws ReflectionException
668
-     */
669
-    public function set_name($name)
670
-    {
671
-        $this->set('EVT_name', $name);
672
-    }
673
-
674
-
675
-    /**
676
-     * @param $order
677
-     * @throws EE_Error
678
-     * @throws ReflectionException
679
-     */
680
-    public function set_order($order)
681
-    {
682
-        $this->set('EVT_order', $order);
683
-    }
684
-
685
-
686
-    /**
687
-     * @param $short_desc
688
-     * @throws EE_Error
689
-     * @throws ReflectionException
690
-     */
691
-    public function set_short_description($short_desc)
692
-    {
693
-        $this->set('EVT_short_desc', $short_desc);
694
-    }
695
-
696
-
697
-    /**
698
-     * @param $slug
699
-     * @throws EE_Error
700
-     * @throws ReflectionException
701
-     */
702
-    public function set_slug($slug)
703
-    {
704
-        $this->set('EVT_slug', $slug);
705
-    }
706
-
707
-
708
-    /**
709
-     * @param $timezone_string
710
-     * @throws EE_Error
711
-     * @throws ReflectionException
712
-     */
713
-    public function set_timezone_string($timezone_string)
714
-    {
715
-        $this->set('EVT_timezone_string', $timezone_string);
716
-    }
717
-
718
-
719
-    /**
720
-     * @param $visible_on
721
-     * @throws EE_Error
722
-     * @throws ReflectionException
723
-     * @deprecated
724
-     */
725
-    public function set_visible_on($visible_on)
726
-    {
727
-        EE_Error::doing_it_wrong(
728
-            __METHOD__,
729
-            esc_html__(
730
-                'This method has been deprecated and there is no replacement for it.',
731
-                'event_espresso'
732
-            ),
733
-            '5.0.0.rc.002'
734
-        );
735
-        $this->set('EVT_visible_on', $visible_on);
736
-    }
737
-
738
-
739
-    /**
740
-     * @param $wp_user
741
-     * @throws EE_Error
742
-     * @throws ReflectionException
743
-     */
744
-    public function set_wp_user($wp_user)
745
-    {
746
-        $this->set('EVT_wp_user', $wp_user);
747
-    }
748
-
749
-
750
-    /**
751
-     * @param $default_registration_status
752
-     * @throws EE_Error
753
-     * @throws ReflectionException
754
-     */
755
-    public function set_default_registration_status($default_registration_status)
756
-    {
757
-        $this->set('EVT_default_registration_status', $default_registration_status);
758
-    }
759
-
760
-
761
-    /**
762
-     * @param $donations
763
-     * @throws EE_Error
764
-     * @throws ReflectionException
765
-     */
766
-    public function set_donations($donations)
767
-    {
768
-        $this->set('EVT_donations', $donations);
769
-    }
770
-
771
-
772
-    /**
773
-     * Adds a venue to this event
774
-     *
775
-     * @param int|EE_Venue /int $venue_id_or_obj
776
-     * @return EE_Base_Class|EE_Venue
777
-     * @throws EE_Error
778
-     * @throws ReflectionException
779
-     */
780
-    public function add_venue($venue_id_or_obj): EE_Venue
781
-    {
782
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
783
-    }
784
-
785
-
786
-    /**
787
-     * Removes a venue from the event
788
-     *
789
-     * @param EE_Venue /int $venue_id_or_obj
790
-     * @return EE_Base_Class|EE_Venue
791
-     * @throws EE_Error
792
-     * @throws ReflectionException
793
-     */
794
-    public function remove_venue($venue_id_or_obj): EE_Venue
795
-    {
796
-        $venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
797
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
798
-    }
799
-
800
-
801
-    /**
802
-     * Gets the venue related to the event. May provide additional $query_params if desired
803
-     *
804
-     * @param array $query_params
805
-     * @return int
806
-     * @throws EE_Error
807
-     * @throws ReflectionException
808
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
809
-     */
810
-    public function venue_ID(array $query_params = []): int
811
-    {
812
-        $venue = $this->get_first_related('Venue', $query_params);
813
-        return $venue instanceof EE_Venue ? $venue->ID() : 0;
814
-    }
815
-
816
-
817
-    /**
818
-     * Gets the venue related to the event. May provide additional $query_params if desired
819
-     *
820
-     * @param array $query_params
821
-     * @return EE_Base_Class|EE_Venue|null
822
-     * @throws EE_Error
823
-     * @throws ReflectionException
824
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
825
-     */
826
-    public function venue(array $query_params = []): ?EE_Venue
827
-    {
828
-        return $this->get_first_related('Venue', $query_params);
829
-    }
830
-
831
-
832
-    /**
833
-     * @param array $query_params
834
-     * @return EE_Base_Class[]|EE_Venue[]
835
-     * @throws EE_Error
836
-     * @throws ReflectionException
837
-     * @deprecated 5.0.0.p
838
-     */
839
-    public function venues(array $query_params = []): array
840
-    {
841
-        $venue = $this->venue($query_params);
842
-        return $venue instanceof EE_Venue ? [$venue] : [];
843
-    }
844
-
845
-
846
-    /**
847
-     * check if event id is present and if event is published
848
-     *
849
-     * @return boolean true yes, false no
850
-     * @throws EE_Error
851
-     * @throws ReflectionException
852
-     */
853
-    private function _has_ID_and_is_published(): bool
854
-    {
855
-        // first check if event id is present and not NULL,
856
-        // then check if this event is published (or any of the equivalent "published" statuses)
857
-        return
858
-            $this->ID() && $this->ID() !== null
859
-            && (
860
-                $this->status() === 'publish'
861
-                || $this->status() === EEM_Event::sold_out
862
-                || $this->status() === EEM_Event::postponed
863
-                || $this->status() === EEM_Event::cancelled
864
-            );
865
-    }
866
-
867
-
868
-    /**
869
-     * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
870
-     *
871
-     * @return boolean true yes, false no
872
-     * @throws EE_Error
873
-     * @throws ReflectionException
874
-     */
875
-    public function is_upcoming(): bool
876
-    {
877
-        // check if event id is present and if this event is published
878
-        if ($this->is_inactive()) {
879
-            return false;
880
-        }
881
-        // set initial value
882
-        $upcoming = false;
883
-        // next let's get all datetimes and loop through them
884
-        $datetimes = $this->datetimes_in_chronological_order();
885
-        foreach ($datetimes as $datetime) {
886
-            if ($datetime instanceof EE_Datetime) {
887
-                // if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
888
-                if ($datetime->is_expired()) {
889
-                    continue;
890
-                }
891
-                // if this dtt is active then we return false.
892
-                if ($datetime->is_active()) {
893
-                    return false;
894
-                }
895
-                // otherwise let's check upcoming status
896
-                $upcoming = $datetime->is_upcoming();
897
-            }
898
-        }
899
-        return $upcoming;
900
-    }
901
-
902
-
903
-    /**
904
-     * @return bool
905
-     * @throws EE_Error
906
-     * @throws ReflectionException
907
-     */
908
-    public function is_active(): bool
909
-    {
910
-        // check if event id is present and if this event is published
911
-        if ($this->is_inactive()) {
912
-            return false;
913
-        }
914
-        // set initial value
915
-        $active = false;
916
-        // next let's get all datetimes and loop through them
917
-        $datetimes = $this->datetimes_in_chronological_order();
918
-        foreach ($datetimes as $datetime) {
919
-            if ($datetime instanceof EE_Datetime) {
920
-                // if this dtt is expired then we continue cause one of the other datetimes might be active.
921
-                if ($datetime->is_expired()) {
922
-                    continue;
923
-                }
924
-                // if this dtt is upcoming then we return false.
925
-                if ($datetime->is_upcoming()) {
926
-                    return false;
927
-                }
928
-                // otherwise let's check active status
929
-                $active = $datetime->is_active();
930
-            }
931
-        }
932
-        return $active;
933
-    }
934
-
935
-
936
-    /**
937
-     * @return bool
938
-     * @throws EE_Error
939
-     * @throws ReflectionException
940
-     */
941
-    public function is_expired(): bool
942
-    {
943
-        // check if event id is present and if this event is published
944
-        if ($this->is_inactive()) {
945
-            return false;
946
-        }
947
-        // set initial value
948
-        $expired = false;
949
-        // first let's get all datetimes and loop through them
950
-        $datetimes = $this->datetimes_in_chronological_order();
951
-        foreach ($datetimes as $datetime) {
952
-            if ($datetime instanceof EE_Datetime) {
953
-                // if this dtt is upcoming or active then we return false.
954
-                if ($datetime->is_upcoming() || $datetime->is_active()) {
955
-                    return false;
956
-                }
957
-                // otherwise let's check active status
958
-                $expired = $datetime->is_expired();
959
-            }
960
-        }
961
-        return $expired;
962
-    }
963
-
964
-
965
-    /**
966
-     * @return bool
967
-     * @throws EE_Error
968
-     * @throws ReflectionException
969
-     */
970
-    public function is_inactive(): bool
971
-    {
972
-        // check if event id is present and if this event is published
973
-        if ($this->_has_ID_and_is_published()) {
974
-            return false;
975
-        }
976
-        return true;
977
-    }
978
-
979
-
980
-    /**
981
-     * calculate spaces remaining based on "saleable" tickets
982
-     *
983
-     * @param array|null $tickets
984
-     * @param bool       $filtered
985
-     * @return int|float
986
-     * @throws EE_Error
987
-     * @throws DomainException
988
-     * @throws UnexpectedEntityException
989
-     * @throws ReflectionException
990
-     */
991
-    public function spaces_remaining(?array $tickets = [], ?bool $filtered = true)
992
-    {
993
-        $this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
994
-        $spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
995
-        return $filtered
996
-            ? apply_filters(
997
-                'FHEE_EE_Event__spaces_remaining',
998
-                $spaces_remaining,
999
-                $this,
1000
-                $tickets
1001
-            )
1002
-            : $spaces_remaining;
1003
-    }
1004
-
1005
-
1006
-    /**
1007
-     *    perform_sold_out_status_check
1008
-     *    checks all of this event's datetime  reg_limit - sold values to determine if ANY datetimes have spaces
1009
-     *    available... if NOT, then the event status will get toggled to 'sold_out'
1010
-     *
1011
-     * @return bool    return the ACTUAL sold out state.
1012
-     * @throws EE_Error
1013
-     * @throws DomainException
1014
-     * @throws UnexpectedEntityException
1015
-     * @throws ReflectionException
1016
-     */
1017
-    public function perform_sold_out_status_check(): bool
1018
-    {
1019
-        // get all tickets
1020
-        $tickets     = $this->tickets(
1021
-            [
1022
-                'default_where_conditions' => 'none',
1023
-                'order_by'                 => ['TKT_qty' => 'ASC'],
1024
-            ]
1025
-        );
1026
-        $all_expired = true;
1027
-        foreach ($tickets as $ticket) {
1028
-            if (! $ticket->is_expired()) {
1029
-                $all_expired = false;
1030
-                break;
1031
-            }
1032
-        }
1033
-        // if all the tickets are just expired, then don't update the event status to sold out
1034
-        if ($all_expired) {
1035
-            return true;
1036
-        }
1037
-        $spaces_remaining = $this->spaces_remaining($tickets);
1038
-        if ($spaces_remaining < 1) {
1039
-            if ($this->status() !== EEM_CPT_Base::post_status_private) {
1040
-                $this->set_status(EEM_Event::sold_out);
1041
-                $this->save();
1042
-            }
1043
-            $sold_out = true;
1044
-        } else {
1045
-            $sold_out = false;
1046
-            // was event previously marked as sold out ?
1047
-            if ($this->status() === EEM_Event::sold_out) {
1048
-                // revert status to previous value, if it was set
1049
-                $previous_event_status = $this->get_post_meta('_previous_event_status', true);
1050
-                if ($previous_event_status) {
1051
-                    $this->set_status($previous_event_status);
1052
-                    $this->save();
1053
-                }
1054
-            }
1055
-        }
1056
-        do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
1057
-        return $sold_out;
1058
-    }
1059
-
1060
-
1061
-    /**
1062
-     * This returns the total remaining spaces for sale on this event.
1063
-     *
1064
-     * @return int|float
1065
-     * @throws EE_Error
1066
-     * @throws DomainException
1067
-     * @throws UnexpectedEntityException
1068
-     * @throws ReflectionException
1069
-     * @uses EE_Event::total_available_spaces()
1070
-     */
1071
-    public function spaces_remaining_for_sale()
1072
-    {
1073
-        return $this->total_available_spaces(true);
1074
-    }
1075
-
1076
-
1077
-    /**
1078
-     * This returns the total spaces available for an event
1079
-     * while considering all the quantities on the tickets and the reg limits
1080
-     * on the datetimes attached to this event.
1081
-     *
1082
-     * @param bool $consider_sold   Whether to consider any tickets that have already sold in our calculation.
1083
-     *                              If this is false, then we return the most tickets that could ever be sold
1084
-     *                              for this event with the datetime and tickets setup on the event under optimal
1085
-     *                              selling conditions.  Otherwise we return a live calculation of spaces available
1086
-     *                              based on tickets sold.  Depending on setup and stage of sales, this
1087
-     *                              may appear to equal remaining tickets.  However, the more tickets are
1088
-     *                              sold out, the more accurate the "live" total is.
1089
-     * @return int|float
1090
-     * @throws EE_Error
1091
-     * @throws DomainException
1092
-     * @throws UnexpectedEntityException
1093
-     * @throws ReflectionException
1094
-     */
1095
-    public function total_available_spaces(bool $consider_sold = false)
1096
-    {
1097
-        $spaces_available = $consider_sold
1098
-            ? $this->getAvailableSpacesCalculator()->spacesRemaining()
1099
-            : $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
1100
-        return apply_filters(
1101
-            'FHEE_EE_Event__total_available_spaces__spaces_available',
1102
-            $spaces_available,
1103
-            $this,
1104
-            $this->getAvailableSpacesCalculator()->getDatetimes(),
1105
-            $this->getAvailableSpacesCalculator()->getActiveTickets()
1106
-        );
1107
-    }
1108
-
1109
-
1110
-    /**
1111
-     * Checks if the event is set to sold out
1112
-     *
1113
-     * @param bool $actual  whether or not to perform calculations to not only figure the
1114
-     *                      actual status but also to flip the status if necessary to sold
1115
-     *                      out If false, we just check the existing status of the event
1116
-     * @return boolean
1117
-     * @throws EE_Error
1118
-     * @throws ReflectionException
1119
-     */
1120
-    public function is_sold_out(bool $actual = false): bool
1121
-    {
1122
-        if (! $actual) {
1123
-            return $this->status() === EEM_Event::sold_out;
1124
-        }
1125
-        return $this->perform_sold_out_status_check();
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * Checks if the event is marked as postponed
1131
-     *
1132
-     * @return boolean
1133
-     */
1134
-    public function is_postponed(): bool
1135
-    {
1136
-        return $this->status() === EEM_Event::postponed;
1137
-    }
1138
-
1139
-
1140
-    /**
1141
-     * Checks if the event is marked as cancelled
1142
-     *
1143
-     * @return boolean
1144
-     */
1145
-    public function is_cancelled(): bool
1146
-    {
1147
-        return $this->status() === EEM_Event::cancelled;
1148
-    }
1149
-
1150
-
1151
-    /**
1152
-     * Get the logical active status in a hierarchical order for all the datetimes.  Note
1153
-     * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1154
-     * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1155
-     * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1156
-     * the event is considered expired.
1157
-     * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a
1158
-     * status set on the EVENT when it is not published and thus is done
1159
-     *
1160
-     * @param bool $reset
1161
-     * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1162
-     * @throws EE_Error
1163
-     * @throws ReflectionException
1164
-     */
1165
-    public function get_active_status(bool $reset = false)
1166
-    {
1167
-        // if the active status has already been set, then just use that value (unless we are resetting it)
1168
-        if (! empty($this->_active_status) && ! $reset) {
1169
-            return $this->_active_status;
1170
-        }
1171
-        // first check if event id is present on this object
1172
-        if (! $this->ID()) {
1173
-            return false;
1174
-        }
1175
-        $where_params_for_event = [['EVT_ID' => $this->ID()]];
1176
-        // if event is published:
1177
-        if (
1178
-            $this->status() === EEM_CPT_Base::post_status_publish
1179
-            || $this->status() === EEM_CPT_Base::post_status_private
1180
-        ) {
1181
-            // active?
1182
-            if (
1183
-                EEM_Datetime::instance()->get_datetime_count_for_status(
1184
-                    EE_Datetime::active,
1185
-                    $where_params_for_event
1186
-                ) > 0
1187
-            ) {
1188
-                $this->_active_status = EE_Datetime::active;
1189
-            } else {
1190
-                // upcoming?
1191
-                if (
1192
-                    EEM_Datetime::instance()->get_datetime_count_for_status(
1193
-                        EE_Datetime::upcoming,
1194
-                        $where_params_for_event
1195
-                    ) > 0
1196
-                ) {
1197
-                    $this->_active_status = EE_Datetime::upcoming;
1198
-                } else {
1199
-                    // expired?
1200
-                    if (
1201
-                        EEM_Datetime::instance()->get_datetime_count_for_status(
1202
-                            EE_Datetime::expired,
1203
-                            $where_params_for_event
1204
-                        ) > 0
1205
-                    ) {
1206
-                        $this->_active_status = EE_Datetime::expired;
1207
-                    } else {
1208
-                        // it would be odd if things make it this far
1209
-                        // because it basically means there are no datetimes attached to the event.
1210
-                        // So in this case it will just be considered inactive.
1211
-                        $this->_active_status = EE_Datetime::inactive;
1212
-                    }
1213
-                }
1214
-            }
1215
-        } else {
1216
-            // the event is not published, so let's just set it's active status according to its' post status
1217
-            switch ($this->status()) {
1218
-                case EEM_Event::sold_out:
1219
-                    $this->_active_status = EE_Datetime::sold_out;
1220
-                    break;
1221
-                case EEM_Event::cancelled:
1222
-                    $this->_active_status = EE_Datetime::cancelled;
1223
-                    break;
1224
-                case EEM_Event::postponed:
1225
-                    $this->_active_status = EE_Datetime::postponed;
1226
-                    break;
1227
-                default:
1228
-                    $this->_active_status = EE_Datetime::inactive;
1229
-            }
1230
-        }
1231
-        return $this->_active_status;
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     *    pretty_active_status
1237
-     *
1238
-     * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1239
-     * @return string
1240
-     * @throws EE_Error
1241
-     * @throws ReflectionException
1242
-     */
1243
-    public function pretty_active_status(bool $echo = true): string
1244
-    {
1245
-        $active_status = $this->get_active_status();
1246
-        $status        = "
19
+	/**
20
+	 * cached value for the the logical active status for the event
21
+	 *
22
+	 * @see get_active_status()
23
+	 * @var string
24
+	 */
25
+	protected $_active_status = '';
26
+
27
+	/**
28
+	 * This is just used for caching the Primary Datetime for the Event on initial retrieval
29
+	 *
30
+	 * @var EE_Datetime
31
+	 */
32
+	protected $_Primary_Datetime;
33
+
34
+	/**
35
+	 * @var EventSpacesCalculator $available_spaces_calculator
36
+	 */
37
+	protected $available_spaces_calculator;
38
+
39
+
40
+	/**
41
+	 * @param array  $props_n_values          incoming values
42
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
43
+	 *                                        used.)
44
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
45
+	 *                                        date_format and the second value is the time format
46
+	 * @return EE_Event
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = []): EE_Event
51
+	{
52
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
53
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
54
+	}
55
+
56
+
57
+	/**
58
+	 * @param array  $props_n_values  incoming values from the database
59
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
60
+	 *                                the website will be used.
61
+	 * @return EE_Event
62
+	 * @throws EE_Error
63
+	 * @throws ReflectionException
64
+	 */
65
+	public static function new_instance_from_db($props_n_values = [], $timezone = ''): EE_Event
66
+	{
67
+		return new self($props_n_values, true, $timezone);
68
+	}
69
+
70
+
71
+	/**
72
+	 * @return EventSpacesCalculator
73
+	 * @throws EE_Error
74
+	 * @throws ReflectionException
75
+	 */
76
+	public function getAvailableSpacesCalculator(): EventSpacesCalculator
77
+	{
78
+		if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79
+			$this->available_spaces_calculator = new EventSpacesCalculator($this);
80
+		}
81
+		return $this->available_spaces_calculator;
82
+	}
83
+
84
+
85
+	/**
86
+	 * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
87
+	 *
88
+	 * @param string $field_name
89
+	 * @param mixed  $field_value
90
+	 * @param bool   $use_default
91
+	 * @throws EE_Error
92
+	 * @throws ReflectionException
93
+	 */
94
+	public function set($field_name, $field_value, $use_default = false)
95
+	{
96
+		switch ($field_name) {
97
+			case 'status':
98
+				$this->set_status($field_value, $use_default);
99
+				break;
100
+			default:
101
+				parent::set($field_name, $field_value, $use_default);
102
+		}
103
+	}
104
+
105
+
106
+	/**
107
+	 *    set_status
108
+	 * Checks if event status is being changed to SOLD OUT
109
+	 * and updates event meta data with previous event status
110
+	 * so that we can revert things if/when the event is no longer sold out
111
+	 *
112
+	 * @param string $status
113
+	 * @param bool   $use_default
114
+	 * @return void
115
+	 * @throws EE_Error
116
+	 * @throws ReflectionException
117
+	 */
118
+	public function set_status($status = '', $use_default = false)
119
+	{
120
+		// if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
+		if (empty($status) && ! $use_default) {
122
+			return;
123
+		}
124
+		// get current Event status
125
+		$old_status = $this->status();
126
+		// if status has changed
127
+		if ($old_status !== $status) {
128
+			// TO sold_out
129
+			if ($status === EEM_Event::sold_out) {
130
+				// save the previous event status so that we can revert if the event is no longer sold out
131
+				$this->add_post_meta('_previous_event_status', $old_status);
132
+				do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $status);
133
+				// OR FROM  sold_out
134
+			} elseif ($old_status === EEM_Event::sold_out) {
135
+				$this->delete_post_meta('_previous_event_status');
136
+				do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $status);
137
+			}
138
+			// clear out the active status so that it gets reset the next time it is requested
139
+			$this->_active_status = null;
140
+			// update status
141
+			parent::set('status', $status, $use_default);
142
+			do_action('AHEE__EE_Event__set_status__after_update', $this);
143
+			return;
144
+		}
145
+		// even though the old value matches the new value, it's still good to
146
+		// allow the parent set method to have a say
147
+		parent::set('status', $status, $use_default);
148
+	}
149
+
150
+
151
+	/**
152
+	 * Gets all the datetimes for this event
153
+	 *
154
+	 * @param array|null $query_params
155
+	 * @return EE_Base_Class[]|EE_Datetime[]
156
+	 * @throws EE_Error
157
+	 * @throws ReflectionException
158
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
159
+	 */
160
+	public function datetimes(?array $query_params = []): array
161
+	{
162
+		return $this->get_many_related('Datetime', $query_params);
163
+	}
164
+
165
+
166
+	/**
167
+	 * Gets all the datetimes for this event that are currently ACTIVE,
168
+	 * meaning the datetime has started and has not yet ended.
169
+	 *
170
+	 * @param int|null   $start_date   timestamp to use for event date start time, defaults to NOW unless set to 0
171
+	 * @param array|null $query_params will recursively replace default values
172
+	 * @throws EE_Error
173
+	 * @throws ReflectionException
174
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
175
+	 */
176
+	public function activeDatetimes(?int $start_date, ?array $query_params = []): array
177
+	{
178
+		// if start date is null, then use current time
179
+		$start_date = $start_date ?? time();
180
+		$where      = [];
181
+		if ($start_date) {
182
+			$where['DTT_EVT_start'] = ['<', $start_date];
183
+			$where['DTT_EVT_end']   = ['>', time()];
184
+		}
185
+		$query_params = array_replace_recursive(
186
+			[
187
+				$where,
188
+				'order_by' => ['DTT_EVT_start' => 'ASC'],
189
+			],
190
+			$query_params
191
+		);
192
+		return $this->get_many_related('Datetime', $query_params);
193
+	}
194
+
195
+
196
+	/**
197
+	 * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
198
+	 *
199
+	 * @return EE_Base_Class[]|EE_Datetime[]
200
+	 * @throws EE_Error
201
+	 * @throws ReflectionException
202
+	 */
203
+	public function datetimes_in_chronological_order(): array
204
+	{
205
+		return $this->get_many_related('Datetime', ['order_by' => ['DTT_EVT_start' => 'ASC']]);
206
+	}
207
+
208
+
209
+	/**
210
+	 * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
211
+	 * @darren, we should probably UNSET timezone on the EEM_Datetime model
212
+	 * after running our query, so that this timezone isn't set for EVERY query
213
+	 * on EEM_Datetime for the rest of the request, no?
214
+	 *
215
+	 * @param bool     $show_expired whether or not to include expired events
216
+	 * @param bool     $show_deleted whether or not to include deleted events
217
+	 * @param int|null $limit
218
+	 * @return EE_Datetime[]
219
+	 * @throws EE_Error
220
+	 * @throws ReflectionException
221
+	 */
222
+	public function datetimes_ordered(bool $show_expired = true, bool $show_deleted = false, ?int $limit = null): array
223
+	{
224
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
225
+			$this->ID(),
226
+			$show_expired,
227
+			$show_deleted,
228
+			$limit
229
+		);
230
+	}
231
+
232
+
233
+	/**
234
+	 * Returns one related datetime. Mostly only used by some legacy code.
235
+	 *
236
+	 * @return EE_Base_Class|EE_Datetime
237
+	 * @throws EE_Error
238
+	 * @throws ReflectionException
239
+	 */
240
+	public function first_datetime(): EE_Datetime
241
+	{
242
+		return $this->get_first_related('Datetime');
243
+	}
244
+
245
+
246
+	/**
247
+	 * Returns the 'primary' datetime for the event
248
+	 *
249
+	 * @param bool $try_to_exclude_expired
250
+	 * @param bool $try_to_exclude_deleted
251
+	 * @return EE_Datetime|null
252
+	 * @throws EE_Error
253
+	 * @throws ReflectionException
254
+	 */
255
+	public function primary_datetime(
256
+		bool $try_to_exclude_expired = true,
257
+		bool $try_to_exclude_deleted = true
258
+	): ?EE_Datetime {
259
+		if (! empty($this->_Primary_Datetime)) {
260
+			return $this->_Primary_Datetime;
261
+		}
262
+		$this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
263
+			$this->ID(),
264
+			$try_to_exclude_expired,
265
+			$try_to_exclude_deleted
266
+		);
267
+		return $this->_Primary_Datetime;
268
+	}
269
+
270
+
271
+	/**
272
+	 * Gets all the tickets available for purchase of this event
273
+	 *
274
+	 * @param array|null $query_params
275
+	 * @return EE_Base_Class[]|EE_Ticket[]
276
+	 * @throws EE_Error
277
+	 * @throws ReflectionException
278
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
279
+	 */
280
+	public function tickets(?array $query_params = []): array
281
+	{
282
+		// first get all datetimes
283
+		$datetimes = $this->datetimes_ordered();
284
+		if (! $datetimes) {
285
+			return [];
286
+		}
287
+		$datetime_ids = [];
288
+		foreach ($datetimes as $datetime) {
289
+			$datetime_ids[] = $datetime->ID();
290
+		}
291
+		$where_params = ['Datetime.DTT_ID' => ['IN', $datetime_ids]];
292
+		// if incoming $query_params has where conditions let's merge but not override existing.
293
+		if (is_array($query_params) && isset($query_params[0])) {
294
+			$where_params = array_merge($query_params[0], $where_params);
295
+			unset($query_params[0]);
296
+		}
297
+		// now add $where_params to $query_params
298
+		$query_params[0] = $where_params;
299
+		return EEM_Ticket::instance()->get_all($query_params);
300
+	}
301
+
302
+
303
+	/**
304
+	 * get all unexpired not-trashed tickets
305
+	 *
306
+	 * @return EE_Ticket[]
307
+	 * @throws EE_Error
308
+	 * @throws ReflectionException
309
+	 */
310
+	public function active_tickets(): array
311
+	{
312
+		return $this->tickets(
313
+			[
314
+				[
315
+					'TKT_end_date' => ['>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')],
316
+					'TKT_deleted'  => false,
317
+				],
318
+			]
319
+		);
320
+	}
321
+
322
+
323
+	/**
324
+	 * @return int
325
+	 * @throws EE_Error
326
+	 * @throws ReflectionException
327
+	 */
328
+	public function additional_limit(): int
329
+	{
330
+		return $this->get('EVT_additional_limit');
331
+	}
332
+
333
+
334
+	/**
335
+	 * @return bool
336
+	 * @throws EE_Error
337
+	 * @throws ReflectionException
338
+	 */
339
+	public function allow_overflow(): bool
340
+	{
341
+		return $this->get('EVT_allow_overflow');
342
+	}
343
+
344
+
345
+	/**
346
+	 * @return string
347
+	 * @throws EE_Error
348
+	 * @throws ReflectionException
349
+	 */
350
+	public function created(): string
351
+	{
352
+		return $this->get('EVT_created');
353
+	}
354
+
355
+
356
+	/**
357
+	 * @return string
358
+	 * @throws EE_Error
359
+	 * @throws ReflectionException
360
+	 */
361
+	public function description(): string
362
+	{
363
+		return $this->get('EVT_desc');
364
+	}
365
+
366
+
367
+	/**
368
+	 * Runs do_shortcode and wpautop on the description
369
+	 *
370
+	 * @return string of html
371
+	 * @throws EE_Error
372
+	 * @throws ReflectionException
373
+	 */
374
+	public function description_filtered(): string
375
+	{
376
+		return $this->get_pretty('EVT_desc');
377
+	}
378
+
379
+
380
+	/**
381
+	 * @return bool
382
+	 * @throws EE_Error
383
+	 * @throws ReflectionException
384
+	 */
385
+	public function display_description(): bool
386
+	{
387
+		return $this->get('EVT_display_desc');
388
+	}
389
+
390
+
391
+	/**
392
+	 * @return bool
393
+	 * @throws EE_Error
394
+	 * @throws ReflectionException
395
+	 */
396
+	public function display_ticket_selector(): bool
397
+	{
398
+		return (bool) $this->get('EVT_display_ticket_selector');
399
+	}
400
+
401
+
402
+	/**
403
+	 * @return string
404
+	 * @throws EE_Error
405
+	 * @throws ReflectionException
406
+	 */
407
+	public function external_url(): ?string
408
+	{
409
+		return $this->get('EVT_external_URL') ?? '';
410
+	}
411
+
412
+
413
+	/**
414
+	 * @return bool
415
+	 * @throws EE_Error
416
+	 * @throws ReflectionException
417
+	 */
418
+	public function member_only(): bool
419
+	{
420
+		return $this->get('EVT_member_only');
421
+	}
422
+
423
+
424
+	/**
425
+	 * @return string
426
+	 * @throws EE_Error
427
+	 * @throws ReflectionException
428
+	 */
429
+	public function phone(): string
430
+	{
431
+		return $this->get('EVT_phone');
432
+	}
433
+
434
+
435
+	/**
436
+	 * @return string
437
+	 * @throws EE_Error
438
+	 * @throws ReflectionException
439
+	 */
440
+	public function modified(): string
441
+	{
442
+		return $this->get('EVT_modified');
443
+	}
444
+
445
+
446
+	/**
447
+	 * @return string
448
+	 * @throws EE_Error
449
+	 * @throws ReflectionException
450
+	 */
451
+	public function name(): string
452
+	{
453
+		return $this->get('EVT_name');
454
+	}
455
+
456
+
457
+	/**
458
+	 * @return int
459
+	 * @throws EE_Error
460
+	 * @throws ReflectionException
461
+	 */
462
+	public function order(): int
463
+	{
464
+		return $this->get('EVT_order');
465
+	}
466
+
467
+
468
+	/**
469
+	 * @return string
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 */
473
+	public function default_registration_status(): string
474
+	{
475
+		$event_default_registration_status = $this->get('EVT_default_registration_status');
476
+		return ! empty($event_default_registration_status)
477
+			? $event_default_registration_status
478
+			: EE_Registry::instance()->CFG->registration->default_STS_ID;
479
+	}
480
+
481
+
482
+	/**
483
+	 * @param int|null    $num_words
484
+	 * @param string|null $more
485
+	 * @param bool        $not_full_desc
486
+	 * @return string
487
+	 * @throws EE_Error
488
+	 * @throws ReflectionException
489
+	 */
490
+	public function short_description(?int $num_words = 55, string $more = null, bool $not_full_desc = false): string
491
+	{
492
+		$short_desc = $this->get('EVT_short_desc');
493
+		if (! empty($short_desc) || $not_full_desc) {
494
+			return $short_desc;
495
+		}
496
+		$full_desc = $this->get('EVT_desc');
497
+		return wp_trim_words($full_desc, $num_words, $more);
498
+	}
499
+
500
+
501
+	/**
502
+	 * @return string
503
+	 * @throws EE_Error
504
+	 * @throws ReflectionException
505
+	 */
506
+	public function slug(): string
507
+	{
508
+		return $this->get('EVT_slug');
509
+	}
510
+
511
+
512
+	/**
513
+	 * @return string
514
+	 * @throws EE_Error
515
+	 * @throws ReflectionException
516
+	 */
517
+	public function timezone_string(): string
518
+	{
519
+		return $this->get('EVT_timezone_string');
520
+	}
521
+
522
+
523
+	/**
524
+	 * @return string
525
+	 * @throws EE_Error
526
+	 * @throws ReflectionException
527
+	 * @deprecated
528
+	 */
529
+	public function visible_on(): string
530
+	{
531
+		EE_Error::doing_it_wrong(
532
+			__METHOD__,
533
+			esc_html__(
534
+				'This method has been deprecated and there is no replacement for it.',
535
+				'event_espresso'
536
+			),
537
+			'5.0.0.rc.002'
538
+		);
539
+		return $this->get('EVT_visible_on');
540
+	}
541
+
542
+
543
+	/**
544
+	 * @return int
545
+	 * @throws EE_Error
546
+	 * @throws ReflectionException
547
+	 */
548
+	public function wp_user(): int
549
+	{
550
+		return $this->get('EVT_wp_user');
551
+	}
552
+
553
+
554
+	/**
555
+	 * @return bool
556
+	 * @throws EE_Error
557
+	 * @throws ReflectionException
558
+	 */
559
+	public function donations(): bool
560
+	{
561
+		return $this->get('EVT_donations');
562
+	}
563
+
564
+
565
+	/**
566
+	 * @param int $limit
567
+	 * @throws EE_Error
568
+	 * @throws ReflectionException
569
+	 */
570
+	public function set_additional_limit(int $limit)
571
+	{
572
+		$this->set('EVT_additional_limit', $limit);
573
+	}
574
+
575
+
576
+	/**
577
+	 * @param $created
578
+	 * @throws EE_Error
579
+	 * @throws ReflectionException
580
+	 */
581
+	public function set_created($created)
582
+	{
583
+		$this->set('EVT_created', $created);
584
+	}
585
+
586
+
587
+	/**
588
+	 * @param $desc
589
+	 * @throws EE_Error
590
+	 * @throws ReflectionException
591
+	 */
592
+	public function set_description($desc)
593
+	{
594
+		$this->set('EVT_desc', $desc);
595
+	}
596
+
597
+
598
+	/**
599
+	 * @param $display_desc
600
+	 * @throws EE_Error
601
+	 * @throws ReflectionException
602
+	 */
603
+	public function set_display_description($display_desc)
604
+	{
605
+		$this->set('EVT_display_desc', $display_desc);
606
+	}
607
+
608
+
609
+	/**
610
+	 * @param $display_ticket_selector
611
+	 * @throws EE_Error
612
+	 * @throws ReflectionException
613
+	 */
614
+	public function set_display_ticket_selector($display_ticket_selector)
615
+	{
616
+		$this->set('EVT_display_ticket_selector', $display_ticket_selector);
617
+	}
618
+
619
+
620
+	/**
621
+	 * @param $external_url
622
+	 * @throws EE_Error
623
+	 * @throws ReflectionException
624
+	 */
625
+	public function set_external_url($external_url)
626
+	{
627
+		$this->set('EVT_external_URL', $external_url);
628
+	}
629
+
630
+
631
+	/**
632
+	 * @param $member_only
633
+	 * @throws EE_Error
634
+	 * @throws ReflectionException
635
+	 */
636
+	public function set_member_only($member_only)
637
+	{
638
+		$this->set('EVT_member_only', $member_only);
639
+	}
640
+
641
+
642
+	/**
643
+	 * @param $event_phone
644
+	 * @throws EE_Error
645
+	 * @throws ReflectionException
646
+	 */
647
+	public function set_event_phone($event_phone)
648
+	{
649
+		$this->set('EVT_phone', $event_phone);
650
+	}
651
+
652
+
653
+	/**
654
+	 * @param $modified
655
+	 * @throws EE_Error
656
+	 * @throws ReflectionException
657
+	 */
658
+	public function set_modified($modified)
659
+	{
660
+		$this->set('EVT_modified', $modified);
661
+	}
662
+
663
+
664
+	/**
665
+	 * @param $name
666
+	 * @throws EE_Error
667
+	 * @throws ReflectionException
668
+	 */
669
+	public function set_name($name)
670
+	{
671
+		$this->set('EVT_name', $name);
672
+	}
673
+
674
+
675
+	/**
676
+	 * @param $order
677
+	 * @throws EE_Error
678
+	 * @throws ReflectionException
679
+	 */
680
+	public function set_order($order)
681
+	{
682
+		$this->set('EVT_order', $order);
683
+	}
684
+
685
+
686
+	/**
687
+	 * @param $short_desc
688
+	 * @throws EE_Error
689
+	 * @throws ReflectionException
690
+	 */
691
+	public function set_short_description($short_desc)
692
+	{
693
+		$this->set('EVT_short_desc', $short_desc);
694
+	}
695
+
696
+
697
+	/**
698
+	 * @param $slug
699
+	 * @throws EE_Error
700
+	 * @throws ReflectionException
701
+	 */
702
+	public function set_slug($slug)
703
+	{
704
+		$this->set('EVT_slug', $slug);
705
+	}
706
+
707
+
708
+	/**
709
+	 * @param $timezone_string
710
+	 * @throws EE_Error
711
+	 * @throws ReflectionException
712
+	 */
713
+	public function set_timezone_string($timezone_string)
714
+	{
715
+		$this->set('EVT_timezone_string', $timezone_string);
716
+	}
717
+
718
+
719
+	/**
720
+	 * @param $visible_on
721
+	 * @throws EE_Error
722
+	 * @throws ReflectionException
723
+	 * @deprecated
724
+	 */
725
+	public function set_visible_on($visible_on)
726
+	{
727
+		EE_Error::doing_it_wrong(
728
+			__METHOD__,
729
+			esc_html__(
730
+				'This method has been deprecated and there is no replacement for it.',
731
+				'event_espresso'
732
+			),
733
+			'5.0.0.rc.002'
734
+		);
735
+		$this->set('EVT_visible_on', $visible_on);
736
+	}
737
+
738
+
739
+	/**
740
+	 * @param $wp_user
741
+	 * @throws EE_Error
742
+	 * @throws ReflectionException
743
+	 */
744
+	public function set_wp_user($wp_user)
745
+	{
746
+		$this->set('EVT_wp_user', $wp_user);
747
+	}
748
+
749
+
750
+	/**
751
+	 * @param $default_registration_status
752
+	 * @throws EE_Error
753
+	 * @throws ReflectionException
754
+	 */
755
+	public function set_default_registration_status($default_registration_status)
756
+	{
757
+		$this->set('EVT_default_registration_status', $default_registration_status);
758
+	}
759
+
760
+
761
+	/**
762
+	 * @param $donations
763
+	 * @throws EE_Error
764
+	 * @throws ReflectionException
765
+	 */
766
+	public function set_donations($donations)
767
+	{
768
+		$this->set('EVT_donations', $donations);
769
+	}
770
+
771
+
772
+	/**
773
+	 * Adds a venue to this event
774
+	 *
775
+	 * @param int|EE_Venue /int $venue_id_or_obj
776
+	 * @return EE_Base_Class|EE_Venue
777
+	 * @throws EE_Error
778
+	 * @throws ReflectionException
779
+	 */
780
+	public function add_venue($venue_id_or_obj): EE_Venue
781
+	{
782
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
783
+	}
784
+
785
+
786
+	/**
787
+	 * Removes a venue from the event
788
+	 *
789
+	 * @param EE_Venue /int $venue_id_or_obj
790
+	 * @return EE_Base_Class|EE_Venue
791
+	 * @throws EE_Error
792
+	 * @throws ReflectionException
793
+	 */
794
+	public function remove_venue($venue_id_or_obj): EE_Venue
795
+	{
796
+		$venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
797
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
798
+	}
799
+
800
+
801
+	/**
802
+	 * Gets the venue related to the event. May provide additional $query_params if desired
803
+	 *
804
+	 * @param array $query_params
805
+	 * @return int
806
+	 * @throws EE_Error
807
+	 * @throws ReflectionException
808
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
809
+	 */
810
+	public function venue_ID(array $query_params = []): int
811
+	{
812
+		$venue = $this->get_first_related('Venue', $query_params);
813
+		return $venue instanceof EE_Venue ? $venue->ID() : 0;
814
+	}
815
+
816
+
817
+	/**
818
+	 * Gets the venue related to the event. May provide additional $query_params if desired
819
+	 *
820
+	 * @param array $query_params
821
+	 * @return EE_Base_Class|EE_Venue|null
822
+	 * @throws EE_Error
823
+	 * @throws ReflectionException
824
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
825
+	 */
826
+	public function venue(array $query_params = []): ?EE_Venue
827
+	{
828
+		return $this->get_first_related('Venue', $query_params);
829
+	}
830
+
831
+
832
+	/**
833
+	 * @param array $query_params
834
+	 * @return EE_Base_Class[]|EE_Venue[]
835
+	 * @throws EE_Error
836
+	 * @throws ReflectionException
837
+	 * @deprecated 5.0.0.p
838
+	 */
839
+	public function venues(array $query_params = []): array
840
+	{
841
+		$venue = $this->venue($query_params);
842
+		return $venue instanceof EE_Venue ? [$venue] : [];
843
+	}
844
+
845
+
846
+	/**
847
+	 * check if event id is present and if event is published
848
+	 *
849
+	 * @return boolean true yes, false no
850
+	 * @throws EE_Error
851
+	 * @throws ReflectionException
852
+	 */
853
+	private function _has_ID_and_is_published(): bool
854
+	{
855
+		// first check if event id is present and not NULL,
856
+		// then check if this event is published (or any of the equivalent "published" statuses)
857
+		return
858
+			$this->ID() && $this->ID() !== null
859
+			&& (
860
+				$this->status() === 'publish'
861
+				|| $this->status() === EEM_Event::sold_out
862
+				|| $this->status() === EEM_Event::postponed
863
+				|| $this->status() === EEM_Event::cancelled
864
+			);
865
+	}
866
+
867
+
868
+	/**
869
+	 * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
870
+	 *
871
+	 * @return boolean true yes, false no
872
+	 * @throws EE_Error
873
+	 * @throws ReflectionException
874
+	 */
875
+	public function is_upcoming(): bool
876
+	{
877
+		// check if event id is present and if this event is published
878
+		if ($this->is_inactive()) {
879
+			return false;
880
+		}
881
+		// set initial value
882
+		$upcoming = false;
883
+		// next let's get all datetimes and loop through them
884
+		$datetimes = $this->datetimes_in_chronological_order();
885
+		foreach ($datetimes as $datetime) {
886
+			if ($datetime instanceof EE_Datetime) {
887
+				// if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
888
+				if ($datetime->is_expired()) {
889
+					continue;
890
+				}
891
+				// if this dtt is active then we return false.
892
+				if ($datetime->is_active()) {
893
+					return false;
894
+				}
895
+				// otherwise let's check upcoming status
896
+				$upcoming = $datetime->is_upcoming();
897
+			}
898
+		}
899
+		return $upcoming;
900
+	}
901
+
902
+
903
+	/**
904
+	 * @return bool
905
+	 * @throws EE_Error
906
+	 * @throws ReflectionException
907
+	 */
908
+	public function is_active(): bool
909
+	{
910
+		// check if event id is present and if this event is published
911
+		if ($this->is_inactive()) {
912
+			return false;
913
+		}
914
+		// set initial value
915
+		$active = false;
916
+		// next let's get all datetimes and loop through them
917
+		$datetimes = $this->datetimes_in_chronological_order();
918
+		foreach ($datetimes as $datetime) {
919
+			if ($datetime instanceof EE_Datetime) {
920
+				// if this dtt is expired then we continue cause one of the other datetimes might be active.
921
+				if ($datetime->is_expired()) {
922
+					continue;
923
+				}
924
+				// if this dtt is upcoming then we return false.
925
+				if ($datetime->is_upcoming()) {
926
+					return false;
927
+				}
928
+				// otherwise let's check active status
929
+				$active = $datetime->is_active();
930
+			}
931
+		}
932
+		return $active;
933
+	}
934
+
935
+
936
+	/**
937
+	 * @return bool
938
+	 * @throws EE_Error
939
+	 * @throws ReflectionException
940
+	 */
941
+	public function is_expired(): bool
942
+	{
943
+		// check if event id is present and if this event is published
944
+		if ($this->is_inactive()) {
945
+			return false;
946
+		}
947
+		// set initial value
948
+		$expired = false;
949
+		// first let's get all datetimes and loop through them
950
+		$datetimes = $this->datetimes_in_chronological_order();
951
+		foreach ($datetimes as $datetime) {
952
+			if ($datetime instanceof EE_Datetime) {
953
+				// if this dtt is upcoming or active then we return false.
954
+				if ($datetime->is_upcoming() || $datetime->is_active()) {
955
+					return false;
956
+				}
957
+				// otherwise let's check active status
958
+				$expired = $datetime->is_expired();
959
+			}
960
+		}
961
+		return $expired;
962
+	}
963
+
964
+
965
+	/**
966
+	 * @return bool
967
+	 * @throws EE_Error
968
+	 * @throws ReflectionException
969
+	 */
970
+	public function is_inactive(): bool
971
+	{
972
+		// check if event id is present and if this event is published
973
+		if ($this->_has_ID_and_is_published()) {
974
+			return false;
975
+		}
976
+		return true;
977
+	}
978
+
979
+
980
+	/**
981
+	 * calculate spaces remaining based on "saleable" tickets
982
+	 *
983
+	 * @param array|null $tickets
984
+	 * @param bool       $filtered
985
+	 * @return int|float
986
+	 * @throws EE_Error
987
+	 * @throws DomainException
988
+	 * @throws UnexpectedEntityException
989
+	 * @throws ReflectionException
990
+	 */
991
+	public function spaces_remaining(?array $tickets = [], ?bool $filtered = true)
992
+	{
993
+		$this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
994
+		$spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
995
+		return $filtered
996
+			? apply_filters(
997
+				'FHEE_EE_Event__spaces_remaining',
998
+				$spaces_remaining,
999
+				$this,
1000
+				$tickets
1001
+			)
1002
+			: $spaces_remaining;
1003
+	}
1004
+
1005
+
1006
+	/**
1007
+	 *    perform_sold_out_status_check
1008
+	 *    checks all of this event's datetime  reg_limit - sold values to determine if ANY datetimes have spaces
1009
+	 *    available... if NOT, then the event status will get toggled to 'sold_out'
1010
+	 *
1011
+	 * @return bool    return the ACTUAL sold out state.
1012
+	 * @throws EE_Error
1013
+	 * @throws DomainException
1014
+	 * @throws UnexpectedEntityException
1015
+	 * @throws ReflectionException
1016
+	 */
1017
+	public function perform_sold_out_status_check(): bool
1018
+	{
1019
+		// get all tickets
1020
+		$tickets     = $this->tickets(
1021
+			[
1022
+				'default_where_conditions' => 'none',
1023
+				'order_by'                 => ['TKT_qty' => 'ASC'],
1024
+			]
1025
+		);
1026
+		$all_expired = true;
1027
+		foreach ($tickets as $ticket) {
1028
+			if (! $ticket->is_expired()) {
1029
+				$all_expired = false;
1030
+				break;
1031
+			}
1032
+		}
1033
+		// if all the tickets are just expired, then don't update the event status to sold out
1034
+		if ($all_expired) {
1035
+			return true;
1036
+		}
1037
+		$spaces_remaining = $this->spaces_remaining($tickets);
1038
+		if ($spaces_remaining < 1) {
1039
+			if ($this->status() !== EEM_CPT_Base::post_status_private) {
1040
+				$this->set_status(EEM_Event::sold_out);
1041
+				$this->save();
1042
+			}
1043
+			$sold_out = true;
1044
+		} else {
1045
+			$sold_out = false;
1046
+			// was event previously marked as sold out ?
1047
+			if ($this->status() === EEM_Event::sold_out) {
1048
+				// revert status to previous value, if it was set
1049
+				$previous_event_status = $this->get_post_meta('_previous_event_status', true);
1050
+				if ($previous_event_status) {
1051
+					$this->set_status($previous_event_status);
1052
+					$this->save();
1053
+				}
1054
+			}
1055
+		}
1056
+		do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
1057
+		return $sold_out;
1058
+	}
1059
+
1060
+
1061
+	/**
1062
+	 * This returns the total remaining spaces for sale on this event.
1063
+	 *
1064
+	 * @return int|float
1065
+	 * @throws EE_Error
1066
+	 * @throws DomainException
1067
+	 * @throws UnexpectedEntityException
1068
+	 * @throws ReflectionException
1069
+	 * @uses EE_Event::total_available_spaces()
1070
+	 */
1071
+	public function spaces_remaining_for_sale()
1072
+	{
1073
+		return $this->total_available_spaces(true);
1074
+	}
1075
+
1076
+
1077
+	/**
1078
+	 * This returns the total spaces available for an event
1079
+	 * while considering all the quantities on the tickets and the reg limits
1080
+	 * on the datetimes attached to this event.
1081
+	 *
1082
+	 * @param bool $consider_sold   Whether to consider any tickets that have already sold in our calculation.
1083
+	 *                              If this is false, then we return the most tickets that could ever be sold
1084
+	 *                              for this event with the datetime and tickets setup on the event under optimal
1085
+	 *                              selling conditions.  Otherwise we return a live calculation of spaces available
1086
+	 *                              based on tickets sold.  Depending on setup and stage of sales, this
1087
+	 *                              may appear to equal remaining tickets.  However, the more tickets are
1088
+	 *                              sold out, the more accurate the "live" total is.
1089
+	 * @return int|float
1090
+	 * @throws EE_Error
1091
+	 * @throws DomainException
1092
+	 * @throws UnexpectedEntityException
1093
+	 * @throws ReflectionException
1094
+	 */
1095
+	public function total_available_spaces(bool $consider_sold = false)
1096
+	{
1097
+		$spaces_available = $consider_sold
1098
+			? $this->getAvailableSpacesCalculator()->spacesRemaining()
1099
+			: $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
1100
+		return apply_filters(
1101
+			'FHEE_EE_Event__total_available_spaces__spaces_available',
1102
+			$spaces_available,
1103
+			$this,
1104
+			$this->getAvailableSpacesCalculator()->getDatetimes(),
1105
+			$this->getAvailableSpacesCalculator()->getActiveTickets()
1106
+		);
1107
+	}
1108
+
1109
+
1110
+	/**
1111
+	 * Checks if the event is set to sold out
1112
+	 *
1113
+	 * @param bool $actual  whether or not to perform calculations to not only figure the
1114
+	 *                      actual status but also to flip the status if necessary to sold
1115
+	 *                      out If false, we just check the existing status of the event
1116
+	 * @return boolean
1117
+	 * @throws EE_Error
1118
+	 * @throws ReflectionException
1119
+	 */
1120
+	public function is_sold_out(bool $actual = false): bool
1121
+	{
1122
+		if (! $actual) {
1123
+			return $this->status() === EEM_Event::sold_out;
1124
+		}
1125
+		return $this->perform_sold_out_status_check();
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * Checks if the event is marked as postponed
1131
+	 *
1132
+	 * @return boolean
1133
+	 */
1134
+	public function is_postponed(): bool
1135
+	{
1136
+		return $this->status() === EEM_Event::postponed;
1137
+	}
1138
+
1139
+
1140
+	/**
1141
+	 * Checks if the event is marked as cancelled
1142
+	 *
1143
+	 * @return boolean
1144
+	 */
1145
+	public function is_cancelled(): bool
1146
+	{
1147
+		return $this->status() === EEM_Event::cancelled;
1148
+	}
1149
+
1150
+
1151
+	/**
1152
+	 * Get the logical active status in a hierarchical order for all the datetimes.  Note
1153
+	 * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1154
+	 * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1155
+	 * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1156
+	 * the event is considered expired.
1157
+	 * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a
1158
+	 * status set on the EVENT when it is not published and thus is done
1159
+	 *
1160
+	 * @param bool $reset
1161
+	 * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1162
+	 * @throws EE_Error
1163
+	 * @throws ReflectionException
1164
+	 */
1165
+	public function get_active_status(bool $reset = false)
1166
+	{
1167
+		// if the active status has already been set, then just use that value (unless we are resetting it)
1168
+		if (! empty($this->_active_status) && ! $reset) {
1169
+			return $this->_active_status;
1170
+		}
1171
+		// first check if event id is present on this object
1172
+		if (! $this->ID()) {
1173
+			return false;
1174
+		}
1175
+		$where_params_for_event = [['EVT_ID' => $this->ID()]];
1176
+		// if event is published:
1177
+		if (
1178
+			$this->status() === EEM_CPT_Base::post_status_publish
1179
+			|| $this->status() === EEM_CPT_Base::post_status_private
1180
+		) {
1181
+			// active?
1182
+			if (
1183
+				EEM_Datetime::instance()->get_datetime_count_for_status(
1184
+					EE_Datetime::active,
1185
+					$where_params_for_event
1186
+				) > 0
1187
+			) {
1188
+				$this->_active_status = EE_Datetime::active;
1189
+			} else {
1190
+				// upcoming?
1191
+				if (
1192
+					EEM_Datetime::instance()->get_datetime_count_for_status(
1193
+						EE_Datetime::upcoming,
1194
+						$where_params_for_event
1195
+					) > 0
1196
+				) {
1197
+					$this->_active_status = EE_Datetime::upcoming;
1198
+				} else {
1199
+					// expired?
1200
+					if (
1201
+						EEM_Datetime::instance()->get_datetime_count_for_status(
1202
+							EE_Datetime::expired,
1203
+							$where_params_for_event
1204
+						) > 0
1205
+					) {
1206
+						$this->_active_status = EE_Datetime::expired;
1207
+					} else {
1208
+						// it would be odd if things make it this far
1209
+						// because it basically means there are no datetimes attached to the event.
1210
+						// So in this case it will just be considered inactive.
1211
+						$this->_active_status = EE_Datetime::inactive;
1212
+					}
1213
+				}
1214
+			}
1215
+		} else {
1216
+			// the event is not published, so let's just set it's active status according to its' post status
1217
+			switch ($this->status()) {
1218
+				case EEM_Event::sold_out:
1219
+					$this->_active_status = EE_Datetime::sold_out;
1220
+					break;
1221
+				case EEM_Event::cancelled:
1222
+					$this->_active_status = EE_Datetime::cancelled;
1223
+					break;
1224
+				case EEM_Event::postponed:
1225
+					$this->_active_status = EE_Datetime::postponed;
1226
+					break;
1227
+				default:
1228
+					$this->_active_status = EE_Datetime::inactive;
1229
+			}
1230
+		}
1231
+		return $this->_active_status;
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 *    pretty_active_status
1237
+	 *
1238
+	 * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1239
+	 * @return string
1240
+	 * @throws EE_Error
1241
+	 * @throws ReflectionException
1242
+	 */
1243
+	public function pretty_active_status(bool $echo = true): string
1244
+	{
1245
+		$active_status = $this->get_active_status();
1246
+		$status        = "
1247 1247
         <span class='ee-status ee-status-bg--$active_status event-active-status-$active_status'>
1248 1248
             " . EEH_Template::pretty_status($active_status, false, 'sentence') . "
1249 1249
         </span >";
1250
-        if ($echo) {
1251
-            echo wp_kses($status, AllowedTags::getAllowedTags());
1252
-            return '';
1253
-        }
1254
-        return $status;
1255
-    }
1256
-
1257
-
1258
-    /**
1259
-     * @return bool|int
1260
-     * @throws EE_Error
1261
-     * @throws ReflectionException
1262
-     */
1263
-    public function get_number_of_tickets_sold()
1264
-    {
1265
-        $tkt_sold = 0;
1266
-        if (! $this->ID()) {
1267
-            return 0;
1268
-        }
1269
-        $datetimes = $this->datetimes();
1270
-        foreach ($datetimes as $datetime) {
1271
-            if ($datetime instanceof EE_Datetime) {
1272
-                $tkt_sold += $datetime->sold();
1273
-            }
1274
-        }
1275
-        return $tkt_sold;
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * This just returns a count of all the registrations for this event
1281
-     *
1282
-     * @return int
1283
-     * @throws EE_Error
1284
-     * @throws ReflectionException
1285
-     */
1286
-    public function get_count_of_all_registrations(): int
1287
-    {
1288
-        return EEM_Event::instance()->count_related($this, 'Registration');
1289
-    }
1290
-
1291
-
1292
-    /**
1293
-     * This returns the ticket with the earliest start time that is
1294
-     * available for this event (across all datetimes attached to the event)
1295
-     *
1296
-     * @return EE_Base_Class|EE_Ticket|null
1297
-     * @throws EE_Error
1298
-     * @throws ReflectionException
1299
-     */
1300
-    public function get_ticket_with_earliest_start_time()
1301
-    {
1302
-        $where['Datetime.EVT_ID'] = $this->ID();
1303
-        $query_params             = [$where, 'order_by' => ['TKT_start_date' => 'ASC']];
1304
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1305
-    }
1306
-
1307
-
1308
-    /**
1309
-     * This returns the ticket with the latest end time that is available
1310
-     * for this event (across all datetimes attached to the event)
1311
-     *
1312
-     * @return EE_Base_Class|EE_Ticket|null
1313
-     * @throws EE_Error
1314
-     * @throws ReflectionException
1315
-     */
1316
-    public function get_ticket_with_latest_end_time()
1317
-    {
1318
-        $where['Datetime.EVT_ID'] = $this->ID();
1319
-        $query_params             = [$where, 'order_by' => ['TKT_end_date' => 'DESC']];
1320
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1321
-    }
1322
-
1323
-
1324
-    /**
1325
-     * This returns the number of different ticket types currently on sale for this event.
1326
-     *
1327
-     * @return int
1328
-     * @throws EE_Error
1329
-     * @throws ReflectionException
1330
-     */
1331
-    public function countTicketsOnSale(): int
1332
-    {
1333
-        $where = [
1334
-            'Datetime.EVT_ID' => $this->ID(),
1335
-            'TKT_start_date'  => ['<', time()],
1336
-            'TKT_end_date'    => ['>', time()],
1337
-        ];
1338
-        return EEM_Ticket::instance()->count([$where]);
1339
-    }
1340
-
1341
-
1342
-    /**
1343
-     * This returns whether there are any tickets on sale for this event.
1344
-     *
1345
-     * @return bool true = YES tickets on sale.
1346
-     * @throws EE_Error
1347
-     * @throws ReflectionException
1348
-     */
1349
-    public function tickets_on_sale(): bool
1350
-    {
1351
-        return $this->countTicketsOnSale() > 0;
1352
-    }
1353
-
1354
-
1355
-    /**
1356
-     * Gets the URL for viewing this event on the front-end. Overrides parent
1357
-     * to check for an external URL first
1358
-     *
1359
-     * @return string
1360
-     * @throws EE_Error
1361
-     * @throws ReflectionException
1362
-     */
1363
-    public function get_permalink(): string
1364
-    {
1365
-        if ($this->external_url()) {
1366
-            return $this->external_url();
1367
-        }
1368
-        return parent::get_permalink();
1369
-    }
1370
-
1371
-
1372
-    /**
1373
-     * Gets the first term for 'espresso_event_categories' we can find
1374
-     *
1375
-     * @param array $query_params
1376
-     * @return EE_Base_Class|EE_Term|null
1377
-     * @throws EE_Error
1378
-     * @throws ReflectionException
1379
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1380
-     */
1381
-    public function first_event_category(array $query_params = []): ?EE_Term
1382
-    {
1383
-        $query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1384
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1385
-        return EEM_Term::instance()->get_one($query_params);
1386
-    }
1387
-
1388
-
1389
-    /**
1390
-     * Gets all terms for 'espresso_event_categories' we can find
1391
-     *
1392
-     * @param array $query_params
1393
-     * @return EE_Base_Class[]|EE_Term[]
1394
-     * @throws EE_Error
1395
-     * @throws ReflectionException
1396
-     */
1397
-    public function get_all_event_categories(array $query_params = []): array
1398
-    {
1399
-        $query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1400
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1401
-        return EEM_Term::instance()->get_all($query_params);
1402
-    }
1403
-
1404
-
1405
-    /**
1406
-     * Adds a question group to this event
1407
-     *
1408
-     * @param EE_Question_Group|int $question_group_id_or_obj
1409
-     * @param bool                  $for_primary if true, the question group will be added for the primary
1410
-     *                                           registrant, if false will be added for others. default: false
1411
-     * @return EE_Base_Class|EE_Question_Group
1412
-     * @throws EE_Error
1413
-     * @throws InvalidArgumentException
1414
-     * @throws InvalidDataTypeException
1415
-     * @throws InvalidInterfaceException
1416
-     * @throws ReflectionException
1417
-     */
1418
-    public function add_question_group($question_group_id_or_obj, bool $for_primary = false): EE_Question_Group
1419
-    {
1420
-        // If the row already exists, it will be updated. If it doesn't, it will be inserted.
1421
-        // That's in EE_HABTM_Relation::add_relation_to().
1422
-        return $this->_add_relation_to(
1423
-            $question_group_id_or_obj,
1424
-            'Question_Group',
1425
-            [
1426
-                EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary) => true,
1427
-            ]
1428
-        );
1429
-    }
1430
-
1431
-
1432
-    /**
1433
-     * Removes a question group from the event
1434
-     *
1435
-     * @param EE_Question_Group|int $question_group_id_or_obj
1436
-     * @param bool                  $for_primary if true, the question group will be removed from the primary
1437
-     *                                           registrant, if false will be removed from others. default: false
1438
-     * @return EE_Base_Class|EE_Question_Group|int
1439
-     * @throws EE_Error
1440
-     * @throws InvalidArgumentException
1441
-     * @throws ReflectionException
1442
-     * @throws InvalidDataTypeException
1443
-     * @throws InvalidInterfaceException
1444
-     */
1445
-    public function remove_question_group($question_group_id_or_obj, bool $for_primary = false)
1446
-    {
1447
-        // If the question group is used for the other type (primary or additional)
1448
-        // then just update it. If not, delete it outright.
1449
-        $existing_relation = $this->get_first_related(
1450
-            'Event_Question_Group',
1451
-            [
1452
-                [
1453
-                    'QSG_ID' => EEM_Question_Group::instance()->ensure_is_ID($question_group_id_or_obj),
1454
-                ],
1455
-            ]
1456
-        );
1457
-        $field_to_update   = EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary);
1458
-        $other_field       = EEM_Event_Question_Group::instance()->fieldNameForContext(! $for_primary);
1459
-        if ($existing_relation->get($other_field) === false) {
1460
-            // Delete it. It's now no longer for primary or additional question groups.
1461
-            return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group');
1462
-        }
1463
-        // Just update it. They'll still use this question group for the other category
1464
-        $existing_relation->save(
1465
-            [
1466
-                $field_to_update => false,
1467
-            ]
1468
-        );
1469
-        return $question_group_id_or_obj;
1470
-    }
1471
-
1472
-
1473
-    /**
1474
-     * Gets all the question groups, ordering them by QSG_order ascending
1475
-     *
1476
-     * @param array $query_params
1477
-     * @return EE_Base_Class[]|EE_Question_Group[]
1478
-     * @throws EE_Error
1479
-     * @throws ReflectionException
1480
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1481
-     */
1482
-    public function question_groups(array $query_params = []): array
1483
-    {
1484
-        $query_params = ! empty($query_params) ? $query_params : ['order_by' => ['QSG_order' => 'ASC']];
1485
-        return $this->get_many_related('Question_Group', $query_params);
1486
-    }
1487
-
1488
-
1489
-    /**
1490
-     * Implementation for EEI_Has_Icon interface method.
1491
-     *
1492
-     * @return string
1493
-     * @see EEI_Visual_Representation for comments
1494
-     */
1495
-    public function get_icon(): string
1496
-    {
1497
-        return '<span class="dashicons dashicons-flag"></span>';
1498
-    }
1499
-
1500
-
1501
-    /**
1502
-     * Implementation for EEI_Admin_Links interface method.
1503
-     *
1504
-     * @return string
1505
-     * @throws EE_Error
1506
-     * @throws ReflectionException
1507
-     * @see EEI_Admin_Links for comments
1508
-     */
1509
-    public function get_admin_details_link(): string
1510
-    {
1511
-        return $this->get_admin_edit_link();
1512
-    }
1513
-
1514
-
1515
-    /**
1516
-     * Implementation for EEI_Admin_Links interface method.
1517
-     *
1518
-     * @return string
1519
-     * @throws EE_Error
1520
-     * @throws ReflectionException
1521
-     * @see EEI_Admin_Links for comments
1522
-     */
1523
-    public function get_admin_edit_link(): string
1524
-    {
1525
-        return EEH_URL::add_query_args_and_nonce(
1526
-            [
1527
-                'page'   => 'espresso_events',
1528
-                'action' => 'edit',
1529
-                'post'   => $this->ID(),
1530
-            ],
1531
-            admin_url('admin.php')
1532
-        );
1533
-    }
1534
-
1535
-
1536
-    /**
1537
-     * Implementation for EEI_Admin_Links interface method.
1538
-     *
1539
-     * @return string
1540
-     * @see EEI_Admin_Links for comments
1541
-     */
1542
-    public function get_admin_settings_link(): string
1543
-    {
1544
-        return EEH_URL::add_query_args_and_nonce(
1545
-            [
1546
-                'page'   => 'espresso_events',
1547
-                'action' => 'default_event_settings',
1548
-            ],
1549
-            admin_url('admin.php')
1550
-        );
1551
-    }
1552
-
1553
-
1554
-    /**
1555
-     * Implementation for EEI_Admin_Links interface method.
1556
-     *
1557
-     * @return string
1558
-     * @see EEI_Admin_Links for comments
1559
-     */
1560
-    public function get_admin_overview_link(): string
1561
-    {
1562
-        return EEH_URL::add_query_args_and_nonce(
1563
-            [
1564
-                'page'   => 'espresso_events',
1565
-                'action' => 'default',
1566
-            ],
1567
-            admin_url('admin.php')
1568
-        );
1569
-    }
1570
-
1571
-
1572
-    /**
1573
-     * @return string|null
1574
-     * @throws EE_Error
1575
-     * @throws ReflectionException
1576
-     */
1577
-    public function registrationFormUuid(): ?string
1578
-    {
1579
-        return $this->get('FSC_UUID') ?? '';
1580
-    }
1581
-
1582
-
1583
-    /**
1584
-     * Gets all the form sections for this event
1585
-     *
1586
-     * @return EE_Base_Class[]|EE_Form_Section[]
1587
-     * @throws EE_Error
1588
-     * @throws ReflectionException
1589
-     */
1590
-    public function registrationForm(): array
1591
-    {
1592
-        $FSC_UUID = $this->registrationFormUuid();
1593
-
1594
-        if (empty($FSC_UUID)) {
1595
-            return [];
1596
-        }
1597
-
1598
-        return EEM_Form_Section::instance()->get_all(
1599
-            [
1600
-                [
1601
-                    'OR' => [
1602
-                        'FSC_UUID'      => $FSC_UUID, // top level form
1603
-                        'FSC_belongsTo' => $FSC_UUID, // child form sections
1604
-                    ],
1605
-                ],
1606
-                'order_by' => ['FSC_order' => 'ASC'],
1607
-            ]
1608
-        );
1609
-    }
1610
-
1611
-
1612
-    /**
1613
-     * @param string $UUID
1614
-     * @throws EE_Error
1615
-     * @throws ReflectionException
1616
-     */
1617
-    public function setRegistrationFormUuid(string $UUID): void
1618
-    {
1619
-        if (! Cuid::isCuid($UUID)) {
1620
-            throw new InvalidArgumentException(
1621
-                sprintf(
1622
-                /* translators: 1: UUID value, 2: UUID generator function. */
1623
-                    esc_html__(
1624
-                        'The supplied UUID "%1$s" is invalid or missing. Please use %2$s to generate a valid one.',
1625
-                        'event_espresso'
1626
-                    ),
1627
-                    $UUID,
1628
-                    '`Cuid::cuid()`'
1629
-                )
1630
-            );
1631
-        }
1632
-        $this->set('FSC_UUID', $UUID);
1633
-    }
1634
-
1635
-
1636
-    /**
1637
-     * Get visibility status of event
1638
-     *
1639
-     * @param bool $hide_public
1640
-     * @return string
1641
-     */
1642
-    public function get_visibility_status(bool $hide_public = true): string
1643
-    {
1644
-        if ($this->status() === 'private') {
1645
-            return esc_html__('Private', 'event_espresso');
1646
-        }
1647
-        if (! empty($this->wp_post()->post_password)) {
1648
-            return esc_html__('Password Protected', 'event_espresso');
1649
-        }
1650
-        if (! $hide_public) {
1651
-            return esc_html__('Public', 'event_espresso');
1652
-        }
1653
-
1654
-        return '';
1655
-    }
1250
+		if ($echo) {
1251
+			echo wp_kses($status, AllowedTags::getAllowedTags());
1252
+			return '';
1253
+		}
1254
+		return $status;
1255
+	}
1256
+
1257
+
1258
+	/**
1259
+	 * @return bool|int
1260
+	 * @throws EE_Error
1261
+	 * @throws ReflectionException
1262
+	 */
1263
+	public function get_number_of_tickets_sold()
1264
+	{
1265
+		$tkt_sold = 0;
1266
+		if (! $this->ID()) {
1267
+			return 0;
1268
+		}
1269
+		$datetimes = $this->datetimes();
1270
+		foreach ($datetimes as $datetime) {
1271
+			if ($datetime instanceof EE_Datetime) {
1272
+				$tkt_sold += $datetime->sold();
1273
+			}
1274
+		}
1275
+		return $tkt_sold;
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * This just returns a count of all the registrations for this event
1281
+	 *
1282
+	 * @return int
1283
+	 * @throws EE_Error
1284
+	 * @throws ReflectionException
1285
+	 */
1286
+	public function get_count_of_all_registrations(): int
1287
+	{
1288
+		return EEM_Event::instance()->count_related($this, 'Registration');
1289
+	}
1290
+
1291
+
1292
+	/**
1293
+	 * This returns the ticket with the earliest start time that is
1294
+	 * available for this event (across all datetimes attached to the event)
1295
+	 *
1296
+	 * @return EE_Base_Class|EE_Ticket|null
1297
+	 * @throws EE_Error
1298
+	 * @throws ReflectionException
1299
+	 */
1300
+	public function get_ticket_with_earliest_start_time()
1301
+	{
1302
+		$where['Datetime.EVT_ID'] = $this->ID();
1303
+		$query_params             = [$where, 'order_by' => ['TKT_start_date' => 'ASC']];
1304
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1305
+	}
1306
+
1307
+
1308
+	/**
1309
+	 * This returns the ticket with the latest end time that is available
1310
+	 * for this event (across all datetimes attached to the event)
1311
+	 *
1312
+	 * @return EE_Base_Class|EE_Ticket|null
1313
+	 * @throws EE_Error
1314
+	 * @throws ReflectionException
1315
+	 */
1316
+	public function get_ticket_with_latest_end_time()
1317
+	{
1318
+		$where['Datetime.EVT_ID'] = $this->ID();
1319
+		$query_params             = [$where, 'order_by' => ['TKT_end_date' => 'DESC']];
1320
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1321
+	}
1322
+
1323
+
1324
+	/**
1325
+	 * This returns the number of different ticket types currently on sale for this event.
1326
+	 *
1327
+	 * @return int
1328
+	 * @throws EE_Error
1329
+	 * @throws ReflectionException
1330
+	 */
1331
+	public function countTicketsOnSale(): int
1332
+	{
1333
+		$where = [
1334
+			'Datetime.EVT_ID' => $this->ID(),
1335
+			'TKT_start_date'  => ['<', time()],
1336
+			'TKT_end_date'    => ['>', time()],
1337
+		];
1338
+		return EEM_Ticket::instance()->count([$where]);
1339
+	}
1340
+
1341
+
1342
+	/**
1343
+	 * This returns whether there are any tickets on sale for this event.
1344
+	 *
1345
+	 * @return bool true = YES tickets on sale.
1346
+	 * @throws EE_Error
1347
+	 * @throws ReflectionException
1348
+	 */
1349
+	public function tickets_on_sale(): bool
1350
+	{
1351
+		return $this->countTicketsOnSale() > 0;
1352
+	}
1353
+
1354
+
1355
+	/**
1356
+	 * Gets the URL for viewing this event on the front-end. Overrides parent
1357
+	 * to check for an external URL first
1358
+	 *
1359
+	 * @return string
1360
+	 * @throws EE_Error
1361
+	 * @throws ReflectionException
1362
+	 */
1363
+	public function get_permalink(): string
1364
+	{
1365
+		if ($this->external_url()) {
1366
+			return $this->external_url();
1367
+		}
1368
+		return parent::get_permalink();
1369
+	}
1370
+
1371
+
1372
+	/**
1373
+	 * Gets the first term for 'espresso_event_categories' we can find
1374
+	 *
1375
+	 * @param array $query_params
1376
+	 * @return EE_Base_Class|EE_Term|null
1377
+	 * @throws EE_Error
1378
+	 * @throws ReflectionException
1379
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1380
+	 */
1381
+	public function first_event_category(array $query_params = []): ?EE_Term
1382
+	{
1383
+		$query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1384
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1385
+		return EEM_Term::instance()->get_one($query_params);
1386
+	}
1387
+
1388
+
1389
+	/**
1390
+	 * Gets all terms for 'espresso_event_categories' we can find
1391
+	 *
1392
+	 * @param array $query_params
1393
+	 * @return EE_Base_Class[]|EE_Term[]
1394
+	 * @throws EE_Error
1395
+	 * @throws ReflectionException
1396
+	 */
1397
+	public function get_all_event_categories(array $query_params = []): array
1398
+	{
1399
+		$query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1400
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1401
+		return EEM_Term::instance()->get_all($query_params);
1402
+	}
1403
+
1404
+
1405
+	/**
1406
+	 * Adds a question group to this event
1407
+	 *
1408
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1409
+	 * @param bool                  $for_primary if true, the question group will be added for the primary
1410
+	 *                                           registrant, if false will be added for others. default: false
1411
+	 * @return EE_Base_Class|EE_Question_Group
1412
+	 * @throws EE_Error
1413
+	 * @throws InvalidArgumentException
1414
+	 * @throws InvalidDataTypeException
1415
+	 * @throws InvalidInterfaceException
1416
+	 * @throws ReflectionException
1417
+	 */
1418
+	public function add_question_group($question_group_id_or_obj, bool $for_primary = false): EE_Question_Group
1419
+	{
1420
+		// If the row already exists, it will be updated. If it doesn't, it will be inserted.
1421
+		// That's in EE_HABTM_Relation::add_relation_to().
1422
+		return $this->_add_relation_to(
1423
+			$question_group_id_or_obj,
1424
+			'Question_Group',
1425
+			[
1426
+				EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary) => true,
1427
+			]
1428
+		);
1429
+	}
1430
+
1431
+
1432
+	/**
1433
+	 * Removes a question group from the event
1434
+	 *
1435
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1436
+	 * @param bool                  $for_primary if true, the question group will be removed from the primary
1437
+	 *                                           registrant, if false will be removed from others. default: false
1438
+	 * @return EE_Base_Class|EE_Question_Group|int
1439
+	 * @throws EE_Error
1440
+	 * @throws InvalidArgumentException
1441
+	 * @throws ReflectionException
1442
+	 * @throws InvalidDataTypeException
1443
+	 * @throws InvalidInterfaceException
1444
+	 */
1445
+	public function remove_question_group($question_group_id_or_obj, bool $for_primary = false)
1446
+	{
1447
+		// If the question group is used for the other type (primary or additional)
1448
+		// then just update it. If not, delete it outright.
1449
+		$existing_relation = $this->get_first_related(
1450
+			'Event_Question_Group',
1451
+			[
1452
+				[
1453
+					'QSG_ID' => EEM_Question_Group::instance()->ensure_is_ID($question_group_id_or_obj),
1454
+				],
1455
+			]
1456
+		);
1457
+		$field_to_update   = EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary);
1458
+		$other_field       = EEM_Event_Question_Group::instance()->fieldNameForContext(! $for_primary);
1459
+		if ($existing_relation->get($other_field) === false) {
1460
+			// Delete it. It's now no longer for primary or additional question groups.
1461
+			return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group');
1462
+		}
1463
+		// Just update it. They'll still use this question group for the other category
1464
+		$existing_relation->save(
1465
+			[
1466
+				$field_to_update => false,
1467
+			]
1468
+		);
1469
+		return $question_group_id_or_obj;
1470
+	}
1471
+
1472
+
1473
+	/**
1474
+	 * Gets all the question groups, ordering them by QSG_order ascending
1475
+	 *
1476
+	 * @param array $query_params
1477
+	 * @return EE_Base_Class[]|EE_Question_Group[]
1478
+	 * @throws EE_Error
1479
+	 * @throws ReflectionException
1480
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1481
+	 */
1482
+	public function question_groups(array $query_params = []): array
1483
+	{
1484
+		$query_params = ! empty($query_params) ? $query_params : ['order_by' => ['QSG_order' => 'ASC']];
1485
+		return $this->get_many_related('Question_Group', $query_params);
1486
+	}
1487
+
1488
+
1489
+	/**
1490
+	 * Implementation for EEI_Has_Icon interface method.
1491
+	 *
1492
+	 * @return string
1493
+	 * @see EEI_Visual_Representation for comments
1494
+	 */
1495
+	public function get_icon(): string
1496
+	{
1497
+		return '<span class="dashicons dashicons-flag"></span>';
1498
+	}
1499
+
1500
+
1501
+	/**
1502
+	 * Implementation for EEI_Admin_Links interface method.
1503
+	 *
1504
+	 * @return string
1505
+	 * @throws EE_Error
1506
+	 * @throws ReflectionException
1507
+	 * @see EEI_Admin_Links for comments
1508
+	 */
1509
+	public function get_admin_details_link(): string
1510
+	{
1511
+		return $this->get_admin_edit_link();
1512
+	}
1513
+
1514
+
1515
+	/**
1516
+	 * Implementation for EEI_Admin_Links interface method.
1517
+	 *
1518
+	 * @return string
1519
+	 * @throws EE_Error
1520
+	 * @throws ReflectionException
1521
+	 * @see EEI_Admin_Links for comments
1522
+	 */
1523
+	public function get_admin_edit_link(): string
1524
+	{
1525
+		return EEH_URL::add_query_args_and_nonce(
1526
+			[
1527
+				'page'   => 'espresso_events',
1528
+				'action' => 'edit',
1529
+				'post'   => $this->ID(),
1530
+			],
1531
+			admin_url('admin.php')
1532
+		);
1533
+	}
1534
+
1535
+
1536
+	/**
1537
+	 * Implementation for EEI_Admin_Links interface method.
1538
+	 *
1539
+	 * @return string
1540
+	 * @see EEI_Admin_Links for comments
1541
+	 */
1542
+	public function get_admin_settings_link(): string
1543
+	{
1544
+		return EEH_URL::add_query_args_and_nonce(
1545
+			[
1546
+				'page'   => 'espresso_events',
1547
+				'action' => 'default_event_settings',
1548
+			],
1549
+			admin_url('admin.php')
1550
+		);
1551
+	}
1552
+
1553
+
1554
+	/**
1555
+	 * Implementation for EEI_Admin_Links interface method.
1556
+	 *
1557
+	 * @return string
1558
+	 * @see EEI_Admin_Links for comments
1559
+	 */
1560
+	public function get_admin_overview_link(): string
1561
+	{
1562
+		return EEH_URL::add_query_args_and_nonce(
1563
+			[
1564
+				'page'   => 'espresso_events',
1565
+				'action' => 'default',
1566
+			],
1567
+			admin_url('admin.php')
1568
+		);
1569
+	}
1570
+
1571
+
1572
+	/**
1573
+	 * @return string|null
1574
+	 * @throws EE_Error
1575
+	 * @throws ReflectionException
1576
+	 */
1577
+	public function registrationFormUuid(): ?string
1578
+	{
1579
+		return $this->get('FSC_UUID') ?? '';
1580
+	}
1581
+
1582
+
1583
+	/**
1584
+	 * Gets all the form sections for this event
1585
+	 *
1586
+	 * @return EE_Base_Class[]|EE_Form_Section[]
1587
+	 * @throws EE_Error
1588
+	 * @throws ReflectionException
1589
+	 */
1590
+	public function registrationForm(): array
1591
+	{
1592
+		$FSC_UUID = $this->registrationFormUuid();
1593
+
1594
+		if (empty($FSC_UUID)) {
1595
+			return [];
1596
+		}
1597
+
1598
+		return EEM_Form_Section::instance()->get_all(
1599
+			[
1600
+				[
1601
+					'OR' => [
1602
+						'FSC_UUID'      => $FSC_UUID, // top level form
1603
+						'FSC_belongsTo' => $FSC_UUID, // child form sections
1604
+					],
1605
+				],
1606
+				'order_by' => ['FSC_order' => 'ASC'],
1607
+			]
1608
+		);
1609
+	}
1610
+
1611
+
1612
+	/**
1613
+	 * @param string $UUID
1614
+	 * @throws EE_Error
1615
+	 * @throws ReflectionException
1616
+	 */
1617
+	public function setRegistrationFormUuid(string $UUID): void
1618
+	{
1619
+		if (! Cuid::isCuid($UUID)) {
1620
+			throw new InvalidArgumentException(
1621
+				sprintf(
1622
+				/* translators: 1: UUID value, 2: UUID generator function. */
1623
+					esc_html__(
1624
+						'The supplied UUID "%1$s" is invalid or missing. Please use %2$s to generate a valid one.',
1625
+						'event_espresso'
1626
+					),
1627
+					$UUID,
1628
+					'`Cuid::cuid()`'
1629
+				)
1630
+			);
1631
+		}
1632
+		$this->set('FSC_UUID', $UUID);
1633
+	}
1634
+
1635
+
1636
+	/**
1637
+	 * Get visibility status of event
1638
+	 *
1639
+	 * @param bool $hide_public
1640
+	 * @return string
1641
+	 */
1642
+	public function get_visibility_status(bool $hide_public = true): string
1643
+	{
1644
+		if ($this->status() === 'private') {
1645
+			return esc_html__('Private', 'event_espresso');
1646
+		}
1647
+		if (! empty($this->wp_post()->post_password)) {
1648
+			return esc_html__('Password Protected', 'event_espresso');
1649
+		}
1650
+		if (! $hide_public) {
1651
+			return esc_html__('Public', 'event_espresso');
1652
+		}
1653
+
1654
+		return '';
1655
+	}
1656 1656
 }
Please login to merge, or discard this patch.
core/db_classes/EE_CPT_Base.class.php 2 patches
Indentation   +440 added lines, -440 removed lines patch added patch discarded remove patch
@@ -13,444 +13,444 @@
 block discarded – undo
13 13
  */
14 14
 abstract class EE_CPT_Base extends EE_Soft_Delete_Base_Class
15 15
 {
16
-    /**
17
-     * @var stdClass
18
-     * @since 5.0.0.p
19
-     */
20
-    public $labels;
21
-
22
-    /**
23
-     * @var string
24
-     * @since 5.0.0.p
25
-     */
26
-    public $name;
27
-
28
-    /**
29
-     * This is a property for holding cached feature images on CPT objects.  Cache's are set on the first
30
-     * "feature_image()" method call.  Each key in the array corresponds to the requested size.
31
-     *
32
-     * @var array
33
-     */
34
-    protected $_feature_image = array();
35
-
36
-    /**
37
-     * @var WP_Post the WP_Post that corresponds with this CPT model object
38
-     */
39
-    protected $_wp_post;
40
-
41
-
42
-    abstract public function wp_user();
43
-
44
-
45
-    /**
46
-     * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
47
-     * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
48
-     *
49
-     * @return WP_Post
50
-     */
51
-    public function wp_post()
52
-    {
53
-        global $wpdb;
54
-        if (! $this->_wp_post instanceof WP_Post) {
55
-            if ($this->ID()) {
56
-                $this->_wp_post = get_post($this->ID());
57
-            } else {
58
-                $simulated_db_result = new stdClass();
59
-                foreach ($this->get_model()->field_settings(true) as $field_name => $field_obj) {
60
-                    if (
61
-                        $this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name()
62
-                        === $wpdb->posts
63
-                    ) {
64
-                        $column = $field_obj->get_table_column();
65
-
66
-                        if ($field_obj instanceof EE_Datetime_Field) {
67
-                            $value_on_model_obj = $this->get_DateTime_object($field_name);
68
-                        } elseif ($field_obj->is_db_only_field()) {
69
-                            $value_on_model_obj = $field_obj->get_default_value();
70
-                        } else {
71
-                            $value_on_model_obj = $this->get_raw($field_name);
72
-                        }
73
-                        $simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
74
-                    }
75
-                }
76
-                $this->_wp_post = new WP_Post($simulated_db_result);
77
-            }
78
-            // and let's make retrieving the EE CPT object easy too
79
-            $classname = get_class($this);
80
-            if (! isset($this->_wp_post->{$classname})) {
81
-                $this->_wp_post->{$classname} = $this;
82
-            }
83
-        }
84
-        return $this->_wp_post;
85
-    }
86
-
87
-    /**
88
-     * When fetching a new value for a post field that uses the global $post for rendering,
89
-     * set the global $post temporarily to be this model object; and afterwards restore it
90
-     *
91
-     * @param string $fieldname
92
-     * @param bool   $pretty
93
-     * @param string $extra_cache_ref
94
-     * @return mixed
95
-     */
96
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
97
-    {
98
-        global $post;
99
-
100
-        if (
101
-            $pretty
102
-            && (
103
-                ! (
104
-                    $post instanceof WP_Post
105
-                    && $post->ID
106
-                )
107
-                || (int) $post->ID !== $this->ID()
108
-            )
109
-            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field
110
-        ) {
111
-            $old_post = $post;
112
-            $post = $this->wp_post();
113
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
114
-            $post = $old_post;
115
-        } else {
116
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
117
-        }
118
-        return $return_value;
119
-    }
120
-
121
-    /**
122
-     * Adds to the specified event category. If it category doesn't exist, creates it.
123
-     *
124
-     * @param string $category_name
125
-     * @param string $category_description    optional
126
-     * @param int    $parent_term_taxonomy_id optional
127
-     * @return EE_Term_Taxonomy
128
-     */
129
-    public function add_event_category($category_name, $category_description = null, $parent_term_taxonomy_id = null)
130
-    {
131
-        return $this->get_model()->add_event_category(
132
-            $this,
133
-            $category_name,
134
-            $category_description,
135
-            $parent_term_taxonomy_id
136
-        );
137
-    }
138
-
139
-
140
-    /**
141
-     * Removes the event category by specified name from being related ot this event
142
-     *
143
-     * @param string $category_name
144
-     * @return bool
145
-     */
146
-    public function remove_event_category($category_name)
147
-    {
148
-        return $this->get_model()->remove_event_category($this, $category_name);
149
-    }
150
-
151
-
152
-    /**
153
-     * Removes the relation to the specified term taxonomy, and maintains the
154
-     * data integrity of the term taxonomy provided
155
-     *
156
-     * @param EE_Term_Taxonomy $term_taxonomy
157
-     * @return EE_Base_Class the relation was removed from
158
-     */
159
-    public function remove_relation_to_term_taxonomy($term_taxonomy)
160
-    {
161
-        if (! $term_taxonomy) {
162
-            EE_Error::add_error(
163
-                sprintf(
164
-                    esc_html__(
165
-                        "No Term_Taxonomy provided which to remove from model object of type %s and id %d",
166
-                        "event_espresso"
167
-                    ),
168
-                    get_class($this),
169
-                    $this->ID()
170
-                ),
171
-                __FILE__,
172
-                __FUNCTION__,
173
-                __LINE__
174
-            );
175
-            return null;
176
-        }
177
-        $term_taxonomy->set_count($term_taxonomy->count() - 1);
178
-        $term_taxonomy->save();
179
-        return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
180
-    }
181
-
182
-
183
-    /**
184
-     * The main purpose of this method is to return the post type for the model object
185
-     *
186
-     * @access public
187
-     * @return string
188
-     */
189
-    public function post_type()
190
-    {
191
-        return $this->get_model()->post_type();
192
-    }
193
-
194
-
195
-    /**
196
-     * The main purpose of this method is to return the parent for the model object
197
-     *
198
-     * @access public
199
-     * @return int
200
-     */
201
-    public function parent()
202
-    {
203
-        return $this->get('parent');
204
-    }
205
-
206
-
207
-    /**
208
-     * return the _status property
209
-     *
210
-     * @return string
211
-     */
212
-    public function status()
213
-    {
214
-        return $this->get('status');
215
-    }
216
-
217
-
218
-    /**
219
-     * @param string $status
220
-     */
221
-    public function set_status($status)
222
-    {
223
-        $this->set('status', $status);
224
-    }
225
-
226
-
227
-    /**
228
-     * This calls the equivalent model method for retrieving the feature image which in turn is a wrapper for
229
-     * WordPress' get_the_post_thumbnail() function.
230
-     *
231
-     * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
232
-     * @access protected
233
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
234
-     *                           representing width and height in pixels (i.e. array(32,32) ).
235
-     * @param string|array $attr Optional. Query string or array of attributes.
236
-     * @return string HTML image element
237
-     */
238
-    protected function _get_feature_image($size, $attr)
239
-    {
240
-        // first let's see if we already have the _feature_image property set AND if it has a cached element on it FOR the given size
241
-        $attr_key = is_array($attr) ? implode('_', $attr) : $attr;
242
-        $cache_key = is_array($size) ? implode('_', $size) . $attr_key : $size . $attr_key;
243
-        $this->_feature_image[ $cache_key ] = $this->_feature_image[ $cache_key ]
244
-                                              ?? $this->get_model()->get_feature_image($this->ID(), $size, $attr);
245
-        return $this->_feature_image[ $cache_key ];
246
-    }
247
-
248
-
249
-    /**
250
-     * See _get_feature_image. Returns the HTML to display a featured image
251
-     *
252
-     * @param string       $size
253
-     * @param string|array $attr
254
-     * @return string of html
255
-     */
256
-    public function feature_image($size = 'thumbnail', $attr = '')
257
-    {
258
-        return $this->_get_feature_image($size, $attr);
259
-    }
260
-
261
-
262
-    /**
263
-     * This uses the wp "wp_get_attachment_image_src()" function to return the feature image for the current class
264
-     * using the given size params.
265
-     *
266
-     * @param  string|array $size can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array
267
-     *                            representing width and height in pixels eg. array(32,32).
268
-     * @return string|boolean          the url of the image or false if not found
269
-     */
270
-    public function feature_image_url($size = 'thumbnail')
271
-    {
272
-        $attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
273
-        return ! empty($attachment) ? $attachment[0] : false;
274
-    }
275
-
276
-
277
-    /**
278
-     * This is a method for restoring this_obj using details from the given $revision_id
279
-     *
280
-     * @param int   $revision_id       ID of the revision we're getting data from
281
-     * @param array $related_obj_names if included this will be used to restore for related obj
282
-     *                                 if not included then we just do restore on the meta.
283
-     *                                 We will accept an array of related_obj_names for restoration here.
284
-     * @param array $where_query       You can optionally include an array of key=>value pairs
285
-     *                                 that allow you to further constrict the relation to being added.
286
-     *                                 However, keep in mind that the columns (keys) given
287
-     *                                 must match a column on the JOIN table and currently
288
-     *                                 only the HABTM models accept these additional conditions.
289
-     *                                 Also remember that if an exact match isn't found for these extra cols/val pairs,
290
-     *                                 then a NEW row is created in the join table.
291
-     *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names
292
-     *                                 sent);
293
-     * @return void
294
-     */
295
-    public function restore_revision($revision_id, $related_obj_names = array(), $where_query = array())
296
-    {
297
-        // get revision object
298
-        $revision_obj = $this->get_model()->get_one_by_ID($revision_id);
299
-        if ($revision_obj instanceof EE_CPT_Base) {
300
-            // no related_obj_name so we assume we're saving a revision on this object.
301
-            if (empty($related_obj_names)) {
302
-                $fields = $this->get_model()->get_meta_table_fields();
303
-                foreach ($fields as $field) {
304
-                    $this->set($field, $revision_obj->get($field));
305
-                }
306
-                $this->save();
307
-            }
308
-            $related_obj_names = (array) $related_obj_names;
309
-            foreach ($related_obj_names as $related_name) {
310
-                // related_obj_name so we're saving a revision on an object related to this object
311
-                // do we have $where_query params for this related object?  If we do then we include that.
312
-                $cols_n_values = isset($where_query[ $related_name ]) ? $where_query[ $related_name ] : array();
313
-                $where_params = ! empty($cols_n_values) ? array($cols_n_values) : array();
314
-                $related_objs = $this->get_many_related($related_name, $where_params);
315
-                $revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
316
-                // load helper
317
-                // remove related objs from this object that are not in revision
318
-                // array_diff *should* work cause I think objects are indexed by ID?
319
-                $related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
320
-                foreach ($related_to_remove as $rr) {
321
-                    $this->_remove_relation_to($rr, $related_name, $cols_n_values);
322
-                }
323
-                // add all related objs attached to revision to this object
324
-                foreach ($revision_related_objs as $r_obj) {
325
-                    $this->_add_relation_to($r_obj, $related_name, $cols_n_values);
326
-                }
327
-            }
328
-        }
329
-    }
330
-
331
-
332
-    /**
333
-     * Wrapper for get_post_meta, http://codex.wordpress.org/Function_Reference/get_post_meta
334
-     *
335
-     * @param string  $meta_key
336
-     * @param boolean $single
337
-     * @return mixed <ul><li>If only $id is set it will return all meta values in an associative array.</li>
338
-     * <li>If $single is set to false, or left blank, the function returns an array containing all values of the
339
-     * specified key.</li>
340
-     * <li>If $single is set to true, the function returns the first value of the specified key (not in an
341
-     * array</li></ul>
342
-     */
343
-    public function get_post_meta($meta_key = null, $single = false)
344
-    {
345
-        return get_post_meta($this->ID(), $meta_key, $single);
346
-    }
347
-
348
-
349
-    /**
350
-     * Wrapper for update_post_meta, http://codex.wordpress.org/Function_Reference/update_post_meta
351
-     *
352
-     * @param string $meta_key
353
-     * @param mixed  $meta_value
354
-     * @param mixed  $prev_value
355
-     * @return mixed Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure.
356
-     *               NOTE: If the meta_value passed to this function is the same as the value that is already in the
357
-     *               database, this function returns false.
358
-     */
359
-    public function update_post_meta($meta_key, $meta_value, $prev_value = null)
360
-    {
361
-        if (! $this->ID()) {
362
-            $this->save();
363
-        }
364
-        return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
365
-    }
366
-
367
-
368
-    /**
369
-     * Wrapper for add_post_meta, http://codex.wordpress.org/Function_Reference/add_post_meta
370
-     *
371
-     * @param mixed $meta_key
372
-     * @param mixed $meta_value
373
-     * @param bool  $unique . If postmeta for this $meta_key already exists, whether to add an additional item or not
374
-     * @return boolean Boolean true, except if the $unique argument was set to true and a custom field with the given
375
-     *                 key already exists, in which case false is returned.
376
-     */
377
-    public function add_post_meta($meta_key, $meta_value, $unique = false)
378
-    {
379
-        if ($this->ID()) {
380
-            $this->save();
381
-        }
382
-        return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
383
-    }
384
-
385
-
386
-    /**
387
-     * Wrapper for delete_post_meta, http://codex.wordpress.org/Function_Reference/delete_post_meta
388
-     *
389
-     * @param mixed $meta_key
390
-     * @param mixed $meta_value
391
-     * @return boolean False for failure. True for success.
392
-     */
393
-    public function delete_post_meta($meta_key, $meta_value = '')
394
-    {
395
-        if (! $this->ID()) {
396
-            // there are obviously no postmetas for this if it's not saved
397
-            // so let's just report this as a success
398
-            return true;
399
-        }
400
-        return delete_post_meta($this->ID(), $meta_key, $meta_value);
401
-    }
402
-
403
-
404
-    /**
405
-     * Gets the URL for viewing this event on the front-end
406
-     *
407
-     * @return string
408
-     */
409
-    public function get_permalink()
410
-    {
411
-        return get_permalink($this->ID());
412
-    }
413
-
414
-
415
-    /**
416
-     * Gets all the term-taxonomies for this CPT
417
-     *
418
-     * @param array $query_params
419
-     * @return EE_Term_Taxonomy
420
-     */
421
-    public function term_taxonomies($query_params = array())
422
-    {
423
-        return $this->get_many_related('Term_Taxonomy', $query_params);
424
-    }
425
-
426
-
427
-    /**
428
-     * @return mixed
429
-     */
430
-    public function get_custom_post_statuses()
431
-    {
432
-        return $this->get_model()->get_custom_post_statuses();
433
-    }
434
-
435
-
436
-    /**
437
-     * @return mixed
438
-     */
439
-    public function get_all_post_statuses()
440
-    {
441
-        return $this->get_model()->get_status_array();
442
-    }
443
-
444
-
445
-    /**
446
-     * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
447
-     *
448
-     * @return array
449
-     */
450
-    public function __sleep()
451
-    {
452
-        $properties_to_serialize = parent::__sleep();
453
-        $properties_to_serialize = array_diff($properties_to_serialize, array('_wp_post'));
454
-        return $properties_to_serialize;
455
-    }
16
+	/**
17
+	 * @var stdClass
18
+	 * @since 5.0.0.p
19
+	 */
20
+	public $labels;
21
+
22
+	/**
23
+	 * @var string
24
+	 * @since 5.0.0.p
25
+	 */
26
+	public $name;
27
+
28
+	/**
29
+	 * This is a property for holding cached feature images on CPT objects.  Cache's are set on the first
30
+	 * "feature_image()" method call.  Each key in the array corresponds to the requested size.
31
+	 *
32
+	 * @var array
33
+	 */
34
+	protected $_feature_image = array();
35
+
36
+	/**
37
+	 * @var WP_Post the WP_Post that corresponds with this CPT model object
38
+	 */
39
+	protected $_wp_post;
40
+
41
+
42
+	abstract public function wp_user();
43
+
44
+
45
+	/**
46
+	 * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
47
+	 * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
48
+	 *
49
+	 * @return WP_Post
50
+	 */
51
+	public function wp_post()
52
+	{
53
+		global $wpdb;
54
+		if (! $this->_wp_post instanceof WP_Post) {
55
+			if ($this->ID()) {
56
+				$this->_wp_post = get_post($this->ID());
57
+			} else {
58
+				$simulated_db_result = new stdClass();
59
+				foreach ($this->get_model()->field_settings(true) as $field_name => $field_obj) {
60
+					if (
61
+						$this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name()
62
+						=== $wpdb->posts
63
+					) {
64
+						$column = $field_obj->get_table_column();
65
+
66
+						if ($field_obj instanceof EE_Datetime_Field) {
67
+							$value_on_model_obj = $this->get_DateTime_object($field_name);
68
+						} elseif ($field_obj->is_db_only_field()) {
69
+							$value_on_model_obj = $field_obj->get_default_value();
70
+						} else {
71
+							$value_on_model_obj = $this->get_raw($field_name);
72
+						}
73
+						$simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
74
+					}
75
+				}
76
+				$this->_wp_post = new WP_Post($simulated_db_result);
77
+			}
78
+			// and let's make retrieving the EE CPT object easy too
79
+			$classname = get_class($this);
80
+			if (! isset($this->_wp_post->{$classname})) {
81
+				$this->_wp_post->{$classname} = $this;
82
+			}
83
+		}
84
+		return $this->_wp_post;
85
+	}
86
+
87
+	/**
88
+	 * When fetching a new value for a post field that uses the global $post for rendering,
89
+	 * set the global $post temporarily to be this model object; and afterwards restore it
90
+	 *
91
+	 * @param string $fieldname
92
+	 * @param bool   $pretty
93
+	 * @param string $extra_cache_ref
94
+	 * @return mixed
95
+	 */
96
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
97
+	{
98
+		global $post;
99
+
100
+		if (
101
+			$pretty
102
+			&& (
103
+				! (
104
+					$post instanceof WP_Post
105
+					&& $post->ID
106
+				)
107
+				|| (int) $post->ID !== $this->ID()
108
+			)
109
+			&& $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field
110
+		) {
111
+			$old_post = $post;
112
+			$post = $this->wp_post();
113
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
114
+			$post = $old_post;
115
+		} else {
116
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
117
+		}
118
+		return $return_value;
119
+	}
120
+
121
+	/**
122
+	 * Adds to the specified event category. If it category doesn't exist, creates it.
123
+	 *
124
+	 * @param string $category_name
125
+	 * @param string $category_description    optional
126
+	 * @param int    $parent_term_taxonomy_id optional
127
+	 * @return EE_Term_Taxonomy
128
+	 */
129
+	public function add_event_category($category_name, $category_description = null, $parent_term_taxonomy_id = null)
130
+	{
131
+		return $this->get_model()->add_event_category(
132
+			$this,
133
+			$category_name,
134
+			$category_description,
135
+			$parent_term_taxonomy_id
136
+		);
137
+	}
138
+
139
+
140
+	/**
141
+	 * Removes the event category by specified name from being related ot this event
142
+	 *
143
+	 * @param string $category_name
144
+	 * @return bool
145
+	 */
146
+	public function remove_event_category($category_name)
147
+	{
148
+		return $this->get_model()->remove_event_category($this, $category_name);
149
+	}
150
+
151
+
152
+	/**
153
+	 * Removes the relation to the specified term taxonomy, and maintains the
154
+	 * data integrity of the term taxonomy provided
155
+	 *
156
+	 * @param EE_Term_Taxonomy $term_taxonomy
157
+	 * @return EE_Base_Class the relation was removed from
158
+	 */
159
+	public function remove_relation_to_term_taxonomy($term_taxonomy)
160
+	{
161
+		if (! $term_taxonomy) {
162
+			EE_Error::add_error(
163
+				sprintf(
164
+					esc_html__(
165
+						"No Term_Taxonomy provided which to remove from model object of type %s and id %d",
166
+						"event_espresso"
167
+					),
168
+					get_class($this),
169
+					$this->ID()
170
+				),
171
+				__FILE__,
172
+				__FUNCTION__,
173
+				__LINE__
174
+			);
175
+			return null;
176
+		}
177
+		$term_taxonomy->set_count($term_taxonomy->count() - 1);
178
+		$term_taxonomy->save();
179
+		return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
180
+	}
181
+
182
+
183
+	/**
184
+	 * The main purpose of this method is to return the post type for the model object
185
+	 *
186
+	 * @access public
187
+	 * @return string
188
+	 */
189
+	public function post_type()
190
+	{
191
+		return $this->get_model()->post_type();
192
+	}
193
+
194
+
195
+	/**
196
+	 * The main purpose of this method is to return the parent for the model object
197
+	 *
198
+	 * @access public
199
+	 * @return int
200
+	 */
201
+	public function parent()
202
+	{
203
+		return $this->get('parent');
204
+	}
205
+
206
+
207
+	/**
208
+	 * return the _status property
209
+	 *
210
+	 * @return string
211
+	 */
212
+	public function status()
213
+	{
214
+		return $this->get('status');
215
+	}
216
+
217
+
218
+	/**
219
+	 * @param string $status
220
+	 */
221
+	public function set_status($status)
222
+	{
223
+		$this->set('status', $status);
224
+	}
225
+
226
+
227
+	/**
228
+	 * This calls the equivalent model method for retrieving the feature image which in turn is a wrapper for
229
+	 * WordPress' get_the_post_thumbnail() function.
230
+	 *
231
+	 * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
232
+	 * @access protected
233
+	 * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
234
+	 *                           representing width and height in pixels (i.e. array(32,32) ).
235
+	 * @param string|array $attr Optional. Query string or array of attributes.
236
+	 * @return string HTML image element
237
+	 */
238
+	protected function _get_feature_image($size, $attr)
239
+	{
240
+		// first let's see if we already have the _feature_image property set AND if it has a cached element on it FOR the given size
241
+		$attr_key = is_array($attr) ? implode('_', $attr) : $attr;
242
+		$cache_key = is_array($size) ? implode('_', $size) . $attr_key : $size . $attr_key;
243
+		$this->_feature_image[ $cache_key ] = $this->_feature_image[ $cache_key ]
244
+											  ?? $this->get_model()->get_feature_image($this->ID(), $size, $attr);
245
+		return $this->_feature_image[ $cache_key ];
246
+	}
247
+
248
+
249
+	/**
250
+	 * See _get_feature_image. Returns the HTML to display a featured image
251
+	 *
252
+	 * @param string       $size
253
+	 * @param string|array $attr
254
+	 * @return string of html
255
+	 */
256
+	public function feature_image($size = 'thumbnail', $attr = '')
257
+	{
258
+		return $this->_get_feature_image($size, $attr);
259
+	}
260
+
261
+
262
+	/**
263
+	 * This uses the wp "wp_get_attachment_image_src()" function to return the feature image for the current class
264
+	 * using the given size params.
265
+	 *
266
+	 * @param  string|array $size can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array
267
+	 *                            representing width and height in pixels eg. array(32,32).
268
+	 * @return string|boolean          the url of the image or false if not found
269
+	 */
270
+	public function feature_image_url($size = 'thumbnail')
271
+	{
272
+		$attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
273
+		return ! empty($attachment) ? $attachment[0] : false;
274
+	}
275
+
276
+
277
+	/**
278
+	 * This is a method for restoring this_obj using details from the given $revision_id
279
+	 *
280
+	 * @param int   $revision_id       ID of the revision we're getting data from
281
+	 * @param array $related_obj_names if included this will be used to restore for related obj
282
+	 *                                 if not included then we just do restore on the meta.
283
+	 *                                 We will accept an array of related_obj_names for restoration here.
284
+	 * @param array $where_query       You can optionally include an array of key=>value pairs
285
+	 *                                 that allow you to further constrict the relation to being added.
286
+	 *                                 However, keep in mind that the columns (keys) given
287
+	 *                                 must match a column on the JOIN table and currently
288
+	 *                                 only the HABTM models accept these additional conditions.
289
+	 *                                 Also remember that if an exact match isn't found for these extra cols/val pairs,
290
+	 *                                 then a NEW row is created in the join table.
291
+	 *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names
292
+	 *                                 sent);
293
+	 * @return void
294
+	 */
295
+	public function restore_revision($revision_id, $related_obj_names = array(), $where_query = array())
296
+	{
297
+		// get revision object
298
+		$revision_obj = $this->get_model()->get_one_by_ID($revision_id);
299
+		if ($revision_obj instanceof EE_CPT_Base) {
300
+			// no related_obj_name so we assume we're saving a revision on this object.
301
+			if (empty($related_obj_names)) {
302
+				$fields = $this->get_model()->get_meta_table_fields();
303
+				foreach ($fields as $field) {
304
+					$this->set($field, $revision_obj->get($field));
305
+				}
306
+				$this->save();
307
+			}
308
+			$related_obj_names = (array) $related_obj_names;
309
+			foreach ($related_obj_names as $related_name) {
310
+				// related_obj_name so we're saving a revision on an object related to this object
311
+				// do we have $where_query params for this related object?  If we do then we include that.
312
+				$cols_n_values = isset($where_query[ $related_name ]) ? $where_query[ $related_name ] : array();
313
+				$where_params = ! empty($cols_n_values) ? array($cols_n_values) : array();
314
+				$related_objs = $this->get_many_related($related_name, $where_params);
315
+				$revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
316
+				// load helper
317
+				// remove related objs from this object that are not in revision
318
+				// array_diff *should* work cause I think objects are indexed by ID?
319
+				$related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
320
+				foreach ($related_to_remove as $rr) {
321
+					$this->_remove_relation_to($rr, $related_name, $cols_n_values);
322
+				}
323
+				// add all related objs attached to revision to this object
324
+				foreach ($revision_related_objs as $r_obj) {
325
+					$this->_add_relation_to($r_obj, $related_name, $cols_n_values);
326
+				}
327
+			}
328
+		}
329
+	}
330
+
331
+
332
+	/**
333
+	 * Wrapper for get_post_meta, http://codex.wordpress.org/Function_Reference/get_post_meta
334
+	 *
335
+	 * @param string  $meta_key
336
+	 * @param boolean $single
337
+	 * @return mixed <ul><li>If only $id is set it will return all meta values in an associative array.</li>
338
+	 * <li>If $single is set to false, or left blank, the function returns an array containing all values of the
339
+	 * specified key.</li>
340
+	 * <li>If $single is set to true, the function returns the first value of the specified key (not in an
341
+	 * array</li></ul>
342
+	 */
343
+	public function get_post_meta($meta_key = null, $single = false)
344
+	{
345
+		return get_post_meta($this->ID(), $meta_key, $single);
346
+	}
347
+
348
+
349
+	/**
350
+	 * Wrapper for update_post_meta, http://codex.wordpress.org/Function_Reference/update_post_meta
351
+	 *
352
+	 * @param string $meta_key
353
+	 * @param mixed  $meta_value
354
+	 * @param mixed  $prev_value
355
+	 * @return mixed Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure.
356
+	 *               NOTE: If the meta_value passed to this function is the same as the value that is already in the
357
+	 *               database, this function returns false.
358
+	 */
359
+	public function update_post_meta($meta_key, $meta_value, $prev_value = null)
360
+	{
361
+		if (! $this->ID()) {
362
+			$this->save();
363
+		}
364
+		return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
365
+	}
366
+
367
+
368
+	/**
369
+	 * Wrapper for add_post_meta, http://codex.wordpress.org/Function_Reference/add_post_meta
370
+	 *
371
+	 * @param mixed $meta_key
372
+	 * @param mixed $meta_value
373
+	 * @param bool  $unique . If postmeta for this $meta_key already exists, whether to add an additional item or not
374
+	 * @return boolean Boolean true, except if the $unique argument was set to true and a custom field with the given
375
+	 *                 key already exists, in which case false is returned.
376
+	 */
377
+	public function add_post_meta($meta_key, $meta_value, $unique = false)
378
+	{
379
+		if ($this->ID()) {
380
+			$this->save();
381
+		}
382
+		return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
383
+	}
384
+
385
+
386
+	/**
387
+	 * Wrapper for delete_post_meta, http://codex.wordpress.org/Function_Reference/delete_post_meta
388
+	 *
389
+	 * @param mixed $meta_key
390
+	 * @param mixed $meta_value
391
+	 * @return boolean False for failure. True for success.
392
+	 */
393
+	public function delete_post_meta($meta_key, $meta_value = '')
394
+	{
395
+		if (! $this->ID()) {
396
+			// there are obviously no postmetas for this if it's not saved
397
+			// so let's just report this as a success
398
+			return true;
399
+		}
400
+		return delete_post_meta($this->ID(), $meta_key, $meta_value);
401
+	}
402
+
403
+
404
+	/**
405
+	 * Gets the URL for viewing this event on the front-end
406
+	 *
407
+	 * @return string
408
+	 */
409
+	public function get_permalink()
410
+	{
411
+		return get_permalink($this->ID());
412
+	}
413
+
414
+
415
+	/**
416
+	 * Gets all the term-taxonomies for this CPT
417
+	 *
418
+	 * @param array $query_params
419
+	 * @return EE_Term_Taxonomy
420
+	 */
421
+	public function term_taxonomies($query_params = array())
422
+	{
423
+		return $this->get_many_related('Term_Taxonomy', $query_params);
424
+	}
425
+
426
+
427
+	/**
428
+	 * @return mixed
429
+	 */
430
+	public function get_custom_post_statuses()
431
+	{
432
+		return $this->get_model()->get_custom_post_statuses();
433
+	}
434
+
435
+
436
+	/**
437
+	 * @return mixed
438
+	 */
439
+	public function get_all_post_statuses()
440
+	{
441
+		return $this->get_model()->get_status_array();
442
+	}
443
+
444
+
445
+	/**
446
+	 * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
447
+	 *
448
+	 * @return array
449
+	 */
450
+	public function __sleep()
451
+	{
452
+		$properties_to_serialize = parent::__sleep();
453
+		$properties_to_serialize = array_diff($properties_to_serialize, array('_wp_post'));
454
+		return $properties_to_serialize;
455
+	}
456 456
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
     public function wp_post()
52 52
     {
53 53
         global $wpdb;
54
-        if (! $this->_wp_post instanceof WP_Post) {
54
+        if ( ! $this->_wp_post instanceof WP_Post) {
55 55
             if ($this->ID()) {
56 56
                 $this->_wp_post = get_post($this->ID());
57 57
             } else {
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
             }
78 78
             // and let's make retrieving the EE CPT object easy too
79 79
             $classname = get_class($this);
80
-            if (! isset($this->_wp_post->{$classname})) {
80
+            if ( ! isset($this->_wp_post->{$classname})) {
81 81
                 $this->_wp_post->{$classname} = $this;
82 82
             }
83 83
         }
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
      */
159 159
     public function remove_relation_to_term_taxonomy($term_taxonomy)
160 160
     {
161
-        if (! $term_taxonomy) {
161
+        if ( ! $term_taxonomy) {
162 162
             EE_Error::add_error(
163 163
                 sprintf(
164 164
                     esc_html__(
@@ -239,10 +239,10 @@  discard block
 block discarded – undo
239 239
     {
240 240
         // first let's see if we already have the _feature_image property set AND if it has a cached element on it FOR the given size
241 241
         $attr_key = is_array($attr) ? implode('_', $attr) : $attr;
242
-        $cache_key = is_array($size) ? implode('_', $size) . $attr_key : $size . $attr_key;
243
-        $this->_feature_image[ $cache_key ] = $this->_feature_image[ $cache_key ]
242
+        $cache_key = is_array($size) ? implode('_', $size).$attr_key : $size.$attr_key;
243
+        $this->_feature_image[$cache_key] = $this->_feature_image[$cache_key]
244 244
                                               ?? $this->get_model()->get_feature_image($this->ID(), $size, $attr);
245
-        return $this->_feature_image[ $cache_key ];
245
+        return $this->_feature_image[$cache_key];
246 246
     }
247 247
 
248 248
 
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
             foreach ($related_obj_names as $related_name) {
310 310
                 // related_obj_name so we're saving a revision on an object related to this object
311 311
                 // do we have $where_query params for this related object?  If we do then we include that.
312
-                $cols_n_values = isset($where_query[ $related_name ]) ? $where_query[ $related_name ] : array();
312
+                $cols_n_values = isset($where_query[$related_name]) ? $where_query[$related_name] : array();
313 313
                 $where_params = ! empty($cols_n_values) ? array($cols_n_values) : array();
314 314
                 $related_objs = $this->get_many_related($related_name, $where_params);
315 315
                 $revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
      */
359 359
     public function update_post_meta($meta_key, $meta_value, $prev_value = null)
360 360
     {
361
-        if (! $this->ID()) {
361
+        if ( ! $this->ID()) {
362 362
             $this->save();
363 363
         }
364 364
         return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
@@ -392,7 +392,7 @@  discard block
 block discarded – undo
392 392
      */
393 393
     public function delete_post_meta($meta_key, $meta_value = '')
394 394
     {
395
-        if (! $this->ID()) {
395
+        if ( ! $this->ID()) {
396 396
             // there are obviously no postmetas for this if it's not saved
397 397
             // so let's just report this as a success
398 398
             return true;
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +3330 added lines, -3330 removed lines patch added patch discarded remove patch
@@ -16,3345 +16,3345 @@
 block discarded – undo
16 16
 abstract class EE_Base_Class
17 17
 {
18 18
 
19
-    /**
20
-     * @var EEM_Base|null
21
-     */
22
-    protected $_model = null;
23
-
24
-    /**
25
-     * This is an array of the original properties and values provided during construction
26
-     * of this model object. (keys are model field names, values are their values).
27
-     * This list is important to remember so that when we are merging data from the db, we know
28
-     * which values to override and which to not override.
29
-     */
30
-    protected ?array $_props_n_values_provided_in_constructor = null;
31
-
32
-    /**
33
-     * Timezone
34
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
35
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
36
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
37
-     * access to it.
38
-     */
39
-    protected string $_timezone = '';
40
-
41
-    /**
42
-     * date format
43
-     * pattern or format for displaying dates
44
-     */
45
-    protected string $_dt_frmt = '';
46
-
47
-    /**
48
-     * time format
49
-     * pattern or format for displaying time
50
-     */
51
-    protected string $_tm_frmt = '';
52
-
53
-    /**
54
-     * This property is for holding a cached array of object properties indexed by property name as the key.
55
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
56
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
-     */
59
-    protected array $_cached_properties = [];
60
-
61
-    /**
62
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
63
-     * single
64
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
65
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
66
-     * all others have an array)
67
-     */
68
-    protected array $_model_relations = [];
69
-
70
-    /**
71
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
72
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
73
-     */
74
-    protected array $_fields = [];
75
-
76
-    /**
77
-     * indicating whether or not this model object is intended to ever be saved
78
-     * For example, we might create model objects intended to only be used for the duration
79
-     * of this request and to be thrown away, and if they were accidentally saved
80
-     * it would be a bug.
81
-     */
82
-    protected bool $_allow_persist = true;
83
-
84
-    /**
85
-     * indicating whether or not this model object's properties have changed since construction
86
-     */
87
-    protected bool $_has_changes = false;
88
-
89
-    /**
90
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
91
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
92
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
93
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
94
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
95
-     * array as:
96
-     * array(
97
-     *  'Registration_Count' => 24
98
-     * );
99
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
100
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
101
-     * info)
102
-     */
103
-    protected array $custom_selection_results = [];
104
-
105
-
106
-    /**
107
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
108
-     * play nice
109
-     *
110
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
111
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
112
-     *                                                         TXN_amount, QST_name, etc) and values are their values
113
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
114
-     *                                                         corresponding db model or not.
115
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
116
-     *                                                         be in when instantiating a EE_Base_Class object.
117
-     * @param array   $date_formats                            An array of date formats to set on construct where first
118
-     *                                                         value is the date_format and second value is the time
119
-     *                                                         format.
120
-     * @throws InvalidArgumentException
121
-     * @throws InvalidInterfaceException
122
-     * @throws InvalidDataTypeException
123
-     * @throws EE_Error
124
-     * @throws ReflectionException
125
-     */
126
-    protected function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
127
-    {
128
-        $className = get_class($this);
129
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
130
-        $model        = $this->get_model();
131
-        $model_fields = $model->field_settings();
132
-        // ensure $fieldValues is an array
133
-        $fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
134
-        // verify client code has not passed any invalid field names
135
-        foreach ($fieldValues as $field_name => $field_value) {
136
-            if (! isset($model_fields[ $field_name ])) {
137
-                throw new EE_Error(
138
-                    sprintf(
139
-                        esc_html__(
140
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
141
-                            'event_espresso'
142
-                        ),
143
-                        $field_name,
144
-                        get_class($this),
145
-                        implode(', ', array_keys($model_fields))
146
-                    )
147
-                );
148
-            }
149
-        }
150
-
151
-        $date_format     = null;
152
-        $time_format     = null;
153
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
154
-        if (! empty($date_formats) && is_array($date_formats)) {
155
-            [$date_format, $time_format] = $date_formats;
156
-        }
157
-        $this->set_date_format($date_format);
158
-        $this->set_time_format($time_format);
159
-        // if db model is instantiating
160
-        foreach ($model_fields as $fieldName => $field) {
161
-            if ($bydb) {
162
-                // client code has indicated these field values are from the database
163
-                $this->set_from_db(
164
-                    $fieldName,
165
-                    $fieldValues[ $fieldName ] ?? null
166
-                );
167
-            } else {
168
-                // we're constructing a brand new instance of the model object.
169
-                // Generally, this means we'll need to do more field validation
170
-                $this->set(
171
-                    $fieldName,
172
-                    $fieldValues[ $fieldName ] ?? null,
173
-                    true
174
-                );
175
-            }
176
-        }
177
-        // remember what values were passed to this constructor
178
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
179
-        // remember in entity mapper
180
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
181
-            $model->add_to_entity_map($this);
182
-        }
183
-        // setup all the relations
184
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
185
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
186
-                $this->_model_relations[ $relation_name ] = null;
187
-            } else {
188
-                $this->_model_relations[ $relation_name ] = [];
189
-            }
190
-        }
191
-        /**
192
-         * Action done at the end of each model object construction
193
-         *
194
-         * @param EE_Base_Class $this the model object just created
195
-         */
196
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
197
-    }
198
-
199
-
200
-    /**
201
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
202
-     *
203
-     * @return boolean
204
-     */
205
-    public function allow_persist()
206
-    {
207
-        return $this->_allow_persist;
208
-    }
209
-
210
-
211
-    /**
212
-     * Sets whether or not this model object should be allowed to be saved to the DB.
213
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
214
-     * you got new information that somehow made you change your mind.
215
-     *
216
-     * @param boolean $allow_persist
217
-     * @return boolean
218
-     */
219
-    public function set_allow_persist($allow_persist)
220
-    {
221
-        return $this->_allow_persist = $allow_persist;
222
-    }
223
-
224
-
225
-    /**
226
-     * Gets the field's original value when this object was constructed during this request.
227
-     * This can be helpful when determining if a model object has changed or not
228
-     *
229
-     * @param string $field_name
230
-     * @return mixed|null
231
-     * @throws ReflectionException
232
-     * @throws InvalidArgumentException
233
-     * @throws InvalidInterfaceException
234
-     * @throws InvalidDataTypeException
235
-     * @throws EE_Error
236
-     */
237
-    public function get_original($field_name)
238
-    {
239
-        if (
240
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
241
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
242
-        ) {
243
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
244
-        }
245
-        return null;
246
-    }
247
-
248
-
249
-    /**
250
-     * @param EE_Base_Class $obj
251
-     * @return string
252
-     */
253
-    public function get_class($obj)
254
-    {
255
-        return get_class($obj);
256
-    }
257
-
258
-
259
-    /**
260
-     * Overrides parent because parent expects old models.
261
-     * This also doesn't do any validation, and won't work for serialized arrays
262
-     *
263
-     * @param string $field_name
264
-     * @param mixed  $field_value
265
-     * @param bool   $use_default
266
-     * @throws InvalidArgumentException
267
-     * @throws InvalidInterfaceException
268
-     * @throws InvalidDataTypeException
269
-     * @throws EE_Error
270
-     * @throws ReflectionException
271
-     * @throws Exception
272
-     */
273
-    public function set(string $field_name, $field_value, bool $use_default = false)
274
-    {
275
-        // if not using default and nothing has changed, and object has already been setup (has ID),
276
-        // then don't do anything
277
-        if (
278
-            ! $use_default
279
-            && $this->_fields[ $field_name ] === $field_value
280
-            && $this->ID()
281
-        ) {
282
-            return;
283
-        }
284
-        $model              = $this->get_model();
285
-        $this->_has_changes = true;
286
-        $field_obj          = $model->field_settings_for($field_name);
287
-        if (! $field_obj instanceof EE_Model_Field_Base) {
288
-            throw new EE_Error(
289
-                sprintf(
290
-                    esc_html__(
291
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
292
-                        'event_espresso'
293
-                    ),
294
-                    $field_name
295
-                )
296
-            );
297
-        }
298
-        // if ( method_exists( $field_obj, 'set_timezone' )) {
299
-        if ($field_obj instanceof EE_Datetime_Field) {
300
-            $field_obj->set_timezone($this->_timezone);
301
-            $field_obj->set_date_format($this->_dt_frmt);
302
-            $field_obj->set_time_format($this->_tm_frmt);
303
-        }
304
-
305
-        // should the value be null?
306
-        $value = $field_value === null && ($use_default || ! $field_obj->is_nullable())
307
-            ? $field_obj->get_default_value()
308
-            : $field_value;
309
-
310
-        $this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
311
-
312
-        // if we're not in the constructor...
313
-        // now check if what we set was a primary key
314
-        if (
315
-            // note: props_n_values_provided_in_constructor is only set at the END of the constructor
316
-            $this->_props_n_values_provided_in_constructor
317
-            && $field_value
318
-            && $field_name === $model->primary_key_name()
319
-        ) {
320
-            // if so, we want all this object's fields to be filled either with
321
-            // what we've explicitly set on this model
322
-            // or what we have in the db
323
-            // echo "setting primary key!";
324
-            $fields_on_model = self::_get_model(get_class($this))->field_settings();
325
-            $obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
326
-            foreach ($fields_on_model as $field_obj) {
327
-                if (
328
-                    ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
329
-                    && $field_obj->get_name() !== $field_name
330
-                ) {
331
-                    $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
332
-                }
333
-            }
334
-            // oh this model object has an ID? well make sure its in the entity mapper
335
-            $model->add_to_entity_map($this);
336
-        }
337
-        // let's unset any cache for this field_name from the $_cached_properties property.
338
-        $this->_clear_cached_property($field_name);
339
-    }
340
-
341
-
342
-    /**
343
-     * Overrides parent because parent expects old models.
344
-     * This also doesn't do any validation, and won't work for serialized arrays
345
-     *
346
-     * @param string $field_name
347
-     * @param mixed  $field_value_from_db
348
-     * @throws ReflectionException
349
-     * @throws InvalidArgumentException
350
-     * @throws InvalidInterfaceException
351
-     * @throws InvalidDataTypeException
352
-     * @throws EE_Error
353
-     */
354
-    public function set_from_db(string $field_name, $field_value_from_db)
355
-    {
356
-        $field_obj = $this->get_model()->field_settings_for($field_name);
357
-        if ($field_obj instanceof EE_Model_Field_Base) {
358
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
359
-            // eg, a CPT model object could have an entry in the posts table, but no
360
-            // entry in the meta table. Meaning that all its columns in the meta table
361
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
362
-            if ($field_value_from_db === null) {
363
-                if ($field_obj->is_nullable()) {
364
-                    // if the field allows nulls, then let it be null
365
-                    $field_value = null;
366
-                } else {
367
-                    $field_value = $field_obj->get_default_value();
368
-                }
369
-            } else {
370
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
371
-            }
372
-            $this->_fields[ $field_name ] = $field_value;
373
-            $this->_clear_cached_property($field_name);
374
-        }
375
-    }
376
-
377
-
378
-    /**
379
-     * Set custom select values for model.
380
-     *
381
-     * @param array $custom_select_values
382
-     */
383
-    public function setCustomSelectsValues(array $custom_select_values)
384
-    {
385
-        $this->custom_selection_results = $custom_select_values;
386
-    }
387
-
388
-
389
-    /**
390
-     * Returns the custom select value for the provided alias if its set.
391
-     * If not set, returns null.
392
-     *
393
-     * @param string $alias
394
-     * @return string|int|float|null
395
-     */
396
-    public function getCustomSelect($alias)
397
-    {
398
-        return $this->custom_selection_results[ $alias ] ?? null;
399
-    }
400
-
401
-
402
-    /**
403
-     * This sets the field value on the db column if it exists for the given $column_name or
404
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
405
-     *
406
-     * @param string $field_name  Must be the exact column name.
407
-     * @param mixed  $field_value The value to set.
408
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
409
-     * @throws InvalidArgumentException
410
-     * @throws InvalidInterfaceException
411
-     * @throws InvalidDataTypeException
412
-     * @throws EE_Error
413
-     * @throws ReflectionException
414
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
415
-     */
416
-    public function set_field_or_extra_meta($field_name, $field_value)
417
-    {
418
-        if ($this->get_model()->has_field($field_name)) {
419
-            $this->set($field_name, $field_value);
420
-            return true;
421
-        }
422
-        // ensure this object is saved first so that extra meta can be properly related.
423
-        $this->save();
424
-        return $this->update_extra_meta($field_name, $field_value);
425
-    }
426
-
427
-
428
-    /**
429
-     * This retrieves the value of the db column set on this class or if that's not present
430
-     * it will attempt to retrieve from extra_meta if found.
431
-     * Example Usage:
432
-     * Via EE_Message child class:
433
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
434
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
435
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
436
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
437
-     * value for those extra fields dynamically via the EE_message object.
438
-     *
439
-     * @param string $field_name expecting the fully qualified field name.
440
-     * @return mixed|null  value for the field if found.  null if not found.
441
-     * @throws ReflectionException
442
-     * @throws InvalidArgumentException
443
-     * @throws InvalidInterfaceException
444
-     * @throws InvalidDataTypeException
445
-     * @throws EE_Error
446
-     */
447
-    public function get_field_or_extra_meta($field_name)
448
-    {
449
-        if ($this->get_model()->has_field($field_name)) {
450
-            $column_value = $this->get($field_name);
451
-        } else {
452
-            // This isn't a column in the main table, let's see if it is in the extra meta.
453
-            $column_value = $this->get_extra_meta($field_name, true, null);
454
-        }
455
-        return $column_value;
456
-    }
457
-
458
-
459
-    /**
460
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
461
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
462
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
463
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
464
-     *
465
-     * @access public
466
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
467
-     * @return void
468
-     * @throws InvalidArgumentException
469
-     * @throws InvalidInterfaceException
470
-     * @throws InvalidDataTypeException
471
-     * @throws EE_Error
472
-     * @throws ReflectionException
473
-     * @throws Exception
474
-     */
475
-    public function set_timezone($timezone = '')
476
-    {
477
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
478
-        // make sure we clear all cached properties because they won't be relevant now
479
-        $this->_clear_cached_properties();
480
-        // make sure we update field settings and the date for all EE_Datetime_Fields
481
-        $model_fields = $this->get_model()->field_settings(false);
482
-        foreach ($model_fields as $field_name => $field_obj) {
483
-            if ($field_obj instanceof EE_Datetime_Field) {
484
-                $field_obj->set_timezone($this->_timezone);
485
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
486
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
487
-                }
488
-            }
489
-        }
490
-    }
491
-
492
-
493
-    /**
494
-     * This just returns whatever is set for the current timezone.
495
-     *
496
-     * @access public
497
-     * @return string timezone string
498
-     */
499
-    public function get_timezone()
500
-    {
501
-        return $this->_timezone;
502
-    }
503
-
504
-
505
-    /**
506
-     * This sets the internal date format to what is sent in to be used as the new default for the class
507
-     * internally instead of wp set date format options
508
-     *
509
-     * @param string|null $format should be a format recognizable by PHP date() functions.
510
-     * @since 4.6
511
-     */
512
-    public function set_date_format(?string $format)
513
-    {
514
-        $this->_dt_frmt = new DateFormat($format);
515
-        // clear cached_properties because they won't be relevant now.
516
-        $this->_clear_cached_properties();
517
-    }
518
-
519
-
520
-    /**
521
-     * This sets the internal time format string to what is sent in to be used as the new default for the
522
-     * class internally instead of wp set time format options.
523
-     *
524
-     * @param string|null $format should be a format recognizable by PHP date() functions.
525
-     * @since 4.6
526
-     */
527
-    public function set_time_format(?string $format)
528
-    {
529
-        $this->_tm_frmt = new TimeFormat($format);
530
-        // clear cached_properties because they won't be relevant now.
531
-        $this->_clear_cached_properties();
532
-    }
533
-
534
-
535
-    /**
536
-     * This returns the current internal set format for the date and time formats.
537
-     *
538
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
539
-     *                             where the first value is the date format and the second value is the time format.
540
-     * @return string|array
541
-     */
542
-    public function get_format($full = true)
543
-    {
544
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
545
-    }
546
-
547
-
548
-    /**
549
-     * cache
550
-     * stores the passed model object on the current model object.
551
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
552
-     *
553
-     * @param string        $relation_name   one of the keys in the _model_relations array on the model. Eg
554
-     *                                       'Registration' associated with this model object
555
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
556
-     *                                       that could be a payment or a registration)
557
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
558
-     *                                       items which will be stored in an array on this object
559
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
560
-     *                                       related thing, no array)
561
-     * @throws InvalidArgumentException
562
-     * @throws InvalidInterfaceException
563
-     * @throws InvalidDataTypeException
564
-     * @throws EE_Error
565
-     * @throws ReflectionException
566
-     */
567
-    public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
568
-    {
569
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
570
-        if (! $object_to_cache instanceof EE_Base_Class) {
571
-            return false;
572
-        }
573
-        // also get "how" the object is related, or throw an error
574
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
575
-            throw new EE_Error(
576
-                sprintf(
577
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
578
-                    $relation_name,
579
-                    get_class($this)
580
-                )
581
-            );
582
-        }
583
-        // how many things are related ?
584
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
585
-            // if it's a "belongs to" relationship, then there's only one related model object
586
-            // eg, if this is a registration, there's only 1 attendee for it
587
-            // so for these model objects just set it to be cached
588
-            $this->_model_relations[ $relation_name ] = $object_to_cache;
589
-            $return                                   = true;
590
-        } else {
591
-            // otherwise, this is the "many" side of a one to many relationship,
592
-            // so we'll add the object to the array of related objects for that type.
593
-            // eg: if this is an event, there are many registrations for that event,
594
-            // so we cache the registrations in an array
595
-            if (! is_array($this->_model_relations[ $relation_name ])) {
596
-                // if for some reason, the cached item is a model object,
597
-                // then stick that in the array, otherwise start with an empty array
598
-                $this->_model_relations[ $relation_name ] =
599
-                    $this->_model_relations[ $relation_name ] instanceof EE_Base_Class
600
-                        ? [$this->_model_relations[ $relation_name ]]
601
-                        : [];
602
-            }
603
-            // first check for a cache_id which is normally empty
604
-            if (! empty($cache_id)) {
605
-                // if the cache_id exists, then it means we are purposely trying to cache this
606
-                // with a known key that can then be used to retrieve the object later on
607
-                $this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
608
-                $return                                                = $cache_id;
609
-            } elseif ($object_to_cache->ID()) {
610
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
611
-                $this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
612
-                $return                                                             = $object_to_cache->ID();
613
-            } else {
614
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
615
-                $this->_model_relations[ $relation_name ][] = $object_to_cache;
616
-                // move the internal pointer to the end of the array
617
-                end($this->_model_relations[ $relation_name ]);
618
-                // and grab the key so that we can return it
619
-                $return = key($this->_model_relations[ $relation_name ]);
620
-            }
621
-        }
622
-        return $return;
623
-    }
624
-
625
-
626
-    /**
627
-     * For adding an item to the cached_properties property.
628
-     *
629
-     * @access protected
630
-     * @param string      $fieldname the property item the corresponding value is for.
631
-     * @param mixed       $value     The value we are caching.
632
-     * @param string|null $cache_type
633
-     * @return void
634
-     * @throws ReflectionException
635
-     * @throws InvalidArgumentException
636
-     * @throws InvalidInterfaceException
637
-     * @throws InvalidDataTypeException
638
-     * @throws EE_Error
639
-     */
640
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
641
-    {
642
-        // first make sure this property exists
643
-        $this->get_model()->field_settings_for($fieldname);
644
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
645
-
646
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
647
-    }
648
-
649
-
650
-    /**
651
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
652
-     * This also SETS the cache if we return the actual property!
653
-     *
654
-     * @param string $fieldname        the name of the property we're trying to retrieve
655
-     * @param bool   $pretty
656
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
657
-     *                                 (in cases where the same property may be used for different outputs
658
-     *                                 - i.e. datetime, money etc.)
659
-     *                                 It can also accept certain pre-defined "schema" strings
660
-     *                                 to define how to output the property.
661
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
662
-     * @return mixed                   whatever the value for the property is we're retrieving
663
-     * @throws ReflectionException
664
-     * @throws InvalidArgumentException
665
-     * @throws InvalidInterfaceException
666
-     * @throws InvalidDataTypeException
667
-     * @throws EE_Error
668
-     */
669
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
670
-    {
671
-        // verify the field exists
672
-        $model = $this->get_model();
673
-        $model->field_settings_for($fieldname);
674
-        $cache_type = $pretty ? 'pretty' : 'standard';
675
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
676
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
677
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
678
-        }
679
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
680
-        $this->_set_cached_property($fieldname, $value, $cache_type);
681
-        return $value;
682
-    }
683
-
684
-
685
-    /**
686
-     * If the cache didn't fetch the needed item, this fetches it.
687
-     *
688
-     * @param string $fieldname
689
-     * @param bool   $pretty
690
-     * @param string $extra_cache_ref
691
-     * @return mixed
692
-     * @throws InvalidArgumentException
693
-     * @throws InvalidInterfaceException
694
-     * @throws InvalidDataTypeException
695
-     * @throws EE_Error
696
-     * @throws ReflectionException
697
-     */
698
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
699
-    {
700
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
701
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
702
-        if ($field_obj instanceof EE_Datetime_Field) {
703
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
704
-        }
705
-        if (! isset($this->_fields[ $fieldname ])) {
706
-            $this->_fields[ $fieldname ] = null;
707
-        }
708
-        return $pretty
709
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
710
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
711
-    }
712
-
713
-
714
-    /**
715
-     * set timezone, formats, and output for EE_Datetime_Field objects
716
-     *
717
-     * @param EE_Datetime_Field $datetime_field
718
-     * @param bool              $pretty
719
-     * @param null              $date_or_time
720
-     * @return void
721
-     * @throws InvalidArgumentException
722
-     * @throws InvalidInterfaceException
723
-     * @throws InvalidDataTypeException
724
-     */
725
-    protected function _prepare_datetime_field(
726
-        EE_Datetime_Field $datetime_field,
727
-        $pretty = false,
728
-        $date_or_time = null
729
-    ) {
730
-        $datetime_field->set_timezone($this->_timezone);
731
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
732
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
733
-        // set the output returned
734
-        switch ($date_or_time) {
735
-            case 'D':
736
-                $datetime_field->set_date_time_output('date');
737
-                break;
738
-            case 'T':
739
-                $datetime_field->set_date_time_output('time');
740
-                break;
741
-            default:
742
-                $datetime_field->set_date_time_output();
743
-        }
744
-    }
745
-
746
-
747
-    /**
748
-     * This just takes care of clearing out the cached_properties
749
-     *
750
-     * @return void
751
-     */
752
-    protected function _clear_cached_properties()
753
-    {
754
-        $this->_cached_properties = [];
755
-    }
756
-
757
-
758
-    /**
759
-     * This just clears out ONE property if it exists in the cache
760
-     *
761
-     * @param string $property_name the property to remove if it exists (from the _cached_properties array)
762
-     * @return void
763
-     */
764
-    protected function _clear_cached_property($property_name)
765
-    {
766
-        if (isset($this->_cached_properties[ $property_name ])) {
767
-            unset($this->_cached_properties[ $property_name ]);
768
-        }
769
-    }
770
-
771
-
772
-    /**
773
-     * Ensures that this related thing is a model object.
774
-     *
775
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
776
-     * @param string $model_name   name of the related thing, eg 'Attendee',
777
-     * @return EE_Base_Class
778
-     * @throws ReflectionException
779
-     * @throws InvalidArgumentException
780
-     * @throws InvalidInterfaceException
781
-     * @throws InvalidDataTypeException
782
-     * @throws EE_Error
783
-     */
784
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
785
-    {
786
-        $other_model_instance = self::_get_model_instance_with_name(
787
-            self::_get_model_classname($model_name),
788
-            $this->_timezone
789
-        );
790
-        return $other_model_instance->ensure_is_obj($object_or_id);
791
-    }
792
-
793
-
794
-    /**
795
-     * Forgets the cached model of the given relation Name. So the next time we request it,
796
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
797
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
798
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
799
-     *
800
-     * @param string $relation_name                        one of the keys in the _model_relations array on the model.
801
-     *                                                     Eg 'Registration'
802
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
803
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
804
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
805
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
806
-     *                                                     this is HasMany or HABTM.
807
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
808
-     *                                                     relation from all
809
-     * @throws InvalidArgumentException
810
-     * @throws InvalidInterfaceException
811
-     * @throws InvalidDataTypeException
812
-     * @throws EE_Error
813
-     * @throws ReflectionException
814
-     */
815
-    public function clear_cache($relation_name, $object_to_remove_or_index_into_array = null, $clear_all = false)
816
-    {
817
-        $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
818
-        $index_in_cache        = '';
819
-        if (! $relationship_to_model) {
820
-            throw new EE_Error(
821
-                sprintf(
822
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
823
-                    $relation_name,
824
-                    get_class($this)
825
-                )
826
-            );
827
-        }
828
-        if ($clear_all) {
829
-            $obj_removed                              = true;
830
-            $this->_model_relations[ $relation_name ] = null;
831
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
-            $obj_removed                              = $this->_model_relations[ $relation_name ];
833
-            $this->_model_relations[ $relation_name ] = null;
834
-        } else {
835
-            if (
836
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
837
-                && $object_to_remove_or_index_into_array->ID()
838
-            ) {
839
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
840
-                if (
841
-                    is_array($this->_model_relations[ $relation_name ])
842
-                    && ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
843
-                ) {
844
-                    $index_found_at = null;
845
-                    // find this object in the array even though it has a different key
846
-                    foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
847
-                        /** @noinspection TypeUnsafeComparisonInspection */
848
-                        if (
849
-                            $obj instanceof EE_Base_Class
850
-                            && (
851
-                                $obj == $object_to_remove_or_index_into_array
852
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
853
-                            )
854
-                        ) {
855
-                            $index_found_at = $index;
856
-                            break;
857
-                        }
858
-                    }
859
-                    if ($index_found_at) {
860
-                        $index_in_cache = $index_found_at;
861
-                    } else {
862
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
863
-                        // if it wasn't in it to begin with. So we're done
864
-                        return $object_to_remove_or_index_into_array;
865
-                    }
866
-                }
867
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
868
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
869
-                foreach ($this->get_all_from_cache($relation_name) as $index => $potentially_obj_we_want) {
870
-                    /** @noinspection TypeUnsafeComparisonInspection */
871
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
872
-                        $index_in_cache = $index;
873
-                    }
874
-                }
875
-            } else {
876
-                $index_in_cache = $object_to_remove_or_index_into_array;
877
-            }
878
-            // supposedly we've found it. But it could just be that the client code
879
-            // provided a bad index/object
880
-            if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
881
-                $obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
882
-                unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
883
-            } else {
884
-                // that thing was never cached anyways.
885
-                $obj_removed = null;
886
-            }
887
-        }
888
-        return $obj_removed;
889
-    }
890
-
891
-
892
-    /**
893
-     * update_cache_after_object_save
894
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
895
-     * obtained after being saved to the db
896
-     *
897
-     * @param string        $relation_name      - the type of object that is cached
898
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
899
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
900
-     * @return boolean TRUE on success, FALSE on fail
901
-     * @throws ReflectionException
902
-     * @throws InvalidArgumentException
903
-     * @throws InvalidInterfaceException
904
-     * @throws InvalidDataTypeException
905
-     * @throws EE_Error
906
-     */
907
-    public function update_cache_after_object_save(
908
-        $relation_name,
909
-        EE_Base_Class $newly_saved_object,
910
-        $current_cache_id = ''
911
-    ) {
912
-        // verify that incoming object is of the correct type
913
-        $obj_class = 'EE_' . $relation_name;
914
-        if ($newly_saved_object instanceof $obj_class) {
915
-            /* @type EE_Base_Class $newly_saved_object */
916
-            // now get the type of relation
917
-            $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
918
-            // if this is a 1:1 relationship
919
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
920
-                // then just replace the cached object with the newly saved object
921
-                $this->_model_relations[ $relation_name ] = $newly_saved_object;
922
-                return true;
923
-                // or if it's some kind of sordid feral polyamorous relationship...
924
-            }
925
-            if (
926
-                is_array($this->_model_relations[ $relation_name ])
927
-                && isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
928
-            ) {
929
-                // then remove the current cached item
930
-                unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
931
-                // and cache the newly saved object using it's new ID
932
-                $this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
933
-                return true;
934
-            }
935
-        }
936
-        return false;
937
-    }
938
-
939
-
940
-    /**
941
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
942
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
943
-     *
944
-     * @param string $relation_name
945
-     * @return EE_Base_Class
946
-     */
947
-    public function get_one_from_cache($relation_name)
948
-    {
949
-        $cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
950
-        if (is_array($cached_array_or_object)) {
951
-            return array_shift($cached_array_or_object);
952
-        }
953
-        return $cached_array_or_object;
954
-    }
955
-
956
-
957
-    /**
958
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
959
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
960
-     *
961
-     * @param string $relation_name
962
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
963
-     * @throws InvalidArgumentException
964
-     * @throws InvalidInterfaceException
965
-     * @throws InvalidDataTypeException
966
-     * @throws EE_Error
967
-     * @throws ReflectionException
968
-     */
969
-    public function get_all_from_cache($relation_name)
970
-    {
971
-        $objects = $this->_model_relations[ $relation_name ] ?? [];
972
-        // if the result is not an array, but exists, make it an array
973
-        $objects = is_array($objects)
974
-            ? $objects
975
-            : [$objects];
976
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
977
-        // basically, if this model object was stored in the session, and these cached model objects
978
-        // already have IDs, let's make sure they're in their model's entity mapper
979
-        // otherwise we will have duplicates next time we call
980
-        // EE_Registry::instance()->load_model( $relation_name )->get_one_by_ID( $result->ID() );
981
-        $model = EE_Registry::instance()->load_model($relation_name);
982
-        foreach ($objects as $model_object) {
983
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
984
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
985
-                if ($model_object->ID()) {
986
-                    $model->add_to_entity_map($model_object);
987
-                }
988
-            } else {
989
-                throw new EE_Error(
990
-                    sprintf(
991
-                        esc_html__(
992
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
993
-                            'event_espresso'
994
-                        ),
995
-                        $relation_name,
996
-                        gettype($model_object)
997
-                    )
998
-                );
999
-            }
1000
-        }
1001
-        return $objects;
1002
-    }
1003
-
1004
-
1005
-    /**
1006
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1007
-     * matching the given query conditions.
1008
-     *
1009
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1010
-     * @param int   $limit              How many objects to return.
1011
-     * @param array $query_params       Any additional conditions on the query.
1012
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1013
-     *                                  you can indicate just the columns you want returned
1014
-     * @return array|EE_Base_Class[]
1015
-     * @throws ReflectionException
1016
-     * @throws InvalidArgumentException
1017
-     * @throws InvalidInterfaceException
1018
-     * @throws InvalidDataTypeException
1019
-     * @throws EE_Error
1020
-     */
1021
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = [], $columns_to_select = null)
1022
-    {
1023
-        $model         = $this->get_model();
1024
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1025
-            ? $model->get_primary_key_field()->get_name()
1026
-            : $field_to_order_by;
1027
-        $current_value = ! empty($field)
1028
-            ? $this->get($field)
1029
-            : null;
1030
-        if (empty($field) || empty($current_value)) {
1031
-            return [];
1032
-        }
1033
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1039
-     * matching the given query conditions.
1040
-     *
1041
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1042
-     * @param int   $limit              How many objects to return.
1043
-     * @param array $query_params       Any additional conditions on the query.
1044
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1045
-     *                                  you can indicate just the columns you want returned
1046
-     * @return array|EE_Base_Class[]
1047
-     * @throws ReflectionException
1048
-     * @throws InvalidArgumentException
1049
-     * @throws InvalidInterfaceException
1050
-     * @throws InvalidDataTypeException
1051
-     * @throws EE_Error
1052
-     */
1053
-    public function previous_x(
1054
-        $field_to_order_by = null,
1055
-        $limit = 1,
1056
-        $query_params = [],
1057
-        $columns_to_select = null
1058
-    ) {
1059
-        $model         = $this->get_model();
1060
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1061
-            ? $model->get_primary_key_field()->get_name()
1062
-            : $field_to_order_by;
1063
-        $current_value = ! empty($field) ? $this->get($field) : null;
1064
-        if (empty($field) || empty($current_value)) {
1065
-            return [];
1066
-        }
1067
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1068
-    }
1069
-
1070
-
1071
-    /**
1072
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1073
-     * matching the given query conditions.
1074
-     *
1075
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1076
-     * @param array $query_params       Any additional conditions on the query.
1077
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1078
-     *                                  you can indicate just the columns you want returned
1079
-     * @return array|EE_Base_Class
1080
-     * @throws ReflectionException
1081
-     * @throws InvalidArgumentException
1082
-     * @throws InvalidInterfaceException
1083
-     * @throws InvalidDataTypeException
1084
-     * @throws EE_Error
1085
-     */
1086
-    public function next($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1087
-    {
1088
-        $model         = $this->get_model();
1089
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1090
-            ? $model->get_primary_key_field()->get_name()
1091
-            : $field_to_order_by;
1092
-        $current_value = ! empty($field) ? $this->get($field) : null;
1093
-        if (empty($field) || empty($current_value)) {
1094
-            return [];
1095
-        }
1096
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1097
-    }
1098
-
1099
-
1100
-    /**
1101
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1102
-     * matching the given query conditions.
1103
-     *
1104
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1105
-     * @param array $query_params       Any additional conditions on the query.
1106
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1107
-     *                                  you can indicate just the column you want returned
1108
-     * @return array|EE_Base_Class
1109
-     * @throws ReflectionException
1110
-     * @throws InvalidArgumentException
1111
-     * @throws InvalidInterfaceException
1112
-     * @throws InvalidDataTypeException
1113
-     * @throws EE_Error
1114
-     */
1115
-    public function previous($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1116
-    {
1117
-        $model         = $this->get_model();
1118
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1119
-            ? $model->get_primary_key_field()->get_name()
1120
-            : $field_to_order_by;
1121
-        $current_value = ! empty($field) ? $this->get($field) : null;
1122
-        if (empty($field) || empty($current_value)) {
1123
-            return [];
1124
-        }
1125
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * verifies that the specified field is of the correct type
1131
-     *
1132
-     * @param string $field_name
1133
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1134
-     *                                (in cases where the same property may be used for different outputs
1135
-     *                                - i.e. datetime, money etc.)
1136
-     * @return mixed
1137
-     * @throws ReflectionException
1138
-     * @throws InvalidArgumentException
1139
-     * @throws InvalidInterfaceException
1140
-     * @throws InvalidDataTypeException
1141
-     * @throws EE_Error
1142
-     */
1143
-    public function get($field_name, $extra_cache_ref = null)
1144
-    {
1145
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1146
-    }
1147
-
1148
-
1149
-    /**
1150
-     * This method simply returns the RAW unprocessed value for the given property in this class
1151
-     *
1152
-     * @param string $field_name A valid fieldname
1153
-     * @return mixed              Whatever the raw value stored on the property is.
1154
-     * @throws ReflectionException
1155
-     * @throws InvalidArgumentException
1156
-     * @throws InvalidInterfaceException
1157
-     * @throws InvalidDataTypeException
1158
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1159
-     */
1160
-    public function get_raw($field_name)
1161
-    {
1162
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1163
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1164
-            ? $this->_fields[ $field_name ]->format('U')
1165
-            : $this->_fields[ $field_name ];
1166
-    }
1167
-
1168
-
1169
-    /**
1170
-     * This is used to return the internal DateTime object used for a field that is a
1171
-     * EE_Datetime_Field.
1172
-     *
1173
-     * @param string $field_name               The field name retrieving the DateTime object.
1174
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1175
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1176
-     *                                         EE_Datetime_Field and but the field value is null, then
1177
-     *                                         just null is returned (because that indicates that likely
1178
-     *                                         this field is nullable).
1179
-     * @throws InvalidArgumentException
1180
-     * @throws InvalidDataTypeException
1181
-     * @throws InvalidInterfaceException
1182
-     * @throws ReflectionException
1183
-     */
1184
-    public function get_DateTime_object($field_name)
1185
-    {
1186
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1187
-        if (! $field_settings instanceof EE_Datetime_Field) {
1188
-            EE_Error::add_error(
1189
-                sprintf(
1190
-                    esc_html__(
1191
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1192
-                        'event_espresso'
1193
-                    ),
1194
-                    $field_name
1195
-                ),
1196
-                __FILE__,
1197
-                __FUNCTION__,
1198
-                __LINE__
1199
-            );
1200
-            return false;
1201
-        }
1202
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1203
-            ? clone $this->_fields[ $field_name ]
1204
-            : null;
1205
-    }
1206
-
1207
-
1208
-    /**
1209
-     * To be used in template to immediately echo out the value, and format it for output.
1210
-     * Eg, should call stripslashes and whatnot before echoing
1211
-     *
1212
-     * @param string $field_name      the name of the field as it appears in the DB
1213
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1214
-     *                                (in cases where the same property may be used for different outputs
1215
-     *                                - i.e. datetime, money etc.)
1216
-     * @return void
1217
-     * @throws ReflectionException
1218
-     * @throws InvalidArgumentException
1219
-     * @throws InvalidInterfaceException
1220
-     * @throws InvalidDataTypeException
1221
-     * @throws EE_Error
1222
-     */
1223
-    public function e($field_name, $extra_cache_ref = null)
1224
-    {
1225
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1231
-     * can be easily used as the value of form input.
1232
-     *
1233
-     * @param string $field_name
1234
-     * @return void
1235
-     * @throws ReflectionException
1236
-     * @throws InvalidArgumentException
1237
-     * @throws InvalidInterfaceException
1238
-     * @throws InvalidDataTypeException
1239
-     * @throws EE_Error
1240
-     */
1241
-    public function f($field_name)
1242
-    {
1243
-        $this->e($field_name, 'form_input');
1244
-    }
1245
-
1246
-
1247
-    /**
1248
-     * Same as `f()` but just returns the value instead of echoing it
1249
-     *
1250
-     * @param string $field_name
1251
-     * @return string
1252
-     * @throws ReflectionException
1253
-     * @throws InvalidArgumentException
1254
-     * @throws InvalidInterfaceException
1255
-     * @throws InvalidDataTypeException
1256
-     * @throws EE_Error
1257
-     */
1258
-    public function get_f($field_name)
1259
-    {
1260
-        return (string) $this->get_pretty($field_name, 'form_input');
1261
-    }
1262
-
1263
-
1264
-    /**
1265
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1266
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1267
-     * to see what options are available.
1268
-     *
1269
-     * @param string $field_name
1270
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1271
-     *                                (in cases where the same property may be used for different outputs
1272
-     *                                - i.e. datetime, money etc.)
1273
-     * @return mixed
1274
-     * @throws ReflectionException
1275
-     * @throws InvalidArgumentException
1276
-     * @throws InvalidInterfaceException
1277
-     * @throws InvalidDataTypeException
1278
-     * @throws EE_Error
1279
-     */
1280
-    public function get_pretty($field_name, $extra_cache_ref = null)
1281
-    {
1282
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1283
-    }
1284
-
1285
-
1286
-    /**
1287
-     * This simply returns the datetime for the given field name
1288
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1289
-     * (and the equivalent e_date, e_time, e_datetime).
1290
-     *
1291
-     * @access   protected
1292
-     * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1293
-     * @param string|null $date_format  valid datetime format used for date
1294
-     *                                  (if '' then we just use the default on the field,
1295
-     *                                  if NULL we use the last-used format)
1296
-     * @param string|null $time_format  Same as above except this is for time format
1297
-     * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1298
-     * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1299
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1300
-     *                                  if field is not a valid dtt field, or void if echoing
1301
-     * @throws EE_Error
1302
-     * @throws ReflectionException
1303
-     */
1304
-    protected function _get_datetime(
1305
-        string $field_name,
1306
-        ?string $date_format = '',
1307
-        ?string $time_format = '',
1308
-        ?string $date_or_time = '',
1309
-        ?bool $echo = false
1310
-    ) {
1311
-        // clear cached property
1312
-        $this->_clear_cached_property($field_name);
1313
-        // reset format properties because they are used in get()
1314
-        $this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1315
-        $this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1316
-        if ($echo) {
1317
-            $this->e($field_name, $date_or_time);
1318
-            return '';
1319
-        }
1320
-        return $this->get($field_name, $date_or_time);
1321
-    }
1322
-
1323
-
1324
-    /**
1325
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1326
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1327
-     * other echoes the pretty value for dtt)
1328
-     *
1329
-     * @param string $field_name name of model object datetime field holding the value
1330
-     * @param string $format     format for the date returned (if NULL we use default in dt_frmt property)
1331
-     * @return string            datetime value formatted
1332
-     * @throws ReflectionException
1333
-     * @throws InvalidArgumentException
1334
-     * @throws InvalidInterfaceException
1335
-     * @throws InvalidDataTypeException
1336
-     * @throws EE_Error
1337
-     */
1338
-    public function get_date($field_name, $format = '')
1339
-    {
1340
-        return $this->_get_datetime($field_name, $format, null, 'D');
1341
-    }
1342
-
1343
-
1344
-    /**
1345
-     * @param        $field_name
1346
-     * @param string $format
1347
-     * @throws ReflectionException
1348
-     * @throws InvalidArgumentException
1349
-     * @throws InvalidInterfaceException
1350
-     * @throws InvalidDataTypeException
1351
-     * @throws EE_Error
1352
-     */
1353
-    public function e_date($field_name, $format = '')
1354
-    {
1355
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1356
-    }
1357
-
1358
-
1359
-    /**
1360
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1361
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1362
-     * other echoes the pretty value for dtt)
1363
-     *
1364
-     * @param string $field_name name of model object datetime field holding the value
1365
-     * @param string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1366
-     * @return string             datetime value formatted
1367
-     * @throws ReflectionException
1368
-     * @throws InvalidArgumentException
1369
-     * @throws InvalidInterfaceException
1370
-     * @throws InvalidDataTypeException
1371
-     * @throws EE_Error
1372
-     */
1373
-    public function get_time($field_name, $format = '')
1374
-    {
1375
-        return $this->_get_datetime($field_name, null, $format, 'T');
1376
-    }
1377
-
1378
-
1379
-    /**
1380
-     * @param        $field_name
1381
-     * @param string $format
1382
-     * @throws ReflectionException
1383
-     * @throws InvalidArgumentException
1384
-     * @throws InvalidInterfaceException
1385
-     * @throws InvalidDataTypeException
1386
-     * @throws EE_Error
1387
-     */
1388
-    public function e_time($field_name, $format = '')
1389
-    {
1390
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1391
-    }
1392
-
1393
-
1394
-    /**
1395
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1396
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1397
-     * other echoes the pretty value for dtt)
1398
-     *
1399
-     * @param string $field_name  name of model object datetime field holding the value
1400
-     * @param string $date_format format for the date returned (if NULL we use default in dt_frmt property)
1401
-     * @param string $time_format format for the time returned (if NULL we use default in tm_frmt property)
1402
-     * @return string             datetime value formatted
1403
-     * @throws ReflectionException
1404
-     * @throws InvalidArgumentException
1405
-     * @throws InvalidInterfaceException
1406
-     * @throws InvalidDataTypeException
1407
-     * @throws EE_Error
1408
-     */
1409
-    public function get_datetime($field_name, $date_format = '', $time_format = '')
1410
-    {
1411
-        return $this->_get_datetime($field_name, $date_format, $time_format);
1412
-    }
1413
-
1414
-
1415
-    /**
1416
-     * @param string $field_name
1417
-     * @param string $date_format
1418
-     * @param string $time_format
1419
-     * @throws ReflectionException
1420
-     * @throws InvalidArgumentException
1421
-     * @throws InvalidInterfaceException
1422
-     * @throws InvalidDataTypeException
1423
-     * @throws EE_Error
1424
-     */
1425
-    public function e_datetime($field_name, $date_format = '', $time_format = '')
1426
-    {
1427
-        $this->_get_datetime($field_name, $date_format, $time_format, null, true);
1428
-    }
1429
-
1430
-
1431
-    /**
1432
-     * Get the i8ln value for a date using the WordPress @param string $field_name The EE_Datetime_Field reference for
1433
-     *                           the date being retrieved.
1434
-     *
1435
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1436
-     *                           on the object will be used.
1437
-     * @return string Date and time string in set locale or false if no field exists for the given
1438
-     * @throws ReflectionException
1439
-     * @throws InvalidArgumentException
1440
-     * @throws InvalidInterfaceException
1441
-     * @throws InvalidDataTypeException
1442
-     * @throws EE_Error
1443
-     *                           field name.
1444
-     * @see date_i18n function.
1445
-     */
1446
-    public function get_i18n_datetime(string $field_name, string $format = ''): string
1447
-    {
1448
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1449
-        return date_i18n(
1450
-            $format,
1451
-            EEH_DTT_Helper::get_timestamp_with_offset(
1452
-                $this->get_raw($field_name),
1453
-                $this->_timezone
1454
-            )
1455
-        );
1456
-    }
1457
-
1458
-
1459
-    /**
1460
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1461
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1462
-     * thrown.
1463
-     *
1464
-     * @param string $field_name The field name being checked
1465
-     * @return EE_Datetime_Field
1466
-     * @throws InvalidArgumentException
1467
-     * @throws InvalidInterfaceException
1468
-     * @throws InvalidDataTypeException
1469
-     * @throws EE_Error
1470
-     * @throws ReflectionException
1471
-     */
1472
-    protected function _get_dtt_field_settings($field_name)
1473
-    {
1474
-        $field = $this->get_model()->field_settings_for($field_name);
1475
-        // check if field is dtt
1476
-        if ($field instanceof EE_Datetime_Field) {
1477
-            return $field;
1478
-        }
1479
-        throw new EE_Error(
1480
-            sprintf(
1481
-                esc_html__(
1482
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1483
-                    'event_espresso'
1484
-                ),
1485
-                $field_name,
1486
-                self::_get_model_classname(get_class($this))
1487
-            )
1488
-        );
1489
-    }
1490
-
1491
-
1492
-
1493
-
1494
-    /**
1495
-     * NOTE ABOUT BELOW:
1496
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1497
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1498
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1499
-     * method and make sure you send the entire datetime value for setting.
1500
-     */
1501
-    /**
1502
-     * sets the time on a datetime property
1503
-     *
1504
-     * @access protected
1505
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1506
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1507
-     * @throws ReflectionException
1508
-     * @throws InvalidArgumentException
1509
-     * @throws InvalidInterfaceException
1510
-     * @throws InvalidDataTypeException
1511
-     * @throws EE_Error
1512
-     */
1513
-    protected function _set_time_for($time, $fieldname)
1514
-    {
1515
-        $this->_set_date_time('T', $time, $fieldname);
1516
-    }
1517
-
1518
-
1519
-    /**
1520
-     * sets the date on a datetime property
1521
-     *
1522
-     * @access protected
1523
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1524
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1525
-     * @throws ReflectionException
1526
-     * @throws InvalidArgumentException
1527
-     * @throws InvalidInterfaceException
1528
-     * @throws InvalidDataTypeException
1529
-     * @throws EE_Error
1530
-     */
1531
-    protected function _set_date_for($date, $fieldname)
1532
-    {
1533
-        $this->_set_date_time('D', $date, $fieldname);
1534
-    }
1535
-
1536
-
1537
-    /**
1538
-     * This takes care of setting a date or time independently on a given model object property. This method also
1539
-     * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1540
-     *
1541
-     * @access protected
1542
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1543
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1544
-     * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1545
-     *                                        EE_Datetime_Field property)
1546
-     * @throws ReflectionException
1547
-     * @throws InvalidArgumentException
1548
-     * @throws InvalidInterfaceException
1549
-     * @throws InvalidDataTypeException
1550
-     * @throws EE_Error
1551
-     */
1552
-    protected function _set_date_time(string $what, $datetime_value, string $field_name)
1553
-    {
1554
-        $field = $this->_get_dtt_field_settings($field_name);
1555
-        $field->set_timezone($this->_timezone);
1556
-        $field->set_date_format($this->_dt_frmt);
1557
-        $field->set_time_format($this->_tm_frmt);
1558
-        switch ($what) {
1559
-            case 'T':
1560
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1561
-                    $datetime_value,
1562
-                    $this->_fields[ $field_name ]
1563
-                );
1564
-                $this->_has_changes           = true;
1565
-                break;
1566
-            case 'D':
1567
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1568
-                    $datetime_value,
1569
-                    $this->_fields[ $field_name ]
1570
-                );
1571
-                $this->_has_changes           = true;
1572
-                break;
1573
-            case 'B':
1574
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1575
-                $this->_has_changes           = true;
1576
-                break;
1577
-        }
1578
-        $this->_clear_cached_property($field_name);
1579
-    }
1580
-
1581
-
1582
-    /**
1583
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1584
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1585
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1586
-     * that could lead to some unexpected results!
1587
-     *
1588
-     * @access public
1589
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1590
-     *                                         value being returned.
1591
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1592
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1593
-     * @param string $prepend                  You can include something to prepend on the timestamp
1594
-     * @param string $append                   You can include something to append on the timestamp
1595
-     * @return string timestamp
1596
-     * @throws ReflectionException
1597
-     * @throws InvalidArgumentException
1598
-     * @throws InvalidInterfaceException
1599
-     * @throws InvalidDataTypeException
1600
-     * @throws EE_Error
1601
-     */
1602
-    public function display_in_my_timezone(
1603
-        $field_name,
1604
-        $callback = 'get_datetime',
1605
-        $args = null,
1606
-        $prepend = '',
1607
-        $append = ''
1608
-    ) {
1609
-        $timezone = EEH_DTT_Helper::get_timezone();
1610
-        if ($timezone === $this->_timezone) {
1611
-            return '';
1612
-        }
1613
-        $original_timezone = $this->_timezone;
1614
-        $this->set_timezone($timezone);
1615
-        $fn   = (array) $field_name;
1616
-        $args = array_merge($fn, (array) $args);
1617
-        if (! method_exists($this, $callback)) {
1618
-            throw new EE_Error(
1619
-                sprintf(
1620
-                    esc_html__(
1621
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1622
-                        'event_espresso'
1623
-                    ),
1624
-                    $callback
1625
-                )
1626
-            );
1627
-        }
1628
-        $args   = (array) $args;
1629
-        $return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1630
-        $this->set_timezone($original_timezone);
1631
-        return $return;
1632
-    }
1633
-
1634
-
1635
-    /**
1636
-     * Deletes this model object.
1637
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1638
-     * override
1639
-     * `EE_Base_Class::_delete` NOT this class.
1640
-     *
1641
-     * @return boolean | int
1642
-     * @throws ReflectionException
1643
-     * @throws InvalidArgumentException
1644
-     * @throws InvalidInterfaceException
1645
-     * @throws InvalidDataTypeException
1646
-     * @throws EE_Error
1647
-     */
1648
-    public function delete()
1649
-    {
1650
-        /**
1651
-         * Called just before the `EE_Base_Class::_delete` method call.
1652
-         * Note:
1653
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1654
-         * should be aware that `_delete` may not always result in a permanent delete.
1655
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1656
-         * soft deletes (trash) the object and does not permanently delete it.
1657
-         *
1658
-         * @param EE_Base_Class $model_object about to be 'deleted'
1659
-         */
1660
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1661
-        $result = $this->_delete();
1662
-        /**
1663
-         * Called just after the `EE_Base_Class::_delete` method call.
1664
-         * Note:
1665
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1666
-         * should be aware that `_delete` may not always result in a permanent delete.
1667
-         * For example `EE_Soft_Base_Class::_delete`
1668
-         * soft deletes (trash) the object and does not permanently delete it.
1669
-         *
1670
-         * @param EE_Base_Class $model_object that was just 'deleted'
1671
-         * @param boolean       $result
1672
-         */
1673
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1674
-        return $result;
1675
-    }
1676
-
1677
-
1678
-    /**
1679
-     * Calls the specific delete method for the instantiated class.
1680
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1681
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1682
-     * `EE_Base_Class::delete`
1683
-     *
1684
-     * @return bool|int
1685
-     * @throws ReflectionException
1686
-     * @throws InvalidArgumentException
1687
-     * @throws InvalidInterfaceException
1688
-     * @throws InvalidDataTypeException
1689
-     * @throws EE_Error
1690
-     */
1691
-    protected function _delete()
1692
-    {
1693
-        return $this->delete_permanently();
1694
-    }
1695
-
1696
-
1697
-    /**
1698
-     * Deletes this model object permanently from db
1699
-     * (but keep in mind related models may block the delete and return an error)
1700
-     *
1701
-     * @return bool | int
1702
-     * @throws ReflectionException
1703
-     * @throws InvalidArgumentException
1704
-     * @throws InvalidInterfaceException
1705
-     * @throws InvalidDataTypeException
1706
-     * @throws EE_Error
1707
-     */
1708
-    public function delete_permanently()
1709
-    {
1710
-        /**
1711
-         * Called just before HARD deleting a model object
1712
-         *
1713
-         * @param EE_Base_Class $model_object about to be 'deleted'
1714
-         */
1715
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1716
-        $model  = $this->get_model();
1717
-        $result = $model->delete_permanently_by_ID($this->ID());
1718
-        $this->refresh_cache_of_related_objects();
1719
-        /**
1720
-         * Called just after HARD deleting a model object
1721
-         *
1722
-         * @param EE_Base_Class $model_object that was just 'deleted'
1723
-         * @param boolean       $result
1724
-         */
1725
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1726
-        return $result;
1727
-    }
1728
-
1729
-
1730
-    /**
1731
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1732
-     * related model objects
1733
-     *
1734
-     * @throws ReflectionException
1735
-     * @throws InvalidArgumentException
1736
-     * @throws InvalidInterfaceException
1737
-     * @throws InvalidDataTypeException
1738
-     * @throws EE_Error
1739
-     */
1740
-    public function refresh_cache_of_related_objects()
1741
-    {
1742
-        $model = $this->get_model();
1743
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1744
-            if (! empty($this->_model_relations[ $relation_name ])) {
1745
-                $related_objects = $this->_model_relations[ $relation_name ];
1746
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1747
-                    // this relation only stores a single model object, not an array
1748
-                    // but let's make it consistent
1749
-                    $related_objects = [$related_objects];
1750
-                }
1751
-                foreach ($related_objects as $related_object) {
1752
-                    // only refresh their cache if they're in memory
1753
-                    if ($related_object instanceof EE_Base_Class) {
1754
-                        $related_object->clear_cache(
1755
-                            $model->get_this_model_name(),
1756
-                            $this
1757
-                        );
1758
-                    }
1759
-                }
1760
-            }
1761
-        }
1762
-    }
1763
-
1764
-
1765
-    /**
1766
-     *        Saves this object to the database. An array may be supplied to set some values on this
1767
-     * object just before saving.
1768
-     *
1769
-     * @access public
1770
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1771
-     *                                 if provided during the save() method (often client code will change the fields'
1772
-     *                                 values before calling save)
1773
-     * @return bool|int|string         1 on a successful update
1774
-     *                                 the ID of the new entry on insert
1775
-     *                                 0 on failure or if the model object isn't allowed to persist
1776
-     *                                 (as determined by EE_Base_Class::allow_persist())
1777
-     * @throws InvalidInterfaceException
1778
-     * @throws InvalidDataTypeException
1779
-     * @throws EE_Error
1780
-     * @throws InvalidArgumentException
1781
-     * @throws ReflectionException
1782
-     */
1783
-    public function save($set_cols_n_values = [])
1784
-    {
1785
-        $model = $this->get_model();
1786
-        /**
1787
-         * Filters the fields we're about to save on the model object
1788
-         *
1789
-         * @param array         $set_cols_n_values
1790
-         * @param EE_Base_Class $model_object
1791
-         */
1792
-        $set_cols_n_values = (array) apply_filters(
1793
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1794
-            $set_cols_n_values,
1795
-            $this
1796
-        );
1797
-        // set attributes as provided in $set_cols_n_values
1798
-        foreach ($set_cols_n_values as $column => $value) {
1799
-            $this->set($column, $value);
1800
-        }
1801
-        // no changes ? then don't do anything
1802
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1803
-            return 0;
1804
-        }
1805
-        /**
1806
-         * Saving a model object.
1807
-         * Before we perform a save, this action is fired.
1808
-         *
1809
-         * @param EE_Base_Class $model_object the model object about to be saved.
1810
-         */
1811
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1812
-        if (! $this->allow_persist()) {
1813
-            return 0;
1814
-        }
1815
-        // now get current attribute values
1816
-        $save_cols_n_values = $this->_fields;
1817
-        // if the object already has an ID, update it. Otherwise, insert it
1818
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1819
-        // They have been
1820
-        $old_assumption_concerning_value_preparation = $model
1821
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1822
-        $model->assume_values_already_prepared_by_model_object(true);
1823
-        // does this model have an autoincrement PK?
1824
-        if ($model->has_primary_key_field()) {
1825
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1826
-                // ok check if it's set, if so: update; if not, insert
1827
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1828
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1829
-                } else {
1830
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1831
-                    $results = $model->insert($save_cols_n_values);
1832
-                    if ($results) {
1833
-                        // if successful, set the primary key
1834
-                        // but don't use the normal SET method, because it will check if
1835
-                        // an item with the same ID exists in the mapper & db, then
1836
-                        // will find it in the db (because we just added it) and THAT object
1837
-                        // will get added to the mapper before we can add this one!
1838
-                        // but if we just avoid using the SET method, all that headache can be avoided
1839
-                        $pk_field_name                   = $model->primary_key_name();
1840
-                        $this->_fields[ $pk_field_name ] = $results;
1841
-                        $this->_clear_cached_property($pk_field_name);
1842
-                        $model->add_to_entity_map($this);
1843
-                        $this->_update_cached_related_model_objs_fks();
1844
-                    }
1845
-                }
1846
-            } else {// PK is NOT auto-increment
1847
-                // so check if one like it already exists in the db
1848
-                if ($model->exists_by_ID($this->ID())) {
1849
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1850
-                        throw new EE_Error(
1851
-                            sprintf(
1852
-                                esc_html__(
1853
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1854
-                                    'event_espresso'
1855
-                                ),
1856
-                                get_class($this),
1857
-                                get_class($model) . '::instance()->add_to_entity_map()',
1858
-                                get_class($model) . '::instance()->get_one_by_ID()',
1859
-                                '<br />'
1860
-                            )
1861
-                        );
1862
-                    }
1863
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1864
-                } else {
1865
-                    $results = $model->insert($save_cols_n_values);
1866
-                    $this->_update_cached_related_model_objs_fks();
1867
-                }
1868
-            }
1869
-        } else {// there is NO primary key
1870
-            $already_in_db = false;
1871
-            foreach ($model->unique_indexes() as $index) {
1872
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1873
-                if ($model->exists([$uniqueness_where_params])) {
1874
-                    $already_in_db = true;
1875
-                }
1876
-            }
1877
-            if ($already_in_db) {
1878
-                $combined_pk_fields_n_values = array_intersect_key(
1879
-                    $save_cols_n_values,
1880
-                    $model->get_combined_primary_key_fields()
1881
-                );
1882
-                $results                     = $model->update(
1883
-                    $save_cols_n_values,
1884
-                    $combined_pk_fields_n_values
1885
-                );
1886
-            } else {
1887
-                $results = $model->insert($save_cols_n_values);
1888
-            }
1889
-        }
1890
-        // restore the old assumption about values being prepared by the model object
1891
-        $model->assume_values_already_prepared_by_model_object(
1892
-            $old_assumption_concerning_value_preparation
1893
-        );
1894
-        /**
1895
-         * After saving the model object this action is called
1896
-         *
1897
-         * @param EE_Base_Class $model_object which was just saved
1898
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1899
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1900
-         */
1901
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1902
-        $this->_has_changes = false;
1903
-        return $results;
1904
-    }
1905
-
1906
-
1907
-    /**
1908
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1909
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1910
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1911
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1912
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1913
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1914
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1915
-     *
1916
-     * @return void
1917
-     * @throws ReflectionException
1918
-     * @throws InvalidArgumentException
1919
-     * @throws InvalidInterfaceException
1920
-     * @throws InvalidDataTypeException
1921
-     * @throws EE_Error
1922
-     */
1923
-    protected function _update_cached_related_model_objs_fks()
1924
-    {
1925
-        $model = $this->get_model();
1926
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1927
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1928
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1929
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1930
-                        $model->get_this_model_name()
1931
-                    );
1932
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1933
-                    if ($related_model_obj_in_cache->ID()) {
1934
-                        $related_model_obj_in_cache->save();
1935
-                    }
1936
-                }
1937
-            }
1938
-        }
1939
-    }
1940
-
1941
-
1942
-    /**
1943
-     * Saves this model object and its NEW cached relations to the database.
1944
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1945
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1946
-     * because otherwise, there's a potential for infinite looping of saving
1947
-     * Saves the cached related model objects, and ensures the relation between them
1948
-     * and this object and properly setup
1949
-     *
1950
-     * @return int ID of new model object on save; 0 on failure+
1951
-     * @throws ReflectionException
1952
-     * @throws InvalidArgumentException
1953
-     * @throws InvalidInterfaceException
1954
-     * @throws InvalidDataTypeException
1955
-     * @throws EE_Error
1956
-     */
1957
-    public function save_new_cached_related_model_objs()
1958
-    {
1959
-        // make sure this has been saved
1960
-        if (! $this->ID()) {
1961
-            $id = $this->save();
1962
-        } else {
1963
-            $id = $this->ID();
1964
-        }
1965
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1966
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1967
-            if ($this->_model_relations[ $relation_name ]) {
1968
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1969
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1970
-                /* @var $related_model_obj EE_Base_Class */
1971
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1972
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
1973
-                    // but ONLY if it DOES NOT exist in the DB
1974
-                    $related_model_obj = $this->_model_relations[ $relation_name ];
1975
-                    // if( ! $related_model_obj->ID()){
1976
-                    $this->_add_relation_to($related_model_obj, $relation_name);
1977
-                    $related_model_obj->save_new_cached_related_model_objs();
1978
-                    // }
1979
-                } else {
1980
-                    foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1981
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
1982
-                        // but ONLY if it DOES NOT exist in the DB
1983
-                        // if( ! $related_model_obj->ID()){
1984
-                        $this->_add_relation_to($related_model_obj, $relation_name);
1985
-                        $related_model_obj->save_new_cached_related_model_objs();
1986
-                        // }
1987
-                    }
1988
-                }
1989
-            }
1990
-        }
1991
-        return $id;
1992
-    }
1993
-
1994
-
1995
-    /**
1996
-     * for getting a model while instantiated.
1997
-     *
1998
-     * @return EEM_Base | EEM_CPT_Base
1999
-     * @throws ReflectionException
2000
-     * @throws InvalidArgumentException
2001
-     * @throws InvalidInterfaceException
2002
-     * @throws InvalidDataTypeException
2003
-     * @throws EE_Error
2004
-     */
2005
-    public function get_model()
2006
-    {
2007
-        if (! $this->_model) {
2008
-            $modelName    = self::_get_model_classname(get_class($this));
2009
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2010
-        } else {
2011
-            $this->_model->set_timezone($this->_timezone);
2012
-        }
2013
-        return $this->_model;
2014
-    }
2015
-
2016
-
2017
-    /**
2018
-     * @param $props_n_values
2019
-     * @param $classname
2020
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2021
-     * @throws ReflectionException
2022
-     * @throws InvalidArgumentException
2023
-     * @throws InvalidInterfaceException
2024
-     * @throws InvalidDataTypeException
2025
-     * @throws EE_Error
2026
-     */
2027
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2028
-    {
2029
-        // TODO: will not work for Term_Relationships because they have no PK!
2030
-        $primary_id_ref = self::_get_primary_key_name($classname);
2031
-        if (
2032
-            array_key_exists($primary_id_ref, $props_n_values)
2033
-            && ! empty($props_n_values[ $primary_id_ref ])
2034
-        ) {
2035
-            $id = $props_n_values[ $primary_id_ref ];
2036
-            return self::_get_model($classname)->get_from_entity_map($id);
2037
-        }
2038
-        return false;
2039
-    }
2040
-
2041
-
2042
-    /**
2043
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2044
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2045
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2046
-     * we return false.
2047
-     *
2048
-     * @param array  $props_n_values    incoming array of properties and their values
2049
-     * @param string $classname         the classname of the child class
2050
-     * @param null   $timezone
2051
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the
2052
-     *                                  date_format and the second value is the time format
2053
-     * @return mixed (EE_Base_Class|bool)
2054
-     * @throws InvalidArgumentException
2055
-     * @throws InvalidInterfaceException
2056
-     * @throws InvalidDataTypeException
2057
-     * @throws EE_Error
2058
-     * @throws ReflectionException
2059
-     */
2060
-    protected static function _check_for_object($props_n_values, $classname, $timezone = '', $date_formats = [])
2061
-    {
2062
-        $existing = null;
2063
-        $model    = self::_get_model($classname, $timezone);
2064
-        if ($model->has_primary_key_field()) {
2065
-            $primary_id_ref = self::_get_primary_key_name($classname);
2066
-            if (
2067
-                array_key_exists($primary_id_ref, $props_n_values)
2068
-                && ! empty($props_n_values[ $primary_id_ref ])
2069
-            ) {
2070
-                $existing = $model->get_one_by_ID(
2071
-                    $props_n_values[ $primary_id_ref ]
2072
-                );
2073
-            }
2074
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2075
-            // no primary key on this model, but there's still a matching item in the DB
2076
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2077
-                self::_get_model($classname, $timezone)
2078
-                    ->get_index_primary_key_string($props_n_values)
2079
-            );
2080
-        }
2081
-        if ($existing) {
2082
-            // set date formats if present before setting values
2083
-            if (! empty($date_formats) && is_array($date_formats)) {
2084
-                $existing->set_date_format($date_formats[0]);
2085
-                $existing->set_time_format($date_formats[1]);
2086
-            } else {
2087
-                // set default formats for date and time
2088
-                $existing->set_date_format(get_option('date_format'));
2089
-                $existing->set_time_format(get_option('time_format'));
2090
-            }
2091
-            foreach ($props_n_values as $property => $field_value) {
2092
-                $existing->set($property, $field_value);
2093
-            }
2094
-            return $existing;
2095
-        }
2096
-        return false;
2097
-    }
2098
-
2099
-
2100
-    /**
2101
-     * Gets the EEM_*_Model for this class
2102
-     *
2103
-     * @access public now, as this is more convenient
2104
-     * @param      $classname
2105
-     * @param null $timezone
2106
-     * @return EEM_Base
2107
-     * @throws InvalidArgumentException
2108
-     * @throws InvalidInterfaceException
2109
-     * @throws InvalidDataTypeException
2110
-     * @throws EE_Error
2111
-     * @throws ReflectionException
2112
-     */
2113
-    protected static function _get_model($classname, $timezone = '')
2114
-    {
2115
-        // find model for this class
2116
-        if (! $classname) {
2117
-            throw new EE_Error(
2118
-                sprintf(
2119
-                    esc_html__(
2120
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2121
-                        'event_espresso'
2122
-                    ),
2123
-                    $classname
2124
-                )
2125
-            );
2126
-        }
2127
-        $modelName = self::_get_model_classname($classname);
2128
-        return self::_get_model_instance_with_name($modelName, $timezone);
2129
-    }
2130
-
2131
-
2132
-    /**
2133
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2134
-     *
2135
-     * @param string $model_classname
2136
-     * @param null   $timezone
2137
-     * @return EEM_Base
2138
-     * @throws ReflectionException
2139
-     * @throws InvalidArgumentException
2140
-     * @throws InvalidInterfaceException
2141
-     * @throws InvalidDataTypeException
2142
-     * @throws EE_Error
2143
-     */
2144
-    protected static function _get_model_instance_with_name($model_classname, $timezone = '')
2145
-    {
2146
-        $model_classname = str_replace('EEM_', '', $model_classname);
2147
-        $model           = EE_Registry::instance()->load_model($model_classname);
2148
-        $model->set_timezone($timezone);
2149
-        return $model;
2150
-    }
2151
-
2152
-
2153
-    /**
2154
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2155
-     * Also works if a model class's classname is provided (eg EE_Registration).
2156
-     *
2157
-     * @param string|null $model_name
2158
-     * @return string like EEM_Attendee
2159
-     */
2160
-    private static function _get_model_classname($model_name = '')
2161
-    {
2162
-        return strpos((string) $model_name, 'EE_') === 0
2163
-            ? str_replace('EE_', 'EEM_', $model_name)
2164
-            : 'EEM_' . $model_name;
2165
-    }
2166
-
2167
-
2168
-    /**
2169
-     * returns the name of the primary key attribute
2170
-     *
2171
-     * @param null $classname
2172
-     * @return string
2173
-     * @throws InvalidArgumentException
2174
-     * @throws InvalidInterfaceException
2175
-     * @throws InvalidDataTypeException
2176
-     * @throws EE_Error
2177
-     * @throws ReflectionException
2178
-     */
2179
-    protected static function _get_primary_key_name($classname = null)
2180
-    {
2181
-        if (! $classname) {
2182
-            throw new EE_Error(
2183
-                sprintf(
2184
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2185
-                    $classname
2186
-                )
2187
-            );
2188
-        }
2189
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2190
-    }
2191
-
2192
-
2193
-    /**
2194
-     * Gets the value of the primary key.
2195
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2196
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2197
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2198
-     *
2199
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2200
-     * @throws ReflectionException
2201
-     * @throws InvalidArgumentException
2202
-     * @throws InvalidInterfaceException
2203
-     * @throws InvalidDataTypeException
2204
-     * @throws EE_Error
2205
-     */
2206
-    public function ID()
2207
-    {
2208
-        $model = $this->get_model();
2209
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2210
-        if ($model->has_primary_key_field()) {
2211
-            return $this->_fields[ $model->primary_key_name() ];
2212
-        }
2213
-        return $model->get_index_primary_key_string($this->_fields);
2214
-    }
2215
-
2216
-
2217
-    /**
2218
-     * @param EE_Base_Class|int|string $otherModelObjectOrID
2219
-     * @param string                   $relation_name
2220
-     * @return bool
2221
-     * @throws EE_Error
2222
-     * @throws ReflectionException
2223
-     * @since   5.0.0.p
2224
-     */
2225
-    public function hasRelation($otherModelObjectOrID, string $relation_name): bool
2226
-    {
2227
-        $other_model = self::_get_model_instance_with_name(
2228
-            self::_get_model_classname($relation_name),
2229
-            $this->_timezone
2230
-        );
2231
-        $primary_key = $other_model->primary_key_name();
2232
-        /** @var EE_Base_Class $otherModelObject */
2233
-        $otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relation_name);
2234
-        return $this->count_related($relation_name, [[$primary_key => $otherModelObject->ID()]]) > 0;
2235
-    }
2236
-
2237
-
2238
-    /**
2239
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2240
-     * model is related to a group of events, the $relation_name should be 'Event', and should be a key in the EE
2241
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2242
-     *
2243
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2244
-     * @param string $relation_name                    eg 'Events','Question',etc.
2245
-     *                                                 an attendee to a group, you also want to specify which role they
2246
-     *                                                 will have in that group. So you would use this parameter to
2247
-     *                                                 specify array('role-column-name'=>'role-id')
2248
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2249
-     *                                                 allow you to further constrict the relation to being added.
2250
-     *                                                 However, keep in mind that the columns (keys) given must match a
2251
-     *                                                 column on the JOIN table and currently only the HABTM models
2252
-     *                                                 accept these additional conditions.  Also remember that if an
2253
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2254
-     *                                                 NEW row is created in the join table.
2255
-     * @param null   $cache_id
2256
-     * @return EE_Base_Class the object the relation was added to
2257
-     * @throws ReflectionException
2258
-     * @throws InvalidArgumentException
2259
-     * @throws InvalidInterfaceException
2260
-     * @throws InvalidDataTypeException
2261
-     * @throws EE_Error
2262
-     */
2263
-    public function _add_relation_to(
2264
-        $otherObjectModelObjectOrID,
2265
-        $relation_name,
2266
-        $extra_join_model_fields_n_values = [],
2267
-        $cache_id = null
2268
-    ) {
2269
-        $model = $this->get_model();
2270
-        // if this thing exists in the DB, save the relation to the DB
2271
-        if ($this->ID()) {
2272
-            $otherObject = $model->add_relationship_to(
2273
-                $this,
2274
-                $otherObjectModelObjectOrID,
2275
-                $relation_name,
2276
-                $extra_join_model_fields_n_values
2277
-            );
2278
-            // clear cache so future get_many_related and get_first_related() return new results.
2279
-            $this->clear_cache($relation_name, $otherObject, true);
2280
-            if ($otherObject instanceof EE_Base_Class) {
2281
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2282
-            }
2283
-        } else {
2284
-            // this thing doesn't exist in the DB,  so just cache it
2285
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2286
-                throw new EE_Error(
2287
-                    sprintf(
2288
-                        esc_html__(
2289
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2290
-                            'event_espresso'
2291
-                        ),
2292
-                        $otherObjectModelObjectOrID,
2293
-                        get_class($this)
2294
-                    )
2295
-                );
2296
-            }
2297
-            $otherObject = $otherObjectModelObjectOrID;
2298
-            $this->cache($relation_name, $otherObjectModelObjectOrID, $cache_id);
2299
-        }
2300
-        if ($otherObject instanceof EE_Base_Class) {
2301
-            // fix the reciprocal relation too
2302
-            if ($otherObject->ID()) {
2303
-                // its saved so assumed relations exist in the DB, so we can just
2304
-                // clear the cache so future queries use the updated info in the DB
2305
-                $otherObject->clear_cache(
2306
-                    $model->get_this_model_name(),
2307
-                    null,
2308
-                    true
2309
-                );
2310
-            } else {
2311
-                // it's not saved, so it caches relations like this
2312
-                $otherObject->cache($model->get_this_model_name(), $this);
2313
-            }
2314
-        }
2315
-        return $otherObject;
2316
-    }
2317
-
2318
-
2319
-    /**
2320
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2321
-     * model is related to a group of events, the $relation_name should be 'Events', and should be a key in the EE
2322
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2323
-     * from the cache
2324
-     *
2325
-     * @param mixed  $otherObjectModelObjectOrID
2326
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2327
-     *                to the DB yet
2328
-     * @param string $relation_name
2329
-     * @param array  $where_query
2330
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2331
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2332
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2333
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2334
-     *                deleted.
2335
-     * @return EE_Base_Class the relation was removed from
2336
-     * @throws ReflectionException
2337
-     * @throws InvalidArgumentException
2338
-     * @throws InvalidInterfaceException
2339
-     * @throws InvalidDataTypeException
2340
-     * @throws EE_Error
2341
-     */
2342
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relation_name, $where_query = [])
2343
-    {
2344
-        if ($this->ID()) {
2345
-            // if this exists in the DB, save the relation change to the DB too
2346
-            $otherObject = $this->get_model()->remove_relationship_to(
2347
-                $this,
2348
-                $otherObjectModelObjectOrID,
2349
-                $relation_name,
2350
-                $where_query
2351
-            );
2352
-            $this->clear_cache(
2353
-                $relation_name,
2354
-                $otherObject
2355
-            );
2356
-        } else {
2357
-            // this doesn't exist in the DB, just remove it from the cache
2358
-            $otherObject = $this->clear_cache(
2359
-                $relation_name,
2360
-                $otherObjectModelObjectOrID
2361
-            );
2362
-        }
2363
-        if ($otherObject instanceof EE_Base_Class) {
2364
-            $otherObject->clear_cache(
2365
-                $this->get_model()->get_this_model_name(),
2366
-                $this
2367
-            );
2368
-        }
2369
-        return $otherObject;
2370
-    }
2371
-
2372
-
2373
-    /**
2374
-     * Removes ALL the related things for the $relation_name.
2375
-     *
2376
-     * @param string $relation_name
2377
-     * @param array  $where_query_params @see
2378
-     *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2379
-     * @return EE_Base_Class
2380
-     * @throws ReflectionException
2381
-     * @throws InvalidArgumentException
2382
-     * @throws InvalidInterfaceException
2383
-     * @throws InvalidDataTypeException
2384
-     * @throws EE_Error
2385
-     */
2386
-    public function _remove_relations($relation_name, $where_query_params = [])
2387
-    {
2388
-        if ($this->ID()) {
2389
-            // if this exists in the DB, save the relation change to the DB too
2390
-            $otherObjects = $this->get_model()->remove_relations(
2391
-                $this,
2392
-                $relation_name,
2393
-                $where_query_params
2394
-            );
2395
-            $this->clear_cache(
2396
-                $relation_name,
2397
-                null,
2398
-                true
2399
-            );
2400
-        } else {
2401
-            // this doesn't exist in the DB, just remove it from the cache
2402
-            $otherObjects = $this->clear_cache(
2403
-                $relation_name,
2404
-                null,
2405
-                true
2406
-            );
2407
-        }
2408
-        if (is_array($otherObjects)) {
2409
-            foreach ($otherObjects as $otherObject) {
2410
-                $otherObject->clear_cache(
2411
-                    $this->get_model()->get_this_model_name(),
2412
-                    $this
2413
-                );
2414
-            }
2415
-        }
2416
-        return $otherObjects;
2417
-    }
2418
-
2419
-
2420
-    /**
2421
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2422
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2423
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2424
-     * because we want to get even deleted items etc.
2425
-     *
2426
-     * @param string      $relation_name key in the model's _model_relations array
2427
-     * @param array|null  $query_params  @see
2428
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2429
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2430
-     *                              keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2431
-     *                              results if you want IDs
2432
-     * @throws ReflectionException
2433
-     * @throws InvalidArgumentException
2434
-     * @throws InvalidInterfaceException
2435
-     * @throws InvalidDataTypeException
2436
-     * @throws EE_Error
2437
-     */
2438
-    public function get_many_related($relation_name, $query_params = [])
2439
-    {
2440
-        if ($this->ID()) {
2441
-            // this exists in the DB, so get the related things from either the cache or the DB
2442
-            // if there are query parameters, forget about caching the related model objects.
2443
-            if ($query_params) {
2444
-                $related_model_objects = $this->get_model()->get_all_related(
2445
-                    $this,
2446
-                    $relation_name,
2447
-                    $query_params
2448
-                );
2449
-            } else {
2450
-                // did we already cache the result of this query?
2451
-                $cached_results = $this->get_all_from_cache($relation_name);
2452
-                if (! $cached_results) {
2453
-                    $related_model_objects = $this->get_model()->get_all_related(
2454
-                        $this,
2455
-                        $relation_name,
2456
-                        $query_params
2457
-                    );
2458
-                    // if no query parameters were passed, then we got all the related model objects
2459
-                    // for that relation. We can cache them then.
2460
-                    foreach ($related_model_objects as $related_model_object) {
2461
-                        $this->cache($relation_name, $related_model_object);
2462
-                    }
2463
-                } else {
2464
-                    $related_model_objects = $cached_results;
2465
-                }
2466
-            }
2467
-        } else {
2468
-            // this doesn't exist in the DB, so just get the related things from the cache
2469
-            $related_model_objects = $this->get_all_from_cache($relation_name);
2470
-        }
2471
-        return $related_model_objects;
2472
-    }
2473
-
2474
-
2475
-    /**
2476
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2477
-     * unless otherwise specified in the $query_params
2478
-     *
2479
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2480
-     * @param array  $query_params   @see
2481
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2482
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2483
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2484
-     *                               that by the setting $distinct to TRUE;
2485
-     * @return int
2486
-     * @throws ReflectionException
2487
-     * @throws InvalidArgumentException
2488
-     * @throws InvalidInterfaceException
2489
-     * @throws InvalidDataTypeException
2490
-     * @throws EE_Error
2491
-     */
2492
-    public function count_related($relation_name, $query_params = [], $field_to_count = null, $distinct = false)
2493
-    {
2494
-        return $this->get_model()->count_related(
2495
-            $this,
2496
-            $relation_name,
2497
-            $query_params,
2498
-            $field_to_count,
2499
-            $distinct
2500
-        );
2501
-    }
2502
-
2503
-
2504
-    /**
2505
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2506
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2507
-     *
2508
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2509
-     * @param array  $query_params  @see
2510
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2511
-     * @param string $field_to_sum  name of field to count by.
2512
-     *                              By default, uses primary key
2513
-     *                              (which doesn't make much sense, so you should probably change it)
2514
-     * @return int
2515
-     * @throws ReflectionException
2516
-     * @throws InvalidArgumentException
2517
-     * @throws InvalidInterfaceException
2518
-     * @throws InvalidDataTypeException
2519
-     * @throws EE_Error
2520
-     */
2521
-    public function sum_related($relation_name, $query_params = [], $field_to_sum = null)
2522
-    {
2523
-        return $this->get_model()->sum_related(
2524
-            $this,
2525
-            $relation_name,
2526
-            $query_params,
2527
-            $field_to_sum
2528
-        );
2529
-    }
2530
-
2531
-
2532
-    /**
2533
-     * Gets the first (ie, one) related model object of the specified type.
2534
-     *
2535
-     * @param string $relation_name key in the model's _model_relations array
2536
-     * @param array  $query_params  @see
2537
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2538
-     * @return EE_Base_Class (not an array, a single object)
2539
-     * @throws ReflectionException
2540
-     * @throws InvalidArgumentException
2541
-     * @throws InvalidInterfaceException
2542
-     * @throws InvalidDataTypeException
2543
-     * @throws EE_Error
2544
-     */
2545
-    public function get_first_related($relation_name, $query_params = [])
2546
-    {
2547
-        $model = $this->get_model();
2548
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2549
-            // if they've provided some query parameters, don't bother trying to cache the result
2550
-            // also make sure we're not caching the result of get_first_related
2551
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2552
-            if (
2553
-                $query_params
2554
-                || ! $model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation
2555
-            ) {
2556
-                $related_model_object = $model->get_first_related(
2557
-                    $this,
2558
-                    $relation_name,
2559
-                    $query_params
2560
-                );
2561
-            } else {
2562
-                // first, check if we've already cached the result of this query
2563
-                $cached_result = $this->get_one_from_cache($relation_name);
2564
-                if (! $cached_result) {
2565
-                    $related_model_object = $model->get_first_related(
2566
-                        $this,
2567
-                        $relation_name,
2568
-                        $query_params
2569
-                    );
2570
-                    $this->cache($relation_name, $related_model_object);
2571
-                } else {
2572
-                    $related_model_object = $cached_result;
2573
-                }
2574
-            }
2575
-        } else {
2576
-            $related_model_object = null;
2577
-            // this doesn't exist in the Db,
2578
-            // but maybe the relation is of type belongs to, and so the related thing might
2579
-            if ($model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation) {
2580
-                $related_model_object = $model->get_first_related(
2581
-                    $this,
2582
-                    $relation_name,
2583
-                    $query_params
2584
-                );
2585
-            }
2586
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2587
-            // just get what's cached on this object
2588
-            if (! $related_model_object) {
2589
-                $related_model_object = $this->get_one_from_cache($relation_name);
2590
-            }
2591
-        }
2592
-        return $related_model_object;
2593
-    }
2594
-
2595
-
2596
-    /**
2597
-     * Does a delete on all related objects of type $relation_name and removes
2598
-     * the current model object's relation to them. If they can't be deleted (because
2599
-     * of blocking related model objects) does nothing. If the related model objects are
2600
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2601
-     * If this model object doesn't exist yet in the DB, just removes its related things
2602
-     *
2603
-     * @param string $relation_name
2604
-     * @param array  $query_params @see
2605
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2606
-     * @return int how many deleted
2607
-     * @throws ReflectionException
2608
-     * @throws InvalidArgumentException
2609
-     * @throws InvalidInterfaceException
2610
-     * @throws InvalidDataTypeException
2611
-     * @throws EE_Error
2612
-     */
2613
-    public function delete_related($relation_name, $query_params = [])
2614
-    {
2615
-        if ($this->ID()) {
2616
-            $count = $this->get_model()->delete_related(
2617
-                $this,
2618
-                $relation_name,
2619
-                $query_params
2620
-            );
2621
-        } else {
2622
-            $count = count($this->get_all_from_cache($relation_name));
2623
-            $this->clear_cache($relation_name, null, true);
2624
-        }
2625
-        return $count;
2626
-    }
2627
-
2628
-
2629
-    /**
2630
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relation_name and removes
2631
-     * the current model object's relation to them. If they can't be deleted (because
2632
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2633
-     * If the related thing isn't a soft-deletable model object, this function is identical
2634
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2635
-     *
2636
-     * @param string $relation_name
2637
-     * @param array  $query_params @see
2638
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2639
-     * @return int how many deleted (including those soft deleted)
2640
-     * @throws ReflectionException
2641
-     * @throws InvalidArgumentException
2642
-     * @throws InvalidInterfaceException
2643
-     * @throws InvalidDataTypeException
2644
-     * @throws EE_Error
2645
-     */
2646
-    public function delete_related_permanently($relation_name, $query_params = [])
2647
-    {
2648
-        $count = $this->ID()
2649
-            ? $this->get_model()->delete_related_permanently(
2650
-                $this,
2651
-                $relation_name,
2652
-                $query_params
2653
-            )
2654
-            : count($this->get_all_from_cache($relation_name));
2655
-
2656
-        $this->clear_cache($relation_name, null, true);
2657
-        return $count;
2658
-    }
2659
-
2660
-
2661
-    /**
2662
-     * is_set
2663
-     * Just a simple utility function children can use for checking if property exists
2664
-     *
2665
-     * @access  public
2666
-     * @param string $field_name property to check
2667
-     * @return bool                              TRUE if existing,FALSE if not.
2668
-     */
2669
-    public function is_set($field_name)
2670
-    {
2671
-        return isset($this->_fields[ $field_name ]);
2672
-    }
2673
-
2674
-
2675
-    /**
2676
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2677
-     * EE_Error exception if they don't
2678
-     *
2679
-     * @param mixed (string|array) $properties properties to check
2680
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2681
-     * @throws EE_Error
2682
-     */
2683
-    protected function _property_exists($properties)
2684
-    {
2685
-        foreach ((array) $properties as $property_name) {
2686
-            // first make sure this property exists
2687
-            if (! $this->_fields[ $property_name ]) {
2688
-                throw new EE_Error(
2689
-                    sprintf(
2690
-                        esc_html__(
2691
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2692
-                            'event_espresso'
2693
-                        ),
2694
-                        $property_name
2695
-                    )
2696
-                );
2697
-            }
2698
-        }
2699
-        return true;
2700
-    }
2701
-
2702
-
2703
-    /**
2704
-     * This simply returns an array of model fields for this object
2705
-     *
2706
-     * @return array
2707
-     * @throws ReflectionException
2708
-     * @throws InvalidArgumentException
2709
-     * @throws InvalidInterfaceException
2710
-     * @throws InvalidDataTypeException
2711
-     * @throws EE_Error
2712
-     */
2713
-    public function model_field_array()
2714
-    {
2715
-        $fields     = $this->get_model()->field_settings(false);
2716
-        $properties = [];
2717
-        // remove prepended underscore
2718
-        foreach ($fields as $field_name => $settings) {
2719
-            $properties[ $field_name ] = $this->get($field_name);
2720
-        }
2721
-        return $properties;
2722
-    }
2723
-
2724
-
2725
-    /**
2726
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2727
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2728
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2729
-     * Instead of requiring a plugin to extend the EE_Base_Class
2730
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2731
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2732
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2733
-     * and accepts 2 arguments: the object on which the function was called,
2734
-     * and an array of the original arguments passed to the function.
2735
-     * Whatever their callback function returns will be returned by this function.
2736
-     * Example: in functions.php (or in a plugin):
2737
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2738
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2739
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2740
-     *          return $previousReturnValue.$returnString;
2741
-     *      }
2742
-     * require('EE_Answer.class.php');
2743
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2744
-     *      ->my_callback('monkeys',100);
2745
-     * // will output "you called my_callback! and passed args:monkeys,100"
2746
-     *
2747
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2748
-     * @param array  $args       array of original arguments passed to the function
2749
-     * @return mixed whatever the plugin which calls add_filter decides
2750
-     * @throws EE_Error
2751
-     */
2752
-    public function __call($methodName, $args)
2753
-    {
2754
-        $className = get_class($this);
2755
-        $tagName   = "FHEE__{$className}__{$methodName}";
2756
-        if (! has_filter($tagName)) {
2757
-            throw new EE_Error(
2758
-                sprintf(
2759
-                    esc_html__(
2760
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2761
-                        'event_espresso'
2762
-                    ),
2763
-                    $methodName,
2764
-                    $className,
2765
-                    $tagName
2766
-                )
2767
-            );
2768
-        }
2769
-        return apply_filters($tagName, null, $this, $args);
2770
-    }
2771
-
2772
-
2773
-    /**
2774
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2775
-     * A $previous_value can be specified in case there are many meta rows with the same key
2776
-     *
2777
-     * @param string $meta_key
2778
-     * @param mixed  $meta_value
2779
-     * @param mixed  $previous_value
2780
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2781
-     *                  NOTE: if the values haven't changed, returns 0
2782
-     * @throws InvalidArgumentException
2783
-     * @throws InvalidInterfaceException
2784
-     * @throws InvalidDataTypeException
2785
-     * @throws EE_Error
2786
-     * @throws ReflectionException
2787
-     */
2788
-    public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2789
-    {
2790
-        $query_params = [
2791
-            [
2792
-                'EXM_key'  => $meta_key,
2793
-                'OBJ_ID'   => $this->ID(),
2794
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2795
-            ],
2796
-        ];
2797
-        if ($previous_value !== null) {
2798
-            $query_params[0]['EXM_value'] = $meta_value;
2799
-        }
2800
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2801
-        if (! $existing_rows_like_that) {
2802
-            return $this->add_extra_meta($meta_key, $meta_value);
2803
-        }
2804
-        foreach ($existing_rows_like_that as $existing_row) {
2805
-            $existing_row->save(['EXM_value' => $meta_value]);
2806
-        }
2807
-        return count($existing_rows_like_that);
2808
-    }
2809
-
2810
-
2811
-    /**
2812
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2813
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2814
-     * extra meta row was entered, false if not
2815
-     *
2816
-     * @param string $meta_key
2817
-     * @param mixed  $meta_value
2818
-     * @param bool   $unique
2819
-     * @return bool
2820
-     * @throws InvalidArgumentException
2821
-     * @throws InvalidInterfaceException
2822
-     * @throws InvalidDataTypeException
2823
-     * @throws EE_Error
2824
-     * @throws ReflectionException
2825
-     */
2826
-    public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2827
-    {
2828
-        if ($unique) {
2829
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2830
-                [
2831
-                    [
2832
-                        'EXM_key'  => $meta_key,
2833
-                        'OBJ_ID'   => $this->ID(),
2834
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2835
-                    ],
2836
-                ]
2837
-            );
2838
-            if ($existing_extra_meta) {
2839
-                return false;
2840
-            }
2841
-        }
2842
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2843
-            [
2844
-                'EXM_key'   => $meta_key,
2845
-                'EXM_value' => $meta_value,
2846
-                'OBJ_ID'    => $this->ID(),
2847
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2848
-            ]
2849
-        );
2850
-        $new_extra_meta->save();
2851
-        return true;
2852
-    }
2853
-
2854
-
2855
-    /**
2856
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2857
-     * is specified, only deletes extra meta records with that value.
2858
-     *
2859
-     * @param string $meta_key
2860
-     * @param mixed  $meta_value
2861
-     * @return int|bool number of extra meta rows deleted
2862
-     * @throws InvalidArgumentException
2863
-     * @throws InvalidInterfaceException
2864
-     * @throws InvalidDataTypeException
2865
-     * @throws EE_Error
2866
-     * @throws ReflectionException
2867
-     */
2868
-    public function delete_extra_meta(string $meta_key, $meta_value = null)
2869
-    {
2870
-        $query_params = [
2871
-            [
2872
-                'EXM_key'  => $meta_key,
2873
-                'OBJ_ID'   => $this->ID(),
2874
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2875
-            ],
2876
-        ];
2877
-        if ($meta_value !== null) {
2878
-            $query_params[0]['EXM_value'] = $meta_value;
2879
-        }
2880
-        return EEM_Extra_Meta::instance()->delete($query_params);
2881
-    }
2882
-
2883
-
2884
-    /**
2885
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2886
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2887
-     * You can specify $default is case you haven't found the extra meta
2888
-     *
2889
-     * @param string     $meta_key
2890
-     * @param bool       $single
2891
-     * @param mixed      $default if we don't find anything, what should we return?
2892
-     * @param array|null $extra_where
2893
-     * @return mixed single value if $single; array if ! $single
2894
-     * @throws ReflectionException
2895
-     * @throws EE_Error
2896
-     */
2897
-    public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2898
-    {
2899
-        $query_params = [$extra_where + ['EXM_key' => $meta_key]];
2900
-        if ($single) {
2901
-            $result = $this->get_first_related('Extra_Meta', $query_params);
2902
-            if ($result instanceof EE_Extra_Meta) {
2903
-                return $result->value();
2904
-            }
2905
-        } else {
2906
-            $results = $this->get_many_related('Extra_Meta', $query_params);
2907
-            if ($results) {
2908
-                $values = [];
2909
-                foreach ($results as $result) {
2910
-                    if ($result instanceof EE_Extra_Meta) {
2911
-                        $values[ $result->ID() ] = $result->value();
2912
-                    }
2913
-                }
2914
-                return $values;
2915
-            }
2916
-        }
2917
-        // if nothing discovered yet return default.
2918
-        return apply_filters(
2919
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2920
-            $default,
2921
-            $meta_key,
2922
-            $single,
2923
-            $this
2924
-        );
2925
-    }
2926
-
2927
-
2928
-    /**
2929
-     * Returns a simple array of all the extra meta associated with this model object.
2930
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2931
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2932
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2933
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2934
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2935
-     * finally the extra meta's value as each sub-value. (eg
2936
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2937
-     *
2938
-     * @param bool $one_of_each_key
2939
-     * @return array
2940
-     * @throws ReflectionException
2941
-     * @throws InvalidArgumentException
2942
-     * @throws InvalidInterfaceException
2943
-     * @throws InvalidDataTypeException
2944
-     * @throws EE_Error
2945
-     */
2946
-    public function all_extra_meta_array(bool $one_of_each_key = true): array
2947
-    {
2948
-        $return_array = [];
2949
-        if ($one_of_each_key) {
2950
-            $extra_meta_objs = $this->get_many_related(
2951
-                'Extra_Meta',
2952
-                ['group_by' => 'EXM_key']
2953
-            );
2954
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2955
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2956
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2957
-                }
2958
-            }
2959
-        } else {
2960
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2961
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2962
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2963
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2964
-                        $return_array[ $extra_meta_obj->key() ] = [];
2965
-                    }
2966
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2967
-                }
2968
-            }
2969
-        }
2970
-        return $return_array;
2971
-    }
2972
-
2973
-
2974
-    /**
2975
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2976
-     *
2977
-     * @return string
2978
-     * @throws ReflectionException
2979
-     * @throws InvalidArgumentException
2980
-     * @throws InvalidInterfaceException
2981
-     * @throws InvalidDataTypeException
2982
-     * @throws EE_Error
2983
-     */
2984
-    public function name()
2985
-    {
2986
-        // find a field that's not a text field
2987
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2988
-        if ($field_we_can_use) {
2989
-            return $this->get($field_we_can_use->get_name());
2990
-        }
2991
-        $first_few_properties = $this->model_field_array();
2992
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
2993
-        $name_parts           = [];
2994
-        foreach ($first_few_properties as $name => $value) {
2995
-            $name_parts[] = "$name:$value";
2996
-        }
2997
-        return implode(',', $name_parts);
2998
-    }
2999
-
3000
-
3001
-    /**
3002
-     * in_entity_map
3003
-     * Checks if this model object has been proven to already be in the entity map
3004
-     *
3005
-     * @return boolean
3006
-     * @throws ReflectionException
3007
-     * @throws InvalidArgumentException
3008
-     * @throws InvalidInterfaceException
3009
-     * @throws InvalidDataTypeException
3010
-     * @throws EE_Error
3011
-     */
3012
-    public function in_entity_map()
3013
-    {
3014
-        // well, if we looked, did we find it in the entity map?
3015
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3016
-    }
3017
-
3018
-
3019
-    /**
3020
-     * refresh_from_db
3021
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3022
-     *
3023
-     * @throws ReflectionException
3024
-     * @throws InvalidArgumentException
3025
-     * @throws InvalidInterfaceException
3026
-     * @throws InvalidDataTypeException
3027
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3028
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3029
-     */
3030
-    public function refresh_from_db()
3031
-    {
3032
-        if ($this->ID() && $this->in_entity_map()) {
3033
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3034
-        } else {
3035
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3036
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3037
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3038
-            // absolutely nothing in it for this ID
3039
-            if (WP_DEBUG) {
3040
-                throw new EE_Error(
3041
-                    sprintf(
3042
-                        esc_html__(
3043
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3044
-                            'event_espresso'
3045
-                        ),
3046
-                        $this->ID(),
3047
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3048
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3049
-                    )
3050
-                );
3051
-            }
3052
-        }
3053
-    }
3054
-
3055
-
3056
-    /**
3057
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3058
-     *
3059
-     * @param EE_Model_Field_Base[] $fields
3060
-     * @param string                $new_value_sql
3061
-     *          example: 'column_name=123',
3062
-     *          or 'column_name=column_name+1',
3063
-     *          or 'column_name= CASE
3064
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3065
-     *          THEN `column_name` + 5
3066
-     *          ELSE `column_name`
3067
-     *          END'
3068
-     *          Also updates $field on this model object with the latest value from the database.
3069
-     * @return bool
3070
-     * @throws EE_Error
3071
-     * @throws InvalidArgumentException
3072
-     * @throws InvalidDataTypeException
3073
-     * @throws InvalidInterfaceException
3074
-     * @throws ReflectionException
3075
-     * @since 4.9.80.p
3076
-     */
3077
-    protected function updateFieldsInDB($fields, $new_value_sql)
3078
-    {
3079
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3080
-        // if it wasn't even there to start off.
3081
-        if (! $this->ID()) {
3082
-            $this->save();
3083
-        }
3084
-        global $wpdb;
3085
-        if (empty($fields)) {
3086
-            throw new InvalidArgumentException(
3087
-                esc_html__(
3088
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3089
-                    'event_espresso'
3090
-                )
3091
-            );
3092
-        }
3093
-        $first_field = reset($fields);
3094
-        $table_alias = $first_field->get_table_alias();
3095
-        foreach ($fields as $field) {
3096
-            if ($table_alias !== $field->get_table_alias()) {
3097
-                throw new InvalidArgumentException(
3098
-                    sprintf(
3099
-                        esc_html__(
3100
-                        // @codingStandardsIgnoreStart
3101
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3102
-                            // @codingStandardsIgnoreEnd
3103
-                            'event_espresso'
3104
-                        ),
3105
-                        $table_alias,
3106
-                        $field->get_table_alias()
3107
-                    )
3108
-                );
3109
-            }
3110
-        }
3111
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3112
-        $table_obj      = $this->get_model()->get_table_obj_by_alias($table_alias);
3113
-        $table_pk_value = $this->ID();
3114
-        $table_name     = $table_obj->get_table_name();
3115
-        if ($table_obj instanceof EE_Secondary_Table) {
3116
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3117
-        } else {
3118
-            $table_pk_field_name = $table_obj->get_pk_column();
3119
-        }
3120
-
3121
-        $query  =
3122
-            "UPDATE `{$table_name}`
19
+	/**
20
+	 * @var EEM_Base|null
21
+	 */
22
+	protected $_model = null;
23
+
24
+	/**
25
+	 * This is an array of the original properties and values provided during construction
26
+	 * of this model object. (keys are model field names, values are their values).
27
+	 * This list is important to remember so that when we are merging data from the db, we know
28
+	 * which values to override and which to not override.
29
+	 */
30
+	protected ?array $_props_n_values_provided_in_constructor = null;
31
+
32
+	/**
33
+	 * Timezone
34
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
35
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
36
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
37
+	 * access to it.
38
+	 */
39
+	protected string $_timezone = '';
40
+
41
+	/**
42
+	 * date format
43
+	 * pattern or format for displaying dates
44
+	 */
45
+	protected string $_dt_frmt = '';
46
+
47
+	/**
48
+	 * time format
49
+	 * pattern or format for displaying time
50
+	 */
51
+	protected string $_tm_frmt = '';
52
+
53
+	/**
54
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
55
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
56
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
+	 */
59
+	protected array $_cached_properties = [];
60
+
61
+	/**
62
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
63
+	 * single
64
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
65
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
66
+	 * all others have an array)
67
+	 */
68
+	protected array $_model_relations = [];
69
+
70
+	/**
71
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
72
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
73
+	 */
74
+	protected array $_fields = [];
75
+
76
+	/**
77
+	 * indicating whether or not this model object is intended to ever be saved
78
+	 * For example, we might create model objects intended to only be used for the duration
79
+	 * of this request and to be thrown away, and if they were accidentally saved
80
+	 * it would be a bug.
81
+	 */
82
+	protected bool $_allow_persist = true;
83
+
84
+	/**
85
+	 * indicating whether or not this model object's properties have changed since construction
86
+	 */
87
+	protected bool $_has_changes = false;
88
+
89
+	/**
90
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
91
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
92
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
93
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
94
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
95
+	 * array as:
96
+	 * array(
97
+	 *  'Registration_Count' => 24
98
+	 * );
99
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
100
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
101
+	 * info)
102
+	 */
103
+	protected array $custom_selection_results = [];
104
+
105
+
106
+	/**
107
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
108
+	 * play nice
109
+	 *
110
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
111
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
112
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
113
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
114
+	 *                                                         corresponding db model or not.
115
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
116
+	 *                                                         be in when instantiating a EE_Base_Class object.
117
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
118
+	 *                                                         value is the date_format and second value is the time
119
+	 *                                                         format.
120
+	 * @throws InvalidArgumentException
121
+	 * @throws InvalidInterfaceException
122
+	 * @throws InvalidDataTypeException
123
+	 * @throws EE_Error
124
+	 * @throws ReflectionException
125
+	 */
126
+	protected function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
127
+	{
128
+		$className = get_class($this);
129
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
130
+		$model        = $this->get_model();
131
+		$model_fields = $model->field_settings();
132
+		// ensure $fieldValues is an array
133
+		$fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
134
+		// verify client code has not passed any invalid field names
135
+		foreach ($fieldValues as $field_name => $field_value) {
136
+			if (! isset($model_fields[ $field_name ])) {
137
+				throw new EE_Error(
138
+					sprintf(
139
+						esc_html__(
140
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
141
+							'event_espresso'
142
+						),
143
+						$field_name,
144
+						get_class($this),
145
+						implode(', ', array_keys($model_fields))
146
+					)
147
+				);
148
+			}
149
+		}
150
+
151
+		$date_format     = null;
152
+		$time_format     = null;
153
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
154
+		if (! empty($date_formats) && is_array($date_formats)) {
155
+			[$date_format, $time_format] = $date_formats;
156
+		}
157
+		$this->set_date_format($date_format);
158
+		$this->set_time_format($time_format);
159
+		// if db model is instantiating
160
+		foreach ($model_fields as $fieldName => $field) {
161
+			if ($bydb) {
162
+				// client code has indicated these field values are from the database
163
+				$this->set_from_db(
164
+					$fieldName,
165
+					$fieldValues[ $fieldName ] ?? null
166
+				);
167
+			} else {
168
+				// we're constructing a brand new instance of the model object.
169
+				// Generally, this means we'll need to do more field validation
170
+				$this->set(
171
+					$fieldName,
172
+					$fieldValues[ $fieldName ] ?? null,
173
+					true
174
+				);
175
+			}
176
+		}
177
+		// remember what values were passed to this constructor
178
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
179
+		// remember in entity mapper
180
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
181
+			$model->add_to_entity_map($this);
182
+		}
183
+		// setup all the relations
184
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
185
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
186
+				$this->_model_relations[ $relation_name ] = null;
187
+			} else {
188
+				$this->_model_relations[ $relation_name ] = [];
189
+			}
190
+		}
191
+		/**
192
+		 * Action done at the end of each model object construction
193
+		 *
194
+		 * @param EE_Base_Class $this the model object just created
195
+		 */
196
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
197
+	}
198
+
199
+
200
+	/**
201
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
202
+	 *
203
+	 * @return boolean
204
+	 */
205
+	public function allow_persist()
206
+	{
207
+		return $this->_allow_persist;
208
+	}
209
+
210
+
211
+	/**
212
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
213
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
214
+	 * you got new information that somehow made you change your mind.
215
+	 *
216
+	 * @param boolean $allow_persist
217
+	 * @return boolean
218
+	 */
219
+	public function set_allow_persist($allow_persist)
220
+	{
221
+		return $this->_allow_persist = $allow_persist;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Gets the field's original value when this object was constructed during this request.
227
+	 * This can be helpful when determining if a model object has changed or not
228
+	 *
229
+	 * @param string $field_name
230
+	 * @return mixed|null
231
+	 * @throws ReflectionException
232
+	 * @throws InvalidArgumentException
233
+	 * @throws InvalidInterfaceException
234
+	 * @throws InvalidDataTypeException
235
+	 * @throws EE_Error
236
+	 */
237
+	public function get_original($field_name)
238
+	{
239
+		if (
240
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
241
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
242
+		) {
243
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
244
+		}
245
+		return null;
246
+	}
247
+
248
+
249
+	/**
250
+	 * @param EE_Base_Class $obj
251
+	 * @return string
252
+	 */
253
+	public function get_class($obj)
254
+	{
255
+		return get_class($obj);
256
+	}
257
+
258
+
259
+	/**
260
+	 * Overrides parent because parent expects old models.
261
+	 * This also doesn't do any validation, and won't work for serialized arrays
262
+	 *
263
+	 * @param string $field_name
264
+	 * @param mixed  $field_value
265
+	 * @param bool   $use_default
266
+	 * @throws InvalidArgumentException
267
+	 * @throws InvalidInterfaceException
268
+	 * @throws InvalidDataTypeException
269
+	 * @throws EE_Error
270
+	 * @throws ReflectionException
271
+	 * @throws Exception
272
+	 */
273
+	public function set(string $field_name, $field_value, bool $use_default = false)
274
+	{
275
+		// if not using default and nothing has changed, and object has already been setup (has ID),
276
+		// then don't do anything
277
+		if (
278
+			! $use_default
279
+			&& $this->_fields[ $field_name ] === $field_value
280
+			&& $this->ID()
281
+		) {
282
+			return;
283
+		}
284
+		$model              = $this->get_model();
285
+		$this->_has_changes = true;
286
+		$field_obj          = $model->field_settings_for($field_name);
287
+		if (! $field_obj instanceof EE_Model_Field_Base) {
288
+			throw new EE_Error(
289
+				sprintf(
290
+					esc_html__(
291
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
292
+						'event_espresso'
293
+					),
294
+					$field_name
295
+				)
296
+			);
297
+		}
298
+		// if ( method_exists( $field_obj, 'set_timezone' )) {
299
+		if ($field_obj instanceof EE_Datetime_Field) {
300
+			$field_obj->set_timezone($this->_timezone);
301
+			$field_obj->set_date_format($this->_dt_frmt);
302
+			$field_obj->set_time_format($this->_tm_frmt);
303
+		}
304
+
305
+		// should the value be null?
306
+		$value = $field_value === null && ($use_default || ! $field_obj->is_nullable())
307
+			? $field_obj->get_default_value()
308
+			: $field_value;
309
+
310
+		$this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
311
+
312
+		// if we're not in the constructor...
313
+		// now check if what we set was a primary key
314
+		if (
315
+			// note: props_n_values_provided_in_constructor is only set at the END of the constructor
316
+			$this->_props_n_values_provided_in_constructor
317
+			&& $field_value
318
+			&& $field_name === $model->primary_key_name()
319
+		) {
320
+			// if so, we want all this object's fields to be filled either with
321
+			// what we've explicitly set on this model
322
+			// or what we have in the db
323
+			// echo "setting primary key!";
324
+			$fields_on_model = self::_get_model(get_class($this))->field_settings();
325
+			$obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
326
+			foreach ($fields_on_model as $field_obj) {
327
+				if (
328
+					! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
329
+					&& $field_obj->get_name() !== $field_name
330
+				) {
331
+					$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
332
+				}
333
+			}
334
+			// oh this model object has an ID? well make sure its in the entity mapper
335
+			$model->add_to_entity_map($this);
336
+		}
337
+		// let's unset any cache for this field_name from the $_cached_properties property.
338
+		$this->_clear_cached_property($field_name);
339
+	}
340
+
341
+
342
+	/**
343
+	 * Overrides parent because parent expects old models.
344
+	 * This also doesn't do any validation, and won't work for serialized arrays
345
+	 *
346
+	 * @param string $field_name
347
+	 * @param mixed  $field_value_from_db
348
+	 * @throws ReflectionException
349
+	 * @throws InvalidArgumentException
350
+	 * @throws InvalidInterfaceException
351
+	 * @throws InvalidDataTypeException
352
+	 * @throws EE_Error
353
+	 */
354
+	public function set_from_db(string $field_name, $field_value_from_db)
355
+	{
356
+		$field_obj = $this->get_model()->field_settings_for($field_name);
357
+		if ($field_obj instanceof EE_Model_Field_Base) {
358
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
359
+			// eg, a CPT model object could have an entry in the posts table, but no
360
+			// entry in the meta table. Meaning that all its columns in the meta table
361
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
362
+			if ($field_value_from_db === null) {
363
+				if ($field_obj->is_nullable()) {
364
+					// if the field allows nulls, then let it be null
365
+					$field_value = null;
366
+				} else {
367
+					$field_value = $field_obj->get_default_value();
368
+				}
369
+			} else {
370
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
371
+			}
372
+			$this->_fields[ $field_name ] = $field_value;
373
+			$this->_clear_cached_property($field_name);
374
+		}
375
+	}
376
+
377
+
378
+	/**
379
+	 * Set custom select values for model.
380
+	 *
381
+	 * @param array $custom_select_values
382
+	 */
383
+	public function setCustomSelectsValues(array $custom_select_values)
384
+	{
385
+		$this->custom_selection_results = $custom_select_values;
386
+	}
387
+
388
+
389
+	/**
390
+	 * Returns the custom select value for the provided alias if its set.
391
+	 * If not set, returns null.
392
+	 *
393
+	 * @param string $alias
394
+	 * @return string|int|float|null
395
+	 */
396
+	public function getCustomSelect($alias)
397
+	{
398
+		return $this->custom_selection_results[ $alias ] ?? null;
399
+	}
400
+
401
+
402
+	/**
403
+	 * This sets the field value on the db column if it exists for the given $column_name or
404
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
405
+	 *
406
+	 * @param string $field_name  Must be the exact column name.
407
+	 * @param mixed  $field_value The value to set.
408
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
409
+	 * @throws InvalidArgumentException
410
+	 * @throws InvalidInterfaceException
411
+	 * @throws InvalidDataTypeException
412
+	 * @throws EE_Error
413
+	 * @throws ReflectionException
414
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
415
+	 */
416
+	public function set_field_or_extra_meta($field_name, $field_value)
417
+	{
418
+		if ($this->get_model()->has_field($field_name)) {
419
+			$this->set($field_name, $field_value);
420
+			return true;
421
+		}
422
+		// ensure this object is saved first so that extra meta can be properly related.
423
+		$this->save();
424
+		return $this->update_extra_meta($field_name, $field_value);
425
+	}
426
+
427
+
428
+	/**
429
+	 * This retrieves the value of the db column set on this class or if that's not present
430
+	 * it will attempt to retrieve from extra_meta if found.
431
+	 * Example Usage:
432
+	 * Via EE_Message child class:
433
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
434
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
435
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
436
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
437
+	 * value for those extra fields dynamically via the EE_message object.
438
+	 *
439
+	 * @param string $field_name expecting the fully qualified field name.
440
+	 * @return mixed|null  value for the field if found.  null if not found.
441
+	 * @throws ReflectionException
442
+	 * @throws InvalidArgumentException
443
+	 * @throws InvalidInterfaceException
444
+	 * @throws InvalidDataTypeException
445
+	 * @throws EE_Error
446
+	 */
447
+	public function get_field_or_extra_meta($field_name)
448
+	{
449
+		if ($this->get_model()->has_field($field_name)) {
450
+			$column_value = $this->get($field_name);
451
+		} else {
452
+			// This isn't a column in the main table, let's see if it is in the extra meta.
453
+			$column_value = $this->get_extra_meta($field_name, true, null);
454
+		}
455
+		return $column_value;
456
+	}
457
+
458
+
459
+	/**
460
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
461
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
462
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
463
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
464
+	 *
465
+	 * @access public
466
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
467
+	 * @return void
468
+	 * @throws InvalidArgumentException
469
+	 * @throws InvalidInterfaceException
470
+	 * @throws InvalidDataTypeException
471
+	 * @throws EE_Error
472
+	 * @throws ReflectionException
473
+	 * @throws Exception
474
+	 */
475
+	public function set_timezone($timezone = '')
476
+	{
477
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
478
+		// make sure we clear all cached properties because they won't be relevant now
479
+		$this->_clear_cached_properties();
480
+		// make sure we update field settings and the date for all EE_Datetime_Fields
481
+		$model_fields = $this->get_model()->field_settings(false);
482
+		foreach ($model_fields as $field_name => $field_obj) {
483
+			if ($field_obj instanceof EE_Datetime_Field) {
484
+				$field_obj->set_timezone($this->_timezone);
485
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
486
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
487
+				}
488
+			}
489
+		}
490
+	}
491
+
492
+
493
+	/**
494
+	 * This just returns whatever is set for the current timezone.
495
+	 *
496
+	 * @access public
497
+	 * @return string timezone string
498
+	 */
499
+	public function get_timezone()
500
+	{
501
+		return $this->_timezone;
502
+	}
503
+
504
+
505
+	/**
506
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
507
+	 * internally instead of wp set date format options
508
+	 *
509
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
510
+	 * @since 4.6
511
+	 */
512
+	public function set_date_format(?string $format)
513
+	{
514
+		$this->_dt_frmt = new DateFormat($format);
515
+		// clear cached_properties because they won't be relevant now.
516
+		$this->_clear_cached_properties();
517
+	}
518
+
519
+
520
+	/**
521
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
522
+	 * class internally instead of wp set time format options.
523
+	 *
524
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
525
+	 * @since 4.6
526
+	 */
527
+	public function set_time_format(?string $format)
528
+	{
529
+		$this->_tm_frmt = new TimeFormat($format);
530
+		// clear cached_properties because they won't be relevant now.
531
+		$this->_clear_cached_properties();
532
+	}
533
+
534
+
535
+	/**
536
+	 * This returns the current internal set format for the date and time formats.
537
+	 *
538
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
539
+	 *                             where the first value is the date format and the second value is the time format.
540
+	 * @return string|array
541
+	 */
542
+	public function get_format($full = true)
543
+	{
544
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
545
+	}
546
+
547
+
548
+	/**
549
+	 * cache
550
+	 * stores the passed model object on the current model object.
551
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
552
+	 *
553
+	 * @param string        $relation_name   one of the keys in the _model_relations array on the model. Eg
554
+	 *                                       'Registration' associated with this model object
555
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
556
+	 *                                       that could be a payment or a registration)
557
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
558
+	 *                                       items which will be stored in an array on this object
559
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
560
+	 *                                       related thing, no array)
561
+	 * @throws InvalidArgumentException
562
+	 * @throws InvalidInterfaceException
563
+	 * @throws InvalidDataTypeException
564
+	 * @throws EE_Error
565
+	 * @throws ReflectionException
566
+	 */
567
+	public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
568
+	{
569
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
570
+		if (! $object_to_cache instanceof EE_Base_Class) {
571
+			return false;
572
+		}
573
+		// also get "how" the object is related, or throw an error
574
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
575
+			throw new EE_Error(
576
+				sprintf(
577
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
578
+					$relation_name,
579
+					get_class($this)
580
+				)
581
+			);
582
+		}
583
+		// how many things are related ?
584
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
585
+			// if it's a "belongs to" relationship, then there's only one related model object
586
+			// eg, if this is a registration, there's only 1 attendee for it
587
+			// so for these model objects just set it to be cached
588
+			$this->_model_relations[ $relation_name ] = $object_to_cache;
589
+			$return                                   = true;
590
+		} else {
591
+			// otherwise, this is the "many" side of a one to many relationship,
592
+			// so we'll add the object to the array of related objects for that type.
593
+			// eg: if this is an event, there are many registrations for that event,
594
+			// so we cache the registrations in an array
595
+			if (! is_array($this->_model_relations[ $relation_name ])) {
596
+				// if for some reason, the cached item is a model object,
597
+				// then stick that in the array, otherwise start with an empty array
598
+				$this->_model_relations[ $relation_name ] =
599
+					$this->_model_relations[ $relation_name ] instanceof EE_Base_Class
600
+						? [$this->_model_relations[ $relation_name ]]
601
+						: [];
602
+			}
603
+			// first check for a cache_id which is normally empty
604
+			if (! empty($cache_id)) {
605
+				// if the cache_id exists, then it means we are purposely trying to cache this
606
+				// with a known key that can then be used to retrieve the object later on
607
+				$this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
608
+				$return                                                = $cache_id;
609
+			} elseif ($object_to_cache->ID()) {
610
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
611
+				$this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
612
+				$return                                                             = $object_to_cache->ID();
613
+			} else {
614
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
615
+				$this->_model_relations[ $relation_name ][] = $object_to_cache;
616
+				// move the internal pointer to the end of the array
617
+				end($this->_model_relations[ $relation_name ]);
618
+				// and grab the key so that we can return it
619
+				$return = key($this->_model_relations[ $relation_name ]);
620
+			}
621
+		}
622
+		return $return;
623
+	}
624
+
625
+
626
+	/**
627
+	 * For adding an item to the cached_properties property.
628
+	 *
629
+	 * @access protected
630
+	 * @param string      $fieldname the property item the corresponding value is for.
631
+	 * @param mixed       $value     The value we are caching.
632
+	 * @param string|null $cache_type
633
+	 * @return void
634
+	 * @throws ReflectionException
635
+	 * @throws InvalidArgumentException
636
+	 * @throws InvalidInterfaceException
637
+	 * @throws InvalidDataTypeException
638
+	 * @throws EE_Error
639
+	 */
640
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
641
+	{
642
+		// first make sure this property exists
643
+		$this->get_model()->field_settings_for($fieldname);
644
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
645
+
646
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
647
+	}
648
+
649
+
650
+	/**
651
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
652
+	 * This also SETS the cache if we return the actual property!
653
+	 *
654
+	 * @param string $fieldname        the name of the property we're trying to retrieve
655
+	 * @param bool   $pretty
656
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
657
+	 *                                 (in cases where the same property may be used for different outputs
658
+	 *                                 - i.e. datetime, money etc.)
659
+	 *                                 It can also accept certain pre-defined "schema" strings
660
+	 *                                 to define how to output the property.
661
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
662
+	 * @return mixed                   whatever the value for the property is we're retrieving
663
+	 * @throws ReflectionException
664
+	 * @throws InvalidArgumentException
665
+	 * @throws InvalidInterfaceException
666
+	 * @throws InvalidDataTypeException
667
+	 * @throws EE_Error
668
+	 */
669
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
670
+	{
671
+		// verify the field exists
672
+		$model = $this->get_model();
673
+		$model->field_settings_for($fieldname);
674
+		$cache_type = $pretty ? 'pretty' : 'standard';
675
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
676
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
677
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
678
+		}
679
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
680
+		$this->_set_cached_property($fieldname, $value, $cache_type);
681
+		return $value;
682
+	}
683
+
684
+
685
+	/**
686
+	 * If the cache didn't fetch the needed item, this fetches it.
687
+	 *
688
+	 * @param string $fieldname
689
+	 * @param bool   $pretty
690
+	 * @param string $extra_cache_ref
691
+	 * @return mixed
692
+	 * @throws InvalidArgumentException
693
+	 * @throws InvalidInterfaceException
694
+	 * @throws InvalidDataTypeException
695
+	 * @throws EE_Error
696
+	 * @throws ReflectionException
697
+	 */
698
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
699
+	{
700
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
701
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
702
+		if ($field_obj instanceof EE_Datetime_Field) {
703
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
704
+		}
705
+		if (! isset($this->_fields[ $fieldname ])) {
706
+			$this->_fields[ $fieldname ] = null;
707
+		}
708
+		return $pretty
709
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
710
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
711
+	}
712
+
713
+
714
+	/**
715
+	 * set timezone, formats, and output for EE_Datetime_Field objects
716
+	 *
717
+	 * @param EE_Datetime_Field $datetime_field
718
+	 * @param bool              $pretty
719
+	 * @param null              $date_or_time
720
+	 * @return void
721
+	 * @throws InvalidArgumentException
722
+	 * @throws InvalidInterfaceException
723
+	 * @throws InvalidDataTypeException
724
+	 */
725
+	protected function _prepare_datetime_field(
726
+		EE_Datetime_Field $datetime_field,
727
+		$pretty = false,
728
+		$date_or_time = null
729
+	) {
730
+		$datetime_field->set_timezone($this->_timezone);
731
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
732
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
733
+		// set the output returned
734
+		switch ($date_or_time) {
735
+			case 'D':
736
+				$datetime_field->set_date_time_output('date');
737
+				break;
738
+			case 'T':
739
+				$datetime_field->set_date_time_output('time');
740
+				break;
741
+			default:
742
+				$datetime_field->set_date_time_output();
743
+		}
744
+	}
745
+
746
+
747
+	/**
748
+	 * This just takes care of clearing out the cached_properties
749
+	 *
750
+	 * @return void
751
+	 */
752
+	protected function _clear_cached_properties()
753
+	{
754
+		$this->_cached_properties = [];
755
+	}
756
+
757
+
758
+	/**
759
+	 * This just clears out ONE property if it exists in the cache
760
+	 *
761
+	 * @param string $property_name the property to remove if it exists (from the _cached_properties array)
762
+	 * @return void
763
+	 */
764
+	protected function _clear_cached_property($property_name)
765
+	{
766
+		if (isset($this->_cached_properties[ $property_name ])) {
767
+			unset($this->_cached_properties[ $property_name ]);
768
+		}
769
+	}
770
+
771
+
772
+	/**
773
+	 * Ensures that this related thing is a model object.
774
+	 *
775
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
776
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
777
+	 * @return EE_Base_Class
778
+	 * @throws ReflectionException
779
+	 * @throws InvalidArgumentException
780
+	 * @throws InvalidInterfaceException
781
+	 * @throws InvalidDataTypeException
782
+	 * @throws EE_Error
783
+	 */
784
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
785
+	{
786
+		$other_model_instance = self::_get_model_instance_with_name(
787
+			self::_get_model_classname($model_name),
788
+			$this->_timezone
789
+		);
790
+		return $other_model_instance->ensure_is_obj($object_or_id);
791
+	}
792
+
793
+
794
+	/**
795
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
796
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
797
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
798
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
799
+	 *
800
+	 * @param string $relation_name                        one of the keys in the _model_relations array on the model.
801
+	 *                                                     Eg 'Registration'
802
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
803
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
804
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
805
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
806
+	 *                                                     this is HasMany or HABTM.
807
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
808
+	 *                                                     relation from all
809
+	 * @throws InvalidArgumentException
810
+	 * @throws InvalidInterfaceException
811
+	 * @throws InvalidDataTypeException
812
+	 * @throws EE_Error
813
+	 * @throws ReflectionException
814
+	 */
815
+	public function clear_cache($relation_name, $object_to_remove_or_index_into_array = null, $clear_all = false)
816
+	{
817
+		$relationship_to_model = $this->get_model()->related_settings_for($relation_name);
818
+		$index_in_cache        = '';
819
+		if (! $relationship_to_model) {
820
+			throw new EE_Error(
821
+				sprintf(
822
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
823
+					$relation_name,
824
+					get_class($this)
825
+				)
826
+			);
827
+		}
828
+		if ($clear_all) {
829
+			$obj_removed                              = true;
830
+			$this->_model_relations[ $relation_name ] = null;
831
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
+			$obj_removed                              = $this->_model_relations[ $relation_name ];
833
+			$this->_model_relations[ $relation_name ] = null;
834
+		} else {
835
+			if (
836
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
837
+				&& $object_to_remove_or_index_into_array->ID()
838
+			) {
839
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
840
+				if (
841
+					is_array($this->_model_relations[ $relation_name ])
842
+					&& ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
843
+				) {
844
+					$index_found_at = null;
845
+					// find this object in the array even though it has a different key
846
+					foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
847
+						/** @noinspection TypeUnsafeComparisonInspection */
848
+						if (
849
+							$obj instanceof EE_Base_Class
850
+							&& (
851
+								$obj == $object_to_remove_or_index_into_array
852
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
853
+							)
854
+						) {
855
+							$index_found_at = $index;
856
+							break;
857
+						}
858
+					}
859
+					if ($index_found_at) {
860
+						$index_in_cache = $index_found_at;
861
+					} else {
862
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
863
+						// if it wasn't in it to begin with. So we're done
864
+						return $object_to_remove_or_index_into_array;
865
+					}
866
+				}
867
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
868
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
869
+				foreach ($this->get_all_from_cache($relation_name) as $index => $potentially_obj_we_want) {
870
+					/** @noinspection TypeUnsafeComparisonInspection */
871
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
872
+						$index_in_cache = $index;
873
+					}
874
+				}
875
+			} else {
876
+				$index_in_cache = $object_to_remove_or_index_into_array;
877
+			}
878
+			// supposedly we've found it. But it could just be that the client code
879
+			// provided a bad index/object
880
+			if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
881
+				$obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
882
+				unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
883
+			} else {
884
+				// that thing was never cached anyways.
885
+				$obj_removed = null;
886
+			}
887
+		}
888
+		return $obj_removed;
889
+	}
890
+
891
+
892
+	/**
893
+	 * update_cache_after_object_save
894
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
895
+	 * obtained after being saved to the db
896
+	 *
897
+	 * @param string        $relation_name      - the type of object that is cached
898
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
899
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
900
+	 * @return boolean TRUE on success, FALSE on fail
901
+	 * @throws ReflectionException
902
+	 * @throws InvalidArgumentException
903
+	 * @throws InvalidInterfaceException
904
+	 * @throws InvalidDataTypeException
905
+	 * @throws EE_Error
906
+	 */
907
+	public function update_cache_after_object_save(
908
+		$relation_name,
909
+		EE_Base_Class $newly_saved_object,
910
+		$current_cache_id = ''
911
+	) {
912
+		// verify that incoming object is of the correct type
913
+		$obj_class = 'EE_' . $relation_name;
914
+		if ($newly_saved_object instanceof $obj_class) {
915
+			/* @type EE_Base_Class $newly_saved_object */
916
+			// now get the type of relation
917
+			$relationship_to_model = $this->get_model()->related_settings_for($relation_name);
918
+			// if this is a 1:1 relationship
919
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
920
+				// then just replace the cached object with the newly saved object
921
+				$this->_model_relations[ $relation_name ] = $newly_saved_object;
922
+				return true;
923
+				// or if it's some kind of sordid feral polyamorous relationship...
924
+			}
925
+			if (
926
+				is_array($this->_model_relations[ $relation_name ])
927
+				&& isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
928
+			) {
929
+				// then remove the current cached item
930
+				unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
931
+				// and cache the newly saved object using it's new ID
932
+				$this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
933
+				return true;
934
+			}
935
+		}
936
+		return false;
937
+	}
938
+
939
+
940
+	/**
941
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
942
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
943
+	 *
944
+	 * @param string $relation_name
945
+	 * @return EE_Base_Class
946
+	 */
947
+	public function get_one_from_cache($relation_name)
948
+	{
949
+		$cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
950
+		if (is_array($cached_array_or_object)) {
951
+			return array_shift($cached_array_or_object);
952
+		}
953
+		return $cached_array_or_object;
954
+	}
955
+
956
+
957
+	/**
958
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
959
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
960
+	 *
961
+	 * @param string $relation_name
962
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
963
+	 * @throws InvalidArgumentException
964
+	 * @throws InvalidInterfaceException
965
+	 * @throws InvalidDataTypeException
966
+	 * @throws EE_Error
967
+	 * @throws ReflectionException
968
+	 */
969
+	public function get_all_from_cache($relation_name)
970
+	{
971
+		$objects = $this->_model_relations[ $relation_name ] ?? [];
972
+		// if the result is not an array, but exists, make it an array
973
+		$objects = is_array($objects)
974
+			? $objects
975
+			: [$objects];
976
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
977
+		// basically, if this model object was stored in the session, and these cached model objects
978
+		// already have IDs, let's make sure they're in their model's entity mapper
979
+		// otherwise we will have duplicates next time we call
980
+		// EE_Registry::instance()->load_model( $relation_name )->get_one_by_ID( $result->ID() );
981
+		$model = EE_Registry::instance()->load_model($relation_name);
982
+		foreach ($objects as $model_object) {
983
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
984
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
985
+				if ($model_object->ID()) {
986
+					$model->add_to_entity_map($model_object);
987
+				}
988
+			} else {
989
+				throw new EE_Error(
990
+					sprintf(
991
+						esc_html__(
992
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
993
+							'event_espresso'
994
+						),
995
+						$relation_name,
996
+						gettype($model_object)
997
+					)
998
+				);
999
+			}
1000
+		}
1001
+		return $objects;
1002
+	}
1003
+
1004
+
1005
+	/**
1006
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1007
+	 * matching the given query conditions.
1008
+	 *
1009
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1010
+	 * @param int   $limit              How many objects to return.
1011
+	 * @param array $query_params       Any additional conditions on the query.
1012
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1013
+	 *                                  you can indicate just the columns you want returned
1014
+	 * @return array|EE_Base_Class[]
1015
+	 * @throws ReflectionException
1016
+	 * @throws InvalidArgumentException
1017
+	 * @throws InvalidInterfaceException
1018
+	 * @throws InvalidDataTypeException
1019
+	 * @throws EE_Error
1020
+	 */
1021
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = [], $columns_to_select = null)
1022
+	{
1023
+		$model         = $this->get_model();
1024
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1025
+			? $model->get_primary_key_field()->get_name()
1026
+			: $field_to_order_by;
1027
+		$current_value = ! empty($field)
1028
+			? $this->get($field)
1029
+			: null;
1030
+		if (empty($field) || empty($current_value)) {
1031
+			return [];
1032
+		}
1033
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1039
+	 * matching the given query conditions.
1040
+	 *
1041
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1042
+	 * @param int   $limit              How many objects to return.
1043
+	 * @param array $query_params       Any additional conditions on the query.
1044
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1045
+	 *                                  you can indicate just the columns you want returned
1046
+	 * @return array|EE_Base_Class[]
1047
+	 * @throws ReflectionException
1048
+	 * @throws InvalidArgumentException
1049
+	 * @throws InvalidInterfaceException
1050
+	 * @throws InvalidDataTypeException
1051
+	 * @throws EE_Error
1052
+	 */
1053
+	public function previous_x(
1054
+		$field_to_order_by = null,
1055
+		$limit = 1,
1056
+		$query_params = [],
1057
+		$columns_to_select = null
1058
+	) {
1059
+		$model         = $this->get_model();
1060
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1061
+			? $model->get_primary_key_field()->get_name()
1062
+			: $field_to_order_by;
1063
+		$current_value = ! empty($field) ? $this->get($field) : null;
1064
+		if (empty($field) || empty($current_value)) {
1065
+			return [];
1066
+		}
1067
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1068
+	}
1069
+
1070
+
1071
+	/**
1072
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1073
+	 * matching the given query conditions.
1074
+	 *
1075
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1076
+	 * @param array $query_params       Any additional conditions on the query.
1077
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1078
+	 *                                  you can indicate just the columns you want returned
1079
+	 * @return array|EE_Base_Class
1080
+	 * @throws ReflectionException
1081
+	 * @throws InvalidArgumentException
1082
+	 * @throws InvalidInterfaceException
1083
+	 * @throws InvalidDataTypeException
1084
+	 * @throws EE_Error
1085
+	 */
1086
+	public function next($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1087
+	{
1088
+		$model         = $this->get_model();
1089
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1090
+			? $model->get_primary_key_field()->get_name()
1091
+			: $field_to_order_by;
1092
+		$current_value = ! empty($field) ? $this->get($field) : null;
1093
+		if (empty($field) || empty($current_value)) {
1094
+			return [];
1095
+		}
1096
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1097
+	}
1098
+
1099
+
1100
+	/**
1101
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1102
+	 * matching the given query conditions.
1103
+	 *
1104
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1105
+	 * @param array $query_params       Any additional conditions on the query.
1106
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1107
+	 *                                  you can indicate just the column you want returned
1108
+	 * @return array|EE_Base_Class
1109
+	 * @throws ReflectionException
1110
+	 * @throws InvalidArgumentException
1111
+	 * @throws InvalidInterfaceException
1112
+	 * @throws InvalidDataTypeException
1113
+	 * @throws EE_Error
1114
+	 */
1115
+	public function previous($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1116
+	{
1117
+		$model         = $this->get_model();
1118
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1119
+			? $model->get_primary_key_field()->get_name()
1120
+			: $field_to_order_by;
1121
+		$current_value = ! empty($field) ? $this->get($field) : null;
1122
+		if (empty($field) || empty($current_value)) {
1123
+			return [];
1124
+		}
1125
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * verifies that the specified field is of the correct type
1131
+	 *
1132
+	 * @param string $field_name
1133
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1134
+	 *                                (in cases where the same property may be used for different outputs
1135
+	 *                                - i.e. datetime, money etc.)
1136
+	 * @return mixed
1137
+	 * @throws ReflectionException
1138
+	 * @throws InvalidArgumentException
1139
+	 * @throws InvalidInterfaceException
1140
+	 * @throws InvalidDataTypeException
1141
+	 * @throws EE_Error
1142
+	 */
1143
+	public function get($field_name, $extra_cache_ref = null)
1144
+	{
1145
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1146
+	}
1147
+
1148
+
1149
+	/**
1150
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1151
+	 *
1152
+	 * @param string $field_name A valid fieldname
1153
+	 * @return mixed              Whatever the raw value stored on the property is.
1154
+	 * @throws ReflectionException
1155
+	 * @throws InvalidArgumentException
1156
+	 * @throws InvalidInterfaceException
1157
+	 * @throws InvalidDataTypeException
1158
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1159
+	 */
1160
+	public function get_raw($field_name)
1161
+	{
1162
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1163
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1164
+			? $this->_fields[ $field_name ]->format('U')
1165
+			: $this->_fields[ $field_name ];
1166
+	}
1167
+
1168
+
1169
+	/**
1170
+	 * This is used to return the internal DateTime object used for a field that is a
1171
+	 * EE_Datetime_Field.
1172
+	 *
1173
+	 * @param string $field_name               The field name retrieving the DateTime object.
1174
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1175
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1176
+	 *                                         EE_Datetime_Field and but the field value is null, then
1177
+	 *                                         just null is returned (because that indicates that likely
1178
+	 *                                         this field is nullable).
1179
+	 * @throws InvalidArgumentException
1180
+	 * @throws InvalidDataTypeException
1181
+	 * @throws InvalidInterfaceException
1182
+	 * @throws ReflectionException
1183
+	 */
1184
+	public function get_DateTime_object($field_name)
1185
+	{
1186
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1187
+		if (! $field_settings instanceof EE_Datetime_Field) {
1188
+			EE_Error::add_error(
1189
+				sprintf(
1190
+					esc_html__(
1191
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1192
+						'event_espresso'
1193
+					),
1194
+					$field_name
1195
+				),
1196
+				__FILE__,
1197
+				__FUNCTION__,
1198
+				__LINE__
1199
+			);
1200
+			return false;
1201
+		}
1202
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1203
+			? clone $this->_fields[ $field_name ]
1204
+			: null;
1205
+	}
1206
+
1207
+
1208
+	/**
1209
+	 * To be used in template to immediately echo out the value, and format it for output.
1210
+	 * Eg, should call stripslashes and whatnot before echoing
1211
+	 *
1212
+	 * @param string $field_name      the name of the field as it appears in the DB
1213
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1214
+	 *                                (in cases where the same property may be used for different outputs
1215
+	 *                                - i.e. datetime, money etc.)
1216
+	 * @return void
1217
+	 * @throws ReflectionException
1218
+	 * @throws InvalidArgumentException
1219
+	 * @throws InvalidInterfaceException
1220
+	 * @throws InvalidDataTypeException
1221
+	 * @throws EE_Error
1222
+	 */
1223
+	public function e($field_name, $extra_cache_ref = null)
1224
+	{
1225
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1231
+	 * can be easily used as the value of form input.
1232
+	 *
1233
+	 * @param string $field_name
1234
+	 * @return void
1235
+	 * @throws ReflectionException
1236
+	 * @throws InvalidArgumentException
1237
+	 * @throws InvalidInterfaceException
1238
+	 * @throws InvalidDataTypeException
1239
+	 * @throws EE_Error
1240
+	 */
1241
+	public function f($field_name)
1242
+	{
1243
+		$this->e($field_name, 'form_input');
1244
+	}
1245
+
1246
+
1247
+	/**
1248
+	 * Same as `f()` but just returns the value instead of echoing it
1249
+	 *
1250
+	 * @param string $field_name
1251
+	 * @return string
1252
+	 * @throws ReflectionException
1253
+	 * @throws InvalidArgumentException
1254
+	 * @throws InvalidInterfaceException
1255
+	 * @throws InvalidDataTypeException
1256
+	 * @throws EE_Error
1257
+	 */
1258
+	public function get_f($field_name)
1259
+	{
1260
+		return (string) $this->get_pretty($field_name, 'form_input');
1261
+	}
1262
+
1263
+
1264
+	/**
1265
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1266
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1267
+	 * to see what options are available.
1268
+	 *
1269
+	 * @param string $field_name
1270
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1271
+	 *                                (in cases where the same property may be used for different outputs
1272
+	 *                                - i.e. datetime, money etc.)
1273
+	 * @return mixed
1274
+	 * @throws ReflectionException
1275
+	 * @throws InvalidArgumentException
1276
+	 * @throws InvalidInterfaceException
1277
+	 * @throws InvalidDataTypeException
1278
+	 * @throws EE_Error
1279
+	 */
1280
+	public function get_pretty($field_name, $extra_cache_ref = null)
1281
+	{
1282
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1283
+	}
1284
+
1285
+
1286
+	/**
1287
+	 * This simply returns the datetime for the given field name
1288
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1289
+	 * (and the equivalent e_date, e_time, e_datetime).
1290
+	 *
1291
+	 * @access   protected
1292
+	 * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1293
+	 * @param string|null $date_format  valid datetime format used for date
1294
+	 *                                  (if '' then we just use the default on the field,
1295
+	 *                                  if NULL we use the last-used format)
1296
+	 * @param string|null $time_format  Same as above except this is for time format
1297
+	 * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1298
+	 * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1299
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1300
+	 *                                  if field is not a valid dtt field, or void if echoing
1301
+	 * @throws EE_Error
1302
+	 * @throws ReflectionException
1303
+	 */
1304
+	protected function _get_datetime(
1305
+		string $field_name,
1306
+		?string $date_format = '',
1307
+		?string $time_format = '',
1308
+		?string $date_or_time = '',
1309
+		?bool $echo = false
1310
+	) {
1311
+		// clear cached property
1312
+		$this->_clear_cached_property($field_name);
1313
+		// reset format properties because they are used in get()
1314
+		$this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1315
+		$this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1316
+		if ($echo) {
1317
+			$this->e($field_name, $date_or_time);
1318
+			return '';
1319
+		}
1320
+		return $this->get($field_name, $date_or_time);
1321
+	}
1322
+
1323
+
1324
+	/**
1325
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1326
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1327
+	 * other echoes the pretty value for dtt)
1328
+	 *
1329
+	 * @param string $field_name name of model object datetime field holding the value
1330
+	 * @param string $format     format for the date returned (if NULL we use default in dt_frmt property)
1331
+	 * @return string            datetime value formatted
1332
+	 * @throws ReflectionException
1333
+	 * @throws InvalidArgumentException
1334
+	 * @throws InvalidInterfaceException
1335
+	 * @throws InvalidDataTypeException
1336
+	 * @throws EE_Error
1337
+	 */
1338
+	public function get_date($field_name, $format = '')
1339
+	{
1340
+		return $this->_get_datetime($field_name, $format, null, 'D');
1341
+	}
1342
+
1343
+
1344
+	/**
1345
+	 * @param        $field_name
1346
+	 * @param string $format
1347
+	 * @throws ReflectionException
1348
+	 * @throws InvalidArgumentException
1349
+	 * @throws InvalidInterfaceException
1350
+	 * @throws InvalidDataTypeException
1351
+	 * @throws EE_Error
1352
+	 */
1353
+	public function e_date($field_name, $format = '')
1354
+	{
1355
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1356
+	}
1357
+
1358
+
1359
+	/**
1360
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1361
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1362
+	 * other echoes the pretty value for dtt)
1363
+	 *
1364
+	 * @param string $field_name name of model object datetime field holding the value
1365
+	 * @param string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1366
+	 * @return string             datetime value formatted
1367
+	 * @throws ReflectionException
1368
+	 * @throws InvalidArgumentException
1369
+	 * @throws InvalidInterfaceException
1370
+	 * @throws InvalidDataTypeException
1371
+	 * @throws EE_Error
1372
+	 */
1373
+	public function get_time($field_name, $format = '')
1374
+	{
1375
+		return $this->_get_datetime($field_name, null, $format, 'T');
1376
+	}
1377
+
1378
+
1379
+	/**
1380
+	 * @param        $field_name
1381
+	 * @param string $format
1382
+	 * @throws ReflectionException
1383
+	 * @throws InvalidArgumentException
1384
+	 * @throws InvalidInterfaceException
1385
+	 * @throws InvalidDataTypeException
1386
+	 * @throws EE_Error
1387
+	 */
1388
+	public function e_time($field_name, $format = '')
1389
+	{
1390
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1391
+	}
1392
+
1393
+
1394
+	/**
1395
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1396
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1397
+	 * other echoes the pretty value for dtt)
1398
+	 *
1399
+	 * @param string $field_name  name of model object datetime field holding the value
1400
+	 * @param string $date_format format for the date returned (if NULL we use default in dt_frmt property)
1401
+	 * @param string $time_format format for the time returned (if NULL we use default in tm_frmt property)
1402
+	 * @return string             datetime value formatted
1403
+	 * @throws ReflectionException
1404
+	 * @throws InvalidArgumentException
1405
+	 * @throws InvalidInterfaceException
1406
+	 * @throws InvalidDataTypeException
1407
+	 * @throws EE_Error
1408
+	 */
1409
+	public function get_datetime($field_name, $date_format = '', $time_format = '')
1410
+	{
1411
+		return $this->_get_datetime($field_name, $date_format, $time_format);
1412
+	}
1413
+
1414
+
1415
+	/**
1416
+	 * @param string $field_name
1417
+	 * @param string $date_format
1418
+	 * @param string $time_format
1419
+	 * @throws ReflectionException
1420
+	 * @throws InvalidArgumentException
1421
+	 * @throws InvalidInterfaceException
1422
+	 * @throws InvalidDataTypeException
1423
+	 * @throws EE_Error
1424
+	 */
1425
+	public function e_datetime($field_name, $date_format = '', $time_format = '')
1426
+	{
1427
+		$this->_get_datetime($field_name, $date_format, $time_format, null, true);
1428
+	}
1429
+
1430
+
1431
+	/**
1432
+	 * Get the i8ln value for a date using the WordPress @param string $field_name The EE_Datetime_Field reference for
1433
+	 *                           the date being retrieved.
1434
+	 *
1435
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1436
+	 *                           on the object will be used.
1437
+	 * @return string Date and time string in set locale or false if no field exists for the given
1438
+	 * @throws ReflectionException
1439
+	 * @throws InvalidArgumentException
1440
+	 * @throws InvalidInterfaceException
1441
+	 * @throws InvalidDataTypeException
1442
+	 * @throws EE_Error
1443
+	 *                           field name.
1444
+	 * @see date_i18n function.
1445
+	 */
1446
+	public function get_i18n_datetime(string $field_name, string $format = ''): string
1447
+	{
1448
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1449
+		return date_i18n(
1450
+			$format,
1451
+			EEH_DTT_Helper::get_timestamp_with_offset(
1452
+				$this->get_raw($field_name),
1453
+				$this->_timezone
1454
+			)
1455
+		);
1456
+	}
1457
+
1458
+
1459
+	/**
1460
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1461
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1462
+	 * thrown.
1463
+	 *
1464
+	 * @param string $field_name The field name being checked
1465
+	 * @return EE_Datetime_Field
1466
+	 * @throws InvalidArgumentException
1467
+	 * @throws InvalidInterfaceException
1468
+	 * @throws InvalidDataTypeException
1469
+	 * @throws EE_Error
1470
+	 * @throws ReflectionException
1471
+	 */
1472
+	protected function _get_dtt_field_settings($field_name)
1473
+	{
1474
+		$field = $this->get_model()->field_settings_for($field_name);
1475
+		// check if field is dtt
1476
+		if ($field instanceof EE_Datetime_Field) {
1477
+			return $field;
1478
+		}
1479
+		throw new EE_Error(
1480
+			sprintf(
1481
+				esc_html__(
1482
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1483
+					'event_espresso'
1484
+				),
1485
+				$field_name,
1486
+				self::_get_model_classname(get_class($this))
1487
+			)
1488
+		);
1489
+	}
1490
+
1491
+
1492
+
1493
+
1494
+	/**
1495
+	 * NOTE ABOUT BELOW:
1496
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1497
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1498
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1499
+	 * method and make sure you send the entire datetime value for setting.
1500
+	 */
1501
+	/**
1502
+	 * sets the time on a datetime property
1503
+	 *
1504
+	 * @access protected
1505
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1506
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1507
+	 * @throws ReflectionException
1508
+	 * @throws InvalidArgumentException
1509
+	 * @throws InvalidInterfaceException
1510
+	 * @throws InvalidDataTypeException
1511
+	 * @throws EE_Error
1512
+	 */
1513
+	protected function _set_time_for($time, $fieldname)
1514
+	{
1515
+		$this->_set_date_time('T', $time, $fieldname);
1516
+	}
1517
+
1518
+
1519
+	/**
1520
+	 * sets the date on a datetime property
1521
+	 *
1522
+	 * @access protected
1523
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1524
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1525
+	 * @throws ReflectionException
1526
+	 * @throws InvalidArgumentException
1527
+	 * @throws InvalidInterfaceException
1528
+	 * @throws InvalidDataTypeException
1529
+	 * @throws EE_Error
1530
+	 */
1531
+	protected function _set_date_for($date, $fieldname)
1532
+	{
1533
+		$this->_set_date_time('D', $date, $fieldname);
1534
+	}
1535
+
1536
+
1537
+	/**
1538
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1539
+	 * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1540
+	 *
1541
+	 * @access protected
1542
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1543
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1544
+	 * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1545
+	 *                                        EE_Datetime_Field property)
1546
+	 * @throws ReflectionException
1547
+	 * @throws InvalidArgumentException
1548
+	 * @throws InvalidInterfaceException
1549
+	 * @throws InvalidDataTypeException
1550
+	 * @throws EE_Error
1551
+	 */
1552
+	protected function _set_date_time(string $what, $datetime_value, string $field_name)
1553
+	{
1554
+		$field = $this->_get_dtt_field_settings($field_name);
1555
+		$field->set_timezone($this->_timezone);
1556
+		$field->set_date_format($this->_dt_frmt);
1557
+		$field->set_time_format($this->_tm_frmt);
1558
+		switch ($what) {
1559
+			case 'T':
1560
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1561
+					$datetime_value,
1562
+					$this->_fields[ $field_name ]
1563
+				);
1564
+				$this->_has_changes           = true;
1565
+				break;
1566
+			case 'D':
1567
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1568
+					$datetime_value,
1569
+					$this->_fields[ $field_name ]
1570
+				);
1571
+				$this->_has_changes           = true;
1572
+				break;
1573
+			case 'B':
1574
+				$this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1575
+				$this->_has_changes           = true;
1576
+				break;
1577
+		}
1578
+		$this->_clear_cached_property($field_name);
1579
+	}
1580
+
1581
+
1582
+	/**
1583
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1584
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1585
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1586
+	 * that could lead to some unexpected results!
1587
+	 *
1588
+	 * @access public
1589
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1590
+	 *                                         value being returned.
1591
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1592
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1593
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1594
+	 * @param string $append                   You can include something to append on the timestamp
1595
+	 * @return string timestamp
1596
+	 * @throws ReflectionException
1597
+	 * @throws InvalidArgumentException
1598
+	 * @throws InvalidInterfaceException
1599
+	 * @throws InvalidDataTypeException
1600
+	 * @throws EE_Error
1601
+	 */
1602
+	public function display_in_my_timezone(
1603
+		$field_name,
1604
+		$callback = 'get_datetime',
1605
+		$args = null,
1606
+		$prepend = '',
1607
+		$append = ''
1608
+	) {
1609
+		$timezone = EEH_DTT_Helper::get_timezone();
1610
+		if ($timezone === $this->_timezone) {
1611
+			return '';
1612
+		}
1613
+		$original_timezone = $this->_timezone;
1614
+		$this->set_timezone($timezone);
1615
+		$fn   = (array) $field_name;
1616
+		$args = array_merge($fn, (array) $args);
1617
+		if (! method_exists($this, $callback)) {
1618
+			throw new EE_Error(
1619
+				sprintf(
1620
+					esc_html__(
1621
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1622
+						'event_espresso'
1623
+					),
1624
+					$callback
1625
+				)
1626
+			);
1627
+		}
1628
+		$args   = (array) $args;
1629
+		$return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1630
+		$this->set_timezone($original_timezone);
1631
+		return $return;
1632
+	}
1633
+
1634
+
1635
+	/**
1636
+	 * Deletes this model object.
1637
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1638
+	 * override
1639
+	 * `EE_Base_Class::_delete` NOT this class.
1640
+	 *
1641
+	 * @return boolean | int
1642
+	 * @throws ReflectionException
1643
+	 * @throws InvalidArgumentException
1644
+	 * @throws InvalidInterfaceException
1645
+	 * @throws InvalidDataTypeException
1646
+	 * @throws EE_Error
1647
+	 */
1648
+	public function delete()
1649
+	{
1650
+		/**
1651
+		 * Called just before the `EE_Base_Class::_delete` method call.
1652
+		 * Note:
1653
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1654
+		 * should be aware that `_delete` may not always result in a permanent delete.
1655
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1656
+		 * soft deletes (trash) the object and does not permanently delete it.
1657
+		 *
1658
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1659
+		 */
1660
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1661
+		$result = $this->_delete();
1662
+		/**
1663
+		 * Called just after the `EE_Base_Class::_delete` method call.
1664
+		 * Note:
1665
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1666
+		 * should be aware that `_delete` may not always result in a permanent delete.
1667
+		 * For example `EE_Soft_Base_Class::_delete`
1668
+		 * soft deletes (trash) the object and does not permanently delete it.
1669
+		 *
1670
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1671
+		 * @param boolean       $result
1672
+		 */
1673
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1674
+		return $result;
1675
+	}
1676
+
1677
+
1678
+	/**
1679
+	 * Calls the specific delete method for the instantiated class.
1680
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1681
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1682
+	 * `EE_Base_Class::delete`
1683
+	 *
1684
+	 * @return bool|int
1685
+	 * @throws ReflectionException
1686
+	 * @throws InvalidArgumentException
1687
+	 * @throws InvalidInterfaceException
1688
+	 * @throws InvalidDataTypeException
1689
+	 * @throws EE_Error
1690
+	 */
1691
+	protected function _delete()
1692
+	{
1693
+		return $this->delete_permanently();
1694
+	}
1695
+
1696
+
1697
+	/**
1698
+	 * Deletes this model object permanently from db
1699
+	 * (but keep in mind related models may block the delete and return an error)
1700
+	 *
1701
+	 * @return bool | int
1702
+	 * @throws ReflectionException
1703
+	 * @throws InvalidArgumentException
1704
+	 * @throws InvalidInterfaceException
1705
+	 * @throws InvalidDataTypeException
1706
+	 * @throws EE_Error
1707
+	 */
1708
+	public function delete_permanently()
1709
+	{
1710
+		/**
1711
+		 * Called just before HARD deleting a model object
1712
+		 *
1713
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1714
+		 */
1715
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1716
+		$model  = $this->get_model();
1717
+		$result = $model->delete_permanently_by_ID($this->ID());
1718
+		$this->refresh_cache_of_related_objects();
1719
+		/**
1720
+		 * Called just after HARD deleting a model object
1721
+		 *
1722
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1723
+		 * @param boolean       $result
1724
+		 */
1725
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1726
+		return $result;
1727
+	}
1728
+
1729
+
1730
+	/**
1731
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1732
+	 * related model objects
1733
+	 *
1734
+	 * @throws ReflectionException
1735
+	 * @throws InvalidArgumentException
1736
+	 * @throws InvalidInterfaceException
1737
+	 * @throws InvalidDataTypeException
1738
+	 * @throws EE_Error
1739
+	 */
1740
+	public function refresh_cache_of_related_objects()
1741
+	{
1742
+		$model = $this->get_model();
1743
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1744
+			if (! empty($this->_model_relations[ $relation_name ])) {
1745
+				$related_objects = $this->_model_relations[ $relation_name ];
1746
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1747
+					// this relation only stores a single model object, not an array
1748
+					// but let's make it consistent
1749
+					$related_objects = [$related_objects];
1750
+				}
1751
+				foreach ($related_objects as $related_object) {
1752
+					// only refresh their cache if they're in memory
1753
+					if ($related_object instanceof EE_Base_Class) {
1754
+						$related_object->clear_cache(
1755
+							$model->get_this_model_name(),
1756
+							$this
1757
+						);
1758
+					}
1759
+				}
1760
+			}
1761
+		}
1762
+	}
1763
+
1764
+
1765
+	/**
1766
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1767
+	 * object just before saving.
1768
+	 *
1769
+	 * @access public
1770
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1771
+	 *                                 if provided during the save() method (often client code will change the fields'
1772
+	 *                                 values before calling save)
1773
+	 * @return bool|int|string         1 on a successful update
1774
+	 *                                 the ID of the new entry on insert
1775
+	 *                                 0 on failure or if the model object isn't allowed to persist
1776
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1777
+	 * @throws InvalidInterfaceException
1778
+	 * @throws InvalidDataTypeException
1779
+	 * @throws EE_Error
1780
+	 * @throws InvalidArgumentException
1781
+	 * @throws ReflectionException
1782
+	 */
1783
+	public function save($set_cols_n_values = [])
1784
+	{
1785
+		$model = $this->get_model();
1786
+		/**
1787
+		 * Filters the fields we're about to save on the model object
1788
+		 *
1789
+		 * @param array         $set_cols_n_values
1790
+		 * @param EE_Base_Class $model_object
1791
+		 */
1792
+		$set_cols_n_values = (array) apply_filters(
1793
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1794
+			$set_cols_n_values,
1795
+			$this
1796
+		);
1797
+		// set attributes as provided in $set_cols_n_values
1798
+		foreach ($set_cols_n_values as $column => $value) {
1799
+			$this->set($column, $value);
1800
+		}
1801
+		// no changes ? then don't do anything
1802
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1803
+			return 0;
1804
+		}
1805
+		/**
1806
+		 * Saving a model object.
1807
+		 * Before we perform a save, this action is fired.
1808
+		 *
1809
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1810
+		 */
1811
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1812
+		if (! $this->allow_persist()) {
1813
+			return 0;
1814
+		}
1815
+		// now get current attribute values
1816
+		$save_cols_n_values = $this->_fields;
1817
+		// if the object already has an ID, update it. Otherwise, insert it
1818
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1819
+		// They have been
1820
+		$old_assumption_concerning_value_preparation = $model
1821
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1822
+		$model->assume_values_already_prepared_by_model_object(true);
1823
+		// does this model have an autoincrement PK?
1824
+		if ($model->has_primary_key_field()) {
1825
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1826
+				// ok check if it's set, if so: update; if not, insert
1827
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1828
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1829
+				} else {
1830
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1831
+					$results = $model->insert($save_cols_n_values);
1832
+					if ($results) {
1833
+						// if successful, set the primary key
1834
+						// but don't use the normal SET method, because it will check if
1835
+						// an item with the same ID exists in the mapper & db, then
1836
+						// will find it in the db (because we just added it) and THAT object
1837
+						// will get added to the mapper before we can add this one!
1838
+						// but if we just avoid using the SET method, all that headache can be avoided
1839
+						$pk_field_name                   = $model->primary_key_name();
1840
+						$this->_fields[ $pk_field_name ] = $results;
1841
+						$this->_clear_cached_property($pk_field_name);
1842
+						$model->add_to_entity_map($this);
1843
+						$this->_update_cached_related_model_objs_fks();
1844
+					}
1845
+				}
1846
+			} else {// PK is NOT auto-increment
1847
+				// so check if one like it already exists in the db
1848
+				if ($model->exists_by_ID($this->ID())) {
1849
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1850
+						throw new EE_Error(
1851
+							sprintf(
1852
+								esc_html__(
1853
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1854
+									'event_espresso'
1855
+								),
1856
+								get_class($this),
1857
+								get_class($model) . '::instance()->add_to_entity_map()',
1858
+								get_class($model) . '::instance()->get_one_by_ID()',
1859
+								'<br />'
1860
+							)
1861
+						);
1862
+					}
1863
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1864
+				} else {
1865
+					$results = $model->insert($save_cols_n_values);
1866
+					$this->_update_cached_related_model_objs_fks();
1867
+				}
1868
+			}
1869
+		} else {// there is NO primary key
1870
+			$already_in_db = false;
1871
+			foreach ($model->unique_indexes() as $index) {
1872
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1873
+				if ($model->exists([$uniqueness_where_params])) {
1874
+					$already_in_db = true;
1875
+				}
1876
+			}
1877
+			if ($already_in_db) {
1878
+				$combined_pk_fields_n_values = array_intersect_key(
1879
+					$save_cols_n_values,
1880
+					$model->get_combined_primary_key_fields()
1881
+				);
1882
+				$results                     = $model->update(
1883
+					$save_cols_n_values,
1884
+					$combined_pk_fields_n_values
1885
+				);
1886
+			} else {
1887
+				$results = $model->insert($save_cols_n_values);
1888
+			}
1889
+		}
1890
+		// restore the old assumption about values being prepared by the model object
1891
+		$model->assume_values_already_prepared_by_model_object(
1892
+			$old_assumption_concerning_value_preparation
1893
+		);
1894
+		/**
1895
+		 * After saving the model object this action is called
1896
+		 *
1897
+		 * @param EE_Base_Class $model_object which was just saved
1898
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1899
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1900
+		 */
1901
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1902
+		$this->_has_changes = false;
1903
+		return $results;
1904
+	}
1905
+
1906
+
1907
+	/**
1908
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1909
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1910
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1911
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1912
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1913
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1914
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1915
+	 *
1916
+	 * @return void
1917
+	 * @throws ReflectionException
1918
+	 * @throws InvalidArgumentException
1919
+	 * @throws InvalidInterfaceException
1920
+	 * @throws InvalidDataTypeException
1921
+	 * @throws EE_Error
1922
+	 */
1923
+	protected function _update_cached_related_model_objs_fks()
1924
+	{
1925
+		$model = $this->get_model();
1926
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1927
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1928
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1929
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1930
+						$model->get_this_model_name()
1931
+					);
1932
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1933
+					if ($related_model_obj_in_cache->ID()) {
1934
+						$related_model_obj_in_cache->save();
1935
+					}
1936
+				}
1937
+			}
1938
+		}
1939
+	}
1940
+
1941
+
1942
+	/**
1943
+	 * Saves this model object and its NEW cached relations to the database.
1944
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1945
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1946
+	 * because otherwise, there's a potential for infinite looping of saving
1947
+	 * Saves the cached related model objects, and ensures the relation between them
1948
+	 * and this object and properly setup
1949
+	 *
1950
+	 * @return int ID of new model object on save; 0 on failure+
1951
+	 * @throws ReflectionException
1952
+	 * @throws InvalidArgumentException
1953
+	 * @throws InvalidInterfaceException
1954
+	 * @throws InvalidDataTypeException
1955
+	 * @throws EE_Error
1956
+	 */
1957
+	public function save_new_cached_related_model_objs()
1958
+	{
1959
+		// make sure this has been saved
1960
+		if (! $this->ID()) {
1961
+			$id = $this->save();
1962
+		} else {
1963
+			$id = $this->ID();
1964
+		}
1965
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1966
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1967
+			if ($this->_model_relations[ $relation_name ]) {
1968
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1969
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1970
+				/* @var $related_model_obj EE_Base_Class */
1971
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1972
+					// add a relation to that relation type (which saves the appropriate thing in the process)
1973
+					// but ONLY if it DOES NOT exist in the DB
1974
+					$related_model_obj = $this->_model_relations[ $relation_name ];
1975
+					// if( ! $related_model_obj->ID()){
1976
+					$this->_add_relation_to($related_model_obj, $relation_name);
1977
+					$related_model_obj->save_new_cached_related_model_objs();
1978
+					// }
1979
+				} else {
1980
+					foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1981
+						// add a relation to that relation type (which saves the appropriate thing in the process)
1982
+						// but ONLY if it DOES NOT exist in the DB
1983
+						// if( ! $related_model_obj->ID()){
1984
+						$this->_add_relation_to($related_model_obj, $relation_name);
1985
+						$related_model_obj->save_new_cached_related_model_objs();
1986
+						// }
1987
+					}
1988
+				}
1989
+			}
1990
+		}
1991
+		return $id;
1992
+	}
1993
+
1994
+
1995
+	/**
1996
+	 * for getting a model while instantiated.
1997
+	 *
1998
+	 * @return EEM_Base | EEM_CPT_Base
1999
+	 * @throws ReflectionException
2000
+	 * @throws InvalidArgumentException
2001
+	 * @throws InvalidInterfaceException
2002
+	 * @throws InvalidDataTypeException
2003
+	 * @throws EE_Error
2004
+	 */
2005
+	public function get_model()
2006
+	{
2007
+		if (! $this->_model) {
2008
+			$modelName    = self::_get_model_classname(get_class($this));
2009
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2010
+		} else {
2011
+			$this->_model->set_timezone($this->_timezone);
2012
+		}
2013
+		return $this->_model;
2014
+	}
2015
+
2016
+
2017
+	/**
2018
+	 * @param $props_n_values
2019
+	 * @param $classname
2020
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2021
+	 * @throws ReflectionException
2022
+	 * @throws InvalidArgumentException
2023
+	 * @throws InvalidInterfaceException
2024
+	 * @throws InvalidDataTypeException
2025
+	 * @throws EE_Error
2026
+	 */
2027
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2028
+	{
2029
+		// TODO: will not work for Term_Relationships because they have no PK!
2030
+		$primary_id_ref = self::_get_primary_key_name($classname);
2031
+		if (
2032
+			array_key_exists($primary_id_ref, $props_n_values)
2033
+			&& ! empty($props_n_values[ $primary_id_ref ])
2034
+		) {
2035
+			$id = $props_n_values[ $primary_id_ref ];
2036
+			return self::_get_model($classname)->get_from_entity_map($id);
2037
+		}
2038
+		return false;
2039
+	}
2040
+
2041
+
2042
+	/**
2043
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2044
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2045
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2046
+	 * we return false.
2047
+	 *
2048
+	 * @param array  $props_n_values    incoming array of properties and their values
2049
+	 * @param string $classname         the classname of the child class
2050
+	 * @param null   $timezone
2051
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the
2052
+	 *                                  date_format and the second value is the time format
2053
+	 * @return mixed (EE_Base_Class|bool)
2054
+	 * @throws InvalidArgumentException
2055
+	 * @throws InvalidInterfaceException
2056
+	 * @throws InvalidDataTypeException
2057
+	 * @throws EE_Error
2058
+	 * @throws ReflectionException
2059
+	 */
2060
+	protected static function _check_for_object($props_n_values, $classname, $timezone = '', $date_formats = [])
2061
+	{
2062
+		$existing = null;
2063
+		$model    = self::_get_model($classname, $timezone);
2064
+		if ($model->has_primary_key_field()) {
2065
+			$primary_id_ref = self::_get_primary_key_name($classname);
2066
+			if (
2067
+				array_key_exists($primary_id_ref, $props_n_values)
2068
+				&& ! empty($props_n_values[ $primary_id_ref ])
2069
+			) {
2070
+				$existing = $model->get_one_by_ID(
2071
+					$props_n_values[ $primary_id_ref ]
2072
+				);
2073
+			}
2074
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2075
+			// no primary key on this model, but there's still a matching item in the DB
2076
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2077
+				self::_get_model($classname, $timezone)
2078
+					->get_index_primary_key_string($props_n_values)
2079
+			);
2080
+		}
2081
+		if ($existing) {
2082
+			// set date formats if present before setting values
2083
+			if (! empty($date_formats) && is_array($date_formats)) {
2084
+				$existing->set_date_format($date_formats[0]);
2085
+				$existing->set_time_format($date_formats[1]);
2086
+			} else {
2087
+				// set default formats for date and time
2088
+				$existing->set_date_format(get_option('date_format'));
2089
+				$existing->set_time_format(get_option('time_format'));
2090
+			}
2091
+			foreach ($props_n_values as $property => $field_value) {
2092
+				$existing->set($property, $field_value);
2093
+			}
2094
+			return $existing;
2095
+		}
2096
+		return false;
2097
+	}
2098
+
2099
+
2100
+	/**
2101
+	 * Gets the EEM_*_Model for this class
2102
+	 *
2103
+	 * @access public now, as this is more convenient
2104
+	 * @param      $classname
2105
+	 * @param null $timezone
2106
+	 * @return EEM_Base
2107
+	 * @throws InvalidArgumentException
2108
+	 * @throws InvalidInterfaceException
2109
+	 * @throws InvalidDataTypeException
2110
+	 * @throws EE_Error
2111
+	 * @throws ReflectionException
2112
+	 */
2113
+	protected static function _get_model($classname, $timezone = '')
2114
+	{
2115
+		// find model for this class
2116
+		if (! $classname) {
2117
+			throw new EE_Error(
2118
+				sprintf(
2119
+					esc_html__(
2120
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2121
+						'event_espresso'
2122
+					),
2123
+					$classname
2124
+				)
2125
+			);
2126
+		}
2127
+		$modelName = self::_get_model_classname($classname);
2128
+		return self::_get_model_instance_with_name($modelName, $timezone);
2129
+	}
2130
+
2131
+
2132
+	/**
2133
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2134
+	 *
2135
+	 * @param string $model_classname
2136
+	 * @param null   $timezone
2137
+	 * @return EEM_Base
2138
+	 * @throws ReflectionException
2139
+	 * @throws InvalidArgumentException
2140
+	 * @throws InvalidInterfaceException
2141
+	 * @throws InvalidDataTypeException
2142
+	 * @throws EE_Error
2143
+	 */
2144
+	protected static function _get_model_instance_with_name($model_classname, $timezone = '')
2145
+	{
2146
+		$model_classname = str_replace('EEM_', '', $model_classname);
2147
+		$model           = EE_Registry::instance()->load_model($model_classname);
2148
+		$model->set_timezone($timezone);
2149
+		return $model;
2150
+	}
2151
+
2152
+
2153
+	/**
2154
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2155
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2156
+	 *
2157
+	 * @param string|null $model_name
2158
+	 * @return string like EEM_Attendee
2159
+	 */
2160
+	private static function _get_model_classname($model_name = '')
2161
+	{
2162
+		return strpos((string) $model_name, 'EE_') === 0
2163
+			? str_replace('EE_', 'EEM_', $model_name)
2164
+			: 'EEM_' . $model_name;
2165
+	}
2166
+
2167
+
2168
+	/**
2169
+	 * returns the name of the primary key attribute
2170
+	 *
2171
+	 * @param null $classname
2172
+	 * @return string
2173
+	 * @throws InvalidArgumentException
2174
+	 * @throws InvalidInterfaceException
2175
+	 * @throws InvalidDataTypeException
2176
+	 * @throws EE_Error
2177
+	 * @throws ReflectionException
2178
+	 */
2179
+	protected static function _get_primary_key_name($classname = null)
2180
+	{
2181
+		if (! $classname) {
2182
+			throw new EE_Error(
2183
+				sprintf(
2184
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2185
+					$classname
2186
+				)
2187
+			);
2188
+		}
2189
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2190
+	}
2191
+
2192
+
2193
+	/**
2194
+	 * Gets the value of the primary key.
2195
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2196
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2197
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2198
+	 *
2199
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2200
+	 * @throws ReflectionException
2201
+	 * @throws InvalidArgumentException
2202
+	 * @throws InvalidInterfaceException
2203
+	 * @throws InvalidDataTypeException
2204
+	 * @throws EE_Error
2205
+	 */
2206
+	public function ID()
2207
+	{
2208
+		$model = $this->get_model();
2209
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2210
+		if ($model->has_primary_key_field()) {
2211
+			return $this->_fields[ $model->primary_key_name() ];
2212
+		}
2213
+		return $model->get_index_primary_key_string($this->_fields);
2214
+	}
2215
+
2216
+
2217
+	/**
2218
+	 * @param EE_Base_Class|int|string $otherModelObjectOrID
2219
+	 * @param string                   $relation_name
2220
+	 * @return bool
2221
+	 * @throws EE_Error
2222
+	 * @throws ReflectionException
2223
+	 * @since   5.0.0.p
2224
+	 */
2225
+	public function hasRelation($otherModelObjectOrID, string $relation_name): bool
2226
+	{
2227
+		$other_model = self::_get_model_instance_with_name(
2228
+			self::_get_model_classname($relation_name),
2229
+			$this->_timezone
2230
+		);
2231
+		$primary_key = $other_model->primary_key_name();
2232
+		/** @var EE_Base_Class $otherModelObject */
2233
+		$otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relation_name);
2234
+		return $this->count_related($relation_name, [[$primary_key => $otherModelObject->ID()]]) > 0;
2235
+	}
2236
+
2237
+
2238
+	/**
2239
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2240
+	 * model is related to a group of events, the $relation_name should be 'Event', and should be a key in the EE
2241
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2242
+	 *
2243
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2244
+	 * @param string $relation_name                    eg 'Events','Question',etc.
2245
+	 *                                                 an attendee to a group, you also want to specify which role they
2246
+	 *                                                 will have in that group. So you would use this parameter to
2247
+	 *                                                 specify array('role-column-name'=>'role-id')
2248
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2249
+	 *                                                 allow you to further constrict the relation to being added.
2250
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2251
+	 *                                                 column on the JOIN table and currently only the HABTM models
2252
+	 *                                                 accept these additional conditions.  Also remember that if an
2253
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2254
+	 *                                                 NEW row is created in the join table.
2255
+	 * @param null   $cache_id
2256
+	 * @return EE_Base_Class the object the relation was added to
2257
+	 * @throws ReflectionException
2258
+	 * @throws InvalidArgumentException
2259
+	 * @throws InvalidInterfaceException
2260
+	 * @throws InvalidDataTypeException
2261
+	 * @throws EE_Error
2262
+	 */
2263
+	public function _add_relation_to(
2264
+		$otherObjectModelObjectOrID,
2265
+		$relation_name,
2266
+		$extra_join_model_fields_n_values = [],
2267
+		$cache_id = null
2268
+	) {
2269
+		$model = $this->get_model();
2270
+		// if this thing exists in the DB, save the relation to the DB
2271
+		if ($this->ID()) {
2272
+			$otherObject = $model->add_relationship_to(
2273
+				$this,
2274
+				$otherObjectModelObjectOrID,
2275
+				$relation_name,
2276
+				$extra_join_model_fields_n_values
2277
+			);
2278
+			// clear cache so future get_many_related and get_first_related() return new results.
2279
+			$this->clear_cache($relation_name, $otherObject, true);
2280
+			if ($otherObject instanceof EE_Base_Class) {
2281
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2282
+			}
2283
+		} else {
2284
+			// this thing doesn't exist in the DB,  so just cache it
2285
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2286
+				throw new EE_Error(
2287
+					sprintf(
2288
+						esc_html__(
2289
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2290
+							'event_espresso'
2291
+						),
2292
+						$otherObjectModelObjectOrID,
2293
+						get_class($this)
2294
+					)
2295
+				);
2296
+			}
2297
+			$otherObject = $otherObjectModelObjectOrID;
2298
+			$this->cache($relation_name, $otherObjectModelObjectOrID, $cache_id);
2299
+		}
2300
+		if ($otherObject instanceof EE_Base_Class) {
2301
+			// fix the reciprocal relation too
2302
+			if ($otherObject->ID()) {
2303
+				// its saved so assumed relations exist in the DB, so we can just
2304
+				// clear the cache so future queries use the updated info in the DB
2305
+				$otherObject->clear_cache(
2306
+					$model->get_this_model_name(),
2307
+					null,
2308
+					true
2309
+				);
2310
+			} else {
2311
+				// it's not saved, so it caches relations like this
2312
+				$otherObject->cache($model->get_this_model_name(), $this);
2313
+			}
2314
+		}
2315
+		return $otherObject;
2316
+	}
2317
+
2318
+
2319
+	/**
2320
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2321
+	 * model is related to a group of events, the $relation_name should be 'Events', and should be a key in the EE
2322
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2323
+	 * from the cache
2324
+	 *
2325
+	 * @param mixed  $otherObjectModelObjectOrID
2326
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2327
+	 *                to the DB yet
2328
+	 * @param string $relation_name
2329
+	 * @param array  $where_query
2330
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2331
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2332
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2333
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2334
+	 *                deleted.
2335
+	 * @return EE_Base_Class the relation was removed from
2336
+	 * @throws ReflectionException
2337
+	 * @throws InvalidArgumentException
2338
+	 * @throws InvalidInterfaceException
2339
+	 * @throws InvalidDataTypeException
2340
+	 * @throws EE_Error
2341
+	 */
2342
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relation_name, $where_query = [])
2343
+	{
2344
+		if ($this->ID()) {
2345
+			// if this exists in the DB, save the relation change to the DB too
2346
+			$otherObject = $this->get_model()->remove_relationship_to(
2347
+				$this,
2348
+				$otherObjectModelObjectOrID,
2349
+				$relation_name,
2350
+				$where_query
2351
+			);
2352
+			$this->clear_cache(
2353
+				$relation_name,
2354
+				$otherObject
2355
+			);
2356
+		} else {
2357
+			// this doesn't exist in the DB, just remove it from the cache
2358
+			$otherObject = $this->clear_cache(
2359
+				$relation_name,
2360
+				$otherObjectModelObjectOrID
2361
+			);
2362
+		}
2363
+		if ($otherObject instanceof EE_Base_Class) {
2364
+			$otherObject->clear_cache(
2365
+				$this->get_model()->get_this_model_name(),
2366
+				$this
2367
+			);
2368
+		}
2369
+		return $otherObject;
2370
+	}
2371
+
2372
+
2373
+	/**
2374
+	 * Removes ALL the related things for the $relation_name.
2375
+	 *
2376
+	 * @param string $relation_name
2377
+	 * @param array  $where_query_params @see
2378
+	 *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2379
+	 * @return EE_Base_Class
2380
+	 * @throws ReflectionException
2381
+	 * @throws InvalidArgumentException
2382
+	 * @throws InvalidInterfaceException
2383
+	 * @throws InvalidDataTypeException
2384
+	 * @throws EE_Error
2385
+	 */
2386
+	public function _remove_relations($relation_name, $where_query_params = [])
2387
+	{
2388
+		if ($this->ID()) {
2389
+			// if this exists in the DB, save the relation change to the DB too
2390
+			$otherObjects = $this->get_model()->remove_relations(
2391
+				$this,
2392
+				$relation_name,
2393
+				$where_query_params
2394
+			);
2395
+			$this->clear_cache(
2396
+				$relation_name,
2397
+				null,
2398
+				true
2399
+			);
2400
+		} else {
2401
+			// this doesn't exist in the DB, just remove it from the cache
2402
+			$otherObjects = $this->clear_cache(
2403
+				$relation_name,
2404
+				null,
2405
+				true
2406
+			);
2407
+		}
2408
+		if (is_array($otherObjects)) {
2409
+			foreach ($otherObjects as $otherObject) {
2410
+				$otherObject->clear_cache(
2411
+					$this->get_model()->get_this_model_name(),
2412
+					$this
2413
+				);
2414
+			}
2415
+		}
2416
+		return $otherObjects;
2417
+	}
2418
+
2419
+
2420
+	/**
2421
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2422
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2423
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2424
+	 * because we want to get even deleted items etc.
2425
+	 *
2426
+	 * @param string      $relation_name key in the model's _model_relations array
2427
+	 * @param array|null  $query_params  @see
2428
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2429
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2430
+	 *                              keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2431
+	 *                              results if you want IDs
2432
+	 * @throws ReflectionException
2433
+	 * @throws InvalidArgumentException
2434
+	 * @throws InvalidInterfaceException
2435
+	 * @throws InvalidDataTypeException
2436
+	 * @throws EE_Error
2437
+	 */
2438
+	public function get_many_related($relation_name, $query_params = [])
2439
+	{
2440
+		if ($this->ID()) {
2441
+			// this exists in the DB, so get the related things from either the cache or the DB
2442
+			// if there are query parameters, forget about caching the related model objects.
2443
+			if ($query_params) {
2444
+				$related_model_objects = $this->get_model()->get_all_related(
2445
+					$this,
2446
+					$relation_name,
2447
+					$query_params
2448
+				);
2449
+			} else {
2450
+				// did we already cache the result of this query?
2451
+				$cached_results = $this->get_all_from_cache($relation_name);
2452
+				if (! $cached_results) {
2453
+					$related_model_objects = $this->get_model()->get_all_related(
2454
+						$this,
2455
+						$relation_name,
2456
+						$query_params
2457
+					);
2458
+					// if no query parameters were passed, then we got all the related model objects
2459
+					// for that relation. We can cache them then.
2460
+					foreach ($related_model_objects as $related_model_object) {
2461
+						$this->cache($relation_name, $related_model_object);
2462
+					}
2463
+				} else {
2464
+					$related_model_objects = $cached_results;
2465
+				}
2466
+			}
2467
+		} else {
2468
+			// this doesn't exist in the DB, so just get the related things from the cache
2469
+			$related_model_objects = $this->get_all_from_cache($relation_name);
2470
+		}
2471
+		return $related_model_objects;
2472
+	}
2473
+
2474
+
2475
+	/**
2476
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2477
+	 * unless otherwise specified in the $query_params
2478
+	 *
2479
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2480
+	 * @param array  $query_params   @see
2481
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2482
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2483
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2484
+	 *                               that by the setting $distinct to TRUE;
2485
+	 * @return int
2486
+	 * @throws ReflectionException
2487
+	 * @throws InvalidArgumentException
2488
+	 * @throws InvalidInterfaceException
2489
+	 * @throws InvalidDataTypeException
2490
+	 * @throws EE_Error
2491
+	 */
2492
+	public function count_related($relation_name, $query_params = [], $field_to_count = null, $distinct = false)
2493
+	{
2494
+		return $this->get_model()->count_related(
2495
+			$this,
2496
+			$relation_name,
2497
+			$query_params,
2498
+			$field_to_count,
2499
+			$distinct
2500
+		);
2501
+	}
2502
+
2503
+
2504
+	/**
2505
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2506
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2507
+	 *
2508
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2509
+	 * @param array  $query_params  @see
2510
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2511
+	 * @param string $field_to_sum  name of field to count by.
2512
+	 *                              By default, uses primary key
2513
+	 *                              (which doesn't make much sense, so you should probably change it)
2514
+	 * @return int
2515
+	 * @throws ReflectionException
2516
+	 * @throws InvalidArgumentException
2517
+	 * @throws InvalidInterfaceException
2518
+	 * @throws InvalidDataTypeException
2519
+	 * @throws EE_Error
2520
+	 */
2521
+	public function sum_related($relation_name, $query_params = [], $field_to_sum = null)
2522
+	{
2523
+		return $this->get_model()->sum_related(
2524
+			$this,
2525
+			$relation_name,
2526
+			$query_params,
2527
+			$field_to_sum
2528
+		);
2529
+	}
2530
+
2531
+
2532
+	/**
2533
+	 * Gets the first (ie, one) related model object of the specified type.
2534
+	 *
2535
+	 * @param string $relation_name key in the model's _model_relations array
2536
+	 * @param array  $query_params  @see
2537
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2538
+	 * @return EE_Base_Class (not an array, a single object)
2539
+	 * @throws ReflectionException
2540
+	 * @throws InvalidArgumentException
2541
+	 * @throws InvalidInterfaceException
2542
+	 * @throws InvalidDataTypeException
2543
+	 * @throws EE_Error
2544
+	 */
2545
+	public function get_first_related($relation_name, $query_params = [])
2546
+	{
2547
+		$model = $this->get_model();
2548
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2549
+			// if they've provided some query parameters, don't bother trying to cache the result
2550
+			// also make sure we're not caching the result of get_first_related
2551
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2552
+			if (
2553
+				$query_params
2554
+				|| ! $model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation
2555
+			) {
2556
+				$related_model_object = $model->get_first_related(
2557
+					$this,
2558
+					$relation_name,
2559
+					$query_params
2560
+				);
2561
+			} else {
2562
+				// first, check if we've already cached the result of this query
2563
+				$cached_result = $this->get_one_from_cache($relation_name);
2564
+				if (! $cached_result) {
2565
+					$related_model_object = $model->get_first_related(
2566
+						$this,
2567
+						$relation_name,
2568
+						$query_params
2569
+					);
2570
+					$this->cache($relation_name, $related_model_object);
2571
+				} else {
2572
+					$related_model_object = $cached_result;
2573
+				}
2574
+			}
2575
+		} else {
2576
+			$related_model_object = null;
2577
+			// this doesn't exist in the Db,
2578
+			// but maybe the relation is of type belongs to, and so the related thing might
2579
+			if ($model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation) {
2580
+				$related_model_object = $model->get_first_related(
2581
+					$this,
2582
+					$relation_name,
2583
+					$query_params
2584
+				);
2585
+			}
2586
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2587
+			// just get what's cached on this object
2588
+			if (! $related_model_object) {
2589
+				$related_model_object = $this->get_one_from_cache($relation_name);
2590
+			}
2591
+		}
2592
+		return $related_model_object;
2593
+	}
2594
+
2595
+
2596
+	/**
2597
+	 * Does a delete on all related objects of type $relation_name and removes
2598
+	 * the current model object's relation to them. If they can't be deleted (because
2599
+	 * of blocking related model objects) does nothing. If the related model objects are
2600
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2601
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2602
+	 *
2603
+	 * @param string $relation_name
2604
+	 * @param array  $query_params @see
2605
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2606
+	 * @return int how many deleted
2607
+	 * @throws ReflectionException
2608
+	 * @throws InvalidArgumentException
2609
+	 * @throws InvalidInterfaceException
2610
+	 * @throws InvalidDataTypeException
2611
+	 * @throws EE_Error
2612
+	 */
2613
+	public function delete_related($relation_name, $query_params = [])
2614
+	{
2615
+		if ($this->ID()) {
2616
+			$count = $this->get_model()->delete_related(
2617
+				$this,
2618
+				$relation_name,
2619
+				$query_params
2620
+			);
2621
+		} else {
2622
+			$count = count($this->get_all_from_cache($relation_name));
2623
+			$this->clear_cache($relation_name, null, true);
2624
+		}
2625
+		return $count;
2626
+	}
2627
+
2628
+
2629
+	/**
2630
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relation_name and removes
2631
+	 * the current model object's relation to them. If they can't be deleted (because
2632
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2633
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2634
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2635
+	 *
2636
+	 * @param string $relation_name
2637
+	 * @param array  $query_params @see
2638
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2639
+	 * @return int how many deleted (including those soft deleted)
2640
+	 * @throws ReflectionException
2641
+	 * @throws InvalidArgumentException
2642
+	 * @throws InvalidInterfaceException
2643
+	 * @throws InvalidDataTypeException
2644
+	 * @throws EE_Error
2645
+	 */
2646
+	public function delete_related_permanently($relation_name, $query_params = [])
2647
+	{
2648
+		$count = $this->ID()
2649
+			? $this->get_model()->delete_related_permanently(
2650
+				$this,
2651
+				$relation_name,
2652
+				$query_params
2653
+			)
2654
+			: count($this->get_all_from_cache($relation_name));
2655
+
2656
+		$this->clear_cache($relation_name, null, true);
2657
+		return $count;
2658
+	}
2659
+
2660
+
2661
+	/**
2662
+	 * is_set
2663
+	 * Just a simple utility function children can use for checking if property exists
2664
+	 *
2665
+	 * @access  public
2666
+	 * @param string $field_name property to check
2667
+	 * @return bool                              TRUE if existing,FALSE if not.
2668
+	 */
2669
+	public function is_set($field_name)
2670
+	{
2671
+		return isset($this->_fields[ $field_name ]);
2672
+	}
2673
+
2674
+
2675
+	/**
2676
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2677
+	 * EE_Error exception if they don't
2678
+	 *
2679
+	 * @param mixed (string|array) $properties properties to check
2680
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2681
+	 * @throws EE_Error
2682
+	 */
2683
+	protected function _property_exists($properties)
2684
+	{
2685
+		foreach ((array) $properties as $property_name) {
2686
+			// first make sure this property exists
2687
+			if (! $this->_fields[ $property_name ]) {
2688
+				throw new EE_Error(
2689
+					sprintf(
2690
+						esc_html__(
2691
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2692
+							'event_espresso'
2693
+						),
2694
+						$property_name
2695
+					)
2696
+				);
2697
+			}
2698
+		}
2699
+		return true;
2700
+	}
2701
+
2702
+
2703
+	/**
2704
+	 * This simply returns an array of model fields for this object
2705
+	 *
2706
+	 * @return array
2707
+	 * @throws ReflectionException
2708
+	 * @throws InvalidArgumentException
2709
+	 * @throws InvalidInterfaceException
2710
+	 * @throws InvalidDataTypeException
2711
+	 * @throws EE_Error
2712
+	 */
2713
+	public function model_field_array()
2714
+	{
2715
+		$fields     = $this->get_model()->field_settings(false);
2716
+		$properties = [];
2717
+		// remove prepended underscore
2718
+		foreach ($fields as $field_name => $settings) {
2719
+			$properties[ $field_name ] = $this->get($field_name);
2720
+		}
2721
+		return $properties;
2722
+	}
2723
+
2724
+
2725
+	/**
2726
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2727
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2728
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2729
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2730
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2731
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2732
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2733
+	 * and accepts 2 arguments: the object on which the function was called,
2734
+	 * and an array of the original arguments passed to the function.
2735
+	 * Whatever their callback function returns will be returned by this function.
2736
+	 * Example: in functions.php (or in a plugin):
2737
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2738
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2739
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2740
+	 *          return $previousReturnValue.$returnString;
2741
+	 *      }
2742
+	 * require('EE_Answer.class.php');
2743
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2744
+	 *      ->my_callback('monkeys',100);
2745
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2746
+	 *
2747
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2748
+	 * @param array  $args       array of original arguments passed to the function
2749
+	 * @return mixed whatever the plugin which calls add_filter decides
2750
+	 * @throws EE_Error
2751
+	 */
2752
+	public function __call($methodName, $args)
2753
+	{
2754
+		$className = get_class($this);
2755
+		$tagName   = "FHEE__{$className}__{$methodName}";
2756
+		if (! has_filter($tagName)) {
2757
+			throw new EE_Error(
2758
+				sprintf(
2759
+					esc_html__(
2760
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2761
+						'event_espresso'
2762
+					),
2763
+					$methodName,
2764
+					$className,
2765
+					$tagName
2766
+				)
2767
+			);
2768
+		}
2769
+		return apply_filters($tagName, null, $this, $args);
2770
+	}
2771
+
2772
+
2773
+	/**
2774
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2775
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2776
+	 *
2777
+	 * @param string $meta_key
2778
+	 * @param mixed  $meta_value
2779
+	 * @param mixed  $previous_value
2780
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2781
+	 *                  NOTE: if the values haven't changed, returns 0
2782
+	 * @throws InvalidArgumentException
2783
+	 * @throws InvalidInterfaceException
2784
+	 * @throws InvalidDataTypeException
2785
+	 * @throws EE_Error
2786
+	 * @throws ReflectionException
2787
+	 */
2788
+	public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2789
+	{
2790
+		$query_params = [
2791
+			[
2792
+				'EXM_key'  => $meta_key,
2793
+				'OBJ_ID'   => $this->ID(),
2794
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2795
+			],
2796
+		];
2797
+		if ($previous_value !== null) {
2798
+			$query_params[0]['EXM_value'] = $meta_value;
2799
+		}
2800
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2801
+		if (! $existing_rows_like_that) {
2802
+			return $this->add_extra_meta($meta_key, $meta_value);
2803
+		}
2804
+		foreach ($existing_rows_like_that as $existing_row) {
2805
+			$existing_row->save(['EXM_value' => $meta_value]);
2806
+		}
2807
+		return count($existing_rows_like_that);
2808
+	}
2809
+
2810
+
2811
+	/**
2812
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2813
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2814
+	 * extra meta row was entered, false if not
2815
+	 *
2816
+	 * @param string $meta_key
2817
+	 * @param mixed  $meta_value
2818
+	 * @param bool   $unique
2819
+	 * @return bool
2820
+	 * @throws InvalidArgumentException
2821
+	 * @throws InvalidInterfaceException
2822
+	 * @throws InvalidDataTypeException
2823
+	 * @throws EE_Error
2824
+	 * @throws ReflectionException
2825
+	 */
2826
+	public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2827
+	{
2828
+		if ($unique) {
2829
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2830
+				[
2831
+					[
2832
+						'EXM_key'  => $meta_key,
2833
+						'OBJ_ID'   => $this->ID(),
2834
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2835
+					],
2836
+				]
2837
+			);
2838
+			if ($existing_extra_meta) {
2839
+				return false;
2840
+			}
2841
+		}
2842
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2843
+			[
2844
+				'EXM_key'   => $meta_key,
2845
+				'EXM_value' => $meta_value,
2846
+				'OBJ_ID'    => $this->ID(),
2847
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2848
+			]
2849
+		);
2850
+		$new_extra_meta->save();
2851
+		return true;
2852
+	}
2853
+
2854
+
2855
+	/**
2856
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2857
+	 * is specified, only deletes extra meta records with that value.
2858
+	 *
2859
+	 * @param string $meta_key
2860
+	 * @param mixed  $meta_value
2861
+	 * @return int|bool number of extra meta rows deleted
2862
+	 * @throws InvalidArgumentException
2863
+	 * @throws InvalidInterfaceException
2864
+	 * @throws InvalidDataTypeException
2865
+	 * @throws EE_Error
2866
+	 * @throws ReflectionException
2867
+	 */
2868
+	public function delete_extra_meta(string $meta_key, $meta_value = null)
2869
+	{
2870
+		$query_params = [
2871
+			[
2872
+				'EXM_key'  => $meta_key,
2873
+				'OBJ_ID'   => $this->ID(),
2874
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2875
+			],
2876
+		];
2877
+		if ($meta_value !== null) {
2878
+			$query_params[0]['EXM_value'] = $meta_value;
2879
+		}
2880
+		return EEM_Extra_Meta::instance()->delete($query_params);
2881
+	}
2882
+
2883
+
2884
+	/**
2885
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2886
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2887
+	 * You can specify $default is case you haven't found the extra meta
2888
+	 *
2889
+	 * @param string     $meta_key
2890
+	 * @param bool       $single
2891
+	 * @param mixed      $default if we don't find anything, what should we return?
2892
+	 * @param array|null $extra_where
2893
+	 * @return mixed single value if $single; array if ! $single
2894
+	 * @throws ReflectionException
2895
+	 * @throws EE_Error
2896
+	 */
2897
+	public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2898
+	{
2899
+		$query_params = [$extra_where + ['EXM_key' => $meta_key]];
2900
+		if ($single) {
2901
+			$result = $this->get_first_related('Extra_Meta', $query_params);
2902
+			if ($result instanceof EE_Extra_Meta) {
2903
+				return $result->value();
2904
+			}
2905
+		} else {
2906
+			$results = $this->get_many_related('Extra_Meta', $query_params);
2907
+			if ($results) {
2908
+				$values = [];
2909
+				foreach ($results as $result) {
2910
+					if ($result instanceof EE_Extra_Meta) {
2911
+						$values[ $result->ID() ] = $result->value();
2912
+					}
2913
+				}
2914
+				return $values;
2915
+			}
2916
+		}
2917
+		// if nothing discovered yet return default.
2918
+		return apply_filters(
2919
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2920
+			$default,
2921
+			$meta_key,
2922
+			$single,
2923
+			$this
2924
+		);
2925
+	}
2926
+
2927
+
2928
+	/**
2929
+	 * Returns a simple array of all the extra meta associated with this model object.
2930
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2931
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2932
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2933
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2934
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2935
+	 * finally the extra meta's value as each sub-value. (eg
2936
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2937
+	 *
2938
+	 * @param bool $one_of_each_key
2939
+	 * @return array
2940
+	 * @throws ReflectionException
2941
+	 * @throws InvalidArgumentException
2942
+	 * @throws InvalidInterfaceException
2943
+	 * @throws InvalidDataTypeException
2944
+	 * @throws EE_Error
2945
+	 */
2946
+	public function all_extra_meta_array(bool $one_of_each_key = true): array
2947
+	{
2948
+		$return_array = [];
2949
+		if ($one_of_each_key) {
2950
+			$extra_meta_objs = $this->get_many_related(
2951
+				'Extra_Meta',
2952
+				['group_by' => 'EXM_key']
2953
+			);
2954
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2955
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2956
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2957
+				}
2958
+			}
2959
+		} else {
2960
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2961
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2962
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2963
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2964
+						$return_array[ $extra_meta_obj->key() ] = [];
2965
+					}
2966
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2967
+				}
2968
+			}
2969
+		}
2970
+		return $return_array;
2971
+	}
2972
+
2973
+
2974
+	/**
2975
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2976
+	 *
2977
+	 * @return string
2978
+	 * @throws ReflectionException
2979
+	 * @throws InvalidArgumentException
2980
+	 * @throws InvalidInterfaceException
2981
+	 * @throws InvalidDataTypeException
2982
+	 * @throws EE_Error
2983
+	 */
2984
+	public function name()
2985
+	{
2986
+		// find a field that's not a text field
2987
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2988
+		if ($field_we_can_use) {
2989
+			return $this->get($field_we_can_use->get_name());
2990
+		}
2991
+		$first_few_properties = $this->model_field_array();
2992
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
2993
+		$name_parts           = [];
2994
+		foreach ($first_few_properties as $name => $value) {
2995
+			$name_parts[] = "$name:$value";
2996
+		}
2997
+		return implode(',', $name_parts);
2998
+	}
2999
+
3000
+
3001
+	/**
3002
+	 * in_entity_map
3003
+	 * Checks if this model object has been proven to already be in the entity map
3004
+	 *
3005
+	 * @return boolean
3006
+	 * @throws ReflectionException
3007
+	 * @throws InvalidArgumentException
3008
+	 * @throws InvalidInterfaceException
3009
+	 * @throws InvalidDataTypeException
3010
+	 * @throws EE_Error
3011
+	 */
3012
+	public function in_entity_map()
3013
+	{
3014
+		// well, if we looked, did we find it in the entity map?
3015
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3016
+	}
3017
+
3018
+
3019
+	/**
3020
+	 * refresh_from_db
3021
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3022
+	 *
3023
+	 * @throws ReflectionException
3024
+	 * @throws InvalidArgumentException
3025
+	 * @throws InvalidInterfaceException
3026
+	 * @throws InvalidDataTypeException
3027
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3028
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3029
+	 */
3030
+	public function refresh_from_db()
3031
+	{
3032
+		if ($this->ID() && $this->in_entity_map()) {
3033
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3034
+		} else {
3035
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3036
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3037
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3038
+			// absolutely nothing in it for this ID
3039
+			if (WP_DEBUG) {
3040
+				throw new EE_Error(
3041
+					sprintf(
3042
+						esc_html__(
3043
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3044
+							'event_espresso'
3045
+						),
3046
+						$this->ID(),
3047
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3048
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3049
+					)
3050
+				);
3051
+			}
3052
+		}
3053
+	}
3054
+
3055
+
3056
+	/**
3057
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3058
+	 *
3059
+	 * @param EE_Model_Field_Base[] $fields
3060
+	 * @param string                $new_value_sql
3061
+	 *          example: 'column_name=123',
3062
+	 *          or 'column_name=column_name+1',
3063
+	 *          or 'column_name= CASE
3064
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3065
+	 *          THEN `column_name` + 5
3066
+	 *          ELSE `column_name`
3067
+	 *          END'
3068
+	 *          Also updates $field on this model object with the latest value from the database.
3069
+	 * @return bool
3070
+	 * @throws EE_Error
3071
+	 * @throws InvalidArgumentException
3072
+	 * @throws InvalidDataTypeException
3073
+	 * @throws InvalidInterfaceException
3074
+	 * @throws ReflectionException
3075
+	 * @since 4.9.80.p
3076
+	 */
3077
+	protected function updateFieldsInDB($fields, $new_value_sql)
3078
+	{
3079
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3080
+		// if it wasn't even there to start off.
3081
+		if (! $this->ID()) {
3082
+			$this->save();
3083
+		}
3084
+		global $wpdb;
3085
+		if (empty($fields)) {
3086
+			throw new InvalidArgumentException(
3087
+				esc_html__(
3088
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3089
+					'event_espresso'
3090
+				)
3091
+			);
3092
+		}
3093
+		$first_field = reset($fields);
3094
+		$table_alias = $first_field->get_table_alias();
3095
+		foreach ($fields as $field) {
3096
+			if ($table_alias !== $field->get_table_alias()) {
3097
+				throw new InvalidArgumentException(
3098
+					sprintf(
3099
+						esc_html__(
3100
+						// @codingStandardsIgnoreStart
3101
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3102
+							// @codingStandardsIgnoreEnd
3103
+							'event_espresso'
3104
+						),
3105
+						$table_alias,
3106
+						$field->get_table_alias()
3107
+					)
3108
+				);
3109
+			}
3110
+		}
3111
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3112
+		$table_obj      = $this->get_model()->get_table_obj_by_alias($table_alias);
3113
+		$table_pk_value = $this->ID();
3114
+		$table_name     = $table_obj->get_table_name();
3115
+		if ($table_obj instanceof EE_Secondary_Table) {
3116
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3117
+		} else {
3118
+			$table_pk_field_name = $table_obj->get_pk_column();
3119
+		}
3120
+
3121
+		$query  =
3122
+			"UPDATE `{$table_name}`
3123 3123
             SET "
3124
-            . $new_value_sql
3125
-            . $wpdb->prepare(
3126
-                "
3124
+			. $new_value_sql
3125
+			. $wpdb->prepare(
3126
+				"
3127 3127
             WHERE `{$table_pk_field_name}` = %d;",
3128
-                $table_pk_value
3129
-            );
3130
-        $result = $wpdb->query($query);
3131
-        foreach ($fields as $field) {
3132
-            // If it was successful, we'd like to know the new value.
3133
-            // If it failed, we'd also like to know the new value.
3134
-            $new_value = $this->get_model()->get_var(
3135
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3136
-                    $this->get_model()->get_index_primary_key_string(
3137
-                        $this->model_field_array()
3138
-                    ),
3139
-                    [
3140
-                        'default_where_conditions' => 'minimum',
3141
-                    ]
3142
-                ),
3143
-                $field->get_name()
3144
-            );
3145
-            $this->set_from_db(
3146
-                $field->get_name(),
3147
-                $new_value
3148
-            );
3149
-        }
3150
-        return (bool) $result;
3151
-    }
3152
-
3153
-
3154
-    /**
3155
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3156
-     * Does not allow negative values, however.
3157
-     *
3158
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3159
-     *                                   (positive or negative). One important gotcha: all these values must be
3160
-     *                                   on the same table (eg don't pass in one field for the posts table and
3161
-     *                                   another for the event meta table.)
3162
-     * @return bool
3163
-     * @throws EE_Error
3164
-     * @throws InvalidArgumentException
3165
-     * @throws InvalidDataTypeException
3166
-     * @throws InvalidInterfaceException
3167
-     * @throws ReflectionException
3168
-     * @since 4.9.80.p
3169
-     */
3170
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3171
-    {
3172
-        global $wpdb;
3173
-        if (empty($fields_n_quantities)) {
3174
-            // No fields to update? Well sure, we updated them to that value just fine.
3175
-            return true;
3176
-        }
3177
-        $fields             = [];
3178
-        $set_sql_statements = [];
3179
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3180
-            $field       = $this->get_model()->field_settings_for($field_name, true);
3181
-            $fields[]    = $field;
3182
-            $column_name = $field->get_table_column();
3183
-
3184
-            $abs_qty = absint($quantity);
3185
-            if ($quantity > 0) {
3186
-                // don't let the value be negative as often these fields are unsigned
3187
-                $set_sql_statements[] = $wpdb->prepare(
3188
-                    "`{$column_name}` = `{$column_name}` + %d",
3189
-                    $abs_qty
3190
-                );
3191
-            } else {
3192
-                $set_sql_statements[] = $wpdb->prepare(
3193
-                    "`{$column_name}` = CASE
3128
+				$table_pk_value
3129
+			);
3130
+		$result = $wpdb->query($query);
3131
+		foreach ($fields as $field) {
3132
+			// If it was successful, we'd like to know the new value.
3133
+			// If it failed, we'd also like to know the new value.
3134
+			$new_value = $this->get_model()->get_var(
3135
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3136
+					$this->get_model()->get_index_primary_key_string(
3137
+						$this->model_field_array()
3138
+					),
3139
+					[
3140
+						'default_where_conditions' => 'minimum',
3141
+					]
3142
+				),
3143
+				$field->get_name()
3144
+			);
3145
+			$this->set_from_db(
3146
+				$field->get_name(),
3147
+				$new_value
3148
+			);
3149
+		}
3150
+		return (bool) $result;
3151
+	}
3152
+
3153
+
3154
+	/**
3155
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3156
+	 * Does not allow negative values, however.
3157
+	 *
3158
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3159
+	 *                                   (positive or negative). One important gotcha: all these values must be
3160
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3161
+	 *                                   another for the event meta table.)
3162
+	 * @return bool
3163
+	 * @throws EE_Error
3164
+	 * @throws InvalidArgumentException
3165
+	 * @throws InvalidDataTypeException
3166
+	 * @throws InvalidInterfaceException
3167
+	 * @throws ReflectionException
3168
+	 * @since 4.9.80.p
3169
+	 */
3170
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3171
+	{
3172
+		global $wpdb;
3173
+		if (empty($fields_n_quantities)) {
3174
+			// No fields to update? Well sure, we updated them to that value just fine.
3175
+			return true;
3176
+		}
3177
+		$fields             = [];
3178
+		$set_sql_statements = [];
3179
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3180
+			$field       = $this->get_model()->field_settings_for($field_name, true);
3181
+			$fields[]    = $field;
3182
+			$column_name = $field->get_table_column();
3183
+
3184
+			$abs_qty = absint($quantity);
3185
+			if ($quantity > 0) {
3186
+				// don't let the value be negative as often these fields are unsigned
3187
+				$set_sql_statements[] = $wpdb->prepare(
3188
+					"`{$column_name}` = `{$column_name}` + %d",
3189
+					$abs_qty
3190
+				);
3191
+			} else {
3192
+				$set_sql_statements[] = $wpdb->prepare(
3193
+					"`{$column_name}` = CASE
3194 3194
                        WHEN (`{$column_name}` >= %d)
3195 3195
                        THEN `{$column_name}` - %d
3196 3196
                        ELSE 0
3197 3197
                     END",
3198
-                    $abs_qty,
3199
-                    $abs_qty
3200
-                );
3201
-            }
3202
-        }
3203
-        return $this->updateFieldsInDB(
3204
-            $fields,
3205
-            implode(', ', $set_sql_statements)
3206
-        );
3207
-    }
3208
-
3209
-
3210
-    /**
3211
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3212
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3213
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3214
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3215
-     * Otherwise returns false.
3216
-     *
3217
-     * @param string $field_name_to_bump
3218
-     * @param string $field_name_affecting_total
3219
-     * @param string $limit_field_name
3220
-     * @param int    $quantity
3221
-     * @return bool
3222
-     * @throws EE_Error
3223
-     * @throws InvalidArgumentException
3224
-     * @throws InvalidDataTypeException
3225
-     * @throws InvalidInterfaceException
3226
-     * @throws ReflectionException
3227
-     * @since 4.9.80.p
3228
-     */
3229
-    public function incrementFieldConditionallyInDb(
3230
-        $field_name_to_bump,
3231
-        $field_name_affecting_total,
3232
-        $limit_field_name,
3233
-        $quantity
3234
-    ) {
3235
-        global $wpdb;
3236
-        $field       = $this->get_model()->field_settings_for($field_name_to_bump, true);
3237
-        $column_name = $field->get_table_column();
3238
-
3239
-        $field_affecting_total  = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3240
-        $column_affecting_total = $field_affecting_total->get_table_column();
3241
-
3242
-        $limiting_field  = $this->get_model()->field_settings_for($limit_field_name, true);
3243
-        $limiting_column = $limiting_field->get_table_column();
3244
-        return $this->updateFieldsInDB(
3245
-            [$field],
3246
-            $wpdb->prepare(
3247
-                "`{$column_name}` =
3198
+					$abs_qty,
3199
+					$abs_qty
3200
+				);
3201
+			}
3202
+		}
3203
+		return $this->updateFieldsInDB(
3204
+			$fields,
3205
+			implode(', ', $set_sql_statements)
3206
+		);
3207
+	}
3208
+
3209
+
3210
+	/**
3211
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3212
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3213
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3214
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3215
+	 * Otherwise returns false.
3216
+	 *
3217
+	 * @param string $field_name_to_bump
3218
+	 * @param string $field_name_affecting_total
3219
+	 * @param string $limit_field_name
3220
+	 * @param int    $quantity
3221
+	 * @return bool
3222
+	 * @throws EE_Error
3223
+	 * @throws InvalidArgumentException
3224
+	 * @throws InvalidDataTypeException
3225
+	 * @throws InvalidInterfaceException
3226
+	 * @throws ReflectionException
3227
+	 * @since 4.9.80.p
3228
+	 */
3229
+	public function incrementFieldConditionallyInDb(
3230
+		$field_name_to_bump,
3231
+		$field_name_affecting_total,
3232
+		$limit_field_name,
3233
+		$quantity
3234
+	) {
3235
+		global $wpdb;
3236
+		$field       = $this->get_model()->field_settings_for($field_name_to_bump, true);
3237
+		$column_name = $field->get_table_column();
3238
+
3239
+		$field_affecting_total  = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3240
+		$column_affecting_total = $field_affecting_total->get_table_column();
3241
+
3242
+		$limiting_field  = $this->get_model()->field_settings_for($limit_field_name, true);
3243
+		$limiting_column = $limiting_field->get_table_column();
3244
+		return $this->updateFieldsInDB(
3245
+			[$field],
3246
+			$wpdb->prepare(
3247
+				"`{$column_name}` =
3248 3248
             CASE
3249 3249
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3250 3250
                THEN `{$column_name}` + %d
3251 3251
                ELSE `{$column_name}`
3252 3252
             END",
3253
-                $quantity,
3254
-                EE_INF_IN_DB,
3255
-                $quantity
3256
-            )
3257
-        );
3258
-    }
3259
-
3260
-
3261
-    /**
3262
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3263
-     * (probably a bad assumption they have made, oh well)
3264
-     *
3265
-     * @return string
3266
-     */
3267
-    public function __toString()
3268
-    {
3269
-        try {
3270
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3271
-        } catch (Exception $e) {
3272
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3273
-            return '';
3274
-        }
3275
-    }
3276
-
3277
-
3278
-    /**
3279
-     * Clear related model objects if they're already in the DB, because otherwise when we
3280
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3281
-     * This means if we have made changes to those related model objects, and want to unserialize
3282
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3283
-     * Instead, those related model objects should be directly serialized and stored.
3284
-     * Eg, the following won't work:
3285
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3286
-     * $att = $reg->attendee();
3287
-     * $att->set( 'ATT_fname', 'Dirk' );
3288
-     * update_option( 'my_option', serialize( $reg ) );
3289
-     * //END REQUEST
3290
-     * //START NEXT REQUEST
3291
-     * $reg = get_option( 'my_option' );
3292
-     * $reg->attendee()->save();
3293
-     * And would need to be replace with:
3294
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3295
-     * $att = $reg->attendee();
3296
-     * $att->set( 'ATT_fname', 'Dirk' );
3297
-     * update_option( 'my_option', serialize( $reg ) );
3298
-     * //END REQUEST
3299
-     * //START NEXT REQUEST
3300
-     * $att = get_option( 'my_option' );
3301
-     * $att->save();
3302
-     *
3303
-     * @return array
3304
-     * @throws ReflectionException
3305
-     * @throws InvalidArgumentException
3306
-     * @throws InvalidInterfaceException
3307
-     * @throws InvalidDataTypeException
3308
-     * @throws EE_Error
3309
-     */
3310
-    public function __sleep()
3311
-    {
3312
-        $model = $this->get_model();
3313
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3314
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3315
-                $classname = 'EE_' . $model->get_this_model_name();
3316
-                if (
3317
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3318
-                    && $this->get_one_from_cache($relation_name)->ID()
3319
-                ) {
3320
-                    $this->clear_cache(
3321
-                        $relation_name,
3322
-                        $this->get_one_from_cache($relation_name)->ID()
3323
-                    );
3324
-                }
3325
-            }
3326
-        }
3327
-        $this->_props_n_values_provided_in_constructor = [];
3328
-        $properties_to_serialize                       = get_object_vars($this);
3329
-        // don't serialize the model. It's big and that risks recursion
3330
-        unset($properties_to_serialize['_model']);
3331
-        return array_keys($properties_to_serialize);
3332
-    }
3333
-
3334
-
3335
-    /**
3336
-     * restore _props_n_values_provided_in_constructor
3337
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3338
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3339
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3340
-     */
3341
-    public function __wakeup()
3342
-    {
3343
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3344
-    }
3345
-
3346
-
3347
-    /**
3348
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3349
-     * distinct with the clone host instance are also cloned.
3350
-     */
3351
-    public function __clone()
3352
-    {
3353
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3354
-        foreach ($this->_fields as $field => $value) {
3355
-            if ($value instanceof DateTime) {
3356
-                $this->_fields[ $field ] = clone $value;
3357
-            }
3358
-        }
3359
-    }
3253
+				$quantity,
3254
+				EE_INF_IN_DB,
3255
+				$quantity
3256
+			)
3257
+		);
3258
+	}
3259
+
3260
+
3261
+	/**
3262
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3263
+	 * (probably a bad assumption they have made, oh well)
3264
+	 *
3265
+	 * @return string
3266
+	 */
3267
+	public function __toString()
3268
+	{
3269
+		try {
3270
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3271
+		} catch (Exception $e) {
3272
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3273
+			return '';
3274
+		}
3275
+	}
3276
+
3277
+
3278
+	/**
3279
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3280
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3281
+	 * This means if we have made changes to those related model objects, and want to unserialize
3282
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3283
+	 * Instead, those related model objects should be directly serialized and stored.
3284
+	 * Eg, the following won't work:
3285
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3286
+	 * $att = $reg->attendee();
3287
+	 * $att->set( 'ATT_fname', 'Dirk' );
3288
+	 * update_option( 'my_option', serialize( $reg ) );
3289
+	 * //END REQUEST
3290
+	 * //START NEXT REQUEST
3291
+	 * $reg = get_option( 'my_option' );
3292
+	 * $reg->attendee()->save();
3293
+	 * And would need to be replace with:
3294
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3295
+	 * $att = $reg->attendee();
3296
+	 * $att->set( 'ATT_fname', 'Dirk' );
3297
+	 * update_option( 'my_option', serialize( $reg ) );
3298
+	 * //END REQUEST
3299
+	 * //START NEXT REQUEST
3300
+	 * $att = get_option( 'my_option' );
3301
+	 * $att->save();
3302
+	 *
3303
+	 * @return array
3304
+	 * @throws ReflectionException
3305
+	 * @throws InvalidArgumentException
3306
+	 * @throws InvalidInterfaceException
3307
+	 * @throws InvalidDataTypeException
3308
+	 * @throws EE_Error
3309
+	 */
3310
+	public function __sleep()
3311
+	{
3312
+		$model = $this->get_model();
3313
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3314
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3315
+				$classname = 'EE_' . $model->get_this_model_name();
3316
+				if (
3317
+					$this->get_one_from_cache($relation_name) instanceof $classname
3318
+					&& $this->get_one_from_cache($relation_name)->ID()
3319
+				) {
3320
+					$this->clear_cache(
3321
+						$relation_name,
3322
+						$this->get_one_from_cache($relation_name)->ID()
3323
+					);
3324
+				}
3325
+			}
3326
+		}
3327
+		$this->_props_n_values_provided_in_constructor = [];
3328
+		$properties_to_serialize                       = get_object_vars($this);
3329
+		// don't serialize the model. It's big and that risks recursion
3330
+		unset($properties_to_serialize['_model']);
3331
+		return array_keys($properties_to_serialize);
3332
+	}
3333
+
3334
+
3335
+	/**
3336
+	 * restore _props_n_values_provided_in_constructor
3337
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3338
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3339
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3340
+	 */
3341
+	public function __wakeup()
3342
+	{
3343
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3344
+	}
3345
+
3346
+
3347
+	/**
3348
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3349
+	 * distinct with the clone host instance are also cloned.
3350
+	 */
3351
+	public function __clone()
3352
+	{
3353
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3354
+		foreach ($this->_fields as $field => $value) {
3355
+			if ($value instanceof DateTime) {
3356
+				$this->_fields[ $field ] = clone $value;
3357
+			}
3358
+		}
3359
+	}
3360 3360
 }
Please login to merge, or discard this patch.
Spacing   +116 added lines, -116 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
         $fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
134 134
         // verify client code has not passed any invalid field names
135 135
         foreach ($fieldValues as $field_name => $field_value) {
136
-            if (! isset($model_fields[ $field_name ])) {
136
+            if ( ! isset($model_fields[$field_name])) {
137 137
                 throw new EE_Error(
138 138
                     sprintf(
139 139
                         esc_html__(
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
         $date_format     = null;
152 152
         $time_format     = null;
153 153
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
154
-        if (! empty($date_formats) && is_array($date_formats)) {
154
+        if ( ! empty($date_formats) && is_array($date_formats)) {
155 155
             [$date_format, $time_format] = $date_formats;
156 156
         }
157 157
         $this->set_date_format($date_format);
@@ -162,14 +162,14 @@  discard block
 block discarded – undo
162 162
                 // client code has indicated these field values are from the database
163 163
                 $this->set_from_db(
164 164
                     $fieldName,
165
-                    $fieldValues[ $fieldName ] ?? null
165
+                    $fieldValues[$fieldName] ?? null
166 166
                 );
167 167
             } else {
168 168
                 // we're constructing a brand new instance of the model object.
169 169
                 // Generally, this means we'll need to do more field validation
170 170
                 $this->set(
171 171
                     $fieldName,
172
-                    $fieldValues[ $fieldName ] ?? null,
172
+                    $fieldValues[$fieldName] ?? null,
173 173
                     true
174 174
                 );
175 175
             }
@@ -177,15 +177,15 @@  discard block
 block discarded – undo
177 177
         // remember what values were passed to this constructor
178 178
         $this->_props_n_values_provided_in_constructor = $fieldValues;
179 179
         // remember in entity mapper
180
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
180
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
181 181
             $model->add_to_entity_map($this);
182 182
         }
183 183
         // setup all the relations
184 184
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
185 185
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
186
-                $this->_model_relations[ $relation_name ] = null;
186
+                $this->_model_relations[$relation_name] = null;
187 187
             } else {
188
-                $this->_model_relations[ $relation_name ] = [];
188
+                $this->_model_relations[$relation_name] = [];
189 189
             }
190 190
         }
191 191
         /**
@@ -237,10 +237,10 @@  discard block
 block discarded – undo
237 237
     public function get_original($field_name)
238 238
     {
239 239
         if (
240
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
240
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
241 241
             && $field_settings = $this->get_model()->field_settings_for($field_name)
242 242
         ) {
243
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
243
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
244 244
         }
245 245
         return null;
246 246
     }
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
         // then don't do anything
277 277
         if (
278 278
             ! $use_default
279
-            && $this->_fields[ $field_name ] === $field_value
279
+            && $this->_fields[$field_name] === $field_value
280 280
             && $this->ID()
281 281
         ) {
282 282
             return;
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
         $model              = $this->get_model();
285 285
         $this->_has_changes = true;
286 286
         $field_obj          = $model->field_settings_for($field_name);
287
-        if (! $field_obj instanceof EE_Model_Field_Base) {
287
+        if ( ! $field_obj instanceof EE_Model_Field_Base) {
288 288
             throw new EE_Error(
289 289
                 sprintf(
290 290
                     esc_html__(
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
             ? $field_obj->get_default_value()
308 308
             : $field_value;
309 309
 
310
-        $this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
310
+        $this->_fields[$field_name] = $field_obj->prepare_for_set($value);
311 311
 
312 312
         // if we're not in the constructor...
313 313
         // now check if what we set was a primary key
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
             } else {
370 370
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
371 371
             }
372
-            $this->_fields[ $field_name ] = $field_value;
372
+            $this->_fields[$field_name] = $field_value;
373 373
             $this->_clear_cached_property($field_name);
374 374
         }
375 375
     }
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
      */
396 396
     public function getCustomSelect($alias)
397 397
     {
398
-        return $this->custom_selection_results[ $alias ] ?? null;
398
+        return $this->custom_selection_results[$alias] ?? null;
399 399
     }
400 400
 
401 401
 
@@ -482,8 +482,8 @@  discard block
 block discarded – undo
482 482
         foreach ($model_fields as $field_name => $field_obj) {
483 483
             if ($field_obj instanceof EE_Datetime_Field) {
484 484
                 $field_obj->set_timezone($this->_timezone);
485
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
486
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
485
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
486
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
487 487
                 }
488 488
             }
489 489
         }
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
      */
542 542
     public function get_format($full = true)
543 543
     {
544
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
544
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
545 545
     }
546 546
 
547 547
 
@@ -567,11 +567,11 @@  discard block
 block discarded – undo
567 567
     public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
568 568
     {
569 569
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
570
-        if (! $object_to_cache instanceof EE_Base_Class) {
570
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
571 571
             return false;
572 572
         }
573 573
         // also get "how" the object is related, or throw an error
574
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
574
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
575 575
             throw new EE_Error(
576 576
                 sprintf(
577 577
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -585,38 +585,38 @@  discard block
 block discarded – undo
585 585
             // if it's a "belongs to" relationship, then there's only one related model object
586 586
             // eg, if this is a registration, there's only 1 attendee for it
587 587
             // so for these model objects just set it to be cached
588
-            $this->_model_relations[ $relation_name ] = $object_to_cache;
588
+            $this->_model_relations[$relation_name] = $object_to_cache;
589 589
             $return                                   = true;
590 590
         } else {
591 591
             // otherwise, this is the "many" side of a one to many relationship,
592 592
             // so we'll add the object to the array of related objects for that type.
593 593
             // eg: if this is an event, there are many registrations for that event,
594 594
             // so we cache the registrations in an array
595
-            if (! is_array($this->_model_relations[ $relation_name ])) {
595
+            if ( ! is_array($this->_model_relations[$relation_name])) {
596 596
                 // if for some reason, the cached item is a model object,
597 597
                 // then stick that in the array, otherwise start with an empty array
598
-                $this->_model_relations[ $relation_name ] =
599
-                    $this->_model_relations[ $relation_name ] instanceof EE_Base_Class
600
-                        ? [$this->_model_relations[ $relation_name ]]
598
+                $this->_model_relations[$relation_name] =
599
+                    $this->_model_relations[$relation_name] instanceof EE_Base_Class
600
+                        ? [$this->_model_relations[$relation_name]]
601 601
                         : [];
602 602
             }
603 603
             // first check for a cache_id which is normally empty
604
-            if (! empty($cache_id)) {
604
+            if ( ! empty($cache_id)) {
605 605
                 // if the cache_id exists, then it means we are purposely trying to cache this
606 606
                 // with a known key that can then be used to retrieve the object later on
607
-                $this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
607
+                $this->_model_relations[$relation_name][$cache_id] = $object_to_cache;
608 608
                 $return                                                = $cache_id;
609 609
             } elseif ($object_to_cache->ID()) {
610 610
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
611
-                $this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
611
+                $this->_model_relations[$relation_name][$object_to_cache->ID()] = $object_to_cache;
612 612
                 $return                                                             = $object_to_cache->ID();
613 613
             } else {
614 614
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
615
-                $this->_model_relations[ $relation_name ][] = $object_to_cache;
615
+                $this->_model_relations[$relation_name][] = $object_to_cache;
616 616
                 // move the internal pointer to the end of the array
617
-                end($this->_model_relations[ $relation_name ]);
617
+                end($this->_model_relations[$relation_name]);
618 618
                 // and grab the key so that we can return it
619
-                $return = key($this->_model_relations[ $relation_name ]);
619
+                $return = key($this->_model_relations[$relation_name]);
620 620
             }
621 621
         }
622 622
         return $return;
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
         $this->get_model()->field_settings_for($fieldname);
644 644
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
645 645
 
646
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
646
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
647 647
     }
648 648
 
649 649
 
@@ -672,9 +672,9 @@  discard block
 block discarded – undo
672 672
         $model = $this->get_model();
673 673
         $model->field_settings_for($fieldname);
674 674
         $cache_type = $pretty ? 'pretty' : 'standard';
675
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
676
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
677
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
675
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
676
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
677
+            return $this->_cached_properties[$fieldname][$cache_type];
678 678
         }
679 679
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
680 680
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -702,12 +702,12 @@  discard block
 block discarded – undo
702 702
         if ($field_obj instanceof EE_Datetime_Field) {
703 703
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
704 704
         }
705
-        if (! isset($this->_fields[ $fieldname ])) {
706
-            $this->_fields[ $fieldname ] = null;
705
+        if ( ! isset($this->_fields[$fieldname])) {
706
+            $this->_fields[$fieldname] = null;
707 707
         }
708 708
         return $pretty
709
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
710
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
709
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
710
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
711 711
     }
712 712
 
713 713
 
@@ -763,8 +763,8 @@  discard block
 block discarded – undo
763 763
      */
764 764
     protected function _clear_cached_property($property_name)
765 765
     {
766
-        if (isset($this->_cached_properties[ $property_name ])) {
767
-            unset($this->_cached_properties[ $property_name ]);
766
+        if (isset($this->_cached_properties[$property_name])) {
767
+            unset($this->_cached_properties[$property_name]);
768 768
         }
769 769
     }
770 770
 
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
     {
817 817
         $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
818 818
         $index_in_cache        = '';
819
-        if (! $relationship_to_model) {
819
+        if ( ! $relationship_to_model) {
820 820
             throw new EE_Error(
821 821
                 sprintf(
822 822
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -827,10 +827,10 @@  discard block
 block discarded – undo
827 827
         }
828 828
         if ($clear_all) {
829 829
             $obj_removed                              = true;
830
-            $this->_model_relations[ $relation_name ] = null;
830
+            $this->_model_relations[$relation_name] = null;
831 831
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
-            $obj_removed                              = $this->_model_relations[ $relation_name ];
833
-            $this->_model_relations[ $relation_name ] = null;
832
+            $obj_removed                              = $this->_model_relations[$relation_name];
833
+            $this->_model_relations[$relation_name] = null;
834 834
         } else {
835 835
             if (
836 836
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -838,12 +838,12 @@  discard block
 block discarded – undo
838 838
             ) {
839 839
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
840 840
                 if (
841
-                    is_array($this->_model_relations[ $relation_name ])
842
-                    && ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
841
+                    is_array($this->_model_relations[$relation_name])
842
+                    && ! isset($this->_model_relations[$relation_name][$index_in_cache])
843 843
                 ) {
844 844
                     $index_found_at = null;
845 845
                     // find this object in the array even though it has a different key
846
-                    foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
846
+                    foreach ($this->_model_relations[$relation_name] as $index => $obj) {
847 847
                         /** @noinspection TypeUnsafeComparisonInspection */
848 848
                         if (
849 849
                             $obj instanceof EE_Base_Class
@@ -877,9 +877,9 @@  discard block
 block discarded – undo
877 877
             }
878 878
             // supposedly we've found it. But it could just be that the client code
879 879
             // provided a bad index/object
880
-            if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
881
-                $obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
882
-                unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
880
+            if (isset($this->_model_relations[$relation_name][$index_in_cache])) {
881
+                $obj_removed = $this->_model_relations[$relation_name][$index_in_cache];
882
+                unset($this->_model_relations[$relation_name][$index_in_cache]);
883 883
             } else {
884 884
                 // that thing was never cached anyways.
885 885
                 $obj_removed = null;
@@ -910,7 +910,7 @@  discard block
 block discarded – undo
910 910
         $current_cache_id = ''
911 911
     ) {
912 912
         // verify that incoming object is of the correct type
913
-        $obj_class = 'EE_' . $relation_name;
913
+        $obj_class = 'EE_'.$relation_name;
914 914
         if ($newly_saved_object instanceof $obj_class) {
915 915
             /* @type EE_Base_Class $newly_saved_object */
916 916
             // now get the type of relation
@@ -918,18 +918,18 @@  discard block
 block discarded – undo
918 918
             // if this is a 1:1 relationship
919 919
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
920 920
                 // then just replace the cached object with the newly saved object
921
-                $this->_model_relations[ $relation_name ] = $newly_saved_object;
921
+                $this->_model_relations[$relation_name] = $newly_saved_object;
922 922
                 return true;
923 923
                 // or if it's some kind of sordid feral polyamorous relationship...
924 924
             }
925 925
             if (
926
-                is_array($this->_model_relations[ $relation_name ])
927
-                && isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
926
+                is_array($this->_model_relations[$relation_name])
927
+                && isset($this->_model_relations[$relation_name][$current_cache_id])
928 928
             ) {
929 929
                 // then remove the current cached item
930
-                unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
930
+                unset($this->_model_relations[$relation_name][$current_cache_id]);
931 931
                 // and cache the newly saved object using it's new ID
932
-                $this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
932
+                $this->_model_relations[$relation_name][$newly_saved_object->ID()] = $newly_saved_object;
933 933
                 return true;
934 934
             }
935 935
         }
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
      */
947 947
     public function get_one_from_cache($relation_name)
948 948
     {
949
-        $cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
949
+        $cached_array_or_object = $this->_model_relations[$relation_name] ?? null;
950 950
         if (is_array($cached_array_or_object)) {
951 951
             return array_shift($cached_array_or_object);
952 952
         }
@@ -968,7 +968,7 @@  discard block
 block discarded – undo
968 968
      */
969 969
     public function get_all_from_cache($relation_name)
970 970
     {
971
-        $objects = $this->_model_relations[ $relation_name ] ?? [];
971
+        $objects = $this->_model_relations[$relation_name] ?? [];
972 972
         // if the result is not an array, but exists, make it an array
973 973
         $objects = is_array($objects)
974 974
             ? $objects
@@ -1160,9 +1160,9 @@  discard block
 block discarded – undo
1160 1160
     public function get_raw($field_name)
1161 1161
     {
1162 1162
         $field_settings = $this->get_model()->field_settings_for($field_name);
1163
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1164
-            ? $this->_fields[ $field_name ]->format('U')
1165
-            : $this->_fields[ $field_name ];
1163
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1164
+            ? $this->_fields[$field_name]->format('U')
1165
+            : $this->_fields[$field_name];
1166 1166
     }
1167 1167
 
1168 1168
 
@@ -1184,7 +1184,7 @@  discard block
 block discarded – undo
1184 1184
     public function get_DateTime_object($field_name)
1185 1185
     {
1186 1186
         $field_settings = $this->get_model()->field_settings_for($field_name);
1187
-        if (! $field_settings instanceof EE_Datetime_Field) {
1187
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1188 1188
             EE_Error::add_error(
1189 1189
                 sprintf(
1190 1190
                     esc_html__(
@@ -1199,8 +1199,8 @@  discard block
 block discarded – undo
1199 1199
             );
1200 1200
             return false;
1201 1201
         }
1202
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1203
-            ? clone $this->_fields[ $field_name ]
1202
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1203
+            ? clone $this->_fields[$field_name]
1204 1204
             : null;
1205 1205
     }
1206 1206
 
@@ -1445,7 +1445,7 @@  discard block
 block discarded – undo
1445 1445
      */
1446 1446
     public function get_i18n_datetime(string $field_name, string $format = ''): string
1447 1447
     {
1448
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1448
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1449 1449
         return date_i18n(
1450 1450
             $format,
1451 1451
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1557,21 +1557,21 @@  discard block
 block discarded – undo
1557 1557
         $field->set_time_format($this->_tm_frmt);
1558 1558
         switch ($what) {
1559 1559
             case 'T':
1560
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1560
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_time(
1561 1561
                     $datetime_value,
1562
-                    $this->_fields[ $field_name ]
1562
+                    $this->_fields[$field_name]
1563 1563
                 );
1564 1564
                 $this->_has_changes           = true;
1565 1565
                 break;
1566 1566
             case 'D':
1567
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1567
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_date(
1568 1568
                     $datetime_value,
1569
-                    $this->_fields[ $field_name ]
1569
+                    $this->_fields[$field_name]
1570 1570
                 );
1571 1571
                 $this->_has_changes           = true;
1572 1572
                 break;
1573 1573
             case 'B':
1574
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1574
+                $this->_fields[$field_name] = $field->prepare_for_set($datetime_value);
1575 1575
                 $this->_has_changes           = true;
1576 1576
                 break;
1577 1577
         }
@@ -1614,7 +1614,7 @@  discard block
 block discarded – undo
1614 1614
         $this->set_timezone($timezone);
1615 1615
         $fn   = (array) $field_name;
1616 1616
         $args = array_merge($fn, (array) $args);
1617
-        if (! method_exists($this, $callback)) {
1617
+        if ( ! method_exists($this, $callback)) {
1618 1618
             throw new EE_Error(
1619 1619
                 sprintf(
1620 1620
                     esc_html__(
@@ -1626,7 +1626,7 @@  discard block
 block discarded – undo
1626 1626
             );
1627 1627
         }
1628 1628
         $args   = (array) $args;
1629
-        $return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1629
+        $return = $prepend.call_user_func_array([$this, $callback], $args).$append;
1630 1630
         $this->set_timezone($original_timezone);
1631 1631
         return $return;
1632 1632
     }
@@ -1741,8 +1741,8 @@  discard block
 block discarded – undo
1741 1741
     {
1742 1742
         $model = $this->get_model();
1743 1743
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1744
-            if (! empty($this->_model_relations[ $relation_name ])) {
1745
-                $related_objects = $this->_model_relations[ $relation_name ];
1744
+            if ( ! empty($this->_model_relations[$relation_name])) {
1745
+                $related_objects = $this->_model_relations[$relation_name];
1746 1746
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1747 1747
                     // this relation only stores a single model object, not an array
1748 1748
                     // but let's make it consistent
@@ -1799,7 +1799,7 @@  discard block
 block discarded – undo
1799 1799
             $this->set($column, $value);
1800 1800
         }
1801 1801
         // no changes ? then don't do anything
1802
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1802
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1803 1803
             return 0;
1804 1804
         }
1805 1805
         /**
@@ -1809,7 +1809,7 @@  discard block
 block discarded – undo
1809 1809
          * @param EE_Base_Class $model_object the model object about to be saved.
1810 1810
          */
1811 1811
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1812
-        if (! $this->allow_persist()) {
1812
+        if ( ! $this->allow_persist()) {
1813 1813
             return 0;
1814 1814
         }
1815 1815
         // now get current attribute values
@@ -1824,10 +1824,10 @@  discard block
 block discarded – undo
1824 1824
         if ($model->has_primary_key_field()) {
1825 1825
             if ($model->get_primary_key_field()->is_auto_increment()) {
1826 1826
                 // ok check if it's set, if so: update; if not, insert
1827
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1827
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1828 1828
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1829 1829
                 } else {
1830
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1830
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1831 1831
                     $results = $model->insert($save_cols_n_values);
1832 1832
                     if ($results) {
1833 1833
                         // if successful, set the primary key
@@ -1837,7 +1837,7 @@  discard block
 block discarded – undo
1837 1837
                         // will get added to the mapper before we can add this one!
1838 1838
                         // but if we just avoid using the SET method, all that headache can be avoided
1839 1839
                         $pk_field_name                   = $model->primary_key_name();
1840
-                        $this->_fields[ $pk_field_name ] = $results;
1840
+                        $this->_fields[$pk_field_name] = $results;
1841 1841
                         $this->_clear_cached_property($pk_field_name);
1842 1842
                         $model->add_to_entity_map($this);
1843 1843
                         $this->_update_cached_related_model_objs_fks();
@@ -1854,8 +1854,8 @@  discard block
 block discarded – undo
1854 1854
                                     'event_espresso'
1855 1855
                                 ),
1856 1856
                                 get_class($this),
1857
-                                get_class($model) . '::instance()->add_to_entity_map()',
1858
-                                get_class($model) . '::instance()->get_one_by_ID()',
1857
+                                get_class($model).'::instance()->add_to_entity_map()',
1858
+                                get_class($model).'::instance()->get_one_by_ID()',
1859 1859
                                 '<br />'
1860 1860
                             )
1861 1861
                         );
@@ -1879,7 +1879,7 @@  discard block
 block discarded – undo
1879 1879
                     $save_cols_n_values,
1880 1880
                     $model->get_combined_primary_key_fields()
1881 1881
                 );
1882
-                $results                     = $model->update(
1882
+                $results = $model->update(
1883 1883
                     $save_cols_n_values,
1884 1884
                     $combined_pk_fields_n_values
1885 1885
                 );
@@ -1957,27 +1957,27 @@  discard block
 block discarded – undo
1957 1957
     public function save_new_cached_related_model_objs()
1958 1958
     {
1959 1959
         // make sure this has been saved
1960
-        if (! $this->ID()) {
1960
+        if ( ! $this->ID()) {
1961 1961
             $id = $this->save();
1962 1962
         } else {
1963 1963
             $id = $this->ID();
1964 1964
         }
1965 1965
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1966 1966
         foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1967
-            if ($this->_model_relations[ $relation_name ]) {
1967
+            if ($this->_model_relations[$relation_name]) {
1968 1968
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1969 1969
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1970 1970
                 /* @var $related_model_obj EE_Base_Class */
1971 1971
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
1972 1972
                     // add a relation to that relation type (which saves the appropriate thing in the process)
1973 1973
                     // but ONLY if it DOES NOT exist in the DB
1974
-                    $related_model_obj = $this->_model_relations[ $relation_name ];
1974
+                    $related_model_obj = $this->_model_relations[$relation_name];
1975 1975
                     // if( ! $related_model_obj->ID()){
1976 1976
                     $this->_add_relation_to($related_model_obj, $relation_name);
1977 1977
                     $related_model_obj->save_new_cached_related_model_objs();
1978 1978
                     // }
1979 1979
                 } else {
1980
-                    foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1980
+                    foreach ($this->_model_relations[$relation_name] as $related_model_obj) {
1981 1981
                         // add a relation to that relation type (which saves the appropriate thing in the process)
1982 1982
                         // but ONLY if it DOES NOT exist in the DB
1983 1983
                         // if( ! $related_model_obj->ID()){
@@ -2004,7 +2004,7 @@  discard block
 block discarded – undo
2004 2004
      */
2005 2005
     public function get_model()
2006 2006
     {
2007
-        if (! $this->_model) {
2007
+        if ( ! $this->_model) {
2008 2008
             $modelName    = self::_get_model_classname(get_class($this));
2009 2009
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2010 2010
         } else {
@@ -2030,9 +2030,9 @@  discard block
 block discarded – undo
2030 2030
         $primary_id_ref = self::_get_primary_key_name($classname);
2031 2031
         if (
2032 2032
             array_key_exists($primary_id_ref, $props_n_values)
2033
-            && ! empty($props_n_values[ $primary_id_ref ])
2033
+            && ! empty($props_n_values[$primary_id_ref])
2034 2034
         ) {
2035
-            $id = $props_n_values[ $primary_id_ref ];
2035
+            $id = $props_n_values[$primary_id_ref];
2036 2036
             return self::_get_model($classname)->get_from_entity_map($id);
2037 2037
         }
2038 2038
         return false;
@@ -2065,10 +2065,10 @@  discard block
 block discarded – undo
2065 2065
             $primary_id_ref = self::_get_primary_key_name($classname);
2066 2066
             if (
2067 2067
                 array_key_exists($primary_id_ref, $props_n_values)
2068
-                && ! empty($props_n_values[ $primary_id_ref ])
2068
+                && ! empty($props_n_values[$primary_id_ref])
2069 2069
             ) {
2070 2070
                 $existing = $model->get_one_by_ID(
2071
-                    $props_n_values[ $primary_id_ref ]
2071
+                    $props_n_values[$primary_id_ref]
2072 2072
                 );
2073 2073
             }
2074 2074
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
         }
2081 2081
         if ($existing) {
2082 2082
             // set date formats if present before setting values
2083
-            if (! empty($date_formats) && is_array($date_formats)) {
2083
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2084 2084
                 $existing->set_date_format($date_formats[0]);
2085 2085
                 $existing->set_time_format($date_formats[1]);
2086 2086
             } else {
@@ -2113,7 +2113,7 @@  discard block
 block discarded – undo
2113 2113
     protected static function _get_model($classname, $timezone = '')
2114 2114
     {
2115 2115
         // find model for this class
2116
-        if (! $classname) {
2116
+        if ( ! $classname) {
2117 2117
             throw new EE_Error(
2118 2118
                 sprintf(
2119 2119
                     esc_html__(
@@ -2161,7 +2161,7 @@  discard block
 block discarded – undo
2161 2161
     {
2162 2162
         return strpos((string) $model_name, 'EE_') === 0
2163 2163
             ? str_replace('EE_', 'EEM_', $model_name)
2164
-            : 'EEM_' . $model_name;
2164
+            : 'EEM_'.$model_name;
2165 2165
     }
2166 2166
 
2167 2167
 
@@ -2178,7 +2178,7 @@  discard block
 block discarded – undo
2178 2178
      */
2179 2179
     protected static function _get_primary_key_name($classname = null)
2180 2180
     {
2181
-        if (! $classname) {
2181
+        if ( ! $classname) {
2182 2182
             throw new EE_Error(
2183 2183
                 sprintf(
2184 2184
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2208,7 +2208,7 @@  discard block
 block discarded – undo
2208 2208
         $model = $this->get_model();
2209 2209
         // now that we know the name of the variable, use a variable variable to get its value and return its
2210 2210
         if ($model->has_primary_key_field()) {
2211
-            return $this->_fields[ $model->primary_key_name() ];
2211
+            return $this->_fields[$model->primary_key_name()];
2212 2212
         }
2213 2213
         return $model->get_index_primary_key_string($this->_fields);
2214 2214
     }
@@ -2282,7 +2282,7 @@  discard block
 block discarded – undo
2282 2282
             }
2283 2283
         } else {
2284 2284
             // this thing doesn't exist in the DB,  so just cache it
2285
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2285
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2286 2286
                 throw new EE_Error(
2287 2287
                     sprintf(
2288 2288
                         esc_html__(
@@ -2449,7 +2449,7 @@  discard block
 block discarded – undo
2449 2449
             } else {
2450 2450
                 // did we already cache the result of this query?
2451 2451
                 $cached_results = $this->get_all_from_cache($relation_name);
2452
-                if (! $cached_results) {
2452
+                if ( ! $cached_results) {
2453 2453
                     $related_model_objects = $this->get_model()->get_all_related(
2454 2454
                         $this,
2455 2455
                         $relation_name,
@@ -2561,7 +2561,7 @@  discard block
 block discarded – undo
2561 2561
             } else {
2562 2562
                 // first, check if we've already cached the result of this query
2563 2563
                 $cached_result = $this->get_one_from_cache($relation_name);
2564
-                if (! $cached_result) {
2564
+                if ( ! $cached_result) {
2565 2565
                     $related_model_object = $model->get_first_related(
2566 2566
                         $this,
2567 2567
                         $relation_name,
@@ -2585,7 +2585,7 @@  discard block
 block discarded – undo
2585 2585
             }
2586 2586
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2587 2587
             // just get what's cached on this object
2588
-            if (! $related_model_object) {
2588
+            if ( ! $related_model_object) {
2589 2589
                 $related_model_object = $this->get_one_from_cache($relation_name);
2590 2590
             }
2591 2591
         }
@@ -2668,7 +2668,7 @@  discard block
 block discarded – undo
2668 2668
      */
2669 2669
     public function is_set($field_name)
2670 2670
     {
2671
-        return isset($this->_fields[ $field_name ]);
2671
+        return isset($this->_fields[$field_name]);
2672 2672
     }
2673 2673
 
2674 2674
 
@@ -2684,7 +2684,7 @@  discard block
 block discarded – undo
2684 2684
     {
2685 2685
         foreach ((array) $properties as $property_name) {
2686 2686
             // first make sure this property exists
2687
-            if (! $this->_fields[ $property_name ]) {
2687
+            if ( ! $this->_fields[$property_name]) {
2688 2688
                 throw new EE_Error(
2689 2689
                     sprintf(
2690 2690
                         esc_html__(
@@ -2716,7 +2716,7 @@  discard block
 block discarded – undo
2716 2716
         $properties = [];
2717 2717
         // remove prepended underscore
2718 2718
         foreach ($fields as $field_name => $settings) {
2719
-            $properties[ $field_name ] = $this->get($field_name);
2719
+            $properties[$field_name] = $this->get($field_name);
2720 2720
         }
2721 2721
         return $properties;
2722 2722
     }
@@ -2753,7 +2753,7 @@  discard block
 block discarded – undo
2753 2753
     {
2754 2754
         $className = get_class($this);
2755 2755
         $tagName   = "FHEE__{$className}__{$methodName}";
2756
-        if (! has_filter($tagName)) {
2756
+        if ( ! has_filter($tagName)) {
2757 2757
             throw new EE_Error(
2758 2758
                 sprintf(
2759 2759
                     esc_html__(
@@ -2798,7 +2798,7 @@  discard block
 block discarded – undo
2798 2798
             $query_params[0]['EXM_value'] = $meta_value;
2799 2799
         }
2800 2800
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2801
-        if (! $existing_rows_like_that) {
2801
+        if ( ! $existing_rows_like_that) {
2802 2802
             return $this->add_extra_meta($meta_key, $meta_value);
2803 2803
         }
2804 2804
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2908,7 +2908,7 @@  discard block
 block discarded – undo
2908 2908
                 $values = [];
2909 2909
                 foreach ($results as $result) {
2910 2910
                     if ($result instanceof EE_Extra_Meta) {
2911
-                        $values[ $result->ID() ] = $result->value();
2911
+                        $values[$result->ID()] = $result->value();
2912 2912
                     }
2913 2913
                 }
2914 2914
                 return $values;
@@ -2953,17 +2953,17 @@  discard block
 block discarded – undo
2953 2953
             );
2954 2954
             foreach ($extra_meta_objs as $extra_meta_obj) {
2955 2955
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2956
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2956
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2957 2957
                 }
2958 2958
             }
2959 2959
         } else {
2960 2960
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2961 2961
             foreach ($extra_meta_objs as $extra_meta_obj) {
2962 2962
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2963
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2964
-                        $return_array[ $extra_meta_obj->key() ] = [];
2963
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2964
+                        $return_array[$extra_meta_obj->key()] = [];
2965 2965
                     }
2966
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2966
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2967 2967
                 }
2968 2968
             }
2969 2969
         }
@@ -3044,8 +3044,8 @@  discard block
 block discarded – undo
3044 3044
                             'event_espresso'
3045 3045
                         ),
3046 3046
                         $this->ID(),
3047
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3048
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3047
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3048
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3049 3049
                     )
3050 3050
                 );
3051 3051
             }
@@ -3078,7 +3078,7 @@  discard block
 block discarded – undo
3078 3078
     {
3079 3079
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3080 3080
         // if it wasn't even there to start off.
3081
-        if (! $this->ID()) {
3081
+        if ( ! $this->ID()) {
3082 3082
             $this->save();
3083 3083
         }
3084 3084
         global $wpdb;
@@ -3118,7 +3118,7 @@  discard block
 block discarded – undo
3118 3118
             $table_pk_field_name = $table_obj->get_pk_column();
3119 3119
         }
3120 3120
 
3121
-        $query  =
3121
+        $query =
3122 3122
             "UPDATE `{$table_name}`
3123 3123
             SET "
3124 3124
             . $new_value_sql
@@ -3312,7 +3312,7 @@  discard block
 block discarded – undo
3312 3312
         $model = $this->get_model();
3313 3313
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3314 3314
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3315
-                $classname = 'EE_' . $model->get_this_model_name();
3315
+                $classname = 'EE_'.$model->get_this_model_name();
3316 3316
                 if (
3317 3317
                     $this->get_one_from_cache($relation_name) instanceof $classname
3318 3318
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3353,7 +3353,7 @@  discard block
 block discarded – undo
3353 3353
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3354 3354
         foreach ($this->_fields as $field => $value) {
3355 3355
             if ($value instanceof DateTime) {
3356
-                $this->_fields[ $field ] = clone $value;
3356
+                $this->_fields[$field] = clone $value;
3357 3357
             }
3358 3358
         }
3359 3359
     }
Please login to merge, or discard this patch.
core/db_classes/EE_Line_Item.class.php 2 patches
Indentation   +1657 added lines, -1657 removed lines patch added patch discarded remove patch
@@ -15,1661 +15,1661 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Line_Item extends EE_Base_Class
17 17
 {
18
-    /**
19
-     * for children line items (currently not a normal relation)
20
-     *
21
-     * @type EE_Line_Item[]
22
-     */
23
-    protected $_children = [];
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 = [], $timezone = '', $date_formats = [])
52
-    {
53
-        $has_object = parent::_check_for_object(
54
-            $props_n_values,
55
-            __CLASS__,
56
-            $timezone,
57
-            $date_formats
58
-        );
59
-        return $has_object ?: new self($props_n_values, false, $timezone);
60
-    }
61
-
62
-
63
-    /**
64
-     * @param array  $props_n_values  incoming values from the database
65
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
66
-     *                                the website will be used.
67
-     * @return EE_Line_Item
68
-     * @throws EE_Error
69
-     * @throws InvalidArgumentException
70
-     * @throws InvalidDataTypeException
71
-     * @throws InvalidInterfaceException
72
-     * @throws ReflectionException
73
-     */
74
-    public static function new_instance_from_db($props_n_values = [], $timezone = '')
75
-    {
76
-        return new self($props_n_values, true, $timezone);
77
-    }
78
-
79
-
80
-    /**
81
-     * Adds some defaults if they're not specified
82
-     *
83
-     * @param array  $fieldValues
84
-     * @param bool   $bydb
85
-     * @param string $timezone
86
-     * @throws EE_Error
87
-     * @throws InvalidArgumentException
88
-     * @throws InvalidDataTypeException
89
-     * @throws InvalidInterfaceException
90
-     * @throws ReflectionException
91
-     */
92
-    protected function __construct($fieldValues = [], $bydb = false, $timezone = '')
93
-    {
94
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
95
-        parent::__construct($fieldValues, $bydb, $timezone);
96
-        if (! $this->get('LIN_code')) {
97
-            $this->set_code($this->generate_code());
98
-        }
99
-    }
100
-
101
-
102
-    public function __wakeup()
103
-    {
104
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
105
-        parent::__wakeup();
106
-    }
107
-
108
-
109
-    /**
110
-     * Gets ID
111
-     *
112
-     * @return int
113
-     * @throws EE_Error
114
-     * @throws InvalidArgumentException
115
-     * @throws InvalidDataTypeException
116
-     * @throws InvalidInterfaceException
117
-     * @throws ReflectionException
118
-     */
119
-    public function ID()
120
-    {
121
-        return $this->get('LIN_ID');
122
-    }
123
-
124
-
125
-    /**
126
-     * Gets TXN_ID
127
-     *
128
-     * @return int
129
-     * @throws EE_Error
130
-     * @throws InvalidArgumentException
131
-     * @throws InvalidDataTypeException
132
-     * @throws InvalidInterfaceException
133
-     * @throws ReflectionException
134
-     */
135
-    public function TXN_ID()
136
-    {
137
-        return $this->get('TXN_ID');
138
-    }
139
-
140
-
141
-    /**
142
-     * Sets TXN_ID
143
-     *
144
-     * @param int $TXN_ID
145
-     * @throws EE_Error
146
-     * @throws InvalidArgumentException
147
-     * @throws InvalidDataTypeException
148
-     * @throws InvalidInterfaceException
149
-     * @throws ReflectionException
150
-     */
151
-    public function set_TXN_ID($TXN_ID)
152
-    {
153
-        $this->set('TXN_ID', $TXN_ID);
154
-    }
155
-
156
-
157
-    /**
158
-     * Gets name
159
-     *
160
-     * @return string
161
-     * @throws EE_Error
162
-     * @throws InvalidArgumentException
163
-     * @throws InvalidDataTypeException
164
-     * @throws InvalidInterfaceException
165
-     * @throws ReflectionException
166
-     */
167
-    public function name()
168
-    {
169
-        $name = $this->get('LIN_name');
170
-        if (! $name) {
171
-            $name = ucwords(str_replace('-', ' ', $this->type()));
172
-        }
173
-        return $name;
174
-    }
175
-
176
-
177
-    /**
178
-     * Sets name
179
-     *
180
-     * @param string $name
181
-     * @throws EE_Error
182
-     * @throws InvalidArgumentException
183
-     * @throws InvalidDataTypeException
184
-     * @throws InvalidInterfaceException
185
-     * @throws ReflectionException
186
-     */
187
-    public function set_name($name)
188
-    {
189
-        $this->set('LIN_name', $name);
190
-    }
191
-
192
-
193
-    /**
194
-     * Gets desc
195
-     *
196
-     * @return string
197
-     * @throws EE_Error
198
-     * @throws InvalidArgumentException
199
-     * @throws InvalidDataTypeException
200
-     * @throws InvalidInterfaceException
201
-     * @throws ReflectionException
202
-     */
203
-    public function desc()
204
-    {
205
-        return $this->get('LIN_desc');
206
-    }
207
-
208
-
209
-    /**
210
-     * Sets desc
211
-     *
212
-     * @param string $desc
213
-     * @throws EE_Error
214
-     * @throws InvalidArgumentException
215
-     * @throws InvalidDataTypeException
216
-     * @throws InvalidInterfaceException
217
-     * @throws ReflectionException
218
-     */
219
-    public function set_desc($desc)
220
-    {
221
-        $this->set('LIN_desc', $desc);
222
-    }
223
-
224
-
225
-    /**
226
-     * Gets quantity
227
-     *
228
-     * @return int
229
-     * @throws EE_Error
230
-     * @throws InvalidArgumentException
231
-     * @throws InvalidDataTypeException
232
-     * @throws InvalidInterfaceException
233
-     * @throws ReflectionException
234
-     */
235
-    public function quantity(): int
236
-    {
237
-        return (int) $this->get('LIN_quantity');
238
-    }
239
-
240
-
241
-    /**
242
-     * Sets quantity
243
-     *
244
-     * @param int $quantity
245
-     * @throws EE_Error
246
-     * @throws InvalidArgumentException
247
-     * @throws InvalidDataTypeException
248
-     * @throws InvalidInterfaceException
249
-     * @throws ReflectionException
250
-     */
251
-    public function set_quantity($quantity)
252
-    {
253
-        $this->set('LIN_quantity', max($quantity, 0));
254
-    }
255
-
256
-
257
-    /**
258
-     * Gets item_id
259
-     *
260
-     * @return int
261
-     * @throws EE_Error
262
-     * @throws InvalidArgumentException
263
-     * @throws InvalidDataTypeException
264
-     * @throws InvalidInterfaceException
265
-     * @throws ReflectionException
266
-     */
267
-    public function OBJ_ID(): int
268
-    {
269
-        return (int) $this->get('OBJ_ID');
270
-    }
271
-
272
-
273
-    /**
274
-     * Sets item_id
275
-     *
276
-     * @param int $item_id
277
-     * @throws EE_Error
278
-     * @throws InvalidArgumentException
279
-     * @throws InvalidDataTypeException
280
-     * @throws InvalidInterfaceException
281
-     * @throws ReflectionException
282
-     */
283
-    public function set_OBJ_ID($item_id)
284
-    {
285
-        $this->set('OBJ_ID', $item_id);
286
-    }
287
-
288
-
289
-    /**
290
-     * Gets item_type
291
-     *
292
-     * @return string
293
-     * @throws EE_Error
294
-     * @throws InvalidArgumentException
295
-     * @throws InvalidDataTypeException
296
-     * @throws InvalidInterfaceException
297
-     * @throws ReflectionException
298
-     */
299
-    public function OBJ_type()
300
-    {
301
-        return $this->get('OBJ_type');
302
-    }
303
-
304
-
305
-    /**
306
-     * Gets item_type
307
-     *
308
-     * @return string
309
-     * @throws EE_Error
310
-     * @throws InvalidArgumentException
311
-     * @throws InvalidDataTypeException
312
-     * @throws InvalidInterfaceException
313
-     * @throws ReflectionException
314
-     */
315
-    public function OBJ_type_i18n()
316
-    {
317
-        $obj_type = $this->OBJ_type();
318
-        switch ($obj_type) {
319
-            case EEM_Line_Item::OBJ_TYPE_EVENT:
320
-                $obj_type = esc_html__('Event', 'event_espresso');
321
-                break;
322
-            case EEM_Line_Item::OBJ_TYPE_PRICE:
323
-                $obj_type = esc_html__('Price', 'event_espresso');
324
-                break;
325
-            case EEM_Line_Item::OBJ_TYPE_PROMOTION:
326
-                $obj_type = esc_html__('Promotion', 'event_espresso');
327
-                break;
328
-            case EEM_Line_Item::OBJ_TYPE_TICKET:
329
-                $obj_type = esc_html__('Ticket', 'event_espresso');
330
-                break;
331
-            case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
332
-                $obj_type = esc_html__('Transaction', 'event_espresso');
333
-                break;
334
-        }
335
-        return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
336
-    }
337
-
338
-
339
-    /**
340
-     * Sets item_type
341
-     *
342
-     * @param string $OBJ_type
343
-     * @throws EE_Error
344
-     * @throws InvalidArgumentException
345
-     * @throws InvalidDataTypeException
346
-     * @throws InvalidInterfaceException
347
-     * @throws ReflectionException
348
-     */
349
-    public function set_OBJ_type($OBJ_type)
350
-    {
351
-        $this->set('OBJ_type', $OBJ_type);
352
-    }
353
-
354
-
355
-    /**
356
-     * Gets unit_price
357
-     *
358
-     * @return float
359
-     * @throws EE_Error
360
-     * @throws InvalidArgumentException
361
-     * @throws InvalidDataTypeException
362
-     * @throws InvalidInterfaceException
363
-     * @throws ReflectionException
364
-     */
365
-    public function unit_price()
366
-    {
367
-        return $this->get('LIN_unit_price');
368
-    }
369
-
370
-
371
-    /**
372
-     * Sets unit_price
373
-     *
374
-     * @param float $unit_price
375
-     * @throws EE_Error
376
-     * @throws InvalidArgumentException
377
-     * @throws InvalidDataTypeException
378
-     * @throws InvalidInterfaceException
379
-     * @throws ReflectionException
380
-     */
381
-    public function set_unit_price($unit_price)
382
-    {
383
-        $this->set('LIN_unit_price', $unit_price);
384
-    }
385
-
386
-
387
-    /**
388
-     * Checks if this item is a percentage modifier or not
389
-     *
390
-     * @return boolean
391
-     * @throws EE_Error
392
-     * @throws InvalidArgumentException
393
-     * @throws InvalidDataTypeException
394
-     * @throws InvalidInterfaceException
395
-     * @throws ReflectionException
396
-     */
397
-    public function is_percent()
398
-    {
399
-        if ($this->is_tax_sub_total()) {
400
-            // tax subtotals HAVE a percent on them, that percentage only applies
401
-            // to taxable items, so its' an exception. Treat it like a flat line item
402
-            return false;
403
-        }
404
-        $unit_price = abs($this->get('LIN_unit_price'));
405
-        $percent    = abs($this->get('LIN_percent'));
406
-        if ($unit_price < .001 && $percent) {
407
-            return true;
408
-        }
409
-        if ($unit_price >= .001 && ! $percent) {
410
-            return false;
411
-        }
412
-        if ($unit_price >= .001 && $percent) {
413
-            throw new EE_Error(
414
-                sprintf(
415
-                    esc_html__(
416
-                        'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
417
-                        'event_espresso'
418
-                    ),
419
-                    $unit_price,
420
-                    $percent
421
-                )
422
-            );
423
-        }
424
-        // if they're both 0, assume its not a percent item
425
-        return false;
426
-    }
427
-
428
-
429
-    /**
430
-     * Gets percent (between 100-.001)
431
-     *
432
-     * @return float
433
-     * @throws EE_Error
434
-     * @throws InvalidArgumentException
435
-     * @throws InvalidDataTypeException
436
-     * @throws InvalidInterfaceException
437
-     * @throws ReflectionException
438
-     */
439
-    public function percent()
440
-    {
441
-        return $this->get('LIN_percent');
442
-    }
443
-
444
-
445
-    /**
446
-     * @return string
447
-     * @throws EE_Error
448
-     * @throws ReflectionException
449
-     * @since 5.0.0.p
450
-     */
451
-    public function prettyPercent(): string
452
-    {
453
-        return $this->get_pretty('LIN_percent');
454
-    }
455
-
456
-
457
-    /**
458
-     * Sets percent (between 100-0.01)
459
-     *
460
-     * @param float $percent
461
-     * @throws EE_Error
462
-     * @throws InvalidArgumentException
463
-     * @throws InvalidDataTypeException
464
-     * @throws InvalidInterfaceException
465
-     * @throws ReflectionException
466
-     */
467
-    public function set_percent($percent)
468
-    {
469
-        $this->set('LIN_percent', $percent);
470
-    }
471
-
472
-
473
-    /**
474
-     * Gets total
475
-     *
476
-     * @return float
477
-     * @throws EE_Error
478
-     * @throws InvalidArgumentException
479
-     * @throws InvalidDataTypeException
480
-     * @throws InvalidInterfaceException
481
-     * @throws ReflectionException
482
-     */
483
-    public function pretaxTotal(): float
484
-    {
485
-        return (float) $this->get('LIN_pretax');
486
-    }
487
-
488
-
489
-    /**
490
-     * Sets total
491
-     *
492
-     * @param float $pretax_total
493
-     * @throws EE_Error
494
-     * @throws InvalidArgumentException
495
-     * @throws InvalidDataTypeException
496
-     * @throws InvalidInterfaceException
497
-     * @throws ReflectionException
498
-     */
499
-    public function setPretaxTotal(float $pretax_total)
500
-    {
501
-        $this->set('LIN_pretax', $pretax_total);
502
-    }
503
-
504
-
505
-    /**
506
-     * @return float
507
-     * @throws EE_Error
508
-     * @throws ReflectionException
509
-     * @since  5.0.0.p
510
-     */
511
-    public function totalWithTax(): float
512
-    {
513
-        return (float) $this->get('LIN_total');
514
-    }
515
-
516
-
517
-    /**
518
-     * Sets total
519
-     *
520
-     * @param float $total
521
-     * @throws EE_Error
522
-     * @throws ReflectionException
523
-     * @since  5.0.0.p
524
-     */
525
-    public function setTotalWithTax(float $total)
526
-    {
527
-        $this->set('LIN_total', $total);
528
-    }
529
-
530
-
531
-    /**
532
-     * Gets total
533
-     *
534
-     * @return float
535
-     * @throws EE_Error
536
-     * @throws ReflectionException
537
-     * @deprecatd 5.0.0.p
538
-     */
539
-    public function total(): float
540
-    {
541
-        return $this->totalWithTax();
542
-    }
543
-
544
-
545
-    /**
546
-     * Sets total
547
-     *
548
-     * @param float $total
549
-     * @throws EE_Error
550
-     * @throws ReflectionException
551
-     * @deprecatd 5.0.0.p
552
-     */
553
-    public function set_total($total)
554
-    {
555
-        $this->setTotalWithTax($total);
556
-    }
557
-
558
-
559
-    /**
560
-     * Gets order
561
-     *
562
-     * @return int
563
-     * @throws EE_Error
564
-     * @throws InvalidArgumentException
565
-     * @throws InvalidDataTypeException
566
-     * @throws InvalidInterfaceException
567
-     * @throws ReflectionException
568
-     */
569
-    public function order()
570
-    {
571
-        return $this->get('LIN_order');
572
-    }
573
-
574
-
575
-    /**
576
-     * Sets order
577
-     *
578
-     * @param int $order
579
-     * @throws EE_Error
580
-     * @throws InvalidArgumentException
581
-     * @throws InvalidDataTypeException
582
-     * @throws InvalidInterfaceException
583
-     * @throws ReflectionException
584
-     */
585
-    public function set_order($order)
586
-    {
587
-        $this->set('LIN_order', $order);
588
-    }
589
-
590
-
591
-    /**
592
-     * Gets parent
593
-     *
594
-     * @return int
595
-     * @throws EE_Error
596
-     * @throws InvalidArgumentException
597
-     * @throws InvalidDataTypeException
598
-     * @throws InvalidInterfaceException
599
-     * @throws ReflectionException
600
-     */
601
-    public function parent_ID()
602
-    {
603
-        return $this->get('LIN_parent');
604
-    }
605
-
606
-
607
-    /**
608
-     * Sets parent
609
-     *
610
-     * @param int $parent
611
-     * @throws EE_Error
612
-     * @throws InvalidArgumentException
613
-     * @throws InvalidDataTypeException
614
-     * @throws InvalidInterfaceException
615
-     * @throws ReflectionException
616
-     */
617
-    public function set_parent_ID($parent)
618
-    {
619
-        $this->set('LIN_parent', $parent);
620
-    }
621
-
622
-
623
-    /**
624
-     * Gets type
625
-     *
626
-     * @return string
627
-     * @throws EE_Error
628
-     * @throws InvalidArgumentException
629
-     * @throws InvalidDataTypeException
630
-     * @throws InvalidInterfaceException
631
-     * @throws ReflectionException
632
-     */
633
-    public function type()
634
-    {
635
-        return $this->get('LIN_type');
636
-    }
637
-
638
-
639
-    /**
640
-     * Sets type
641
-     *
642
-     * @param string $type
643
-     * @throws EE_Error
644
-     * @throws InvalidArgumentException
645
-     * @throws InvalidDataTypeException
646
-     * @throws InvalidInterfaceException
647
-     * @throws ReflectionException
648
-     */
649
-    public function set_type($type)
650
-    {
651
-        $this->set('LIN_type', $type);
652
-    }
653
-
654
-
655
-    /**
656
-     * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
657
-     * 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
658
-     * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
659
-     * or indirectly by `EE_Line_item::add_child_line_item()`)
660
-     *
661
-     * @return EE_Base_Class|EE_Line_Item
662
-     * @throws EE_Error
663
-     * @throws InvalidArgumentException
664
-     * @throws InvalidDataTypeException
665
-     * @throws InvalidInterfaceException
666
-     * @throws ReflectionException
667
-     */
668
-    public function parent()
669
-    {
670
-        return $this->ID()
671
-            ? $this->get_model()->get_one_by_ID($this->parent_ID())
672
-            : $this->_parent;
673
-    }
674
-
675
-
676
-    /**
677
-     * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
678
-     *
679
-     * @return EE_Line_Item[]
680
-     * @throws EE_Error
681
-     * @throws InvalidArgumentException
682
-     * @throws InvalidDataTypeException
683
-     * @throws InvalidInterfaceException
684
-     * @throws ReflectionException
685
-     */
686
-    public function children(array $query_params = []): array
687
-    {
688
-        if ($this->ID()) {
689
-            // ensure where params are an array
690
-            $query_params[0] = $query_params[0] ?? [];
691
-            // add defaults for line item parent and orderby
692
-            $query_params[0] += ['LIN_parent' => $this->ID()];
693
-            $query_params    += ['order_by' => ['LIN_order' => 'ASC']];
694
-            return $this->get_model()->get_all($query_params);
695
-        }
696
-        if (! is_array($this->_children)) {
697
-            $this->_children = [];
698
-        }
699
-        return $this->_children;
700
-    }
701
-
702
-
703
-    /**
704
-     * Gets code
705
-     *
706
-     * @return string
707
-     * @throws EE_Error
708
-     * @throws InvalidArgumentException
709
-     * @throws InvalidDataTypeException
710
-     * @throws InvalidInterfaceException
711
-     * @throws ReflectionException
712
-     */
713
-    public function code()
714
-    {
715
-        return $this->get('LIN_code');
716
-    }
717
-
718
-
719
-    /**
720
-     * Sets code
721
-     *
722
-     * @param string $code
723
-     * @throws EE_Error
724
-     * @throws InvalidArgumentException
725
-     * @throws InvalidDataTypeException
726
-     * @throws InvalidInterfaceException
727
-     * @throws ReflectionException
728
-     */
729
-    public function set_code($code)
730
-    {
731
-        $this->set('LIN_code', $code);
732
-    }
733
-
734
-
735
-    /**
736
-     * Gets is_taxable
737
-     *
738
-     * @return boolean
739
-     * @throws EE_Error
740
-     * @throws InvalidArgumentException
741
-     * @throws InvalidDataTypeException
742
-     * @throws InvalidInterfaceException
743
-     * @throws ReflectionException
744
-     */
745
-    public function is_taxable()
746
-    {
747
-        return $this->get('LIN_is_taxable');
748
-    }
749
-
750
-
751
-    /**
752
-     * Sets is_taxable
753
-     *
754
-     * @param boolean $is_taxable
755
-     * @throws EE_Error
756
-     * @throws InvalidArgumentException
757
-     * @throws InvalidDataTypeException
758
-     * @throws InvalidInterfaceException
759
-     * @throws ReflectionException
760
-     */
761
-    public function set_is_taxable($is_taxable)
762
-    {
763
-        $this->set('LIN_is_taxable', $is_taxable);
764
-    }
765
-
766
-
767
-    /**
768
-     * @param int $timestamp
769
-     * @throws EE_Error
770
-     * @throws ReflectionException
771
-     * @since 5.0.0.p
772
-     */
773
-    public function setTimestamp(int $timestamp)
774
-    {
775
-        $this->set('LIN_timestamp', $timestamp);
776
-    }
777
-
778
-
779
-    /**
780
-     * Gets the object that this model-joins-to.
781
-     * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
782
-     * EEM_Promotion_Object
783
-     *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
784
-     *
785
-     * @return EE_Base_Class | NULL
786
-     * @throws EE_Error
787
-     * @throws InvalidArgumentException
788
-     * @throws InvalidDataTypeException
789
-     * @throws InvalidInterfaceException
790
-     * @throws ReflectionException
791
-     */
792
-    public function get_object()
793
-    {
794
-        $model_name_of_related_obj = $this->OBJ_type();
795
-        return $this->get_model()->has_relation($model_name_of_related_obj)
796
-            ? $this->get_first_related($model_name_of_related_obj)
797
-            : null;
798
-    }
799
-
800
-
801
-    /**
802
-     * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
803
-     * (IE, if this line item is for a price or something else, will return NULL)
804
-     *
805
-     * @param array $query_params
806
-     * @return EE_Base_Class|EE_Ticket
807
-     * @throws EE_Error
808
-     * @throws InvalidArgumentException
809
-     * @throws InvalidDataTypeException
810
-     * @throws InvalidInterfaceException
811
-     * @throws ReflectionException
812
-     */
813
-    public function ticket($query_params = [])
814
-    {
815
-        // we're going to assume that when this method is called
816
-        // we always want to receive the attached ticket EVEN if that ticket is archived.
817
-        // This can be overridden via the incoming $query_params argument
818
-        $remove_defaults = ['default_where_conditions' => 'none'];
819
-        $query_params    = array_merge($remove_defaults, $query_params);
820
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
821
-    }
822
-
823
-
824
-    /**
825
-     * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
826
-     *
827
-     * @return EE_Datetime | NULL
828
-     * @throws EE_Error
829
-     * @throws InvalidArgumentException
830
-     * @throws InvalidDataTypeException
831
-     * @throws InvalidInterfaceException
832
-     * @throws ReflectionException
833
-     */
834
-    public function get_ticket_datetime()
835
-    {
836
-        if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
837
-            $ticket = $this->ticket();
838
-            if ($ticket instanceof EE_Ticket) {
839
-                $datetime = $ticket->first_datetime();
840
-                if ($datetime instanceof EE_Datetime) {
841
-                    return $datetime;
842
-                }
843
-            }
844
-        }
845
-        return null;
846
-    }
847
-
848
-
849
-    /**
850
-     * Gets the event's name that's related to the ticket, if this is for
851
-     * a ticket
852
-     *
853
-     * @return string
854
-     * @throws EE_Error
855
-     * @throws InvalidArgumentException
856
-     * @throws InvalidDataTypeException
857
-     * @throws InvalidInterfaceException
858
-     * @throws ReflectionException
859
-     */
860
-    public function ticket_event_name()
861
-    {
862
-        $event_name = esc_html__('Unknown', 'event_espresso');
863
-        $event      = $this->ticket_event();
864
-        if ($event instanceof EE_Event) {
865
-            $event_name = $event->name();
866
-        }
867
-        return $event_name;
868
-    }
869
-
870
-
871
-    /**
872
-     * Gets the event that's related to the ticket, if this line item represents a ticket.
873
-     *
874
-     * @return EE_Event|null
875
-     * @throws EE_Error
876
-     * @throws InvalidArgumentException
877
-     * @throws InvalidDataTypeException
878
-     * @throws InvalidInterfaceException
879
-     * @throws ReflectionException
880
-     */
881
-    public function ticket_event()
882
-    {
883
-        $event  = null;
884
-        $ticket = $this->ticket();
885
-        if ($ticket instanceof EE_Ticket) {
886
-            $datetime = $ticket->first_datetime();
887
-            if ($datetime instanceof EE_Datetime) {
888
-                $event = $datetime->event();
889
-            }
890
-        }
891
-        return $event;
892
-    }
893
-
894
-
895
-    /**
896
-     * Gets the first datetime for this lien item, assuming it's for a ticket
897
-     *
898
-     * @param string $date_format
899
-     * @param string $time_format
900
-     * @return string
901
-     * @throws EE_Error
902
-     * @throws InvalidArgumentException
903
-     * @throws InvalidDataTypeException
904
-     * @throws InvalidInterfaceException
905
-     * @throws ReflectionException
906
-     */
907
-    public function ticket_datetime_start($date_format = '', $time_format = '')
908
-    {
909
-        $first_datetime_string = esc_html__('Unknown', 'event_espresso');
910
-        $datetime              = $this->get_ticket_datetime();
911
-        if ($datetime) {
912
-            $first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
913
-        }
914
-        return $first_datetime_string;
915
-    }
916
-
917
-
918
-    /**
919
-     * Adds the line item as a child to this line item. If there is another child line
920
-     * item with the same LIN_code, it is overwritten by this new one
921
-     *
922
-     * @param EE_Line_Item $line_item
923
-     * @param bool         $set_order
924
-     * @return bool success
925
-     * @throws EE_Error
926
-     * @throws InvalidArgumentException
927
-     * @throws InvalidDataTypeException
928
-     * @throws InvalidInterfaceException
929
-     * @throws ReflectionException
930
-     */
931
-    public function add_child_line_item(EE_Line_Item $line_item, $set_order = true)
932
-    {
933
-        // should we calculate the LIN_order for this line item ?
934
-        if ($set_order || $line_item->order() === null) {
935
-            $line_item->set_order(count($this->children()));
936
-        }
937
-        if ($this->ID()) {
938
-            // check for any duplicate line items (with the same code), if so, this replaces it
939
-            $line_item_with_same_code = $this->get_child_line_item($line_item->code());
940
-            if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
941
-                $this->delete_child_line_item($line_item_with_same_code->code());
942
-            }
943
-            $line_item->set_parent_ID($this->ID());
944
-            if ($this->TXN_ID()) {
945
-                $line_item->set_TXN_ID($this->TXN_ID());
946
-            }
947
-            return $line_item->save();
948
-        }
949
-        $this->_children[ $line_item->code() ] = $line_item;
950
-        if ($line_item->parent() !== $this) {
951
-            $line_item->set_parent($this);
952
-        }
953
-        return true;
954
-    }
955
-
956
-
957
-    /**
958
-     * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
959
-     * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
960
-     * However, if this line item is NOT saved to the DB, this just caches the parent on
961
-     * the EE_Line_Item::_parent property.
962
-     *
963
-     * @param EE_Line_Item $line_item
964
-     * @throws EE_Error
965
-     * @throws InvalidArgumentException
966
-     * @throws InvalidDataTypeException
967
-     * @throws InvalidInterfaceException
968
-     * @throws ReflectionException
969
-     */
970
-    public function set_parent($line_item)
971
-    {
972
-        if ($this->ID()) {
973
-            if (! $line_item->ID()) {
974
-                $line_item->save();
975
-            }
976
-            $this->set_parent_ID($line_item->ID());
977
-            $this->save();
978
-        } else {
979
-            $this->_parent = $line_item;
980
-            $this->set_parent_ID($line_item->ID());
981
-        }
982
-    }
983
-
984
-
985
-    /**
986
-     * Gets the child line item as specified by its code. Because this returns an object (by reference)
987
-     * you can modify this child line item and the parent (this object) can know about them
988
-     * because it also has a reference to that line item
989
-     *
990
-     * @param string $code
991
-     * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
992
-     * @throws EE_Error
993
-     * @throws InvalidArgumentException
994
-     * @throws InvalidDataTypeException
995
-     * @throws InvalidInterfaceException
996
-     * @throws ReflectionException
997
-     */
998
-    public function get_child_line_item($code)
999
-    {
1000
-        if ($this->ID()) {
1001
-            return $this->get_model()->get_one(
1002
-                [['LIN_parent' => $this->ID(), 'LIN_code' => $code]]
1003
-            );
1004
-        }
1005
-        return isset($this->_children[ $code ])
1006
-            ? $this->_children[ $code ]
1007
-            : null;
1008
-    }
1009
-
1010
-
1011
-    /**
1012
-     * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1013
-     * cached on it)
1014
-     *
1015
-     * @return int
1016
-     * @throws EE_Error
1017
-     * @throws InvalidArgumentException
1018
-     * @throws InvalidDataTypeException
1019
-     * @throws InvalidInterfaceException
1020
-     * @throws ReflectionException
1021
-     */
1022
-    public function delete_children_line_items()
1023
-    {
1024
-        if ($this->ID()) {
1025
-            return $this->get_model()->delete([['LIN_parent' => $this->ID()]]);
1026
-        }
1027
-        $count           = count($this->_children);
1028
-        $this->_children = [];
1029
-        return $count;
1030
-    }
1031
-
1032
-
1033
-    /**
1034
-     * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1035
-     * HAS NOT been saved to the DB, removes the child line item with index $code.
1036
-     * Also searches through the child's children for a matching line item. However, once a line item has been found
1037
-     * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1038
-     * deleted)
1039
-     *
1040
-     * @param string $code
1041
-     * @param bool   $stop_search_once_found
1042
-     * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1043
-     *             the DB yet)
1044
-     * @throws EE_Error
1045
-     * @throws InvalidArgumentException
1046
-     * @throws InvalidDataTypeException
1047
-     * @throws InvalidInterfaceException
1048
-     * @throws ReflectionException
1049
-     */
1050
-    public function delete_child_line_item($code, $stop_search_once_found = true)
1051
-    {
1052
-        if ($this->ID()) {
1053
-            $items_deleted = 0;
1054
-            if ($this->code() === $code) {
1055
-                $items_deleted += EEH_Line_Item::delete_all_child_items($this);
1056
-                $items_deleted += (int) $this->delete();
1057
-                if ($stop_search_once_found) {
1058
-                    return $items_deleted;
1059
-                }
1060
-            }
1061
-            foreach ($this->children() as $child_line_item) {
1062
-                $items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1063
-            }
1064
-            return $items_deleted;
1065
-        }
1066
-        if (isset($this->_children[ $code ])) {
1067
-            unset($this->_children[ $code ]);
1068
-            return 1;
1069
-        }
1070
-        return 0;
1071
-    }
1072
-
1073
-
1074
-    /**
1075
-     * If this line item is in the database, is of the type subtotal, and
1076
-     * has no children, why do we have it? It should be deleted so this function
1077
-     * does that
1078
-     *
1079
-     * @return boolean
1080
-     * @throws EE_Error
1081
-     * @throws InvalidArgumentException
1082
-     * @throws InvalidDataTypeException
1083
-     * @throws InvalidInterfaceException
1084
-     * @throws ReflectionException
1085
-     */
1086
-    public function delete_if_childless_subtotal()
1087
-    {
1088
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1089
-            return $this->delete();
1090
-        }
1091
-        return false;
1092
-    }
1093
-
1094
-
1095
-    /**
1096
-     * Creates a code and returns a string. doesn't assign the code to this model object
1097
-     *
1098
-     * @return string
1099
-     * @throws EE_Error
1100
-     * @throws InvalidArgumentException
1101
-     * @throws InvalidDataTypeException
1102
-     * @throws InvalidInterfaceException
1103
-     * @throws ReflectionException
1104
-     */
1105
-    public function generate_code()
1106
-    {
1107
-        // each line item in the cart requires a unique identifier
1108
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1109
-    }
1110
-
1111
-
1112
-    /**
1113
-     * @return bool
1114
-     * @throws EE_Error
1115
-     * @throws InvalidArgumentException
1116
-     * @throws InvalidDataTypeException
1117
-     * @throws InvalidInterfaceException
1118
-     * @throws ReflectionException
1119
-     */
1120
-    public function isGlobalTax(): bool
1121
-    {
1122
-        return $this->type() === EEM_Line_Item::type_tax;
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * @return bool
1128
-     * @throws EE_Error
1129
-     * @throws InvalidArgumentException
1130
-     * @throws InvalidDataTypeException
1131
-     * @throws InvalidInterfaceException
1132
-     * @throws ReflectionException
1133
-     */
1134
-    public function isSubTax(): bool
1135
-    {
1136
-        return $this->type() === EEM_Line_Item::type_sub_tax;
1137
-    }
1138
-
1139
-
1140
-    /**
1141
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1142
-     *
1143
-     * @return array
1144
-     * @throws EE_Error
1145
-     * @throws InvalidArgumentException
1146
-     * @throws InvalidDataTypeException
1147
-     * @throws InvalidInterfaceException
1148
-     * @throws ReflectionException
1149
-     */
1150
-    public function getSubTaxes(): array
1151
-    {
1152
-        if (! $this->is_line_item()) {
1153
-            return [];
1154
-        }
1155
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1161
-     *
1162
-     * @return bool
1163
-     * @throws EE_Error
1164
-     * @throws InvalidArgumentException
1165
-     * @throws InvalidDataTypeException
1166
-     * @throws InvalidInterfaceException
1167
-     * @throws ReflectionException
1168
-     */
1169
-    public function hasSubTaxes(): bool
1170
-    {
1171
-        if (! $this->is_line_item()) {
1172
-            return false;
1173
-        }
1174
-        $sub_taxes = $this->getSubTaxes();
1175
-        return ! empty($sub_taxes);
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * @return bool
1181
-     * @throws EE_Error
1182
-     * @throws ReflectionException
1183
-     * @deprecated   5.0.0.p
1184
-     */
1185
-    public function is_tax(): bool
1186
-    {
1187
-        return $this->isGlobalTax();
1188
-    }
1189
-
1190
-
1191
-    /**
1192
-     * @return bool
1193
-     * @throws EE_Error
1194
-     * @throws InvalidArgumentException
1195
-     * @throws InvalidDataTypeException
1196
-     * @throws InvalidInterfaceException
1197
-     * @throws ReflectionException
1198
-     */
1199
-    public function is_tax_sub_total()
1200
-    {
1201
-        return $this->type() === EEM_Line_Item::type_tax_sub_total;
1202
-    }
1203
-
1204
-
1205
-    /**
1206
-     * @return bool
1207
-     * @throws EE_Error
1208
-     * @throws InvalidArgumentException
1209
-     * @throws InvalidDataTypeException
1210
-     * @throws InvalidInterfaceException
1211
-     * @throws ReflectionException
1212
-     */
1213
-    public function is_line_item()
1214
-    {
1215
-        return $this->type() === EEM_Line_Item::type_line_item;
1216
-    }
1217
-
1218
-
1219
-    /**
1220
-     * @return bool
1221
-     * @throws EE_Error
1222
-     * @throws InvalidArgumentException
1223
-     * @throws InvalidDataTypeException
1224
-     * @throws InvalidInterfaceException
1225
-     * @throws ReflectionException
1226
-     */
1227
-    public function is_sub_line_item()
1228
-    {
1229
-        return $this->type() === EEM_Line_Item::type_sub_line_item;
1230
-    }
1231
-
1232
-
1233
-    /**
1234
-     * @return bool
1235
-     * @throws EE_Error
1236
-     * @throws InvalidArgumentException
1237
-     * @throws InvalidDataTypeException
1238
-     * @throws InvalidInterfaceException
1239
-     * @throws ReflectionException
1240
-     */
1241
-    public function is_sub_total()
1242
-    {
1243
-        return $this->type() === EEM_Line_Item::type_sub_total;
1244
-    }
1245
-
1246
-
1247
-    /**
1248
-     * Whether or not this line item is a cancellation line item
1249
-     *
1250
-     * @return boolean
1251
-     * @throws EE_Error
1252
-     * @throws InvalidArgumentException
1253
-     * @throws InvalidDataTypeException
1254
-     * @throws InvalidInterfaceException
1255
-     * @throws ReflectionException
1256
-     */
1257
-    public function is_cancellation()
1258
-    {
1259
-        return EEM_Line_Item::type_cancellation === $this->type();
1260
-    }
1261
-
1262
-
1263
-    /**
1264
-     * @return bool
1265
-     * @throws EE_Error
1266
-     * @throws InvalidArgumentException
1267
-     * @throws InvalidDataTypeException
1268
-     * @throws InvalidInterfaceException
1269
-     * @throws ReflectionException
1270
-     */
1271
-    public function is_total()
1272
-    {
1273
-        return $this->type() === EEM_Line_Item::type_total;
1274
-    }
1275
-
1276
-
1277
-    /**
1278
-     * @return bool
1279
-     * @throws EE_Error
1280
-     * @throws InvalidArgumentException
1281
-     * @throws InvalidDataTypeException
1282
-     * @throws InvalidInterfaceException
1283
-     * @throws ReflectionException
1284
-     */
1285
-    public function is_cancelled()
1286
-    {
1287
-        return $this->type() === EEM_Line_Item::type_cancellation;
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     * @return string like '2, 004.00', formatted according to the localized currency
1293
-     * @throws EE_Error
1294
-     * @throws ReflectionException
1295
-     */
1296
-    public function unit_price_no_code(): string
1297
-    {
1298
-        return $this->prettyUnitPrice();
1299
-    }
1300
-
1301
-
1302
-    /**
1303
-     * @return string like '2, 004.00', formatted according to the localized currency
1304
-     * @throws EE_Error
1305
-     * @throws ReflectionException
1306
-     * @since 5.0.0.p
1307
-     */
1308
-    public function prettyUnitPrice(): string
1309
-    {
1310
-        return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1311
-    }
1312
-
1313
-
1314
-    /**
1315
-     * @return string like '2, 004.00', formatted according to the localized currency
1316
-     * @throws EE_Error
1317
-     * @throws ReflectionException
1318
-     */
1319
-    public function total_no_code(): string
1320
-    {
1321
-        return $this->prettyTotal();
1322
-    }
1323
-
1324
-
1325
-    /**
1326
-     * @return string like '2, 004.00', formatted according to the localized currency
1327
-     * @throws EE_Error
1328
-     * @throws ReflectionException
1329
-     * @since 5.0.0.p
1330
-     */
1331
-    public function prettyTotal(): string
1332
-    {
1333
-        return $this->get_pretty('LIN_total', 'no_currency_code');
1334
-    }
1335
-
1336
-
1337
-    /**
1338
-     * Gets the final total on this item, taking taxes into account.
1339
-     * Has the side-effect of setting the sub-total as it was just calculated.
1340
-     * If this is used on a grand-total line item, also updates the transaction's
1341
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
1342
-     * want to change a persistable transaction with info from a non-persistent line item)
1343
-     *
1344
-     * @param bool $update_txn_status
1345
-     * @return float
1346
-     * @throws EE_Error
1347
-     * @throws InvalidArgumentException
1348
-     * @throws InvalidDataTypeException
1349
-     * @throws InvalidInterfaceException
1350
-     * @throws ReflectionException
1351
-     * @throws RuntimeException
1352
-     */
1353
-    public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1354
-    {
1355
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1356
-        return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1357
-    }
1358
-
1359
-
1360
-    /**
1361
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1362
-     * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1363
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1364
-     * when this is called on the grand total
1365
-     *
1366
-     * @return float
1367
-     * @throws EE_Error
1368
-     * @throws InvalidArgumentException
1369
-     * @throws InvalidDataTypeException
1370
-     * @throws InvalidInterfaceException
1371
-     * @throws ReflectionException
1372
-     */
1373
-    public function recalculate_pre_tax_total(): float
1374
-    {
1375
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1376
-        [$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1377
-        return (float) $total;
1378
-    }
1379
-
1380
-
1381
-    /**
1382
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1383
-     * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1384
-     * and tax sub-total if already in the DB
1385
-     *
1386
-     * @return float
1387
-     * @throws EE_Error
1388
-     * @throws InvalidArgumentException
1389
-     * @throws InvalidDataTypeException
1390
-     * @throws InvalidInterfaceException
1391
-     * @throws ReflectionException
1392
-     */
1393
-    public function recalculate_taxes_and_tax_total(): float
1394
-    {
1395
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1396
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1397
-    }
1398
-
1399
-
1400
-    /**
1401
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
1402
-     * recalculate_taxes_and_total
1403
-     *
1404
-     * @return float
1405
-     * @throws EE_Error
1406
-     * @throws InvalidArgumentException
1407
-     * @throws InvalidDataTypeException
1408
-     * @throws InvalidInterfaceException
1409
-     * @throws ReflectionException
1410
-     */
1411
-    public function get_total_tax()
1412
-    {
1413
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1414
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1415
-    }
1416
-
1417
-
1418
-    /**
1419
-     * Gets the total for all the items purchased only
1420
-     *
1421
-     * @return float
1422
-     * @throws EE_Error
1423
-     * @throws InvalidArgumentException
1424
-     * @throws InvalidDataTypeException
1425
-     * @throws InvalidInterfaceException
1426
-     * @throws ReflectionException
1427
-     */
1428
-    public function get_items_total()
1429
-    {
1430
-        // by default, let's make sure we're consistent with the existing line item
1431
-        if ($this->is_total()) {
1432
-            return $this->pretaxTotal();
1433
-        }
1434
-        $total = 0;
1435
-        foreach ($this->get_items() as $item) {
1436
-            if ($item instanceof EE_Line_Item) {
1437
-                $total += $item->pretaxTotal();
1438
-            }
1439
-        }
1440
-        return $total;
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * Gets all the descendants (ie, children or children of children etc) that
1446
-     * are of the type 'tax'
1447
-     *
1448
-     * @return EE_Line_Item[]
1449
-     * @throws EE_Error
1450
-     */
1451
-    public function tax_descendants()
1452
-    {
1453
-        return EEH_Line_Item::get_tax_descendants($this);
1454
-    }
1455
-
1456
-
1457
-    /**
1458
-     * Gets all the real items purchased which are children of this item
1459
-     *
1460
-     * @return EE_Line_Item[]
1461
-     * @throws EE_Error
1462
-     */
1463
-    public function get_items()
1464
-    {
1465
-        return EEH_Line_Item::get_line_item_descendants($this);
1466
-    }
1467
-
1468
-
1469
-    /**
1470
-     * Returns the amount taxable among this line item's children (or if it has no children,
1471
-     * how much of it is taxable). Does not recalculate totals or subtotals.
1472
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
1473
-     * but there is a "Taxable" discount), returns 0.
1474
-     *
1475
-     * @return float
1476
-     * @throws EE_Error
1477
-     * @throws InvalidArgumentException
1478
-     * @throws InvalidDataTypeException
1479
-     * @throws InvalidInterfaceException
1480
-     * @throws ReflectionException
1481
-     */
1482
-    public function taxable_total(): float
1483
-    {
1484
-        return $this->calculator->taxableAmountForGlobalTaxes($this);
1485
-    }
1486
-
1487
-
1488
-    /**
1489
-     * Gets the transaction for this line item
1490
-     *
1491
-     * @return EE_Base_Class|EE_Transaction
1492
-     * @throws EE_Error
1493
-     * @throws InvalidArgumentException
1494
-     * @throws InvalidDataTypeException
1495
-     * @throws InvalidInterfaceException
1496
-     * @throws ReflectionException
1497
-     */
1498
-    public function transaction()
1499
-    {
1500
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1501
-    }
1502
-
1503
-
1504
-    /**
1505
-     * Saves this line item to the DB, and recursively saves its descendants.
1506
-     * Because there currently is no proper parent-child relation on the model,
1507
-     * save_this_and_cached() will NOT save the descendants.
1508
-     * Also sets the transaction on this line item and all its descendants before saving
1509
-     *
1510
-     * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1511
-     * @return int count of items saved
1512
-     * @throws EE_Error
1513
-     * @throws InvalidArgumentException
1514
-     * @throws InvalidDataTypeException
1515
-     * @throws InvalidInterfaceException
1516
-     * @throws ReflectionException
1517
-     */
1518
-    public function save_this_and_descendants_to_txn($txn_id = null)
1519
-    {
1520
-        $count = 0;
1521
-        if (! $txn_id) {
1522
-            $txn_id = $this->TXN_ID();
1523
-        }
1524
-        $this->set_TXN_ID($txn_id);
1525
-        $children = $this->children();
1526
-        $count    += $this->save()
1527
-            ? 1
1528
-            : 0;
1529
-        foreach ($children as $child_line_item) {
1530
-            if ($child_line_item instanceof EE_Line_Item) {
1531
-                $child_line_item->set_parent_ID($this->ID());
1532
-                $count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1533
-            }
1534
-        }
1535
-        return $count;
1536
-    }
1537
-
1538
-
1539
-    /**
1540
-     * Saves this line item to the DB, and recursively saves its descendants.
1541
-     *
1542
-     * @return int count of items saved
1543
-     * @throws EE_Error
1544
-     * @throws InvalidArgumentException
1545
-     * @throws InvalidDataTypeException
1546
-     * @throws InvalidInterfaceException
1547
-     * @throws ReflectionException
1548
-     */
1549
-    public function save_this_and_descendants()
1550
-    {
1551
-        $count    = 0;
1552
-        $children = $this->children();
1553
-        $count    += $this->save()
1554
-            ? 1
1555
-            : 0;
1556
-        foreach ($children as $child_line_item) {
1557
-            if ($child_line_item instanceof EE_Line_Item) {
1558
-                $child_line_item->set_parent_ID($this->ID());
1559
-                $count += $child_line_item->save_this_and_descendants();
1560
-            }
1561
-        }
1562
-        return $count;
1563
-    }
1564
-
1565
-
1566
-    /**
1567
-     * returns the cancellation line item if this item was cancelled
1568
-     *
1569
-     * @return EE_Line_Item[]
1570
-     * @throws InvalidArgumentException
1571
-     * @throws InvalidInterfaceException
1572
-     * @throws InvalidDataTypeException
1573
-     * @throws ReflectionException
1574
-     * @throws EE_Error
1575
-     */
1576
-    public function get_cancellations()
1577
-    {
1578
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1579
-    }
1580
-
1581
-
1582
-    /**
1583
-     * If this item has an ID, then this saves it again to update the db
1584
-     *
1585
-     * @return int count of items saved
1586
-     * @throws EE_Error
1587
-     * @throws InvalidArgumentException
1588
-     * @throws InvalidDataTypeException
1589
-     * @throws InvalidInterfaceException
1590
-     * @throws ReflectionException
1591
-     */
1592
-    public function maybe_save()
1593
-    {
1594
-        if ($this->ID()) {
1595
-            return $this->save();
1596
-        }
1597
-        return false;
1598
-    }
1599
-
1600
-
1601
-    /**
1602
-     * clears the cached children and parent from the line item
1603
-     *
1604
-     * @return void
1605
-     */
1606
-    public function clear_related_line_item_cache()
1607
-    {
1608
-        $this->_children = [];
1609
-        $this->_parent   = null;
1610
-    }
1611
-
1612
-
1613
-    /**
1614
-     * @param bool $raw
1615
-     * @return int
1616
-     * @throws EE_Error
1617
-     * @throws InvalidArgumentException
1618
-     * @throws InvalidDataTypeException
1619
-     * @throws InvalidInterfaceException
1620
-     * @throws ReflectionException
1621
-     */
1622
-    public function timestamp($raw = false)
1623
-    {
1624
-        return $raw
1625
-            ? $this->get_raw('LIN_timestamp')
1626
-            : $this->get('LIN_timestamp');
1627
-    }
1628
-
1629
-
1630
-
1631
-
1632
-    /************************* DEPRECATED *************************/
1633
-    /**
1634
-     * @param string $type one of the constants on EEM_Line_Item
1635
-     * @return EE_Line_Item[]
1636
-     * @throws EE_Error
1637
-     * @deprecated 4.6.0
1638
-     */
1639
-    protected function _get_descendants_of_type($type)
1640
-    {
1641
-        EE_Error::doing_it_wrong(
1642
-            'EE_Line_Item::_get_descendants_of_type()',
1643
-            sprintf(
1644
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1645
-                'EEH_Line_Item::get_descendants_of_type()'
1646
-            ),
1647
-            '4.6.0'
1648
-        );
1649
-        return EEH_Line_Item::get_descendants_of_type($this, $type);
1650
-    }
1651
-
1652
-
1653
-    /**
1654
-     * @param string $type like one of the EEM_Line_Item::type_*
1655
-     * @return EE_Line_Item
1656
-     * @throws EE_Error
1657
-     * @throws InvalidArgumentException
1658
-     * @throws InvalidDataTypeException
1659
-     * @throws InvalidInterfaceException
1660
-     * @throws ReflectionException
1661
-     * @deprecated 4.6.0
1662
-     */
1663
-    public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1664
-    {
1665
-        EE_Error::doing_it_wrong(
1666
-            'EE_Line_Item::get_nearest_descendant_of_type()',
1667
-            sprintf(
1668
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1669
-                'EEH_Line_Item::get_nearest_descendant_of_type()'
1670
-            ),
1671
-            '4.6.0'
1672
-        );
1673
-        return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1674
-    }
18
+	/**
19
+	 * for children line items (currently not a normal relation)
20
+	 *
21
+	 * @type EE_Line_Item[]
22
+	 */
23
+	protected $_children = [];
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 = [], $timezone = '', $date_formats = [])
52
+	{
53
+		$has_object = parent::_check_for_object(
54
+			$props_n_values,
55
+			__CLASS__,
56
+			$timezone,
57
+			$date_formats
58
+		);
59
+		return $has_object ?: new self($props_n_values, false, $timezone);
60
+	}
61
+
62
+
63
+	/**
64
+	 * @param array  $props_n_values  incoming values from the database
65
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
66
+	 *                                the website will be used.
67
+	 * @return EE_Line_Item
68
+	 * @throws EE_Error
69
+	 * @throws InvalidArgumentException
70
+	 * @throws InvalidDataTypeException
71
+	 * @throws InvalidInterfaceException
72
+	 * @throws ReflectionException
73
+	 */
74
+	public static function new_instance_from_db($props_n_values = [], $timezone = '')
75
+	{
76
+		return new self($props_n_values, true, $timezone);
77
+	}
78
+
79
+
80
+	/**
81
+	 * Adds some defaults if they're not specified
82
+	 *
83
+	 * @param array  $fieldValues
84
+	 * @param bool   $bydb
85
+	 * @param string $timezone
86
+	 * @throws EE_Error
87
+	 * @throws InvalidArgumentException
88
+	 * @throws InvalidDataTypeException
89
+	 * @throws InvalidInterfaceException
90
+	 * @throws ReflectionException
91
+	 */
92
+	protected function __construct($fieldValues = [], $bydb = false, $timezone = '')
93
+	{
94
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
95
+		parent::__construct($fieldValues, $bydb, $timezone);
96
+		if (! $this->get('LIN_code')) {
97
+			$this->set_code($this->generate_code());
98
+		}
99
+	}
100
+
101
+
102
+	public function __wakeup()
103
+	{
104
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
105
+		parent::__wakeup();
106
+	}
107
+
108
+
109
+	/**
110
+	 * Gets ID
111
+	 *
112
+	 * @return int
113
+	 * @throws EE_Error
114
+	 * @throws InvalidArgumentException
115
+	 * @throws InvalidDataTypeException
116
+	 * @throws InvalidInterfaceException
117
+	 * @throws ReflectionException
118
+	 */
119
+	public function ID()
120
+	{
121
+		return $this->get('LIN_ID');
122
+	}
123
+
124
+
125
+	/**
126
+	 * Gets TXN_ID
127
+	 *
128
+	 * @return int
129
+	 * @throws EE_Error
130
+	 * @throws InvalidArgumentException
131
+	 * @throws InvalidDataTypeException
132
+	 * @throws InvalidInterfaceException
133
+	 * @throws ReflectionException
134
+	 */
135
+	public function TXN_ID()
136
+	{
137
+		return $this->get('TXN_ID');
138
+	}
139
+
140
+
141
+	/**
142
+	 * Sets TXN_ID
143
+	 *
144
+	 * @param int $TXN_ID
145
+	 * @throws EE_Error
146
+	 * @throws InvalidArgumentException
147
+	 * @throws InvalidDataTypeException
148
+	 * @throws InvalidInterfaceException
149
+	 * @throws ReflectionException
150
+	 */
151
+	public function set_TXN_ID($TXN_ID)
152
+	{
153
+		$this->set('TXN_ID', $TXN_ID);
154
+	}
155
+
156
+
157
+	/**
158
+	 * Gets name
159
+	 *
160
+	 * @return string
161
+	 * @throws EE_Error
162
+	 * @throws InvalidArgumentException
163
+	 * @throws InvalidDataTypeException
164
+	 * @throws InvalidInterfaceException
165
+	 * @throws ReflectionException
166
+	 */
167
+	public function name()
168
+	{
169
+		$name = $this->get('LIN_name');
170
+		if (! $name) {
171
+			$name = ucwords(str_replace('-', ' ', $this->type()));
172
+		}
173
+		return $name;
174
+	}
175
+
176
+
177
+	/**
178
+	 * Sets name
179
+	 *
180
+	 * @param string $name
181
+	 * @throws EE_Error
182
+	 * @throws InvalidArgumentException
183
+	 * @throws InvalidDataTypeException
184
+	 * @throws InvalidInterfaceException
185
+	 * @throws ReflectionException
186
+	 */
187
+	public function set_name($name)
188
+	{
189
+		$this->set('LIN_name', $name);
190
+	}
191
+
192
+
193
+	/**
194
+	 * Gets desc
195
+	 *
196
+	 * @return string
197
+	 * @throws EE_Error
198
+	 * @throws InvalidArgumentException
199
+	 * @throws InvalidDataTypeException
200
+	 * @throws InvalidInterfaceException
201
+	 * @throws ReflectionException
202
+	 */
203
+	public function desc()
204
+	{
205
+		return $this->get('LIN_desc');
206
+	}
207
+
208
+
209
+	/**
210
+	 * Sets desc
211
+	 *
212
+	 * @param string $desc
213
+	 * @throws EE_Error
214
+	 * @throws InvalidArgumentException
215
+	 * @throws InvalidDataTypeException
216
+	 * @throws InvalidInterfaceException
217
+	 * @throws ReflectionException
218
+	 */
219
+	public function set_desc($desc)
220
+	{
221
+		$this->set('LIN_desc', $desc);
222
+	}
223
+
224
+
225
+	/**
226
+	 * Gets quantity
227
+	 *
228
+	 * @return int
229
+	 * @throws EE_Error
230
+	 * @throws InvalidArgumentException
231
+	 * @throws InvalidDataTypeException
232
+	 * @throws InvalidInterfaceException
233
+	 * @throws ReflectionException
234
+	 */
235
+	public function quantity(): int
236
+	{
237
+		return (int) $this->get('LIN_quantity');
238
+	}
239
+
240
+
241
+	/**
242
+	 * Sets quantity
243
+	 *
244
+	 * @param int $quantity
245
+	 * @throws EE_Error
246
+	 * @throws InvalidArgumentException
247
+	 * @throws InvalidDataTypeException
248
+	 * @throws InvalidInterfaceException
249
+	 * @throws ReflectionException
250
+	 */
251
+	public function set_quantity($quantity)
252
+	{
253
+		$this->set('LIN_quantity', max($quantity, 0));
254
+	}
255
+
256
+
257
+	/**
258
+	 * Gets item_id
259
+	 *
260
+	 * @return int
261
+	 * @throws EE_Error
262
+	 * @throws InvalidArgumentException
263
+	 * @throws InvalidDataTypeException
264
+	 * @throws InvalidInterfaceException
265
+	 * @throws ReflectionException
266
+	 */
267
+	public function OBJ_ID(): int
268
+	{
269
+		return (int) $this->get('OBJ_ID');
270
+	}
271
+
272
+
273
+	/**
274
+	 * Sets item_id
275
+	 *
276
+	 * @param int $item_id
277
+	 * @throws EE_Error
278
+	 * @throws InvalidArgumentException
279
+	 * @throws InvalidDataTypeException
280
+	 * @throws InvalidInterfaceException
281
+	 * @throws ReflectionException
282
+	 */
283
+	public function set_OBJ_ID($item_id)
284
+	{
285
+		$this->set('OBJ_ID', $item_id);
286
+	}
287
+
288
+
289
+	/**
290
+	 * Gets item_type
291
+	 *
292
+	 * @return string
293
+	 * @throws EE_Error
294
+	 * @throws InvalidArgumentException
295
+	 * @throws InvalidDataTypeException
296
+	 * @throws InvalidInterfaceException
297
+	 * @throws ReflectionException
298
+	 */
299
+	public function OBJ_type()
300
+	{
301
+		return $this->get('OBJ_type');
302
+	}
303
+
304
+
305
+	/**
306
+	 * Gets item_type
307
+	 *
308
+	 * @return string
309
+	 * @throws EE_Error
310
+	 * @throws InvalidArgumentException
311
+	 * @throws InvalidDataTypeException
312
+	 * @throws InvalidInterfaceException
313
+	 * @throws ReflectionException
314
+	 */
315
+	public function OBJ_type_i18n()
316
+	{
317
+		$obj_type = $this->OBJ_type();
318
+		switch ($obj_type) {
319
+			case EEM_Line_Item::OBJ_TYPE_EVENT:
320
+				$obj_type = esc_html__('Event', 'event_espresso');
321
+				break;
322
+			case EEM_Line_Item::OBJ_TYPE_PRICE:
323
+				$obj_type = esc_html__('Price', 'event_espresso');
324
+				break;
325
+			case EEM_Line_Item::OBJ_TYPE_PROMOTION:
326
+				$obj_type = esc_html__('Promotion', 'event_espresso');
327
+				break;
328
+			case EEM_Line_Item::OBJ_TYPE_TICKET:
329
+				$obj_type = esc_html__('Ticket', 'event_espresso');
330
+				break;
331
+			case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
332
+				$obj_type = esc_html__('Transaction', 'event_espresso');
333
+				break;
334
+		}
335
+		return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
336
+	}
337
+
338
+
339
+	/**
340
+	 * Sets item_type
341
+	 *
342
+	 * @param string $OBJ_type
343
+	 * @throws EE_Error
344
+	 * @throws InvalidArgumentException
345
+	 * @throws InvalidDataTypeException
346
+	 * @throws InvalidInterfaceException
347
+	 * @throws ReflectionException
348
+	 */
349
+	public function set_OBJ_type($OBJ_type)
350
+	{
351
+		$this->set('OBJ_type', $OBJ_type);
352
+	}
353
+
354
+
355
+	/**
356
+	 * Gets unit_price
357
+	 *
358
+	 * @return float
359
+	 * @throws EE_Error
360
+	 * @throws InvalidArgumentException
361
+	 * @throws InvalidDataTypeException
362
+	 * @throws InvalidInterfaceException
363
+	 * @throws ReflectionException
364
+	 */
365
+	public function unit_price()
366
+	{
367
+		return $this->get('LIN_unit_price');
368
+	}
369
+
370
+
371
+	/**
372
+	 * Sets unit_price
373
+	 *
374
+	 * @param float $unit_price
375
+	 * @throws EE_Error
376
+	 * @throws InvalidArgumentException
377
+	 * @throws InvalidDataTypeException
378
+	 * @throws InvalidInterfaceException
379
+	 * @throws ReflectionException
380
+	 */
381
+	public function set_unit_price($unit_price)
382
+	{
383
+		$this->set('LIN_unit_price', $unit_price);
384
+	}
385
+
386
+
387
+	/**
388
+	 * Checks if this item is a percentage modifier or not
389
+	 *
390
+	 * @return boolean
391
+	 * @throws EE_Error
392
+	 * @throws InvalidArgumentException
393
+	 * @throws InvalidDataTypeException
394
+	 * @throws InvalidInterfaceException
395
+	 * @throws ReflectionException
396
+	 */
397
+	public function is_percent()
398
+	{
399
+		if ($this->is_tax_sub_total()) {
400
+			// tax subtotals HAVE a percent on them, that percentage only applies
401
+			// to taxable items, so its' an exception. Treat it like a flat line item
402
+			return false;
403
+		}
404
+		$unit_price = abs($this->get('LIN_unit_price'));
405
+		$percent    = abs($this->get('LIN_percent'));
406
+		if ($unit_price < .001 && $percent) {
407
+			return true;
408
+		}
409
+		if ($unit_price >= .001 && ! $percent) {
410
+			return false;
411
+		}
412
+		if ($unit_price >= .001 && $percent) {
413
+			throw new EE_Error(
414
+				sprintf(
415
+					esc_html__(
416
+						'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
417
+						'event_espresso'
418
+					),
419
+					$unit_price,
420
+					$percent
421
+				)
422
+			);
423
+		}
424
+		// if they're both 0, assume its not a percent item
425
+		return false;
426
+	}
427
+
428
+
429
+	/**
430
+	 * Gets percent (between 100-.001)
431
+	 *
432
+	 * @return float
433
+	 * @throws EE_Error
434
+	 * @throws InvalidArgumentException
435
+	 * @throws InvalidDataTypeException
436
+	 * @throws InvalidInterfaceException
437
+	 * @throws ReflectionException
438
+	 */
439
+	public function percent()
440
+	{
441
+		return $this->get('LIN_percent');
442
+	}
443
+
444
+
445
+	/**
446
+	 * @return string
447
+	 * @throws EE_Error
448
+	 * @throws ReflectionException
449
+	 * @since 5.0.0.p
450
+	 */
451
+	public function prettyPercent(): string
452
+	{
453
+		return $this->get_pretty('LIN_percent');
454
+	}
455
+
456
+
457
+	/**
458
+	 * Sets percent (between 100-0.01)
459
+	 *
460
+	 * @param float $percent
461
+	 * @throws EE_Error
462
+	 * @throws InvalidArgumentException
463
+	 * @throws InvalidDataTypeException
464
+	 * @throws InvalidInterfaceException
465
+	 * @throws ReflectionException
466
+	 */
467
+	public function set_percent($percent)
468
+	{
469
+		$this->set('LIN_percent', $percent);
470
+	}
471
+
472
+
473
+	/**
474
+	 * Gets total
475
+	 *
476
+	 * @return float
477
+	 * @throws EE_Error
478
+	 * @throws InvalidArgumentException
479
+	 * @throws InvalidDataTypeException
480
+	 * @throws InvalidInterfaceException
481
+	 * @throws ReflectionException
482
+	 */
483
+	public function pretaxTotal(): float
484
+	{
485
+		return (float) $this->get('LIN_pretax');
486
+	}
487
+
488
+
489
+	/**
490
+	 * Sets total
491
+	 *
492
+	 * @param float $pretax_total
493
+	 * @throws EE_Error
494
+	 * @throws InvalidArgumentException
495
+	 * @throws InvalidDataTypeException
496
+	 * @throws InvalidInterfaceException
497
+	 * @throws ReflectionException
498
+	 */
499
+	public function setPretaxTotal(float $pretax_total)
500
+	{
501
+		$this->set('LIN_pretax', $pretax_total);
502
+	}
503
+
504
+
505
+	/**
506
+	 * @return float
507
+	 * @throws EE_Error
508
+	 * @throws ReflectionException
509
+	 * @since  5.0.0.p
510
+	 */
511
+	public function totalWithTax(): float
512
+	{
513
+		return (float) $this->get('LIN_total');
514
+	}
515
+
516
+
517
+	/**
518
+	 * Sets total
519
+	 *
520
+	 * @param float $total
521
+	 * @throws EE_Error
522
+	 * @throws ReflectionException
523
+	 * @since  5.0.0.p
524
+	 */
525
+	public function setTotalWithTax(float $total)
526
+	{
527
+		$this->set('LIN_total', $total);
528
+	}
529
+
530
+
531
+	/**
532
+	 * Gets total
533
+	 *
534
+	 * @return float
535
+	 * @throws EE_Error
536
+	 * @throws ReflectionException
537
+	 * @deprecatd 5.0.0.p
538
+	 */
539
+	public function total(): float
540
+	{
541
+		return $this->totalWithTax();
542
+	}
543
+
544
+
545
+	/**
546
+	 * Sets total
547
+	 *
548
+	 * @param float $total
549
+	 * @throws EE_Error
550
+	 * @throws ReflectionException
551
+	 * @deprecatd 5.0.0.p
552
+	 */
553
+	public function set_total($total)
554
+	{
555
+		$this->setTotalWithTax($total);
556
+	}
557
+
558
+
559
+	/**
560
+	 * Gets order
561
+	 *
562
+	 * @return int
563
+	 * @throws EE_Error
564
+	 * @throws InvalidArgumentException
565
+	 * @throws InvalidDataTypeException
566
+	 * @throws InvalidInterfaceException
567
+	 * @throws ReflectionException
568
+	 */
569
+	public function order()
570
+	{
571
+		return $this->get('LIN_order');
572
+	}
573
+
574
+
575
+	/**
576
+	 * Sets order
577
+	 *
578
+	 * @param int $order
579
+	 * @throws EE_Error
580
+	 * @throws InvalidArgumentException
581
+	 * @throws InvalidDataTypeException
582
+	 * @throws InvalidInterfaceException
583
+	 * @throws ReflectionException
584
+	 */
585
+	public function set_order($order)
586
+	{
587
+		$this->set('LIN_order', $order);
588
+	}
589
+
590
+
591
+	/**
592
+	 * Gets parent
593
+	 *
594
+	 * @return int
595
+	 * @throws EE_Error
596
+	 * @throws InvalidArgumentException
597
+	 * @throws InvalidDataTypeException
598
+	 * @throws InvalidInterfaceException
599
+	 * @throws ReflectionException
600
+	 */
601
+	public function parent_ID()
602
+	{
603
+		return $this->get('LIN_parent');
604
+	}
605
+
606
+
607
+	/**
608
+	 * Sets parent
609
+	 *
610
+	 * @param int $parent
611
+	 * @throws EE_Error
612
+	 * @throws InvalidArgumentException
613
+	 * @throws InvalidDataTypeException
614
+	 * @throws InvalidInterfaceException
615
+	 * @throws ReflectionException
616
+	 */
617
+	public function set_parent_ID($parent)
618
+	{
619
+		$this->set('LIN_parent', $parent);
620
+	}
621
+
622
+
623
+	/**
624
+	 * Gets type
625
+	 *
626
+	 * @return string
627
+	 * @throws EE_Error
628
+	 * @throws InvalidArgumentException
629
+	 * @throws InvalidDataTypeException
630
+	 * @throws InvalidInterfaceException
631
+	 * @throws ReflectionException
632
+	 */
633
+	public function type()
634
+	{
635
+		return $this->get('LIN_type');
636
+	}
637
+
638
+
639
+	/**
640
+	 * Sets type
641
+	 *
642
+	 * @param string $type
643
+	 * @throws EE_Error
644
+	 * @throws InvalidArgumentException
645
+	 * @throws InvalidDataTypeException
646
+	 * @throws InvalidInterfaceException
647
+	 * @throws ReflectionException
648
+	 */
649
+	public function set_type($type)
650
+	{
651
+		$this->set('LIN_type', $type);
652
+	}
653
+
654
+
655
+	/**
656
+	 * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
657
+	 * 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
658
+	 * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
659
+	 * or indirectly by `EE_Line_item::add_child_line_item()`)
660
+	 *
661
+	 * @return EE_Base_Class|EE_Line_Item
662
+	 * @throws EE_Error
663
+	 * @throws InvalidArgumentException
664
+	 * @throws InvalidDataTypeException
665
+	 * @throws InvalidInterfaceException
666
+	 * @throws ReflectionException
667
+	 */
668
+	public function parent()
669
+	{
670
+		return $this->ID()
671
+			? $this->get_model()->get_one_by_ID($this->parent_ID())
672
+			: $this->_parent;
673
+	}
674
+
675
+
676
+	/**
677
+	 * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
678
+	 *
679
+	 * @return EE_Line_Item[]
680
+	 * @throws EE_Error
681
+	 * @throws InvalidArgumentException
682
+	 * @throws InvalidDataTypeException
683
+	 * @throws InvalidInterfaceException
684
+	 * @throws ReflectionException
685
+	 */
686
+	public function children(array $query_params = []): array
687
+	{
688
+		if ($this->ID()) {
689
+			// ensure where params are an array
690
+			$query_params[0] = $query_params[0] ?? [];
691
+			// add defaults for line item parent and orderby
692
+			$query_params[0] += ['LIN_parent' => $this->ID()];
693
+			$query_params    += ['order_by' => ['LIN_order' => 'ASC']];
694
+			return $this->get_model()->get_all($query_params);
695
+		}
696
+		if (! is_array($this->_children)) {
697
+			$this->_children = [];
698
+		}
699
+		return $this->_children;
700
+	}
701
+
702
+
703
+	/**
704
+	 * Gets code
705
+	 *
706
+	 * @return string
707
+	 * @throws EE_Error
708
+	 * @throws InvalidArgumentException
709
+	 * @throws InvalidDataTypeException
710
+	 * @throws InvalidInterfaceException
711
+	 * @throws ReflectionException
712
+	 */
713
+	public function code()
714
+	{
715
+		return $this->get('LIN_code');
716
+	}
717
+
718
+
719
+	/**
720
+	 * Sets code
721
+	 *
722
+	 * @param string $code
723
+	 * @throws EE_Error
724
+	 * @throws InvalidArgumentException
725
+	 * @throws InvalidDataTypeException
726
+	 * @throws InvalidInterfaceException
727
+	 * @throws ReflectionException
728
+	 */
729
+	public function set_code($code)
730
+	{
731
+		$this->set('LIN_code', $code);
732
+	}
733
+
734
+
735
+	/**
736
+	 * Gets is_taxable
737
+	 *
738
+	 * @return boolean
739
+	 * @throws EE_Error
740
+	 * @throws InvalidArgumentException
741
+	 * @throws InvalidDataTypeException
742
+	 * @throws InvalidInterfaceException
743
+	 * @throws ReflectionException
744
+	 */
745
+	public function is_taxable()
746
+	{
747
+		return $this->get('LIN_is_taxable');
748
+	}
749
+
750
+
751
+	/**
752
+	 * Sets is_taxable
753
+	 *
754
+	 * @param boolean $is_taxable
755
+	 * @throws EE_Error
756
+	 * @throws InvalidArgumentException
757
+	 * @throws InvalidDataTypeException
758
+	 * @throws InvalidInterfaceException
759
+	 * @throws ReflectionException
760
+	 */
761
+	public function set_is_taxable($is_taxable)
762
+	{
763
+		$this->set('LIN_is_taxable', $is_taxable);
764
+	}
765
+
766
+
767
+	/**
768
+	 * @param int $timestamp
769
+	 * @throws EE_Error
770
+	 * @throws ReflectionException
771
+	 * @since 5.0.0.p
772
+	 */
773
+	public function setTimestamp(int $timestamp)
774
+	{
775
+		$this->set('LIN_timestamp', $timestamp);
776
+	}
777
+
778
+
779
+	/**
780
+	 * Gets the object that this model-joins-to.
781
+	 * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
782
+	 * EEM_Promotion_Object
783
+	 *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
784
+	 *
785
+	 * @return EE_Base_Class | NULL
786
+	 * @throws EE_Error
787
+	 * @throws InvalidArgumentException
788
+	 * @throws InvalidDataTypeException
789
+	 * @throws InvalidInterfaceException
790
+	 * @throws ReflectionException
791
+	 */
792
+	public function get_object()
793
+	{
794
+		$model_name_of_related_obj = $this->OBJ_type();
795
+		return $this->get_model()->has_relation($model_name_of_related_obj)
796
+			? $this->get_first_related($model_name_of_related_obj)
797
+			: null;
798
+	}
799
+
800
+
801
+	/**
802
+	 * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
803
+	 * (IE, if this line item is for a price or something else, will return NULL)
804
+	 *
805
+	 * @param array $query_params
806
+	 * @return EE_Base_Class|EE_Ticket
807
+	 * @throws EE_Error
808
+	 * @throws InvalidArgumentException
809
+	 * @throws InvalidDataTypeException
810
+	 * @throws InvalidInterfaceException
811
+	 * @throws ReflectionException
812
+	 */
813
+	public function ticket($query_params = [])
814
+	{
815
+		// we're going to assume that when this method is called
816
+		// we always want to receive the attached ticket EVEN if that ticket is archived.
817
+		// This can be overridden via the incoming $query_params argument
818
+		$remove_defaults = ['default_where_conditions' => 'none'];
819
+		$query_params    = array_merge($remove_defaults, $query_params);
820
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
821
+	}
822
+
823
+
824
+	/**
825
+	 * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
826
+	 *
827
+	 * @return EE_Datetime | NULL
828
+	 * @throws EE_Error
829
+	 * @throws InvalidArgumentException
830
+	 * @throws InvalidDataTypeException
831
+	 * @throws InvalidInterfaceException
832
+	 * @throws ReflectionException
833
+	 */
834
+	public function get_ticket_datetime()
835
+	{
836
+		if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
837
+			$ticket = $this->ticket();
838
+			if ($ticket instanceof EE_Ticket) {
839
+				$datetime = $ticket->first_datetime();
840
+				if ($datetime instanceof EE_Datetime) {
841
+					return $datetime;
842
+				}
843
+			}
844
+		}
845
+		return null;
846
+	}
847
+
848
+
849
+	/**
850
+	 * Gets the event's name that's related to the ticket, if this is for
851
+	 * a ticket
852
+	 *
853
+	 * @return string
854
+	 * @throws EE_Error
855
+	 * @throws InvalidArgumentException
856
+	 * @throws InvalidDataTypeException
857
+	 * @throws InvalidInterfaceException
858
+	 * @throws ReflectionException
859
+	 */
860
+	public function ticket_event_name()
861
+	{
862
+		$event_name = esc_html__('Unknown', 'event_espresso');
863
+		$event      = $this->ticket_event();
864
+		if ($event instanceof EE_Event) {
865
+			$event_name = $event->name();
866
+		}
867
+		return $event_name;
868
+	}
869
+
870
+
871
+	/**
872
+	 * Gets the event that's related to the ticket, if this line item represents a ticket.
873
+	 *
874
+	 * @return EE_Event|null
875
+	 * @throws EE_Error
876
+	 * @throws InvalidArgumentException
877
+	 * @throws InvalidDataTypeException
878
+	 * @throws InvalidInterfaceException
879
+	 * @throws ReflectionException
880
+	 */
881
+	public function ticket_event()
882
+	{
883
+		$event  = null;
884
+		$ticket = $this->ticket();
885
+		if ($ticket instanceof EE_Ticket) {
886
+			$datetime = $ticket->first_datetime();
887
+			if ($datetime instanceof EE_Datetime) {
888
+				$event = $datetime->event();
889
+			}
890
+		}
891
+		return $event;
892
+	}
893
+
894
+
895
+	/**
896
+	 * Gets the first datetime for this lien item, assuming it's for a ticket
897
+	 *
898
+	 * @param string $date_format
899
+	 * @param string $time_format
900
+	 * @return string
901
+	 * @throws EE_Error
902
+	 * @throws InvalidArgumentException
903
+	 * @throws InvalidDataTypeException
904
+	 * @throws InvalidInterfaceException
905
+	 * @throws ReflectionException
906
+	 */
907
+	public function ticket_datetime_start($date_format = '', $time_format = '')
908
+	{
909
+		$first_datetime_string = esc_html__('Unknown', 'event_espresso');
910
+		$datetime              = $this->get_ticket_datetime();
911
+		if ($datetime) {
912
+			$first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
913
+		}
914
+		return $first_datetime_string;
915
+	}
916
+
917
+
918
+	/**
919
+	 * Adds the line item as a child to this line item. If there is another child line
920
+	 * item with the same LIN_code, it is overwritten by this new one
921
+	 *
922
+	 * @param EE_Line_Item $line_item
923
+	 * @param bool         $set_order
924
+	 * @return bool success
925
+	 * @throws EE_Error
926
+	 * @throws InvalidArgumentException
927
+	 * @throws InvalidDataTypeException
928
+	 * @throws InvalidInterfaceException
929
+	 * @throws ReflectionException
930
+	 */
931
+	public function add_child_line_item(EE_Line_Item $line_item, $set_order = true)
932
+	{
933
+		// should we calculate the LIN_order for this line item ?
934
+		if ($set_order || $line_item->order() === null) {
935
+			$line_item->set_order(count($this->children()));
936
+		}
937
+		if ($this->ID()) {
938
+			// check for any duplicate line items (with the same code), if so, this replaces it
939
+			$line_item_with_same_code = $this->get_child_line_item($line_item->code());
940
+			if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
941
+				$this->delete_child_line_item($line_item_with_same_code->code());
942
+			}
943
+			$line_item->set_parent_ID($this->ID());
944
+			if ($this->TXN_ID()) {
945
+				$line_item->set_TXN_ID($this->TXN_ID());
946
+			}
947
+			return $line_item->save();
948
+		}
949
+		$this->_children[ $line_item->code() ] = $line_item;
950
+		if ($line_item->parent() !== $this) {
951
+			$line_item->set_parent($this);
952
+		}
953
+		return true;
954
+	}
955
+
956
+
957
+	/**
958
+	 * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
959
+	 * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
960
+	 * However, if this line item is NOT saved to the DB, this just caches the parent on
961
+	 * the EE_Line_Item::_parent property.
962
+	 *
963
+	 * @param EE_Line_Item $line_item
964
+	 * @throws EE_Error
965
+	 * @throws InvalidArgumentException
966
+	 * @throws InvalidDataTypeException
967
+	 * @throws InvalidInterfaceException
968
+	 * @throws ReflectionException
969
+	 */
970
+	public function set_parent($line_item)
971
+	{
972
+		if ($this->ID()) {
973
+			if (! $line_item->ID()) {
974
+				$line_item->save();
975
+			}
976
+			$this->set_parent_ID($line_item->ID());
977
+			$this->save();
978
+		} else {
979
+			$this->_parent = $line_item;
980
+			$this->set_parent_ID($line_item->ID());
981
+		}
982
+	}
983
+
984
+
985
+	/**
986
+	 * Gets the child line item as specified by its code. Because this returns an object (by reference)
987
+	 * you can modify this child line item and the parent (this object) can know about them
988
+	 * because it also has a reference to that line item
989
+	 *
990
+	 * @param string $code
991
+	 * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
992
+	 * @throws EE_Error
993
+	 * @throws InvalidArgumentException
994
+	 * @throws InvalidDataTypeException
995
+	 * @throws InvalidInterfaceException
996
+	 * @throws ReflectionException
997
+	 */
998
+	public function get_child_line_item($code)
999
+	{
1000
+		if ($this->ID()) {
1001
+			return $this->get_model()->get_one(
1002
+				[['LIN_parent' => $this->ID(), 'LIN_code' => $code]]
1003
+			);
1004
+		}
1005
+		return isset($this->_children[ $code ])
1006
+			? $this->_children[ $code ]
1007
+			: null;
1008
+	}
1009
+
1010
+
1011
+	/**
1012
+	 * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1013
+	 * cached on it)
1014
+	 *
1015
+	 * @return int
1016
+	 * @throws EE_Error
1017
+	 * @throws InvalidArgumentException
1018
+	 * @throws InvalidDataTypeException
1019
+	 * @throws InvalidInterfaceException
1020
+	 * @throws ReflectionException
1021
+	 */
1022
+	public function delete_children_line_items()
1023
+	{
1024
+		if ($this->ID()) {
1025
+			return $this->get_model()->delete([['LIN_parent' => $this->ID()]]);
1026
+		}
1027
+		$count           = count($this->_children);
1028
+		$this->_children = [];
1029
+		return $count;
1030
+	}
1031
+
1032
+
1033
+	/**
1034
+	 * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1035
+	 * HAS NOT been saved to the DB, removes the child line item with index $code.
1036
+	 * Also searches through the child's children for a matching line item. However, once a line item has been found
1037
+	 * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1038
+	 * deleted)
1039
+	 *
1040
+	 * @param string $code
1041
+	 * @param bool   $stop_search_once_found
1042
+	 * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1043
+	 *             the DB yet)
1044
+	 * @throws EE_Error
1045
+	 * @throws InvalidArgumentException
1046
+	 * @throws InvalidDataTypeException
1047
+	 * @throws InvalidInterfaceException
1048
+	 * @throws ReflectionException
1049
+	 */
1050
+	public function delete_child_line_item($code, $stop_search_once_found = true)
1051
+	{
1052
+		if ($this->ID()) {
1053
+			$items_deleted = 0;
1054
+			if ($this->code() === $code) {
1055
+				$items_deleted += EEH_Line_Item::delete_all_child_items($this);
1056
+				$items_deleted += (int) $this->delete();
1057
+				if ($stop_search_once_found) {
1058
+					return $items_deleted;
1059
+				}
1060
+			}
1061
+			foreach ($this->children() as $child_line_item) {
1062
+				$items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1063
+			}
1064
+			return $items_deleted;
1065
+		}
1066
+		if (isset($this->_children[ $code ])) {
1067
+			unset($this->_children[ $code ]);
1068
+			return 1;
1069
+		}
1070
+		return 0;
1071
+	}
1072
+
1073
+
1074
+	/**
1075
+	 * If this line item is in the database, is of the type subtotal, and
1076
+	 * has no children, why do we have it? It should be deleted so this function
1077
+	 * does that
1078
+	 *
1079
+	 * @return boolean
1080
+	 * @throws EE_Error
1081
+	 * @throws InvalidArgumentException
1082
+	 * @throws InvalidDataTypeException
1083
+	 * @throws InvalidInterfaceException
1084
+	 * @throws ReflectionException
1085
+	 */
1086
+	public function delete_if_childless_subtotal()
1087
+	{
1088
+		if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1089
+			return $this->delete();
1090
+		}
1091
+		return false;
1092
+	}
1093
+
1094
+
1095
+	/**
1096
+	 * Creates a code and returns a string. doesn't assign the code to this model object
1097
+	 *
1098
+	 * @return string
1099
+	 * @throws EE_Error
1100
+	 * @throws InvalidArgumentException
1101
+	 * @throws InvalidDataTypeException
1102
+	 * @throws InvalidInterfaceException
1103
+	 * @throws ReflectionException
1104
+	 */
1105
+	public function generate_code()
1106
+	{
1107
+		// each line item in the cart requires a unique identifier
1108
+		return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1109
+	}
1110
+
1111
+
1112
+	/**
1113
+	 * @return bool
1114
+	 * @throws EE_Error
1115
+	 * @throws InvalidArgumentException
1116
+	 * @throws InvalidDataTypeException
1117
+	 * @throws InvalidInterfaceException
1118
+	 * @throws ReflectionException
1119
+	 */
1120
+	public function isGlobalTax(): bool
1121
+	{
1122
+		return $this->type() === EEM_Line_Item::type_tax;
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * @return bool
1128
+	 * @throws EE_Error
1129
+	 * @throws InvalidArgumentException
1130
+	 * @throws InvalidDataTypeException
1131
+	 * @throws InvalidInterfaceException
1132
+	 * @throws ReflectionException
1133
+	 */
1134
+	public function isSubTax(): bool
1135
+	{
1136
+		return $this->type() === EEM_Line_Item::type_sub_tax;
1137
+	}
1138
+
1139
+
1140
+	/**
1141
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1142
+	 *
1143
+	 * @return array
1144
+	 * @throws EE_Error
1145
+	 * @throws InvalidArgumentException
1146
+	 * @throws InvalidDataTypeException
1147
+	 * @throws InvalidInterfaceException
1148
+	 * @throws ReflectionException
1149
+	 */
1150
+	public function getSubTaxes(): array
1151
+	{
1152
+		if (! $this->is_line_item()) {
1153
+			return [];
1154
+		}
1155
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1161
+	 *
1162
+	 * @return bool
1163
+	 * @throws EE_Error
1164
+	 * @throws InvalidArgumentException
1165
+	 * @throws InvalidDataTypeException
1166
+	 * @throws InvalidInterfaceException
1167
+	 * @throws ReflectionException
1168
+	 */
1169
+	public function hasSubTaxes(): bool
1170
+	{
1171
+		if (! $this->is_line_item()) {
1172
+			return false;
1173
+		}
1174
+		$sub_taxes = $this->getSubTaxes();
1175
+		return ! empty($sub_taxes);
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * @return bool
1181
+	 * @throws EE_Error
1182
+	 * @throws ReflectionException
1183
+	 * @deprecated   5.0.0.p
1184
+	 */
1185
+	public function is_tax(): bool
1186
+	{
1187
+		return $this->isGlobalTax();
1188
+	}
1189
+
1190
+
1191
+	/**
1192
+	 * @return bool
1193
+	 * @throws EE_Error
1194
+	 * @throws InvalidArgumentException
1195
+	 * @throws InvalidDataTypeException
1196
+	 * @throws InvalidInterfaceException
1197
+	 * @throws ReflectionException
1198
+	 */
1199
+	public function is_tax_sub_total()
1200
+	{
1201
+		return $this->type() === EEM_Line_Item::type_tax_sub_total;
1202
+	}
1203
+
1204
+
1205
+	/**
1206
+	 * @return bool
1207
+	 * @throws EE_Error
1208
+	 * @throws InvalidArgumentException
1209
+	 * @throws InvalidDataTypeException
1210
+	 * @throws InvalidInterfaceException
1211
+	 * @throws ReflectionException
1212
+	 */
1213
+	public function is_line_item()
1214
+	{
1215
+		return $this->type() === EEM_Line_Item::type_line_item;
1216
+	}
1217
+
1218
+
1219
+	/**
1220
+	 * @return bool
1221
+	 * @throws EE_Error
1222
+	 * @throws InvalidArgumentException
1223
+	 * @throws InvalidDataTypeException
1224
+	 * @throws InvalidInterfaceException
1225
+	 * @throws ReflectionException
1226
+	 */
1227
+	public function is_sub_line_item()
1228
+	{
1229
+		return $this->type() === EEM_Line_Item::type_sub_line_item;
1230
+	}
1231
+
1232
+
1233
+	/**
1234
+	 * @return bool
1235
+	 * @throws EE_Error
1236
+	 * @throws InvalidArgumentException
1237
+	 * @throws InvalidDataTypeException
1238
+	 * @throws InvalidInterfaceException
1239
+	 * @throws ReflectionException
1240
+	 */
1241
+	public function is_sub_total()
1242
+	{
1243
+		return $this->type() === EEM_Line_Item::type_sub_total;
1244
+	}
1245
+
1246
+
1247
+	/**
1248
+	 * Whether or not this line item is a cancellation line item
1249
+	 *
1250
+	 * @return boolean
1251
+	 * @throws EE_Error
1252
+	 * @throws InvalidArgumentException
1253
+	 * @throws InvalidDataTypeException
1254
+	 * @throws InvalidInterfaceException
1255
+	 * @throws ReflectionException
1256
+	 */
1257
+	public function is_cancellation()
1258
+	{
1259
+		return EEM_Line_Item::type_cancellation === $this->type();
1260
+	}
1261
+
1262
+
1263
+	/**
1264
+	 * @return bool
1265
+	 * @throws EE_Error
1266
+	 * @throws InvalidArgumentException
1267
+	 * @throws InvalidDataTypeException
1268
+	 * @throws InvalidInterfaceException
1269
+	 * @throws ReflectionException
1270
+	 */
1271
+	public function is_total()
1272
+	{
1273
+		return $this->type() === EEM_Line_Item::type_total;
1274
+	}
1275
+
1276
+
1277
+	/**
1278
+	 * @return bool
1279
+	 * @throws EE_Error
1280
+	 * @throws InvalidArgumentException
1281
+	 * @throws InvalidDataTypeException
1282
+	 * @throws InvalidInterfaceException
1283
+	 * @throws ReflectionException
1284
+	 */
1285
+	public function is_cancelled()
1286
+	{
1287
+		return $this->type() === EEM_Line_Item::type_cancellation;
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 * @return string like '2, 004.00', formatted according to the localized currency
1293
+	 * @throws EE_Error
1294
+	 * @throws ReflectionException
1295
+	 */
1296
+	public function unit_price_no_code(): string
1297
+	{
1298
+		return $this->prettyUnitPrice();
1299
+	}
1300
+
1301
+
1302
+	/**
1303
+	 * @return string like '2, 004.00', formatted according to the localized currency
1304
+	 * @throws EE_Error
1305
+	 * @throws ReflectionException
1306
+	 * @since 5.0.0.p
1307
+	 */
1308
+	public function prettyUnitPrice(): string
1309
+	{
1310
+		return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1311
+	}
1312
+
1313
+
1314
+	/**
1315
+	 * @return string like '2, 004.00', formatted according to the localized currency
1316
+	 * @throws EE_Error
1317
+	 * @throws ReflectionException
1318
+	 */
1319
+	public function total_no_code(): string
1320
+	{
1321
+		return $this->prettyTotal();
1322
+	}
1323
+
1324
+
1325
+	/**
1326
+	 * @return string like '2, 004.00', formatted according to the localized currency
1327
+	 * @throws EE_Error
1328
+	 * @throws ReflectionException
1329
+	 * @since 5.0.0.p
1330
+	 */
1331
+	public function prettyTotal(): string
1332
+	{
1333
+		return $this->get_pretty('LIN_total', 'no_currency_code');
1334
+	}
1335
+
1336
+
1337
+	/**
1338
+	 * Gets the final total on this item, taking taxes into account.
1339
+	 * Has the side-effect of setting the sub-total as it was just calculated.
1340
+	 * If this is used on a grand-total line item, also updates the transaction's
1341
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
1342
+	 * want to change a persistable transaction with info from a non-persistent line item)
1343
+	 *
1344
+	 * @param bool $update_txn_status
1345
+	 * @return float
1346
+	 * @throws EE_Error
1347
+	 * @throws InvalidArgumentException
1348
+	 * @throws InvalidDataTypeException
1349
+	 * @throws InvalidInterfaceException
1350
+	 * @throws ReflectionException
1351
+	 * @throws RuntimeException
1352
+	 */
1353
+	public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1354
+	{
1355
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1356
+		return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1357
+	}
1358
+
1359
+
1360
+	/**
1361
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1362
+	 * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1363
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1364
+	 * when this is called on the grand total
1365
+	 *
1366
+	 * @return float
1367
+	 * @throws EE_Error
1368
+	 * @throws InvalidArgumentException
1369
+	 * @throws InvalidDataTypeException
1370
+	 * @throws InvalidInterfaceException
1371
+	 * @throws ReflectionException
1372
+	 */
1373
+	public function recalculate_pre_tax_total(): float
1374
+	{
1375
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1376
+		[$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1377
+		return (float) $total;
1378
+	}
1379
+
1380
+
1381
+	/**
1382
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1383
+	 * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1384
+	 * and tax sub-total if already in the DB
1385
+	 *
1386
+	 * @return float
1387
+	 * @throws EE_Error
1388
+	 * @throws InvalidArgumentException
1389
+	 * @throws InvalidDataTypeException
1390
+	 * @throws InvalidInterfaceException
1391
+	 * @throws ReflectionException
1392
+	 */
1393
+	public function recalculate_taxes_and_tax_total(): float
1394
+	{
1395
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1396
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1397
+	}
1398
+
1399
+
1400
+	/**
1401
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
1402
+	 * recalculate_taxes_and_total
1403
+	 *
1404
+	 * @return float
1405
+	 * @throws EE_Error
1406
+	 * @throws InvalidArgumentException
1407
+	 * @throws InvalidDataTypeException
1408
+	 * @throws InvalidInterfaceException
1409
+	 * @throws ReflectionException
1410
+	 */
1411
+	public function get_total_tax()
1412
+	{
1413
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1414
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1415
+	}
1416
+
1417
+
1418
+	/**
1419
+	 * Gets the total for all the items purchased only
1420
+	 *
1421
+	 * @return float
1422
+	 * @throws EE_Error
1423
+	 * @throws InvalidArgumentException
1424
+	 * @throws InvalidDataTypeException
1425
+	 * @throws InvalidInterfaceException
1426
+	 * @throws ReflectionException
1427
+	 */
1428
+	public function get_items_total()
1429
+	{
1430
+		// by default, let's make sure we're consistent with the existing line item
1431
+		if ($this->is_total()) {
1432
+			return $this->pretaxTotal();
1433
+		}
1434
+		$total = 0;
1435
+		foreach ($this->get_items() as $item) {
1436
+			if ($item instanceof EE_Line_Item) {
1437
+				$total += $item->pretaxTotal();
1438
+			}
1439
+		}
1440
+		return $total;
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * Gets all the descendants (ie, children or children of children etc) that
1446
+	 * are of the type 'tax'
1447
+	 *
1448
+	 * @return EE_Line_Item[]
1449
+	 * @throws EE_Error
1450
+	 */
1451
+	public function tax_descendants()
1452
+	{
1453
+		return EEH_Line_Item::get_tax_descendants($this);
1454
+	}
1455
+
1456
+
1457
+	/**
1458
+	 * Gets all the real items purchased which are children of this item
1459
+	 *
1460
+	 * @return EE_Line_Item[]
1461
+	 * @throws EE_Error
1462
+	 */
1463
+	public function get_items()
1464
+	{
1465
+		return EEH_Line_Item::get_line_item_descendants($this);
1466
+	}
1467
+
1468
+
1469
+	/**
1470
+	 * Returns the amount taxable among this line item's children (or if it has no children,
1471
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
1472
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
1473
+	 * but there is a "Taxable" discount), returns 0.
1474
+	 *
1475
+	 * @return float
1476
+	 * @throws EE_Error
1477
+	 * @throws InvalidArgumentException
1478
+	 * @throws InvalidDataTypeException
1479
+	 * @throws InvalidInterfaceException
1480
+	 * @throws ReflectionException
1481
+	 */
1482
+	public function taxable_total(): float
1483
+	{
1484
+		return $this->calculator->taxableAmountForGlobalTaxes($this);
1485
+	}
1486
+
1487
+
1488
+	/**
1489
+	 * Gets the transaction for this line item
1490
+	 *
1491
+	 * @return EE_Base_Class|EE_Transaction
1492
+	 * @throws EE_Error
1493
+	 * @throws InvalidArgumentException
1494
+	 * @throws InvalidDataTypeException
1495
+	 * @throws InvalidInterfaceException
1496
+	 * @throws ReflectionException
1497
+	 */
1498
+	public function transaction()
1499
+	{
1500
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1501
+	}
1502
+
1503
+
1504
+	/**
1505
+	 * Saves this line item to the DB, and recursively saves its descendants.
1506
+	 * Because there currently is no proper parent-child relation on the model,
1507
+	 * save_this_and_cached() will NOT save the descendants.
1508
+	 * Also sets the transaction on this line item and all its descendants before saving
1509
+	 *
1510
+	 * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1511
+	 * @return int count of items saved
1512
+	 * @throws EE_Error
1513
+	 * @throws InvalidArgumentException
1514
+	 * @throws InvalidDataTypeException
1515
+	 * @throws InvalidInterfaceException
1516
+	 * @throws ReflectionException
1517
+	 */
1518
+	public function save_this_and_descendants_to_txn($txn_id = null)
1519
+	{
1520
+		$count = 0;
1521
+		if (! $txn_id) {
1522
+			$txn_id = $this->TXN_ID();
1523
+		}
1524
+		$this->set_TXN_ID($txn_id);
1525
+		$children = $this->children();
1526
+		$count    += $this->save()
1527
+			? 1
1528
+			: 0;
1529
+		foreach ($children as $child_line_item) {
1530
+			if ($child_line_item instanceof EE_Line_Item) {
1531
+				$child_line_item->set_parent_ID($this->ID());
1532
+				$count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1533
+			}
1534
+		}
1535
+		return $count;
1536
+	}
1537
+
1538
+
1539
+	/**
1540
+	 * Saves this line item to the DB, and recursively saves its descendants.
1541
+	 *
1542
+	 * @return int count of items saved
1543
+	 * @throws EE_Error
1544
+	 * @throws InvalidArgumentException
1545
+	 * @throws InvalidDataTypeException
1546
+	 * @throws InvalidInterfaceException
1547
+	 * @throws ReflectionException
1548
+	 */
1549
+	public function save_this_and_descendants()
1550
+	{
1551
+		$count    = 0;
1552
+		$children = $this->children();
1553
+		$count    += $this->save()
1554
+			? 1
1555
+			: 0;
1556
+		foreach ($children as $child_line_item) {
1557
+			if ($child_line_item instanceof EE_Line_Item) {
1558
+				$child_line_item->set_parent_ID($this->ID());
1559
+				$count += $child_line_item->save_this_and_descendants();
1560
+			}
1561
+		}
1562
+		return $count;
1563
+	}
1564
+
1565
+
1566
+	/**
1567
+	 * returns the cancellation line item if this item was cancelled
1568
+	 *
1569
+	 * @return EE_Line_Item[]
1570
+	 * @throws InvalidArgumentException
1571
+	 * @throws InvalidInterfaceException
1572
+	 * @throws InvalidDataTypeException
1573
+	 * @throws ReflectionException
1574
+	 * @throws EE_Error
1575
+	 */
1576
+	public function get_cancellations()
1577
+	{
1578
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1579
+	}
1580
+
1581
+
1582
+	/**
1583
+	 * If this item has an ID, then this saves it again to update the db
1584
+	 *
1585
+	 * @return int count of items saved
1586
+	 * @throws EE_Error
1587
+	 * @throws InvalidArgumentException
1588
+	 * @throws InvalidDataTypeException
1589
+	 * @throws InvalidInterfaceException
1590
+	 * @throws ReflectionException
1591
+	 */
1592
+	public function maybe_save()
1593
+	{
1594
+		if ($this->ID()) {
1595
+			return $this->save();
1596
+		}
1597
+		return false;
1598
+	}
1599
+
1600
+
1601
+	/**
1602
+	 * clears the cached children and parent from the line item
1603
+	 *
1604
+	 * @return void
1605
+	 */
1606
+	public function clear_related_line_item_cache()
1607
+	{
1608
+		$this->_children = [];
1609
+		$this->_parent   = null;
1610
+	}
1611
+
1612
+
1613
+	/**
1614
+	 * @param bool $raw
1615
+	 * @return int
1616
+	 * @throws EE_Error
1617
+	 * @throws InvalidArgumentException
1618
+	 * @throws InvalidDataTypeException
1619
+	 * @throws InvalidInterfaceException
1620
+	 * @throws ReflectionException
1621
+	 */
1622
+	public function timestamp($raw = false)
1623
+	{
1624
+		return $raw
1625
+			? $this->get_raw('LIN_timestamp')
1626
+			: $this->get('LIN_timestamp');
1627
+	}
1628
+
1629
+
1630
+
1631
+
1632
+	/************************* DEPRECATED *************************/
1633
+	/**
1634
+	 * @param string $type one of the constants on EEM_Line_Item
1635
+	 * @return EE_Line_Item[]
1636
+	 * @throws EE_Error
1637
+	 * @deprecated 4.6.0
1638
+	 */
1639
+	protected function _get_descendants_of_type($type)
1640
+	{
1641
+		EE_Error::doing_it_wrong(
1642
+			'EE_Line_Item::_get_descendants_of_type()',
1643
+			sprintf(
1644
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1645
+				'EEH_Line_Item::get_descendants_of_type()'
1646
+			),
1647
+			'4.6.0'
1648
+		);
1649
+		return EEH_Line_Item::get_descendants_of_type($this, $type);
1650
+	}
1651
+
1652
+
1653
+	/**
1654
+	 * @param string $type like one of the EEM_Line_Item::type_*
1655
+	 * @return EE_Line_Item
1656
+	 * @throws EE_Error
1657
+	 * @throws InvalidArgumentException
1658
+	 * @throws InvalidDataTypeException
1659
+	 * @throws InvalidInterfaceException
1660
+	 * @throws ReflectionException
1661
+	 * @deprecated 4.6.0
1662
+	 */
1663
+	public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1664
+	{
1665
+		EE_Error::doing_it_wrong(
1666
+			'EE_Line_Item::get_nearest_descendant_of_type()',
1667
+			sprintf(
1668
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1669
+				'EEH_Line_Item::get_nearest_descendant_of_type()'
1670
+			),
1671
+			'4.6.0'
1672
+		);
1673
+		return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1674
+	}
1675 1675
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
     {
94 94
         $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
95 95
         parent::__construct($fieldValues, $bydb, $timezone);
96
-        if (! $this->get('LIN_code')) {
96
+        if ( ! $this->get('LIN_code')) {
97 97
             $this->set_code($this->generate_code());
98 98
         }
99 99
     }
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
     public function name()
168 168
     {
169 169
         $name = $this->get('LIN_name');
170
-        if (! $name) {
170
+        if ( ! $name) {
171 171
             $name = ucwords(str_replace('-', ' ', $this->type()));
172 172
         }
173 173
         return $name;
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
             $query_params    += ['order_by' => ['LIN_order' => 'ASC']];
694 694
             return $this->get_model()->get_all($query_params);
695 695
         }
696
-        if (! is_array($this->_children)) {
696
+        if ( ! is_array($this->_children)) {
697 697
             $this->_children = [];
698 698
         }
699 699
         return $this->_children;
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
             }
947 947
             return $line_item->save();
948 948
         }
949
-        $this->_children[ $line_item->code() ] = $line_item;
949
+        $this->_children[$line_item->code()] = $line_item;
950 950
         if ($line_item->parent() !== $this) {
951 951
             $line_item->set_parent($this);
952 952
         }
@@ -970,7 +970,7 @@  discard block
 block discarded – undo
970 970
     public function set_parent($line_item)
971 971
     {
972 972
         if ($this->ID()) {
973
-            if (! $line_item->ID()) {
973
+            if ( ! $line_item->ID()) {
974 974
                 $line_item->save();
975 975
             }
976 976
             $this->set_parent_ID($line_item->ID());
@@ -1002,8 +1002,8 @@  discard block
 block discarded – undo
1002 1002
                 [['LIN_parent' => $this->ID(), 'LIN_code' => $code]]
1003 1003
             );
1004 1004
         }
1005
-        return isset($this->_children[ $code ])
1006
-            ? $this->_children[ $code ]
1005
+        return isset($this->_children[$code])
1006
+            ? $this->_children[$code]
1007 1007
             : null;
1008 1008
     }
1009 1009
 
@@ -1063,8 +1063,8 @@  discard block
 block discarded – undo
1063 1063
             }
1064 1064
             return $items_deleted;
1065 1065
         }
1066
-        if (isset($this->_children[ $code ])) {
1067
-            unset($this->_children[ $code ]);
1066
+        if (isset($this->_children[$code])) {
1067
+            unset($this->_children[$code]);
1068 1068
             return 1;
1069 1069
         }
1070 1070
         return 0;
@@ -1105,7 +1105,7 @@  discard block
 block discarded – undo
1105 1105
     public function generate_code()
1106 1106
     {
1107 1107
         // each line item in the cart requires a unique identifier
1108
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1108
+        return md5($this->get('OBJ_type').$this->get('OBJ_ID').microtime());
1109 1109
     }
1110 1110
 
1111 1111
 
@@ -1149,7 +1149,7 @@  discard block
 block discarded – undo
1149 1149
      */
1150 1150
     public function getSubTaxes(): array
1151 1151
     {
1152
-        if (! $this->is_line_item()) {
1152
+        if ( ! $this->is_line_item()) {
1153 1153
             return [];
1154 1154
         }
1155 1155
         return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
@@ -1168,7 +1168,7 @@  discard block
 block discarded – undo
1168 1168
      */
1169 1169
     public function hasSubTaxes(): bool
1170 1170
     {
1171
-        if (! $this->is_line_item()) {
1171
+        if ( ! $this->is_line_item()) {
1172 1172
             return false;
1173 1173
         }
1174 1174
         $sub_taxes = $this->getSubTaxes();
@@ -1518,12 +1518,12 @@  discard block
 block discarded – undo
1518 1518
     public function save_this_and_descendants_to_txn($txn_id = null)
1519 1519
     {
1520 1520
         $count = 0;
1521
-        if (! $txn_id) {
1521
+        if ( ! $txn_id) {
1522 1522
             $txn_id = $this->TXN_ID();
1523 1523
         }
1524 1524
         $this->set_TXN_ID($txn_id);
1525 1525
         $children = $this->children();
1526
-        $count    += $this->save()
1526
+        $count += $this->save()
1527 1527
             ? 1
1528 1528
             : 0;
1529 1529
         foreach ($children as $child_line_item) {
@@ -1550,7 +1550,7 @@  discard block
 block discarded – undo
1550 1550
     {
1551 1551
         $count    = 0;
1552 1552
         $children = $this->children();
1553
-        $count    += $this->save()
1553
+        $count += $this->save()
1554 1554
             ? 1
1555 1555
             : 0;
1556 1556
         foreach ($children as $child_line_item) {
Please login to merge, or discard this patch.
core/db_classes/EE_Currency_Payment_Method.class.php 1 patch
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -11,33 +11,33 @@
 block discarded – undo
11 11
  */
12 12
 class EE_Currency_Payment_Method extends EE_Base_Class
13 13
 {
14
-    /**
15
-     * @param array $props_n_values           incoming values
16
-     * @param null  $timezone                 incoming timezone (if not set the timezone set for the website will be
17
-     *                                        used.)
18
-     * @param array $date_formats             incoming date_formats in an array where the first value is the
19
-     *                                        date_format and the second value is the time format
20
-     * @return EE_Currency_Payment_Method
21
-     * @throws EE_Error
22
-     * @throws ReflectionException
23
-     */
24
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
25
-    {
26
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
27
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
28
-    }
14
+	/**
15
+	 * @param array $props_n_values           incoming values
16
+	 * @param null  $timezone                 incoming timezone (if not set the timezone set for the website will be
17
+	 *                                        used.)
18
+	 * @param array $date_formats             incoming date_formats in an array where the first value is the
19
+	 *                                        date_format and the second value is the time format
20
+	 * @return EE_Currency_Payment_Method
21
+	 * @throws EE_Error
22
+	 * @throws ReflectionException
23
+	 */
24
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
25
+	{
26
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
27
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
28
+	}
29 29
 
30 30
 
31
-    /**
32
-     * @param array $props_n_values   incoming values from the database
33
-     * @param null  $timezone         incoming timezone as set by the model.  If not set the timezone for
34
-     *                                the website will be used.
35
-     * @return EE_Currency_Payment_Method
36
-     * @throws EE_Error
37
-     * @throws ReflectionException
38
-     */
39
-    public static function new_instance_from_db($props_n_values = [], $timezone = '')
40
-    {
41
-        return new self($props_n_values, true, $timezone);
42
-    }
31
+	/**
32
+	 * @param array $props_n_values   incoming values from the database
33
+	 * @param null  $timezone         incoming timezone as set by the model.  If not set the timezone for
34
+	 *                                the website will be used.
35
+	 * @return EE_Currency_Payment_Method
36
+	 * @throws EE_Error
37
+	 * @throws ReflectionException
38
+	 */
39
+	public static function new_instance_from_db($props_n_values = [], $timezone = '')
40
+	{
41
+		return new self($props_n_values, true, $timezone);
42
+	}
43 43
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Attendee.class.php 2 patches
Indentation   +737 added lines, -737 removed lines patch added patch discarded remove patch
@@ -15,741 +15,741 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Attendee extends EE_CPT_Base implements EEI_Contact, AddressInterface, EEI_Admin_Links, EEI_Attendee
17 17
 {
18
-    /**
19
-     * Sets some dynamic defaults
20
-     *
21
-     * @param array  $fieldValues
22
-     * @param bool   $bydb
23
-     * @param string $timezone
24
-     * @param array  $date_formats
25
-     * @throws EE_Error
26
-     * @throws ReflectionException
27
-     */
28
-    protected function __construct($fieldValues = null, $bydb = false, $timezone = '', $date_formats = [])
29
-    {
30
-        if (! isset($fieldValues['ATT_full_name'])) {
31
-            $fname                        = $fieldValues['ATT_fname'] ?? '';
32
-            $lname                        = $fieldValues['ATT_lname'] ?? '';
33
-            $fieldValues['ATT_full_name'] = "$fname $lname";
34
-        }
35
-        if (! isset($fieldValues['ATT_slug'])) {
36
-            // $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
37
-            $fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
38
-        }
39
-        if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
40
-            $fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
41
-        }
42
-        parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
43
-    }
44
-
45
-
46
-    /**
47
-     * @param array       $props_n_values     incoming values
48
-     * @param string|null $timezone           incoming timezone (if not set the timezone set for the website
49
-     *                                        will be
50
-     *                                        used.)
51
-     * @param array       $date_formats       incoming date_formats in an array where the first value is the
52
-     *                                        date_format and the second value is the time format
53
-     * @return EE_Attendee
54
-     * @throws EE_Error
55
-     * @throws ReflectionException
56
-     */
57
-    public static function new_instance(
58
-        array $props_n_values = [],
59
-        ?string $timezone = '',
60
-        array $date_formats = []
61
-    ): EE_Attendee {
62
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
63
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
64
-    }
65
-
66
-
67
-    /**
68
-     * @param array       $props_n_values incoming values from the database
69
-     * @param string|null $timezone       incoming timezone as set by the model.
70
-     *                                    If not set, the timezone for the website will be used.
71
-     * @return EE_Attendee
72
-     * @throws EE_Error
73
-     * @throws ReflectionException
74
-     */
75
-    public static function new_instance_from_db(array $props_n_values = [], ?string $timezone = ''): EE_Attendee
76
-    {
77
-        return new self($props_n_values, true, $timezone);
78
-    }
79
-
80
-
81
-    /**
82
-     * @param string|null $fname
83
-     * @throws EE_Error
84
-     * @throws ReflectionException
85
-     */
86
-    public function set_fname(?string $fname = '')
87
-    {
88
-        $this->set('ATT_fname', (string) $fname);
89
-    }
90
-
91
-
92
-    /**
93
-     * @param string|null $lname
94
-     * @throws EE_Error
95
-     * @throws ReflectionException
96
-     */
97
-    public function set_lname(?string $lname = '')
98
-    {
99
-        $this->set('ATT_lname', (string) $lname);
100
-    }
101
-
102
-
103
-    /**
104
-     * @param string|null $address
105
-     * @throws EE_Error
106
-     * @throws ReflectionException
107
-     */
108
-    public function set_address(?string $address = '')
109
-    {
110
-        $this->set('ATT_address', (string) $address);
111
-    }
112
-
113
-
114
-    /**
115
-     * @param string|null $address2
116
-     * @throws EE_Error
117
-     * @throws ReflectionException
118
-     */
119
-    public function set_address2(?string $address2 = '')
120
-    {
121
-        $this->set('ATT_address2', (string) $address2);
122
-    }
123
-
124
-
125
-    /**
126
-     * @param string|null $city
127
-     * @throws EE_Error
128
-     * @throws ReflectionException
129
-     */
130
-    public function set_city(?string $city = '')
131
-    {
132
-        $this->set('ATT_city', $city);
133
-    }
134
-
135
-
136
-    /**
137
-     * @param int|null $STA_ID
138
-     * @throws EE_Error
139
-     * @throws ReflectionException
140
-     */
141
-    public function set_state(?int $STA_ID = 0)
142
-    {
143
-        $this->set('STA_ID', $STA_ID);
144
-    }
145
-
146
-
147
-    /**
148
-     * @param string|null $CNT_ISO
149
-     * @throws EE_Error
150
-     * @throws ReflectionException
151
-     */
152
-    public function set_country(?string $CNT_ISO = '')
153
-    {
154
-        $this->set('CNT_ISO', $CNT_ISO);
155
-    }
156
-
157
-
158
-    /**
159
-     * @param string|null $zip
160
-     * @throws EE_Error
161
-     * @throws ReflectionException
162
-     */
163
-    public function set_zip(?string $zip = '')
164
-    {
165
-        $this->set('ATT_zip', $zip);
166
-    }
167
-
168
-
169
-    /**
170
-     * @param string|null $email
171
-     * @throws EE_Error
172
-     * @throws ReflectionException
173
-     */
174
-    public function set_email(?string $email = '')
175
-    {
176
-        $this->set('ATT_email', $email);
177
-    }
178
-
179
-
180
-    /**
181
-     * @param string|null $phone
182
-     * @throws EE_Error
183
-     * @throws ReflectionException
184
-     */
185
-    public function set_phone(?string $phone = '')
186
-    {
187
-        $this->set('ATT_phone', $phone);
188
-    }
189
-
190
-
191
-    /**
192
-     * @param bool|int|string|null $ATT_deleted
193
-     * @throws EE_Error
194
-     * @throws ReflectionException
195
-     */
196
-    public function set_deleted($ATT_deleted = false)
197
-    {
198
-        $this->set('ATT_deleted', $ATT_deleted);
199
-    }
200
-
201
-
202
-    /**
203
-     * Returns the value for the post_author id saved with the cpt
204
-     *
205
-     * @return int
206
-     * @throws EE_Error
207
-     * @throws ReflectionException
208
-     * @since 4.5.0
209
-     */
210
-    public function wp_user(): int
211
-    {
212
-        return (int) $this->get('ATT_author');
213
-    }
214
-
215
-
216
-    /**
217
-     * @return string
218
-     * @throws EE_Error
219
-     * @throws ReflectionException
220
-     */
221
-    public function fname(): string
222
-    {
223
-        return (string) $this->get('ATT_fname');
224
-    }
225
-
226
-
227
-    /**
228
-     * echoes out the attendee's first name
229
-     *
230
-     * @return void
231
-     * @throws EE_Error
232
-     * @throws ReflectionException
233
-     */
234
-    public function e_full_name()
235
-    {
236
-        echo esc_html($this->full_name());
237
-    }
238
-
239
-
240
-    /**
241
-     * Returns the first and last name concatenated together with a space.
242
-     *
243
-     * @param bool $apply_html_entities
244
-     * @return string
245
-     * @throws EE_Error
246
-     * @throws ReflectionException
247
-     */
248
-    public function full_name(bool $apply_html_entities = false): string
249
-    {
250
-        $full_name = [$this->fname(), $this->lname()];
251
-        $full_name = array_filter($full_name);
252
-        $full_name = implode(' ', $full_name);
253
-        return $apply_html_entities
254
-            ? htmlentities($full_name, ENT_QUOTES, 'UTF-8')
255
-            : $full_name;
256
-    }
257
-
258
-
259
-    /**
260
-     * This returns the value of the `ATT_full_name` field which is usually equivalent to calling `full_name()` unless
261
-     * the post_title field has been directly modified in the db for the post (espresso_attendees post type) for this
262
-     * attendee.
263
-     *
264
-     * @param bool $apply_html_entities
265
-     * @return string
266
-     * @throws EE_Error
267
-     * @throws ReflectionException
268
-     */
269
-    public function ATT_full_name(bool $apply_html_entities = false): string
270
-    {
271
-        return $apply_html_entities
272
-            ? htmlentities((string) $this->get('ATT_full_name'), ENT_QUOTES, 'UTF-8')
273
-            : (string) $this->get('ATT_full_name');
274
-    }
275
-
276
-
277
-    /**
278
-     * @return string
279
-     * @throws EE_Error
280
-     * @throws ReflectionException
281
-     */
282
-    public function lname(): string
283
-    {
284
-        return (string) $this->get('ATT_lname');
285
-    }
286
-
287
-
288
-    /**
289
-     * @return string
290
-     * @throws EE_Error
291
-     * @throws ReflectionException
292
-     */
293
-    public function bio(): string
294
-    {
295
-        return (string) $this->get('ATT_bio');
296
-    }
297
-
298
-
299
-    /**
300
-     * @return string
301
-     * @throws EE_Error
302
-     * @throws ReflectionException
303
-     */
304
-    public function short_bio(): string
305
-    {
306
-        return (string) $this->get('ATT_short_bio');
307
-    }
308
-
309
-
310
-    /**
311
-     * Gets the attendee's full address as an array so client code can decide hwo to display it
312
-     *
313
-     * @return array numerically indexed, with each part of the address that is known.
314
-     * Eg, if the user only responded to state and country,
315
-     * it would be array(0=>'Alabama',1=>'USA')
316
-     * @return array
317
-     * @throws EE_Error
318
-     * @throws ReflectionException
319
-     */
320
-    public function full_address_as_array(): array
321
-    {
322
-        $full_address_array     = [];
323
-        $initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
324
-        foreach ($initial_address_fields as $address_field_name) {
325
-            $address_fields_value = $this->get($address_field_name);
326
-            if (! empty($address_fields_value)) {
327
-                $full_address_array[] = $address_fields_value;
328
-            }
329
-        }
330
-        // now handle state and country
331
-        $state_obj = $this->state_obj();
332
-        if ($state_obj instanceof EE_State) {
333
-            $full_address_array[] = $state_obj->name();
334
-        }
335
-        $country_obj = $this->country_obj();
336
-        if ($country_obj instanceof EE_Country) {
337
-            $full_address_array[] = $country_obj->name();
338
-        }
339
-        // lastly get the xip
340
-        $zip_value = $this->zip();
341
-        if (! empty($zip_value)) {
342
-            $full_address_array[] = $zip_value;
343
-        }
344
-        return $full_address_array;
345
-    }
346
-
347
-
348
-    /**
349
-     * @return string
350
-     * @throws EE_Error
351
-     * @throws ReflectionException
352
-     */
353
-    public function address(): string
354
-    {
355
-        return (string) $this->get('ATT_address');
356
-    }
357
-
358
-
359
-    /**
360
-     * @return string
361
-     * @throws EE_Error
362
-     * @throws ReflectionException
363
-     */
364
-    public function address2(): string
365
-    {
366
-        return (string) $this->get('ATT_address2');
367
-    }
368
-
369
-
370
-    /**
371
-     * @return string
372
-     * @throws EE_Error
373
-     * @throws ReflectionException
374
-     */
375
-    public function city(): string
376
-    {
377
-        return (string) $this->get('ATT_city');
378
-    }
379
-
380
-
381
-    /**
382
-     * @return int
383
-     * @throws EE_Error
384
-     * @throws ReflectionException
385
-     */
386
-    public function state_ID(): int
387
-    {
388
-        return (int) $this->get('STA_ID');
389
-    }
390
-
391
-
392
-    /**
393
-     * @return string
394
-     * @throws EE_Error
395
-     * @throws ReflectionException
396
-     */
397
-    public function state_abbrev(): string
398
-    {
399
-        return $this->state_obj() instanceof EE_State
400
-            ? $this->state_obj()->abbrev()
401
-            : '';
402
-    }
403
-
404
-
405
-    /**
406
-     * @return EE_State|null
407
-     * @throws EE_Error
408
-     * @throws ReflectionException
409
-     */
410
-    public function state_obj(): ?EE_State
411
-    {
412
-        return $this->get_first_related('State');
413
-    }
414
-
415
-
416
-    /**
417
-     * @return string
418
-     * @throws EE_Error
419
-     * @throws ReflectionException
420
-     */
421
-    public function state_name(): string
422
-    {
423
-        return $this->state_obj() instanceof EE_State
424
-            ? $this->state_obj()->name()
425
-            : '';
426
-    }
427
-
428
-
429
-    /**
430
-     * either displays the state abbreviation or the state name, as determined
431
-     * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
432
-     * defaults to abbreviation
433
-     *
434
-     * @return string
435
-     * @throws EE_Error
436
-     * @throws ReflectionException
437
-     */
438
-    public function state(): string
439
-    {
440
-        return apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())
441
-            ? $this->state_abbrev()
442
-            : $this->state_name();
443
-    }
444
-
445
-
446
-    /**
447
-     * @return string
448
-     * @throws EE_Error
449
-     * @throws ReflectionException
450
-     */
451
-    public function country_ID(): string
452
-    {
453
-        return (string) $this->get('CNT_ISO');
454
-    }
455
-
456
-
457
-    /**
458
-     * @return EE_Country|null
459
-     * @throws EE_Error
460
-     * @throws ReflectionException
461
-     */
462
-    public function country_obj(): ?EE_Country
463
-    {
464
-        return $this->get_first_related('Country');
465
-    }
466
-
467
-
468
-    /**
469
-     * @return string
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     */
473
-    public function country_name(): string
474
-    {
475
-        return $this->country_obj() instanceof EE_Country
476
-            ? $this->country_obj()->name()
477
-            : '';
478
-    }
479
-
480
-
481
-    /**
482
-     * either displays the country ISO2 code or the country name, as determined
483
-     * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
484
-     * defaults to abbreviation
485
-     *
486
-     * @return string
487
-     * @throws EE_Error
488
-     * @throws ReflectionException
489
-     */
490
-    public function country(): string
491
-    {
492
-        return apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())
493
-            ? $this->country_ID()
494
-            : $this->country_name();
495
-    }
496
-
497
-
498
-    /**
499
-     * @return string
500
-     * @throws EE_Error
501
-     * @throws ReflectionException
502
-     */
503
-    public function zip(): string
504
-    {
505
-        return (string) $this->get('ATT_zip');
506
-    }
507
-
508
-
509
-    /**
510
-     * @return string
511
-     * @throws EE_Error
512
-     * @throws ReflectionException
513
-     */
514
-    public function email(): string
515
-    {
516
-        return (string) $this->get('ATT_email');
517
-    }
518
-
519
-
520
-    /**
521
-     * @return string
522
-     * @throws EE_Error
523
-     * @throws ReflectionException
524
-     */
525
-    public function phone(): string
526
-    {
527
-        return (string) $this->get('ATT_phone');
528
-    }
529
-
530
-
531
-    /**
532
-     * @return bool
533
-     * @throws EE_Error
534
-     * @throws ReflectionException
535
-     */
536
-    public function deleted(): bool
537
-    {
538
-        return (bool) $this->get('ATT_deleted');
539
-    }
540
-
541
-
542
-    /**
543
-     * @param array $query_params
544
-     * @return EE_Registration[]
545
-     * @throws EE_Error
546
-     * @throws ReflectionException
547
-     */
548
-    public function get_registrations(array $query_params = []): array
549
-    {
550
-        return $this->get_many_related('Registration', $query_params);
551
-    }
552
-
553
-
554
-    /**
555
-     * Gets the most recent registration of this attendee
556
-     *
557
-     * @return EE_Registration|null
558
-     * @throws EE_Error
559
-     * @throws ReflectionException
560
-     */
561
-    public function get_most_recent_registration(): ?EE_Registration
562
-    {
563
-        return $this->get_first_related('Registration', ['order_by' => ['REG_date' => 'DESC']]);
564
-    }
565
-
566
-
567
-    /**
568
-     * Gets the most recent registration for this attend at this event
569
-     *
570
-     * @param int $event_id
571
-     * @return EE_Registration|null
572
-     * @throws EE_Error
573
-     * @throws ReflectionException
574
-     */
575
-    public function get_most_recent_registration_for_event(int $event_id): ?EE_Registration
576
-    {
577
-        return $this->get_first_related(
578
-            'Registration',
579
-            [['EVT_ID' => $event_id], 'order_by' => ['REG_date' => 'DESC']]
580
-        );
581
-    }
582
-
583
-
584
-    /**
585
-     * returns any events attached to this attendee ($_Event property);
586
-     *
587
-     * @return EE_Event[]
588
-     * @throws EE_Error
589
-     * @throws ReflectionException
590
-     */
591
-    public function events(): array
592
-    {
593
-        return $this->get_many_related('Event');
594
-    }
595
-
596
-
597
-    /**
598
-     * Gets the billing info array where keys match espresso_reg_page_billing_inputs(),
599
-     * and keys are their cleaned values. @param EE_Payment_Method $payment_method the _gateway_name property on the
600
-     * gateway class
601
-     *
602
-     * @return EE_Form_Section_Proper|null
603
-     * @throws EE_Error
604
-     * @throws ReflectionException
605
-     * @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was used to save the billing info
606
-     */
607
-    public function billing_info_for_payment_method(EE_Payment_Method $payment_method): ?EE_Form_Section_Proper
608
-    {
609
-        $pm_type = $payment_method->type_obj();
610
-        if (! $pm_type instanceof EE_PMT_Base) {
611
-            return null;
612
-        }
613
-        $billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
614
-        if (! $billing_info) {
615
-            return null;
616
-        }
617
-        $billing_form = $pm_type->billing_form();
618
-        // double-check the form isn't totally hidden, in which case pretend there is no form
619
-        $form_totally_hidden = true;
620
-        foreach ($billing_form->inputs_in_subsections() as $input) {
621
-            if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
622
-                $form_totally_hidden = false;
623
-                break;
624
-            }
625
-        }
626
-        if ($form_totally_hidden) {
627
-            return null;
628
-        }
629
-        if ($billing_form instanceof EE_Form_Section_Proper) {
630
-            $billing_form->receive_form_submission([$billing_form->name() => $billing_info], false);
631
-        }
632
-
633
-        return $billing_form;
634
-    }
635
-
636
-
637
-    /**
638
-     * Gets the postmeta key that holds this attendee's billing info for the
639
-     * specified payment method
640
-     *
641
-     * @param EE_Payment_Method $payment_method
642
-     * @return string
643
-     * @throws EE_Error
644
-     */
645
-    public function get_billing_info_postmeta_name(EE_Payment_Method $payment_method): string
646
-    {
647
-        return $payment_method->type_obj() instanceof EE_PMT_Base
648
-            ? 'billing_info_' . $payment_method->type_obj()->system_name()
649
-            : '';
650
-    }
651
-
652
-
653
-    /**
654
-     * Saves the billing info to the attendee.
655
-     *
656
-     * @param EE_Billing_Attendee_Info_Form|null $billing_form
657
-     * @param EE_Payment_Method                  $payment_method
658
-     * @return boolean
659
-     * @throws EE_Error
660
-     * @throws ReflectionException
661
-     * @see EE_Attendee::billing_info_for_payment_method() which is used to retrieve it
662
-     */
663
-    public function save_and_clean_billing_info_for_payment_method(
664
-        ?EE_Billing_Attendee_Info_Form $billing_form,
665
-        EE_Payment_Method $payment_method
666
-    ): bool {
667
-        if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
668
-            EE_Error::add_error(
669
-                esc_html__('Cannot save billing info because there is none.', 'event_espresso'),
670
-                __FILE__,
671
-                __FUNCTION__,
672
-                __LINE__
673
-            );
674
-            return false;
675
-        }
676
-        $billing_form->clean_sensitive_data();
677
-        return update_post_meta(
678
-            $this->ID(),
679
-            $this->get_billing_info_postmeta_name($payment_method),
680
-            $billing_form->input_values(true)
681
-        );
682
-    }
683
-
684
-
685
-    /**
686
-     * Return the link to the admin details for the object.
687
-     *
688
-     * @return string
689
-     * @throws EE_Error
690
-     * @throws InvalidArgumentException
691
-     * @throws InvalidDataTypeException
692
-     * @throws InvalidInterfaceException
693
-     * @throws ReflectionException
694
-     */
695
-    public function get_admin_details_link(): string
696
-    {
697
-        return $this->get_admin_edit_link();
698
-    }
699
-
700
-
701
-    /**
702
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
703
-     *
704
-     * @return string
705
-     * @throws EE_Error
706
-     * @throws InvalidArgumentException
707
-     * @throws ReflectionException
708
-     * @throws InvalidDataTypeException
709
-     * @throws InvalidInterfaceException
710
-     */
711
-    public function get_admin_edit_link(): string
712
-    {
713
-        return EEH_URL::add_query_args_and_nonce(
714
-            [
715
-                'page'   => 'espresso_registrations',
716
-                'action' => 'edit_attendee',
717
-                'post'   => $this->ID(),
718
-            ],
719
-            admin_url('admin.php')
720
-        );
721
-    }
722
-
723
-
724
-    /**
725
-     * Returns the link to a settings page for the object.
726
-     *
727
-     * @return string
728
-     * @throws EE_Error
729
-     * @throws InvalidArgumentException
730
-     * @throws InvalidDataTypeException
731
-     * @throws InvalidInterfaceException
732
-     * @throws ReflectionException
733
-     */
734
-    public function get_admin_settings_link(): string
735
-    {
736
-        return $this->get_admin_edit_link();
737
-    }
738
-
739
-
740
-    /**
741
-     * Returns the link to the "overview" for the object (typically the "list table" view).
742
-     *
743
-     * @return string
744
-     */
745
-    public function get_admin_overview_link(): string
746
-    {
747
-        return EEH_URL::add_query_args_and_nonce(
748
-            [
749
-                'page'   => 'espresso_registrations',
750
-                'action' => 'contact_list',
751
-            ],
752
-            admin_url('admin.php')
753
-        );
754
-    }
18
+	/**
19
+	 * Sets some dynamic defaults
20
+	 *
21
+	 * @param array  $fieldValues
22
+	 * @param bool   $bydb
23
+	 * @param string $timezone
24
+	 * @param array  $date_formats
25
+	 * @throws EE_Error
26
+	 * @throws ReflectionException
27
+	 */
28
+	protected function __construct($fieldValues = null, $bydb = false, $timezone = '', $date_formats = [])
29
+	{
30
+		if (! isset($fieldValues['ATT_full_name'])) {
31
+			$fname                        = $fieldValues['ATT_fname'] ?? '';
32
+			$lname                        = $fieldValues['ATT_lname'] ?? '';
33
+			$fieldValues['ATT_full_name'] = "$fname $lname";
34
+		}
35
+		if (! isset($fieldValues['ATT_slug'])) {
36
+			// $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
37
+			$fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
38
+		}
39
+		if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
40
+			$fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
41
+		}
42
+		parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
43
+	}
44
+
45
+
46
+	/**
47
+	 * @param array       $props_n_values     incoming values
48
+	 * @param string|null $timezone           incoming timezone (if not set the timezone set for the website
49
+	 *                                        will be
50
+	 *                                        used.)
51
+	 * @param array       $date_formats       incoming date_formats in an array where the first value is the
52
+	 *                                        date_format and the second value is the time format
53
+	 * @return EE_Attendee
54
+	 * @throws EE_Error
55
+	 * @throws ReflectionException
56
+	 */
57
+	public static function new_instance(
58
+		array $props_n_values = [],
59
+		?string $timezone = '',
60
+		array $date_formats = []
61
+	): EE_Attendee {
62
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
63
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
64
+	}
65
+
66
+
67
+	/**
68
+	 * @param array       $props_n_values incoming values from the database
69
+	 * @param string|null $timezone       incoming timezone as set by the model.
70
+	 *                                    If not set, the timezone for the website will be used.
71
+	 * @return EE_Attendee
72
+	 * @throws EE_Error
73
+	 * @throws ReflectionException
74
+	 */
75
+	public static function new_instance_from_db(array $props_n_values = [], ?string $timezone = ''): EE_Attendee
76
+	{
77
+		return new self($props_n_values, true, $timezone);
78
+	}
79
+
80
+
81
+	/**
82
+	 * @param string|null $fname
83
+	 * @throws EE_Error
84
+	 * @throws ReflectionException
85
+	 */
86
+	public function set_fname(?string $fname = '')
87
+	{
88
+		$this->set('ATT_fname', (string) $fname);
89
+	}
90
+
91
+
92
+	/**
93
+	 * @param string|null $lname
94
+	 * @throws EE_Error
95
+	 * @throws ReflectionException
96
+	 */
97
+	public function set_lname(?string $lname = '')
98
+	{
99
+		$this->set('ATT_lname', (string) $lname);
100
+	}
101
+
102
+
103
+	/**
104
+	 * @param string|null $address
105
+	 * @throws EE_Error
106
+	 * @throws ReflectionException
107
+	 */
108
+	public function set_address(?string $address = '')
109
+	{
110
+		$this->set('ATT_address', (string) $address);
111
+	}
112
+
113
+
114
+	/**
115
+	 * @param string|null $address2
116
+	 * @throws EE_Error
117
+	 * @throws ReflectionException
118
+	 */
119
+	public function set_address2(?string $address2 = '')
120
+	{
121
+		$this->set('ATT_address2', (string) $address2);
122
+	}
123
+
124
+
125
+	/**
126
+	 * @param string|null $city
127
+	 * @throws EE_Error
128
+	 * @throws ReflectionException
129
+	 */
130
+	public function set_city(?string $city = '')
131
+	{
132
+		$this->set('ATT_city', $city);
133
+	}
134
+
135
+
136
+	/**
137
+	 * @param int|null $STA_ID
138
+	 * @throws EE_Error
139
+	 * @throws ReflectionException
140
+	 */
141
+	public function set_state(?int $STA_ID = 0)
142
+	{
143
+		$this->set('STA_ID', $STA_ID);
144
+	}
145
+
146
+
147
+	/**
148
+	 * @param string|null $CNT_ISO
149
+	 * @throws EE_Error
150
+	 * @throws ReflectionException
151
+	 */
152
+	public function set_country(?string $CNT_ISO = '')
153
+	{
154
+		$this->set('CNT_ISO', $CNT_ISO);
155
+	}
156
+
157
+
158
+	/**
159
+	 * @param string|null $zip
160
+	 * @throws EE_Error
161
+	 * @throws ReflectionException
162
+	 */
163
+	public function set_zip(?string $zip = '')
164
+	{
165
+		$this->set('ATT_zip', $zip);
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param string|null $email
171
+	 * @throws EE_Error
172
+	 * @throws ReflectionException
173
+	 */
174
+	public function set_email(?string $email = '')
175
+	{
176
+		$this->set('ATT_email', $email);
177
+	}
178
+
179
+
180
+	/**
181
+	 * @param string|null $phone
182
+	 * @throws EE_Error
183
+	 * @throws ReflectionException
184
+	 */
185
+	public function set_phone(?string $phone = '')
186
+	{
187
+		$this->set('ATT_phone', $phone);
188
+	}
189
+
190
+
191
+	/**
192
+	 * @param bool|int|string|null $ATT_deleted
193
+	 * @throws EE_Error
194
+	 * @throws ReflectionException
195
+	 */
196
+	public function set_deleted($ATT_deleted = false)
197
+	{
198
+		$this->set('ATT_deleted', $ATT_deleted);
199
+	}
200
+
201
+
202
+	/**
203
+	 * Returns the value for the post_author id saved with the cpt
204
+	 *
205
+	 * @return int
206
+	 * @throws EE_Error
207
+	 * @throws ReflectionException
208
+	 * @since 4.5.0
209
+	 */
210
+	public function wp_user(): int
211
+	{
212
+		return (int) $this->get('ATT_author');
213
+	}
214
+
215
+
216
+	/**
217
+	 * @return string
218
+	 * @throws EE_Error
219
+	 * @throws ReflectionException
220
+	 */
221
+	public function fname(): string
222
+	{
223
+		return (string) $this->get('ATT_fname');
224
+	}
225
+
226
+
227
+	/**
228
+	 * echoes out the attendee's first name
229
+	 *
230
+	 * @return void
231
+	 * @throws EE_Error
232
+	 * @throws ReflectionException
233
+	 */
234
+	public function e_full_name()
235
+	{
236
+		echo esc_html($this->full_name());
237
+	}
238
+
239
+
240
+	/**
241
+	 * Returns the first and last name concatenated together with a space.
242
+	 *
243
+	 * @param bool $apply_html_entities
244
+	 * @return string
245
+	 * @throws EE_Error
246
+	 * @throws ReflectionException
247
+	 */
248
+	public function full_name(bool $apply_html_entities = false): string
249
+	{
250
+		$full_name = [$this->fname(), $this->lname()];
251
+		$full_name = array_filter($full_name);
252
+		$full_name = implode(' ', $full_name);
253
+		return $apply_html_entities
254
+			? htmlentities($full_name, ENT_QUOTES, 'UTF-8')
255
+			: $full_name;
256
+	}
257
+
258
+
259
+	/**
260
+	 * This returns the value of the `ATT_full_name` field which is usually equivalent to calling `full_name()` unless
261
+	 * the post_title field has been directly modified in the db for the post (espresso_attendees post type) for this
262
+	 * attendee.
263
+	 *
264
+	 * @param bool $apply_html_entities
265
+	 * @return string
266
+	 * @throws EE_Error
267
+	 * @throws ReflectionException
268
+	 */
269
+	public function ATT_full_name(bool $apply_html_entities = false): string
270
+	{
271
+		return $apply_html_entities
272
+			? htmlentities((string) $this->get('ATT_full_name'), ENT_QUOTES, 'UTF-8')
273
+			: (string) $this->get('ATT_full_name');
274
+	}
275
+
276
+
277
+	/**
278
+	 * @return string
279
+	 * @throws EE_Error
280
+	 * @throws ReflectionException
281
+	 */
282
+	public function lname(): string
283
+	{
284
+		return (string) $this->get('ATT_lname');
285
+	}
286
+
287
+
288
+	/**
289
+	 * @return string
290
+	 * @throws EE_Error
291
+	 * @throws ReflectionException
292
+	 */
293
+	public function bio(): string
294
+	{
295
+		return (string) $this->get('ATT_bio');
296
+	}
297
+
298
+
299
+	/**
300
+	 * @return string
301
+	 * @throws EE_Error
302
+	 * @throws ReflectionException
303
+	 */
304
+	public function short_bio(): string
305
+	{
306
+		return (string) $this->get('ATT_short_bio');
307
+	}
308
+
309
+
310
+	/**
311
+	 * Gets the attendee's full address as an array so client code can decide hwo to display it
312
+	 *
313
+	 * @return array numerically indexed, with each part of the address that is known.
314
+	 * Eg, if the user only responded to state and country,
315
+	 * it would be array(0=>'Alabama',1=>'USA')
316
+	 * @return array
317
+	 * @throws EE_Error
318
+	 * @throws ReflectionException
319
+	 */
320
+	public function full_address_as_array(): array
321
+	{
322
+		$full_address_array     = [];
323
+		$initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
324
+		foreach ($initial_address_fields as $address_field_name) {
325
+			$address_fields_value = $this->get($address_field_name);
326
+			if (! empty($address_fields_value)) {
327
+				$full_address_array[] = $address_fields_value;
328
+			}
329
+		}
330
+		// now handle state and country
331
+		$state_obj = $this->state_obj();
332
+		if ($state_obj instanceof EE_State) {
333
+			$full_address_array[] = $state_obj->name();
334
+		}
335
+		$country_obj = $this->country_obj();
336
+		if ($country_obj instanceof EE_Country) {
337
+			$full_address_array[] = $country_obj->name();
338
+		}
339
+		// lastly get the xip
340
+		$zip_value = $this->zip();
341
+		if (! empty($zip_value)) {
342
+			$full_address_array[] = $zip_value;
343
+		}
344
+		return $full_address_array;
345
+	}
346
+
347
+
348
+	/**
349
+	 * @return string
350
+	 * @throws EE_Error
351
+	 * @throws ReflectionException
352
+	 */
353
+	public function address(): string
354
+	{
355
+		return (string) $this->get('ATT_address');
356
+	}
357
+
358
+
359
+	/**
360
+	 * @return string
361
+	 * @throws EE_Error
362
+	 * @throws ReflectionException
363
+	 */
364
+	public function address2(): string
365
+	{
366
+		return (string) $this->get('ATT_address2');
367
+	}
368
+
369
+
370
+	/**
371
+	 * @return string
372
+	 * @throws EE_Error
373
+	 * @throws ReflectionException
374
+	 */
375
+	public function city(): string
376
+	{
377
+		return (string) $this->get('ATT_city');
378
+	}
379
+
380
+
381
+	/**
382
+	 * @return int
383
+	 * @throws EE_Error
384
+	 * @throws ReflectionException
385
+	 */
386
+	public function state_ID(): int
387
+	{
388
+		return (int) $this->get('STA_ID');
389
+	}
390
+
391
+
392
+	/**
393
+	 * @return string
394
+	 * @throws EE_Error
395
+	 * @throws ReflectionException
396
+	 */
397
+	public function state_abbrev(): string
398
+	{
399
+		return $this->state_obj() instanceof EE_State
400
+			? $this->state_obj()->abbrev()
401
+			: '';
402
+	}
403
+
404
+
405
+	/**
406
+	 * @return EE_State|null
407
+	 * @throws EE_Error
408
+	 * @throws ReflectionException
409
+	 */
410
+	public function state_obj(): ?EE_State
411
+	{
412
+		return $this->get_first_related('State');
413
+	}
414
+
415
+
416
+	/**
417
+	 * @return string
418
+	 * @throws EE_Error
419
+	 * @throws ReflectionException
420
+	 */
421
+	public function state_name(): string
422
+	{
423
+		return $this->state_obj() instanceof EE_State
424
+			? $this->state_obj()->name()
425
+			: '';
426
+	}
427
+
428
+
429
+	/**
430
+	 * either displays the state abbreviation or the state name, as determined
431
+	 * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
432
+	 * defaults to abbreviation
433
+	 *
434
+	 * @return string
435
+	 * @throws EE_Error
436
+	 * @throws ReflectionException
437
+	 */
438
+	public function state(): string
439
+	{
440
+		return apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())
441
+			? $this->state_abbrev()
442
+			: $this->state_name();
443
+	}
444
+
445
+
446
+	/**
447
+	 * @return string
448
+	 * @throws EE_Error
449
+	 * @throws ReflectionException
450
+	 */
451
+	public function country_ID(): string
452
+	{
453
+		return (string) $this->get('CNT_ISO');
454
+	}
455
+
456
+
457
+	/**
458
+	 * @return EE_Country|null
459
+	 * @throws EE_Error
460
+	 * @throws ReflectionException
461
+	 */
462
+	public function country_obj(): ?EE_Country
463
+	{
464
+		return $this->get_first_related('Country');
465
+	}
466
+
467
+
468
+	/**
469
+	 * @return string
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 */
473
+	public function country_name(): string
474
+	{
475
+		return $this->country_obj() instanceof EE_Country
476
+			? $this->country_obj()->name()
477
+			: '';
478
+	}
479
+
480
+
481
+	/**
482
+	 * either displays the country ISO2 code or the country name, as determined
483
+	 * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
484
+	 * defaults to abbreviation
485
+	 *
486
+	 * @return string
487
+	 * @throws EE_Error
488
+	 * @throws ReflectionException
489
+	 */
490
+	public function country(): string
491
+	{
492
+		return apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())
493
+			? $this->country_ID()
494
+			: $this->country_name();
495
+	}
496
+
497
+
498
+	/**
499
+	 * @return string
500
+	 * @throws EE_Error
501
+	 * @throws ReflectionException
502
+	 */
503
+	public function zip(): string
504
+	{
505
+		return (string) $this->get('ATT_zip');
506
+	}
507
+
508
+
509
+	/**
510
+	 * @return string
511
+	 * @throws EE_Error
512
+	 * @throws ReflectionException
513
+	 */
514
+	public function email(): string
515
+	{
516
+		return (string) $this->get('ATT_email');
517
+	}
518
+
519
+
520
+	/**
521
+	 * @return string
522
+	 * @throws EE_Error
523
+	 * @throws ReflectionException
524
+	 */
525
+	public function phone(): string
526
+	{
527
+		return (string) $this->get('ATT_phone');
528
+	}
529
+
530
+
531
+	/**
532
+	 * @return bool
533
+	 * @throws EE_Error
534
+	 * @throws ReflectionException
535
+	 */
536
+	public function deleted(): bool
537
+	{
538
+		return (bool) $this->get('ATT_deleted');
539
+	}
540
+
541
+
542
+	/**
543
+	 * @param array $query_params
544
+	 * @return EE_Registration[]
545
+	 * @throws EE_Error
546
+	 * @throws ReflectionException
547
+	 */
548
+	public function get_registrations(array $query_params = []): array
549
+	{
550
+		return $this->get_many_related('Registration', $query_params);
551
+	}
552
+
553
+
554
+	/**
555
+	 * Gets the most recent registration of this attendee
556
+	 *
557
+	 * @return EE_Registration|null
558
+	 * @throws EE_Error
559
+	 * @throws ReflectionException
560
+	 */
561
+	public function get_most_recent_registration(): ?EE_Registration
562
+	{
563
+		return $this->get_first_related('Registration', ['order_by' => ['REG_date' => 'DESC']]);
564
+	}
565
+
566
+
567
+	/**
568
+	 * Gets the most recent registration for this attend at this event
569
+	 *
570
+	 * @param int $event_id
571
+	 * @return EE_Registration|null
572
+	 * @throws EE_Error
573
+	 * @throws ReflectionException
574
+	 */
575
+	public function get_most_recent_registration_for_event(int $event_id): ?EE_Registration
576
+	{
577
+		return $this->get_first_related(
578
+			'Registration',
579
+			[['EVT_ID' => $event_id], 'order_by' => ['REG_date' => 'DESC']]
580
+		);
581
+	}
582
+
583
+
584
+	/**
585
+	 * returns any events attached to this attendee ($_Event property);
586
+	 *
587
+	 * @return EE_Event[]
588
+	 * @throws EE_Error
589
+	 * @throws ReflectionException
590
+	 */
591
+	public function events(): array
592
+	{
593
+		return $this->get_many_related('Event');
594
+	}
595
+
596
+
597
+	/**
598
+	 * Gets the billing info array where keys match espresso_reg_page_billing_inputs(),
599
+	 * and keys are their cleaned values. @param EE_Payment_Method $payment_method the _gateway_name property on the
600
+	 * gateway class
601
+	 *
602
+	 * @return EE_Form_Section_Proper|null
603
+	 * @throws EE_Error
604
+	 * @throws ReflectionException
605
+	 * @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was used to save the billing info
606
+	 */
607
+	public function billing_info_for_payment_method(EE_Payment_Method $payment_method): ?EE_Form_Section_Proper
608
+	{
609
+		$pm_type = $payment_method->type_obj();
610
+		if (! $pm_type instanceof EE_PMT_Base) {
611
+			return null;
612
+		}
613
+		$billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
614
+		if (! $billing_info) {
615
+			return null;
616
+		}
617
+		$billing_form = $pm_type->billing_form();
618
+		// double-check the form isn't totally hidden, in which case pretend there is no form
619
+		$form_totally_hidden = true;
620
+		foreach ($billing_form->inputs_in_subsections() as $input) {
621
+			if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
622
+				$form_totally_hidden = false;
623
+				break;
624
+			}
625
+		}
626
+		if ($form_totally_hidden) {
627
+			return null;
628
+		}
629
+		if ($billing_form instanceof EE_Form_Section_Proper) {
630
+			$billing_form->receive_form_submission([$billing_form->name() => $billing_info], false);
631
+		}
632
+
633
+		return $billing_form;
634
+	}
635
+
636
+
637
+	/**
638
+	 * Gets the postmeta key that holds this attendee's billing info for the
639
+	 * specified payment method
640
+	 *
641
+	 * @param EE_Payment_Method $payment_method
642
+	 * @return string
643
+	 * @throws EE_Error
644
+	 */
645
+	public function get_billing_info_postmeta_name(EE_Payment_Method $payment_method): string
646
+	{
647
+		return $payment_method->type_obj() instanceof EE_PMT_Base
648
+			? 'billing_info_' . $payment_method->type_obj()->system_name()
649
+			: '';
650
+	}
651
+
652
+
653
+	/**
654
+	 * Saves the billing info to the attendee.
655
+	 *
656
+	 * @param EE_Billing_Attendee_Info_Form|null $billing_form
657
+	 * @param EE_Payment_Method                  $payment_method
658
+	 * @return boolean
659
+	 * @throws EE_Error
660
+	 * @throws ReflectionException
661
+	 * @see EE_Attendee::billing_info_for_payment_method() which is used to retrieve it
662
+	 */
663
+	public function save_and_clean_billing_info_for_payment_method(
664
+		?EE_Billing_Attendee_Info_Form $billing_form,
665
+		EE_Payment_Method $payment_method
666
+	): bool {
667
+		if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
668
+			EE_Error::add_error(
669
+				esc_html__('Cannot save billing info because there is none.', 'event_espresso'),
670
+				__FILE__,
671
+				__FUNCTION__,
672
+				__LINE__
673
+			);
674
+			return false;
675
+		}
676
+		$billing_form->clean_sensitive_data();
677
+		return update_post_meta(
678
+			$this->ID(),
679
+			$this->get_billing_info_postmeta_name($payment_method),
680
+			$billing_form->input_values(true)
681
+		);
682
+	}
683
+
684
+
685
+	/**
686
+	 * Return the link to the admin details for the object.
687
+	 *
688
+	 * @return string
689
+	 * @throws EE_Error
690
+	 * @throws InvalidArgumentException
691
+	 * @throws InvalidDataTypeException
692
+	 * @throws InvalidInterfaceException
693
+	 * @throws ReflectionException
694
+	 */
695
+	public function get_admin_details_link(): string
696
+	{
697
+		return $this->get_admin_edit_link();
698
+	}
699
+
700
+
701
+	/**
702
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
703
+	 *
704
+	 * @return string
705
+	 * @throws EE_Error
706
+	 * @throws InvalidArgumentException
707
+	 * @throws ReflectionException
708
+	 * @throws InvalidDataTypeException
709
+	 * @throws InvalidInterfaceException
710
+	 */
711
+	public function get_admin_edit_link(): string
712
+	{
713
+		return EEH_URL::add_query_args_and_nonce(
714
+			[
715
+				'page'   => 'espresso_registrations',
716
+				'action' => 'edit_attendee',
717
+				'post'   => $this->ID(),
718
+			],
719
+			admin_url('admin.php')
720
+		);
721
+	}
722
+
723
+
724
+	/**
725
+	 * Returns the link to a settings page for the object.
726
+	 *
727
+	 * @return string
728
+	 * @throws EE_Error
729
+	 * @throws InvalidArgumentException
730
+	 * @throws InvalidDataTypeException
731
+	 * @throws InvalidInterfaceException
732
+	 * @throws ReflectionException
733
+	 */
734
+	public function get_admin_settings_link(): string
735
+	{
736
+		return $this->get_admin_edit_link();
737
+	}
738
+
739
+
740
+	/**
741
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
742
+	 *
743
+	 * @return string
744
+	 */
745
+	public function get_admin_overview_link(): string
746
+	{
747
+		return EEH_URL::add_query_args_and_nonce(
748
+			[
749
+				'page'   => 'espresso_registrations',
750
+				'action' => 'contact_list',
751
+			],
752
+			admin_url('admin.php')
753
+		);
754
+	}
755 755
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -27,16 +27,16 @@  discard block
 block discarded – undo
27 27
      */
28 28
     protected function __construct($fieldValues = null, $bydb = false, $timezone = '', $date_formats = [])
29 29
     {
30
-        if (! isset($fieldValues['ATT_full_name'])) {
30
+        if ( ! isset($fieldValues['ATT_full_name'])) {
31 31
             $fname                        = $fieldValues['ATT_fname'] ?? '';
32 32
             $lname                        = $fieldValues['ATT_lname'] ?? '';
33 33
             $fieldValues['ATT_full_name'] = "$fname $lname";
34 34
         }
35
-        if (! isset($fieldValues['ATT_slug'])) {
35
+        if ( ! isset($fieldValues['ATT_slug'])) {
36 36
             // $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
37 37
             $fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
38 38
         }
39
-        if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
39
+        if ( ! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
40 40
             $fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
41 41
         }
42 42
         parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
@@ -320,10 +320,10 @@  discard block
 block discarded – undo
320 320
     public function full_address_as_array(): array
321 321
     {
322 322
         $full_address_array     = [];
323
-        $initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
323
+        $initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city', ];
324 324
         foreach ($initial_address_fields as $address_field_name) {
325 325
             $address_fields_value = $this->get($address_field_name);
326
-            if (! empty($address_fields_value)) {
326
+            if ( ! empty($address_fields_value)) {
327 327
                 $full_address_array[] = $address_fields_value;
328 328
             }
329 329
         }
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
         }
339 339
         // lastly get the xip
340 340
         $zip_value = $this->zip();
341
-        if (! empty($zip_value)) {
341
+        if ( ! empty($zip_value)) {
342 342
             $full_address_array[] = $zip_value;
343 343
         }
344 344
         return $full_address_array;
@@ -607,18 +607,18 @@  discard block
 block discarded – undo
607 607
     public function billing_info_for_payment_method(EE_Payment_Method $payment_method): ?EE_Form_Section_Proper
608 608
     {
609 609
         $pm_type = $payment_method->type_obj();
610
-        if (! $pm_type instanceof EE_PMT_Base) {
610
+        if ( ! $pm_type instanceof EE_PMT_Base) {
611 611
             return null;
612 612
         }
613 613
         $billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
614
-        if (! $billing_info) {
614
+        if ( ! $billing_info) {
615 615
             return null;
616 616
         }
617 617
         $billing_form = $pm_type->billing_form();
618 618
         // double-check the form isn't totally hidden, in which case pretend there is no form
619 619
         $form_totally_hidden = true;
620 620
         foreach ($billing_form->inputs_in_subsections() as $input) {
621
-            if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
621
+            if ( ! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
622 622
                 $form_totally_hidden = false;
623 623
                 break;
624 624
             }
@@ -645,7 +645,7 @@  discard block
 block discarded – undo
645 645
     public function get_billing_info_postmeta_name(EE_Payment_Method $payment_method): string
646 646
     {
647 647
         return $payment_method->type_obj() instanceof EE_PMT_Base
648
-            ? 'billing_info_' . $payment_method->type_obj()->system_name()
648
+            ? 'billing_info_'.$payment_method->type_obj()->system_name()
649 649
             : '';
650 650
     }
651 651
 
@@ -664,7 +664,7 @@  discard block
 block discarded – undo
664 664
         ?EE_Billing_Attendee_Info_Form $billing_form,
665 665
         EE_Payment_Method $payment_method
666 666
     ): bool {
667
-        if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
667
+        if ( ! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
668 668
             EE_Error::add_error(
669 669
                 esc_html__('Cannot save billing info because there is none.', 'event_espresso'),
670 670
                 __FILE__,
Please login to merge, or discard this patch.
core/db_classes/EE_Payment.class.php 2 patches
Indentation   +873 added lines, -873 removed lines patch added patch discarded remove patch
@@ -11,877 +11,877 @@
 block discarded – undo
11 11
  */
12 12
 class EE_Payment extends EE_Base_Class implements EEI_Payment
13 13
 {
14
-    /**
15
-     * @param array  $props_n_values          incoming values
16
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
17
-     *                                        used.)
18
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
19
-     *                                        date_format and the second value is the time format
20
-     * @return EE_Payment
21
-     * @throws EE_Error|ReflectionException
22
-     */
23
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
24
-    {
25
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
26
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
27
-    }
28
-
29
-
30
-    /**
31
-     * @param array  $props_n_values  incoming values from the database
32
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
33
-     *                                the website will be used.
34
-     * @return EE_Payment
35
-     * @throws EE_Error
36
-     */
37
-    public static function new_instance_from_db($props_n_values = [], $timezone = '')
38
-    {
39
-        return new self($props_n_values, true, $timezone);
40
-    }
41
-
42
-
43
-    /**
44
-     * Set Transaction ID
45
-     *
46
-     * @access public
47
-     * @param int $TXN_ID
48
-     * @throws EE_Error
49
-     */
50
-    public function set_transaction_id($TXN_ID = 0)
51
-    {
52
-        $this->set('TXN_ID', $TXN_ID);
53
-    }
54
-
55
-
56
-    /**
57
-     * Gets the transaction related to this payment
58
-     *
59
-     * @return EE_Transaction
60
-     * @throws EE_Error
61
-     */
62
-    public function transaction()
63
-    {
64
-        return $this->get_first_related('Transaction');
65
-    }
66
-
67
-
68
-    /**
69
-     * Set Status
70
-     *
71
-     * @access public
72
-     * @param string $STS_ID
73
-     * @throws EE_Error
74
-     */
75
-    public function set_status($STS_ID = '')
76
-    {
77
-        $this->set('STS_ID', $STS_ID);
78
-    }
79
-
80
-
81
-    /**
82
-     * Set Payment Timestamp
83
-     *
84
-     * @access public
85
-     * @param int $timestamp
86
-     * @throws EE_Error
87
-     */
88
-    public function set_timestamp($timestamp = 0)
89
-    {
90
-        $this->set('PAY_timestamp', $timestamp);
91
-    }
92
-
93
-
94
-    /**
95
-     * Set Payment Method
96
-     *
97
-     * @access public
98
-     * @param string $PAY_source
99
-     * @throws EE_Error
100
-     */
101
-    public function set_source($PAY_source = '')
102
-    {
103
-        $this->set('PAY_source', $PAY_source);
104
-    }
105
-
106
-
107
-    /**
108
-     * Set Payment Amount
109
-     *
110
-     * @access public
111
-     * @param float $amount
112
-     * @throws EE_Error
113
-     */
114
-    public function set_amount($amount = 0.00)
115
-    {
116
-        $this->set('PAY_amount', (float) $amount);
117
-    }
118
-
119
-
120
-    /**
121
-     * Set Payment Gateway Response
122
-     *
123
-     * @access public
124
-     * @param string $gateway_response
125
-     * @throws EE_Error
126
-     */
127
-    public function set_gateway_response($gateway_response = '')
128
-    {
129
-        $this->set('PAY_gateway_response', $gateway_response);
130
-    }
131
-
132
-
133
-    /**
134
-     * Returns the name of the payment method used on this payment (previously known merely as 'gateway')
135
-     * but since 4.6.0, payment methods are models and the payment keeps a foreign key to the payment method
136
-     * used on it
137
-     *
138
-     * @return string
139
-     * @throws EE_Error
140
-     * @deprecated
141
-     */
142
-    public function gateway()
143
-    {
144
-        EE_Error::doing_it_wrong(
145
-            'EE_Payment::gateway',
146
-            esc_html__(
147
-                'The method EE_Payment::gateway() has been deprecated. Consider instead using EE_Payment::payment_method()->name()',
148
-                'event_espresso'
149
-            ),
150
-            '4.6.0'
151
-        );
152
-        return $this->payment_method() ? $this->payment_method()->name() : esc_html__('Unknown', 'event_espresso');
153
-    }
154
-
155
-
156
-    /**
157
-     * Set Gateway Transaction ID
158
-     *
159
-     * @access public
160
-     * @param string $txn_id_chq_nmbr
161
-     * @throws EE_Error
162
-     */
163
-    public function set_txn_id_chq_nmbr($txn_id_chq_nmbr = '')
164
-    {
165
-        $this->set('PAY_txn_id_chq_nmbr', $txn_id_chq_nmbr);
166
-    }
167
-
168
-
169
-    /**
170
-     * Set Purchase Order Number
171
-     *
172
-     * @access public
173
-     * @param string $po_number
174
-     * @throws EE_Error
175
-     */
176
-    public function set_po_number($po_number = '')
177
-    {
178
-        $this->set('PAY_po_number', $po_number);
179
-    }
180
-
181
-
182
-    /**
183
-     * Set Extra Accounting Field
184
-     *
185
-     * @access public
186
-     * @param string $extra_accntng
187
-     * @throws EE_Error
188
-     */
189
-    public function set_extra_accntng($extra_accntng = '')
190
-    {
191
-        $this->set('PAY_extra_accntng', $extra_accntng);
192
-    }
193
-
194
-
195
-    /**
196
-     * Set Payment made via admin flag
197
-     *
198
-     * @access public
199
-     * @param bool $via_admin
200
-     * @throws EE_Error
201
-     */
202
-    public function set_payment_made_via_admin($via_admin = false)
203
-    {
204
-        if ($via_admin) {
205
-            $this->set('PAY_source', EEM_Payment_Method::scope_admin);
206
-        } else {
207
-            $this->set('PAY_source', EEM_Payment_Method::scope_cart);
208
-        }
209
-    }
210
-
211
-
212
-    /**
213
-     * Set Payment Details
214
-     *
215
-     * @access public
216
-     * @param string|array $details
217
-     * @throws EE_Error
218
-     */
219
-    public function set_details($details = '')
220
-    {
221
-        if (is_array($details)) {
222
-            array_walk_recursive($details, [$this, '_strip_all_tags_within_array']);
223
-        } else {
224
-            $details = wp_strip_all_tags($details);
225
-        }
226
-        $this->set('PAY_details', $details);
227
-    }
228
-
229
-
230
-    /**
231
-     * Sets redirect_url
232
-     *
233
-     * @param string $redirect_url
234
-     * @throws EE_Error
235
-     */
236
-    public function set_redirect_url($redirect_url)
237
-    {
238
-        $this->set('PAY_redirect_url', $redirect_url);
239
-    }
240
-
241
-
242
-    /**
243
-     * Sets redirect_args
244
-     *
245
-     * @param array $redirect_args
246
-     * @throws EE_Error
247
-     */
248
-    public function set_redirect_args($redirect_args)
249
-    {
250
-        $this->set('PAY_redirect_args', $redirect_args);
251
-    }
252
-
253
-
254
-    /**
255
-     * get Payment Transaction ID
256
-     *
257
-     * @access public
258
-     * @throws EE_Error
259
-     */
260
-    public function TXN_ID()
261
-    {
262
-        return $this->get('TXN_ID');
263
-    }
264
-
265
-
266
-    /**
267
-     * get Payment Status
268
-     *
269
-     * @access public
270
-     * @throws EE_Error
271
-     */
272
-    public function status()
273
-    {
274
-        return $this->get('STS_ID');
275
-    }
276
-
277
-
278
-    /**
279
-     * get Payment Status
280
-     *
281
-     * @access public
282
-     * @throws EE_Error
283
-     */
284
-    public function STS_ID()
285
-    {
286
-        return $this->get('STS_ID');
287
-    }
288
-
289
-
290
-    /**
291
-     * get Payment Timestamp
292
-     *
293
-     * @access public
294
-     * @param string $dt_frmt
295
-     * @param string $tm_frmt
296
-     * @return string
297
-     * @throws EE_Error
298
-     */
299
-    public function timestamp($dt_frmt = '', $tm_frmt = '')
300
-    {
301
-        return $this->get_i18n_datetime('PAY_timestamp', trim($dt_frmt . ' ' . $tm_frmt));
302
-    }
303
-
304
-
305
-    /**
306
-     * get Payment Source
307
-     *
308
-     * @access public
309
-     * @throws EE_Error
310
-     */
311
-    public function source()
312
-    {
313
-        return $this->get('PAY_source');
314
-    }
315
-
316
-
317
-    /**
318
-     * get Payment Amount
319
-     *
320
-     * @access public
321
-     * @return float
322
-     * @throws EE_Error
323
-     */
324
-    public function amount()
325
-    {
326
-        return (float) $this->get('PAY_amount');
327
-    }
328
-
329
-
330
-    /**
331
-     * @return mixed
332
-     * @throws EE_Error
333
-     */
334
-    public function amount_no_code()
335
-    {
336
-        return $this->get_pretty('PAY_amount', 'no_currency_code');
337
-    }
338
-
339
-
340
-    /**
341
-     * get Payment Gateway Response
342
-     *
343
-     * @access public
344
-     * @throws EE_Error
345
-     */
346
-    public function gateway_response()
347
-    {
348
-        return $this->get('PAY_gateway_response');
349
-    }
350
-
351
-
352
-    /**
353
-     * get Payment Gateway Transaction ID
354
-     *
355
-     * @access public
356
-     * @throws EE_Error
357
-     */
358
-    public function txn_id_chq_nmbr()
359
-    {
360
-        return $this->get('PAY_txn_id_chq_nmbr');
361
-    }
362
-
363
-
364
-    /**
365
-     * get Purchase Order Number
366
-     *
367
-     * @access public
368
-     * @throws EE_Error
369
-     */
370
-    public function po_number()
371
-    {
372
-        return $this->get('PAY_po_number');
373
-    }
374
-
375
-
376
-    /**
377
-     * get Extra Accounting Field
378
-     *
379
-     * @access public
380
-     * @throws EE_Error
381
-     */
382
-    public function extra_accntng()
383
-    {
384
-        return $this->get('PAY_extra_accntng');
385
-    }
386
-
387
-
388
-    /**
389
-     * get Payment made via admin source
390
-     *
391
-     * @access public
392
-     * @throws EE_Error
393
-     */
394
-    public function payment_made_via_admin()
395
-    {
396
-        return ($this->get('PAY_source') === EEM_Payment_Method::scope_admin);
397
-    }
398
-
399
-
400
-    /**
401
-     * get Payment Details
402
-     *
403
-     * @access public
404
-     * @throws EE_Error
405
-     */
406
-    public function details()
407
-    {
408
-        return $this->get('PAY_details');
409
-    }
410
-
411
-
412
-    /**
413
-     * Gets redirect_url
414
-     *
415
-     * @return string
416
-     * @throws EE_Error
417
-     */
418
-    public function redirect_url()
419
-    {
420
-        return $this->get('PAY_redirect_url');
421
-    }
422
-
423
-
424
-    /**
425
-     * Gets redirect_args
426
-     *
427
-     * @return array
428
-     * @throws EE_Error
429
-     */
430
-    public function redirect_args()
431
-    {
432
-        return $this->get('PAY_redirect_args');
433
-    }
434
-
435
-
436
-    /**
437
-     * echoes $this->pretty_status()
438
-     *
439
-     * @param bool $show_icons
440
-     * @return void
441
-     * @throws EE_Error
442
-     */
443
-    public function e_pretty_status($show_icons = false)
444
-    {
445
-        echo wp_kses($this->pretty_status($show_icons), AllowedTags::getAllowedTags());
446
-    }
447
-
448
-
449
-    /**
450
-     * returns a pretty version of the status, good for displaying to users
451
-     *
452
-     * @param bool $show_icons
453
-     * @return string
454
-     * @throws EE_Error
455
-     */
456
-    public function pretty_status($show_icons = false)
457
-    {
458
-        $status = EEM_Status::instance()->localized_status(
459
-            [$this->STS_ID() => esc_html__('unknown', 'event_espresso')],
460
-            false,
461
-            'sentence'
462
-        );
463
-        $icon   = '';
464
-        switch ($this->STS_ID()) {
465
-            case EEM_Payment::status_id_approved:
466
-                $icon = $show_icons
467
-                    ? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>'
468
-                    : '';
469
-                break;
470
-            case EEM_Payment::status_id_pending:
471
-                $icon = $show_icons
472
-                    ? '<span class="dashicons dashicons-clock ee-icon-size-16 orange-text"></span>'
473
-                    : '';
474
-                break;
475
-            case EEM_Payment::status_id_cancelled:
476
-                $icon = $show_icons
477
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
478
-                    : '';
479
-                break;
480
-            case EEM_Payment::status_id_declined:
481
-                $icon = $show_icons
482
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
483
-                    : '';
484
-                break;
485
-        }
486
-        return $icon . $status[ $this->STS_ID() ];
487
-    }
488
-
489
-
490
-    /**
491
-     * For determining the status of the payment
492
-     *
493
-     * @return boolean whether the payment is approved or not
494
-     * @throws EE_Error
495
-     */
496
-    public function is_approved()
497
-    {
498
-        return $this->status_is(EEM_Payment::status_id_approved);
499
-    }
500
-
501
-
502
-    /**
503
-     * Generally determines if the status of this payment equals
504
-     * the $STS_ID string
505
-     *
506
-     * @param string $STS_ID an ID from the esp_status table/
507
-     *                       one of the status_id_* on the EEM_Payment model
508
-     * @return boolean whether the status of this payment equals the status id
509
-     * @throws EE_Error
510
-     */
511
-    protected function status_is($STS_ID)
512
-    {
513
-        return $STS_ID === $this->STS_ID() ? true : false;
514
-    }
515
-
516
-
517
-    /**
518
-     * For determining the status of the payment
519
-     *
520
-     * @return boolean whether the payment is pending or not
521
-     * @throws EE_Error
522
-     */
523
-    public function is_pending()
524
-    {
525
-        return $this->status_is(EEM_Payment::status_id_pending);
526
-    }
527
-
528
-
529
-    /**
530
-     * For determining the status of the payment
531
-     *
532
-     * @return boolean
533
-     * @throws EE_Error
534
-     */
535
-    public function is_cancelled()
536
-    {
537
-        return $this->status_is(EEM_Payment::status_id_cancelled);
538
-    }
539
-
540
-
541
-    /**
542
-     * For determining the status of the payment
543
-     *
544
-     * @return boolean
545
-     * @throws EE_Error
546
-     */
547
-    public function is_declined()
548
-    {
549
-        return $this->status_is(EEM_Payment::status_id_declined);
550
-    }
551
-
552
-
553
-    /**
554
-     * For determining the status of the payment
555
-     *
556
-     * @return boolean
557
-     * @throws EE_Error
558
-     */
559
-    public function is_failed()
560
-    {
561
-        return $this->status_is(EEM_Payment::status_id_failed);
562
-    }
563
-
564
-
565
-    /**
566
-     * For determining if the payment is actually a refund ( ie: has a negative value )
567
-     *
568
-     * @return boolean
569
-     * @throws EE_Error
570
-     */
571
-    public function is_a_refund()
572
-    {
573
-        return $this->amount() < 0 ? true : false;
574
-    }
575
-
576
-
577
-    /**
578
-     * Get the status object of this object
579
-     *
580
-     * @return EE_Status
581
-     * @throws EE_Error
582
-     */
583
-    public function status_obj()
584
-    {
585
-        return $this->get_first_related('Status');
586
-    }
587
-
588
-
589
-    /**
590
-     * Gets all the extra meta info on this payment
591
-     *
592
-     * @param array $query_params @see
593
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
594
-     * @return EE_Extra_Meta
595
-     * @throws EE_Error
596
-     */
597
-    public function extra_meta($query_params = [])
598
-    {
599
-        return $this->get_many_related('Extra_Meta', $query_params);
600
-    }
601
-
602
-
603
-    /**
604
-     * Gets the last-used payment method on this transaction
605
-     * (we COULD just use the last-made payment, but some payment methods, namely
606
-     * offline ones, dont' create payments)
607
-     *
608
-     * @return EE_Payment_Method
609
-     * @throws EE_Error
610
-     */
611
-    public function payment_method()
612
-    {
613
-        return $this->get_first_related('Payment_Method');
614
-    }
615
-
616
-
617
-    /**
618
-     * Gets the HTML for redirecting the user to an offsite gateway
619
-     * You can pass it special content to put inside the form, or use
620
-     * the default inner content (or possibly generate this all yourself using
621
-     * redirect_url() and redirect_args() or redirect_args_as_inputs()).
622
-     * Creates a POST request by default, but if no redirect args are specified, creates a GET request instead
623
-     * (and any querystring variables in the redirect_url are converted into html inputs
624
-     * so browsers submit them properly)
625
-     *
626
-     * @param string $inside_form_html
627
-     * @return string html
628
-     * @throws EE_Error
629
-     */
630
-    public function redirect_form($inside_form_html = null)
631
-    {
632
-        $redirect_url = $this->redirect_url();
633
-        if (! empty($redirect_url)) {
634
-            // what ? no inner form content?
635
-            if ($inside_form_html === null) {
636
-                $inside_form_html = EEH_HTML::p(
637
-                    sprintf(
638
-                        esc_html__(
639
-                            'If you are not automatically redirected to the payment website within 10 seconds... %1$s %2$s Click Here %3$s',
640
-                            'event_espresso'
641
-                        ),
642
-                        EEH_HTML::br(2),
643
-                        '<input type="submit" value="',
644
-                        '">'
645
-                    ),
646
-                    '',
647
-                    '',
648
-                    'text-align:center;'
649
-                );
650
-            }
651
-            $method = apply_filters(
652
-                'FHEE__EE_Payment__redirect_form__method',
653
-                $this->redirect_args() ? 'POST' : 'GET',
654
-                $this
655
-            );
656
-            // if it's a GET request, we need to remove all the GET params in the querystring
657
-            // and put them into the form instead
658
-            if ($method === 'GET') {
659
-                $querystring = parse_url($redirect_url, PHP_URL_QUERY);
660
-                $get_params  = null;
661
-                parse_str($querystring, $get_params);
662
-                $inside_form_html .= $this->_args_as_inputs($get_params);
663
-                $redirect_url     = str_replace('?' . $querystring, '', $redirect_url);
664
-            }
665
-            $form = EEH_HTML::nl(1)
666
-                    . '<form method="'
667
-                    . $method
668
-                    . '" name="gateway_form" action="'
669
-                    . $redirect_url
670
-                    . '">';
671
-            $form .= EEH_HTML::nl(1) . $this->redirect_args_as_inputs();
672
-            $form .= $inside_form_html;
673
-            $form .= EEH_HTML::nl(-1) . '</form>' . EEH_HTML::nl(-1);
674
-            return $form;
675
-        } else {
676
-            return null;
677
-        }
678
-    }
679
-
680
-
681
-    /**
682
-     * Changes all the name-value pairs of the redirect args into html inputs
683
-     * and returns the html as a string
684
-     *
685
-     * @return string
686
-     * @throws EE_Error
687
-     */
688
-    public function redirect_args_as_inputs()
689
-    {
690
-        return $this->_args_as_inputs($this->redirect_args());
691
-    }
692
-
693
-
694
-    /**
695
-     * Converts a 2d array of key-value pairs into html hidden inputs
696
-     * and returns the string of html
697
-     *
698
-     * @param array $args key-value pairs
699
-     * @return string
700
-     */
701
-    protected function _args_as_inputs($args)
702
-    {
703
-        $html = '';
704
-        if ($args !== null && is_array($args)) {
705
-            foreach ($args as $name => $value) {
706
-                $html .= $this->generateInput($name, $value);
707
-            }
708
-        }
709
-        return $html;
710
-    }
711
-
712
-
713
-    /**
714
-     * Converts either a single name and value or array of values into html hidden inputs
715
-     * and returns the string of html
716
-     *
717
-     * @param string       $name
718
-     * @param string|array $value
719
-     * @return string
720
-     */
721
-    private function generateInput($name, $value)
722
-    {
723
-        if (is_array($value)) {
724
-            $html = '';
725
-            $name = "{$name}[]";
726
-            foreach ($value as $array_value) {
727
-                $html .= $this->generateInput($name, $array_value);
728
-            }
729
-            return $html;
730
-        }
731
-        return EEH_HTML::nl()
732
-               . '<input type="hidden" name="' . $name . '"'
733
-               . ' value="' . esc_attr($value) . '"/>';
734
-    }
735
-
736
-
737
-    /**
738
-     * Returns the currency of the payment.
739
-     * (At the time of writing, this will always be the currency in the configuration;
740
-     * however in the future it is anticipated that this will be stored on the payment
741
-     * object itself)
742
-     *
743
-     * @return string for the currency code
744
-     */
745
-    public function currency_code()
746
-    {
747
-        return EE_Config::instance()->currency->code;
748
-    }
749
-
750
-
751
-    /**
752
-     * apply wp_strip_all_tags to all elements within an array
753
-     *
754
-     * @access private
755
-     * @param mixed $item
756
-     */
757
-    private function _strip_all_tags_within_array(&$item)
758
-    {
759
-        if (is_object($item)) {
760
-            $item = (array) $item;
761
-        }
762
-        if (is_array($item)) {
763
-            array_walk_recursive($item, [$this, '_strip_all_tags_within_array']);
764
-        } else {
765
-            $item = wp_strip_all_tags((string) $item);
766
-        }
767
-    }
768
-
769
-
770
-    /**
771
-     * Returns TRUE is this payment was set to approved during this request (or
772
-     * is approved and was created during this request). False otherwise.
773
-     *
774
-     * @return boolean
775
-     * @throws EE_Error
776
-     */
777
-    public function just_approved()
778
-    {
779
-        $original_status = EEH_Array::is_set(
780
-            $this->_props_n_values_provided_in_constructor,
781
-            'STS_ID',
782
-            $this->get_model()->field_settings_for('STS_ID')->get_default_value()
783
-        );
784
-        $current_status  = $this->status();
785
-        if (
786
-            $original_status !== EEM_Payment::status_id_approved
787
-            && $current_status === EEM_Payment::status_id_approved
788
-        ) {
789
-            return true;
790
-        } else {
791
-            return false;
792
-        }
793
-    }
794
-
795
-
796
-    /**
797
-     * Overrides parents' get_pretty() function just for legacy reasons
798
-     * (to allow ticket https://events.codebasehq.com/projects/event-espresso/tickets/7420)
799
-     *
800
-     * @param string $field_name
801
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
802
-     *                                (in cases where the same property may be used for different outputs
803
-     *                                - i.e. datetime, money etc.)
804
-     * @return mixed
805
-     * @throws EE_Error
806
-     */
807
-    public function get_pretty($field_name, $extra_cache_ref = null)
808
-    {
809
-        if ($field_name === 'PAY_gateway') {
810
-            return $this->payment_method() ? $this->payment_method()->name() : esc_html__('Unknown', 'event_espresso');
811
-        }
812
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
813
-    }
814
-
815
-
816
-    /**
817
-     * Gets details regarding which registrations this payment was applied to
818
-     *
819
-     * @param array $query_params @see
820
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
821
-     * @return EE_Registration_Payment[]
822
-     * @throws EE_Error
823
-     */
824
-    public function registration_payments($query_params = [])
825
-    {
826
-        return $this->get_many_related('Registration_Payment', $query_params);
827
-    }
828
-
829
-
830
-    /**
831
-     * Gets the first event for this payment (it's possible that it could be for multiple)
832
-     *
833
-     * @return EE_Event|null
834
-     */
835
-    public function get_first_event()
836
-    {
837
-        $transaction = $this->transaction();
838
-        if ($transaction instanceof EE_Transaction) {
839
-            $primary_registrant = $transaction->primary_registration();
840
-            if ($primary_registrant instanceof EE_Registration) {
841
-                return $primary_registrant->event_obj();
842
-            }
843
-        }
844
-        return null;
845
-    }
846
-
847
-
848
-    /**
849
-     * Gets the name of the first event for which is being paid
850
-     *
851
-     * @return string
852
-     */
853
-    public function get_first_event_name()
854
-    {
855
-        $event = $this->get_first_event();
856
-        return $event instanceof EE_Event ? $event->name() : esc_html__('Event', 'event_espresso');
857
-    }
858
-
859
-
860
-    /**
861
-     * Returns the payment's transaction's primary registration
862
-     *
863
-     * @return EE_Registration|null
864
-     */
865
-    public function get_primary_registration()
866
-    {
867
-        if ($this->transaction() instanceof EE_Transaction) {
868
-            return $this->transaction()->primary_registration();
869
-        }
870
-        return null;
871
-    }
872
-
873
-
874
-    /**
875
-     * Gets the payment's transaction's primary registration's attendee, or null
876
-     *
877
-     * @return EE_Attendee|null
878
-     */
879
-    public function get_primary_attendee()
880
-    {
881
-        $primary_reg = $this->get_primary_registration();
882
-        if ($primary_reg instanceof EE_Registration) {
883
-            return $primary_reg->attendee();
884
-        }
885
-        return null;
886
-    }
14
+	/**
15
+	 * @param array  $props_n_values          incoming values
16
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
17
+	 *                                        used.)
18
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
19
+	 *                                        date_format and the second value is the time format
20
+	 * @return EE_Payment
21
+	 * @throws EE_Error|ReflectionException
22
+	 */
23
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
24
+	{
25
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
26
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
27
+	}
28
+
29
+
30
+	/**
31
+	 * @param array  $props_n_values  incoming values from the database
32
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
33
+	 *                                the website will be used.
34
+	 * @return EE_Payment
35
+	 * @throws EE_Error
36
+	 */
37
+	public static function new_instance_from_db($props_n_values = [], $timezone = '')
38
+	{
39
+		return new self($props_n_values, true, $timezone);
40
+	}
41
+
42
+
43
+	/**
44
+	 * Set Transaction ID
45
+	 *
46
+	 * @access public
47
+	 * @param int $TXN_ID
48
+	 * @throws EE_Error
49
+	 */
50
+	public function set_transaction_id($TXN_ID = 0)
51
+	{
52
+		$this->set('TXN_ID', $TXN_ID);
53
+	}
54
+
55
+
56
+	/**
57
+	 * Gets the transaction related to this payment
58
+	 *
59
+	 * @return EE_Transaction
60
+	 * @throws EE_Error
61
+	 */
62
+	public function transaction()
63
+	{
64
+		return $this->get_first_related('Transaction');
65
+	}
66
+
67
+
68
+	/**
69
+	 * Set Status
70
+	 *
71
+	 * @access public
72
+	 * @param string $STS_ID
73
+	 * @throws EE_Error
74
+	 */
75
+	public function set_status($STS_ID = '')
76
+	{
77
+		$this->set('STS_ID', $STS_ID);
78
+	}
79
+
80
+
81
+	/**
82
+	 * Set Payment Timestamp
83
+	 *
84
+	 * @access public
85
+	 * @param int $timestamp
86
+	 * @throws EE_Error
87
+	 */
88
+	public function set_timestamp($timestamp = 0)
89
+	{
90
+		$this->set('PAY_timestamp', $timestamp);
91
+	}
92
+
93
+
94
+	/**
95
+	 * Set Payment Method
96
+	 *
97
+	 * @access public
98
+	 * @param string $PAY_source
99
+	 * @throws EE_Error
100
+	 */
101
+	public function set_source($PAY_source = '')
102
+	{
103
+		$this->set('PAY_source', $PAY_source);
104
+	}
105
+
106
+
107
+	/**
108
+	 * Set Payment Amount
109
+	 *
110
+	 * @access public
111
+	 * @param float $amount
112
+	 * @throws EE_Error
113
+	 */
114
+	public function set_amount($amount = 0.00)
115
+	{
116
+		$this->set('PAY_amount', (float) $amount);
117
+	}
118
+
119
+
120
+	/**
121
+	 * Set Payment Gateway Response
122
+	 *
123
+	 * @access public
124
+	 * @param string $gateway_response
125
+	 * @throws EE_Error
126
+	 */
127
+	public function set_gateway_response($gateway_response = '')
128
+	{
129
+		$this->set('PAY_gateway_response', $gateway_response);
130
+	}
131
+
132
+
133
+	/**
134
+	 * Returns the name of the payment method used on this payment (previously known merely as 'gateway')
135
+	 * but since 4.6.0, payment methods are models and the payment keeps a foreign key to the payment method
136
+	 * used on it
137
+	 *
138
+	 * @return string
139
+	 * @throws EE_Error
140
+	 * @deprecated
141
+	 */
142
+	public function gateway()
143
+	{
144
+		EE_Error::doing_it_wrong(
145
+			'EE_Payment::gateway',
146
+			esc_html__(
147
+				'The method EE_Payment::gateway() has been deprecated. Consider instead using EE_Payment::payment_method()->name()',
148
+				'event_espresso'
149
+			),
150
+			'4.6.0'
151
+		);
152
+		return $this->payment_method() ? $this->payment_method()->name() : esc_html__('Unknown', 'event_espresso');
153
+	}
154
+
155
+
156
+	/**
157
+	 * Set Gateway Transaction ID
158
+	 *
159
+	 * @access public
160
+	 * @param string $txn_id_chq_nmbr
161
+	 * @throws EE_Error
162
+	 */
163
+	public function set_txn_id_chq_nmbr($txn_id_chq_nmbr = '')
164
+	{
165
+		$this->set('PAY_txn_id_chq_nmbr', $txn_id_chq_nmbr);
166
+	}
167
+
168
+
169
+	/**
170
+	 * Set Purchase Order Number
171
+	 *
172
+	 * @access public
173
+	 * @param string $po_number
174
+	 * @throws EE_Error
175
+	 */
176
+	public function set_po_number($po_number = '')
177
+	{
178
+		$this->set('PAY_po_number', $po_number);
179
+	}
180
+
181
+
182
+	/**
183
+	 * Set Extra Accounting Field
184
+	 *
185
+	 * @access public
186
+	 * @param string $extra_accntng
187
+	 * @throws EE_Error
188
+	 */
189
+	public function set_extra_accntng($extra_accntng = '')
190
+	{
191
+		$this->set('PAY_extra_accntng', $extra_accntng);
192
+	}
193
+
194
+
195
+	/**
196
+	 * Set Payment made via admin flag
197
+	 *
198
+	 * @access public
199
+	 * @param bool $via_admin
200
+	 * @throws EE_Error
201
+	 */
202
+	public function set_payment_made_via_admin($via_admin = false)
203
+	{
204
+		if ($via_admin) {
205
+			$this->set('PAY_source', EEM_Payment_Method::scope_admin);
206
+		} else {
207
+			$this->set('PAY_source', EEM_Payment_Method::scope_cart);
208
+		}
209
+	}
210
+
211
+
212
+	/**
213
+	 * Set Payment Details
214
+	 *
215
+	 * @access public
216
+	 * @param string|array $details
217
+	 * @throws EE_Error
218
+	 */
219
+	public function set_details($details = '')
220
+	{
221
+		if (is_array($details)) {
222
+			array_walk_recursive($details, [$this, '_strip_all_tags_within_array']);
223
+		} else {
224
+			$details = wp_strip_all_tags($details);
225
+		}
226
+		$this->set('PAY_details', $details);
227
+	}
228
+
229
+
230
+	/**
231
+	 * Sets redirect_url
232
+	 *
233
+	 * @param string $redirect_url
234
+	 * @throws EE_Error
235
+	 */
236
+	public function set_redirect_url($redirect_url)
237
+	{
238
+		$this->set('PAY_redirect_url', $redirect_url);
239
+	}
240
+
241
+
242
+	/**
243
+	 * Sets redirect_args
244
+	 *
245
+	 * @param array $redirect_args
246
+	 * @throws EE_Error
247
+	 */
248
+	public function set_redirect_args($redirect_args)
249
+	{
250
+		$this->set('PAY_redirect_args', $redirect_args);
251
+	}
252
+
253
+
254
+	/**
255
+	 * get Payment Transaction ID
256
+	 *
257
+	 * @access public
258
+	 * @throws EE_Error
259
+	 */
260
+	public function TXN_ID()
261
+	{
262
+		return $this->get('TXN_ID');
263
+	}
264
+
265
+
266
+	/**
267
+	 * get Payment Status
268
+	 *
269
+	 * @access public
270
+	 * @throws EE_Error
271
+	 */
272
+	public function status()
273
+	{
274
+		return $this->get('STS_ID');
275
+	}
276
+
277
+
278
+	/**
279
+	 * get Payment Status
280
+	 *
281
+	 * @access public
282
+	 * @throws EE_Error
283
+	 */
284
+	public function STS_ID()
285
+	{
286
+		return $this->get('STS_ID');
287
+	}
288
+
289
+
290
+	/**
291
+	 * get Payment Timestamp
292
+	 *
293
+	 * @access public
294
+	 * @param string $dt_frmt
295
+	 * @param string $tm_frmt
296
+	 * @return string
297
+	 * @throws EE_Error
298
+	 */
299
+	public function timestamp($dt_frmt = '', $tm_frmt = '')
300
+	{
301
+		return $this->get_i18n_datetime('PAY_timestamp', trim($dt_frmt . ' ' . $tm_frmt));
302
+	}
303
+
304
+
305
+	/**
306
+	 * get Payment Source
307
+	 *
308
+	 * @access public
309
+	 * @throws EE_Error
310
+	 */
311
+	public function source()
312
+	{
313
+		return $this->get('PAY_source');
314
+	}
315
+
316
+
317
+	/**
318
+	 * get Payment Amount
319
+	 *
320
+	 * @access public
321
+	 * @return float
322
+	 * @throws EE_Error
323
+	 */
324
+	public function amount()
325
+	{
326
+		return (float) $this->get('PAY_amount');
327
+	}
328
+
329
+
330
+	/**
331
+	 * @return mixed
332
+	 * @throws EE_Error
333
+	 */
334
+	public function amount_no_code()
335
+	{
336
+		return $this->get_pretty('PAY_amount', 'no_currency_code');
337
+	}
338
+
339
+
340
+	/**
341
+	 * get Payment Gateway Response
342
+	 *
343
+	 * @access public
344
+	 * @throws EE_Error
345
+	 */
346
+	public function gateway_response()
347
+	{
348
+		return $this->get('PAY_gateway_response');
349
+	}
350
+
351
+
352
+	/**
353
+	 * get Payment Gateway Transaction ID
354
+	 *
355
+	 * @access public
356
+	 * @throws EE_Error
357
+	 */
358
+	public function txn_id_chq_nmbr()
359
+	{
360
+		return $this->get('PAY_txn_id_chq_nmbr');
361
+	}
362
+
363
+
364
+	/**
365
+	 * get Purchase Order Number
366
+	 *
367
+	 * @access public
368
+	 * @throws EE_Error
369
+	 */
370
+	public function po_number()
371
+	{
372
+		return $this->get('PAY_po_number');
373
+	}
374
+
375
+
376
+	/**
377
+	 * get Extra Accounting Field
378
+	 *
379
+	 * @access public
380
+	 * @throws EE_Error
381
+	 */
382
+	public function extra_accntng()
383
+	{
384
+		return $this->get('PAY_extra_accntng');
385
+	}
386
+
387
+
388
+	/**
389
+	 * get Payment made via admin source
390
+	 *
391
+	 * @access public
392
+	 * @throws EE_Error
393
+	 */
394
+	public function payment_made_via_admin()
395
+	{
396
+		return ($this->get('PAY_source') === EEM_Payment_Method::scope_admin);
397
+	}
398
+
399
+
400
+	/**
401
+	 * get Payment Details
402
+	 *
403
+	 * @access public
404
+	 * @throws EE_Error
405
+	 */
406
+	public function details()
407
+	{
408
+		return $this->get('PAY_details');
409
+	}
410
+
411
+
412
+	/**
413
+	 * Gets redirect_url
414
+	 *
415
+	 * @return string
416
+	 * @throws EE_Error
417
+	 */
418
+	public function redirect_url()
419
+	{
420
+		return $this->get('PAY_redirect_url');
421
+	}
422
+
423
+
424
+	/**
425
+	 * Gets redirect_args
426
+	 *
427
+	 * @return array
428
+	 * @throws EE_Error
429
+	 */
430
+	public function redirect_args()
431
+	{
432
+		return $this->get('PAY_redirect_args');
433
+	}
434
+
435
+
436
+	/**
437
+	 * echoes $this->pretty_status()
438
+	 *
439
+	 * @param bool $show_icons
440
+	 * @return void
441
+	 * @throws EE_Error
442
+	 */
443
+	public function e_pretty_status($show_icons = false)
444
+	{
445
+		echo wp_kses($this->pretty_status($show_icons), AllowedTags::getAllowedTags());
446
+	}
447
+
448
+
449
+	/**
450
+	 * returns a pretty version of the status, good for displaying to users
451
+	 *
452
+	 * @param bool $show_icons
453
+	 * @return string
454
+	 * @throws EE_Error
455
+	 */
456
+	public function pretty_status($show_icons = false)
457
+	{
458
+		$status = EEM_Status::instance()->localized_status(
459
+			[$this->STS_ID() => esc_html__('unknown', 'event_espresso')],
460
+			false,
461
+			'sentence'
462
+		);
463
+		$icon   = '';
464
+		switch ($this->STS_ID()) {
465
+			case EEM_Payment::status_id_approved:
466
+				$icon = $show_icons
467
+					? '<span class="dashicons dashicons-yes ee-icon-size-24 green-text"></span>'
468
+					: '';
469
+				break;
470
+			case EEM_Payment::status_id_pending:
471
+				$icon = $show_icons
472
+					? '<span class="dashicons dashicons-clock ee-icon-size-16 orange-text"></span>'
473
+					: '';
474
+				break;
475
+			case EEM_Payment::status_id_cancelled:
476
+				$icon = $show_icons
477
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
478
+					: '';
479
+				break;
480
+			case EEM_Payment::status_id_declined:
481
+				$icon = $show_icons
482
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
483
+					: '';
484
+				break;
485
+		}
486
+		return $icon . $status[ $this->STS_ID() ];
487
+	}
488
+
489
+
490
+	/**
491
+	 * For determining the status of the payment
492
+	 *
493
+	 * @return boolean whether the payment is approved or not
494
+	 * @throws EE_Error
495
+	 */
496
+	public function is_approved()
497
+	{
498
+		return $this->status_is(EEM_Payment::status_id_approved);
499
+	}
500
+
501
+
502
+	/**
503
+	 * Generally determines if the status of this payment equals
504
+	 * the $STS_ID string
505
+	 *
506
+	 * @param string $STS_ID an ID from the esp_status table/
507
+	 *                       one of the status_id_* on the EEM_Payment model
508
+	 * @return boolean whether the status of this payment equals the status id
509
+	 * @throws EE_Error
510
+	 */
511
+	protected function status_is($STS_ID)
512
+	{
513
+		return $STS_ID === $this->STS_ID() ? true : false;
514
+	}
515
+
516
+
517
+	/**
518
+	 * For determining the status of the payment
519
+	 *
520
+	 * @return boolean whether the payment is pending or not
521
+	 * @throws EE_Error
522
+	 */
523
+	public function is_pending()
524
+	{
525
+		return $this->status_is(EEM_Payment::status_id_pending);
526
+	}
527
+
528
+
529
+	/**
530
+	 * For determining the status of the payment
531
+	 *
532
+	 * @return boolean
533
+	 * @throws EE_Error
534
+	 */
535
+	public function is_cancelled()
536
+	{
537
+		return $this->status_is(EEM_Payment::status_id_cancelled);
538
+	}
539
+
540
+
541
+	/**
542
+	 * For determining the status of the payment
543
+	 *
544
+	 * @return boolean
545
+	 * @throws EE_Error
546
+	 */
547
+	public function is_declined()
548
+	{
549
+		return $this->status_is(EEM_Payment::status_id_declined);
550
+	}
551
+
552
+
553
+	/**
554
+	 * For determining the status of the payment
555
+	 *
556
+	 * @return boolean
557
+	 * @throws EE_Error
558
+	 */
559
+	public function is_failed()
560
+	{
561
+		return $this->status_is(EEM_Payment::status_id_failed);
562
+	}
563
+
564
+
565
+	/**
566
+	 * For determining if the payment is actually a refund ( ie: has a negative value )
567
+	 *
568
+	 * @return boolean
569
+	 * @throws EE_Error
570
+	 */
571
+	public function is_a_refund()
572
+	{
573
+		return $this->amount() < 0 ? true : false;
574
+	}
575
+
576
+
577
+	/**
578
+	 * Get the status object of this object
579
+	 *
580
+	 * @return EE_Status
581
+	 * @throws EE_Error
582
+	 */
583
+	public function status_obj()
584
+	{
585
+		return $this->get_first_related('Status');
586
+	}
587
+
588
+
589
+	/**
590
+	 * Gets all the extra meta info on this payment
591
+	 *
592
+	 * @param array $query_params @see
593
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
594
+	 * @return EE_Extra_Meta
595
+	 * @throws EE_Error
596
+	 */
597
+	public function extra_meta($query_params = [])
598
+	{
599
+		return $this->get_many_related('Extra_Meta', $query_params);
600
+	}
601
+
602
+
603
+	/**
604
+	 * Gets the last-used payment method on this transaction
605
+	 * (we COULD just use the last-made payment, but some payment methods, namely
606
+	 * offline ones, dont' create payments)
607
+	 *
608
+	 * @return EE_Payment_Method
609
+	 * @throws EE_Error
610
+	 */
611
+	public function payment_method()
612
+	{
613
+		return $this->get_first_related('Payment_Method');
614
+	}
615
+
616
+
617
+	/**
618
+	 * Gets the HTML for redirecting the user to an offsite gateway
619
+	 * You can pass it special content to put inside the form, or use
620
+	 * the default inner content (or possibly generate this all yourself using
621
+	 * redirect_url() and redirect_args() or redirect_args_as_inputs()).
622
+	 * Creates a POST request by default, but if no redirect args are specified, creates a GET request instead
623
+	 * (and any querystring variables in the redirect_url are converted into html inputs
624
+	 * so browsers submit them properly)
625
+	 *
626
+	 * @param string $inside_form_html
627
+	 * @return string html
628
+	 * @throws EE_Error
629
+	 */
630
+	public function redirect_form($inside_form_html = null)
631
+	{
632
+		$redirect_url = $this->redirect_url();
633
+		if (! empty($redirect_url)) {
634
+			// what ? no inner form content?
635
+			if ($inside_form_html === null) {
636
+				$inside_form_html = EEH_HTML::p(
637
+					sprintf(
638
+						esc_html__(
639
+							'If you are not automatically redirected to the payment website within 10 seconds... %1$s %2$s Click Here %3$s',
640
+							'event_espresso'
641
+						),
642
+						EEH_HTML::br(2),
643
+						'<input type="submit" value="',
644
+						'">'
645
+					),
646
+					'',
647
+					'',
648
+					'text-align:center;'
649
+				);
650
+			}
651
+			$method = apply_filters(
652
+				'FHEE__EE_Payment__redirect_form__method',
653
+				$this->redirect_args() ? 'POST' : 'GET',
654
+				$this
655
+			);
656
+			// if it's a GET request, we need to remove all the GET params in the querystring
657
+			// and put them into the form instead
658
+			if ($method === 'GET') {
659
+				$querystring = parse_url($redirect_url, PHP_URL_QUERY);
660
+				$get_params  = null;
661
+				parse_str($querystring, $get_params);
662
+				$inside_form_html .= $this->_args_as_inputs($get_params);
663
+				$redirect_url     = str_replace('?' . $querystring, '', $redirect_url);
664
+			}
665
+			$form = EEH_HTML::nl(1)
666
+					. '<form method="'
667
+					. $method
668
+					. '" name="gateway_form" action="'
669
+					. $redirect_url
670
+					. '">';
671
+			$form .= EEH_HTML::nl(1) . $this->redirect_args_as_inputs();
672
+			$form .= $inside_form_html;
673
+			$form .= EEH_HTML::nl(-1) . '</form>' . EEH_HTML::nl(-1);
674
+			return $form;
675
+		} else {
676
+			return null;
677
+		}
678
+	}
679
+
680
+
681
+	/**
682
+	 * Changes all the name-value pairs of the redirect args into html inputs
683
+	 * and returns the html as a string
684
+	 *
685
+	 * @return string
686
+	 * @throws EE_Error
687
+	 */
688
+	public function redirect_args_as_inputs()
689
+	{
690
+		return $this->_args_as_inputs($this->redirect_args());
691
+	}
692
+
693
+
694
+	/**
695
+	 * Converts a 2d array of key-value pairs into html hidden inputs
696
+	 * and returns the string of html
697
+	 *
698
+	 * @param array $args key-value pairs
699
+	 * @return string
700
+	 */
701
+	protected function _args_as_inputs($args)
702
+	{
703
+		$html = '';
704
+		if ($args !== null && is_array($args)) {
705
+			foreach ($args as $name => $value) {
706
+				$html .= $this->generateInput($name, $value);
707
+			}
708
+		}
709
+		return $html;
710
+	}
711
+
712
+
713
+	/**
714
+	 * Converts either a single name and value or array of values into html hidden inputs
715
+	 * and returns the string of html
716
+	 *
717
+	 * @param string       $name
718
+	 * @param string|array $value
719
+	 * @return string
720
+	 */
721
+	private function generateInput($name, $value)
722
+	{
723
+		if (is_array($value)) {
724
+			$html = '';
725
+			$name = "{$name}[]";
726
+			foreach ($value as $array_value) {
727
+				$html .= $this->generateInput($name, $array_value);
728
+			}
729
+			return $html;
730
+		}
731
+		return EEH_HTML::nl()
732
+			   . '<input type="hidden" name="' . $name . '"'
733
+			   . ' value="' . esc_attr($value) . '"/>';
734
+	}
735
+
736
+
737
+	/**
738
+	 * Returns the currency of the payment.
739
+	 * (At the time of writing, this will always be the currency in the configuration;
740
+	 * however in the future it is anticipated that this will be stored on the payment
741
+	 * object itself)
742
+	 *
743
+	 * @return string for the currency code
744
+	 */
745
+	public function currency_code()
746
+	{
747
+		return EE_Config::instance()->currency->code;
748
+	}
749
+
750
+
751
+	/**
752
+	 * apply wp_strip_all_tags to all elements within an array
753
+	 *
754
+	 * @access private
755
+	 * @param mixed $item
756
+	 */
757
+	private function _strip_all_tags_within_array(&$item)
758
+	{
759
+		if (is_object($item)) {
760
+			$item = (array) $item;
761
+		}
762
+		if (is_array($item)) {
763
+			array_walk_recursive($item, [$this, '_strip_all_tags_within_array']);
764
+		} else {
765
+			$item = wp_strip_all_tags((string) $item);
766
+		}
767
+	}
768
+
769
+
770
+	/**
771
+	 * Returns TRUE is this payment was set to approved during this request (or
772
+	 * is approved and was created during this request). False otherwise.
773
+	 *
774
+	 * @return boolean
775
+	 * @throws EE_Error
776
+	 */
777
+	public function just_approved()
778
+	{
779
+		$original_status = EEH_Array::is_set(
780
+			$this->_props_n_values_provided_in_constructor,
781
+			'STS_ID',
782
+			$this->get_model()->field_settings_for('STS_ID')->get_default_value()
783
+		);
784
+		$current_status  = $this->status();
785
+		if (
786
+			$original_status !== EEM_Payment::status_id_approved
787
+			&& $current_status === EEM_Payment::status_id_approved
788
+		) {
789
+			return true;
790
+		} else {
791
+			return false;
792
+		}
793
+	}
794
+
795
+
796
+	/**
797
+	 * Overrides parents' get_pretty() function just for legacy reasons
798
+	 * (to allow ticket https://events.codebasehq.com/projects/event-espresso/tickets/7420)
799
+	 *
800
+	 * @param string $field_name
801
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
802
+	 *                                (in cases where the same property may be used for different outputs
803
+	 *                                - i.e. datetime, money etc.)
804
+	 * @return mixed
805
+	 * @throws EE_Error
806
+	 */
807
+	public function get_pretty($field_name, $extra_cache_ref = null)
808
+	{
809
+		if ($field_name === 'PAY_gateway') {
810
+			return $this->payment_method() ? $this->payment_method()->name() : esc_html__('Unknown', 'event_espresso');
811
+		}
812
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
813
+	}
814
+
815
+
816
+	/**
817
+	 * Gets details regarding which registrations this payment was applied to
818
+	 *
819
+	 * @param array $query_params @see
820
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
821
+	 * @return EE_Registration_Payment[]
822
+	 * @throws EE_Error
823
+	 */
824
+	public function registration_payments($query_params = [])
825
+	{
826
+		return $this->get_many_related('Registration_Payment', $query_params);
827
+	}
828
+
829
+
830
+	/**
831
+	 * Gets the first event for this payment (it's possible that it could be for multiple)
832
+	 *
833
+	 * @return EE_Event|null
834
+	 */
835
+	public function get_first_event()
836
+	{
837
+		$transaction = $this->transaction();
838
+		if ($transaction instanceof EE_Transaction) {
839
+			$primary_registrant = $transaction->primary_registration();
840
+			if ($primary_registrant instanceof EE_Registration) {
841
+				return $primary_registrant->event_obj();
842
+			}
843
+		}
844
+		return null;
845
+	}
846
+
847
+
848
+	/**
849
+	 * Gets the name of the first event for which is being paid
850
+	 *
851
+	 * @return string
852
+	 */
853
+	public function get_first_event_name()
854
+	{
855
+		$event = $this->get_first_event();
856
+		return $event instanceof EE_Event ? $event->name() : esc_html__('Event', 'event_espresso');
857
+	}
858
+
859
+
860
+	/**
861
+	 * Returns the payment's transaction's primary registration
862
+	 *
863
+	 * @return EE_Registration|null
864
+	 */
865
+	public function get_primary_registration()
866
+	{
867
+		if ($this->transaction() instanceof EE_Transaction) {
868
+			return $this->transaction()->primary_registration();
869
+		}
870
+		return null;
871
+	}
872
+
873
+
874
+	/**
875
+	 * Gets the payment's transaction's primary registration's attendee, or null
876
+	 *
877
+	 * @return EE_Attendee|null
878
+	 */
879
+	public function get_primary_attendee()
880
+	{
881
+		$primary_reg = $this->get_primary_registration();
882
+		if ($primary_reg instanceof EE_Registration) {
883
+			return $primary_reg->attendee();
884
+		}
885
+		return null;
886
+	}
887 887
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
      */
299 299
     public function timestamp($dt_frmt = '', $tm_frmt = '')
300 300
     {
301
-        return $this->get_i18n_datetime('PAY_timestamp', trim($dt_frmt . ' ' . $tm_frmt));
301
+        return $this->get_i18n_datetime('PAY_timestamp', trim($dt_frmt.' '.$tm_frmt));
302 302
     }
303 303
 
304 304
 
@@ -460,7 +460,7 @@  discard block
 block discarded – undo
460 460
             false,
461 461
             'sentence'
462 462
         );
463
-        $icon   = '';
463
+        $icon = '';
464 464
         switch ($this->STS_ID()) {
465 465
             case EEM_Payment::status_id_approved:
466 466
                 $icon = $show_icons
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
                     : '';
484 484
                 break;
485 485
         }
486
-        return $icon . $status[ $this->STS_ID() ];
486
+        return $icon.$status[$this->STS_ID()];
487 487
     }
488 488
 
489 489
 
@@ -630,7 +630,7 @@  discard block
 block discarded – undo
630 630
     public function redirect_form($inside_form_html = null)
631 631
     {
632 632
         $redirect_url = $this->redirect_url();
633
-        if (! empty($redirect_url)) {
633
+        if ( ! empty($redirect_url)) {
634 634
             // what ? no inner form content?
635 635
             if ($inside_form_html === null) {
636 636
                 $inside_form_html = EEH_HTML::p(
@@ -660,7 +660,7 @@  discard block
 block discarded – undo
660 660
                 $get_params  = null;
661 661
                 parse_str($querystring, $get_params);
662 662
                 $inside_form_html .= $this->_args_as_inputs($get_params);
663
-                $redirect_url     = str_replace('?' . $querystring, '', $redirect_url);
663
+                $redirect_url = str_replace('?'.$querystring, '', $redirect_url);
664 664
             }
665 665
             $form = EEH_HTML::nl(1)
666 666
                     . '<form method="'
@@ -668,9 +668,9 @@  discard block
 block discarded – undo
668 668
                     . '" name="gateway_form" action="'
669 669
                     . $redirect_url
670 670
                     . '">';
671
-            $form .= EEH_HTML::nl(1) . $this->redirect_args_as_inputs();
671
+            $form .= EEH_HTML::nl(1).$this->redirect_args_as_inputs();
672 672
             $form .= $inside_form_html;
673
-            $form .= EEH_HTML::nl(-1) . '</form>' . EEH_HTML::nl(-1);
673
+            $form .= EEH_HTML::nl(-1).'</form>'.EEH_HTML::nl(-1);
674 674
             return $form;
675 675
         } else {
676 676
             return null;
@@ -729,8 +729,8 @@  discard block
 block discarded – undo
729 729
             return $html;
730 730
         }
731 731
         return EEH_HTML::nl()
732
-               . '<input type="hidden" name="' . $name . '"'
733
-               . ' value="' . esc_attr($value) . '"/>';
732
+               . '<input type="hidden" name="'.$name.'"'
733
+               . ' value="'.esc_attr($value).'"/>';
734 734
     }
735 735
 
736 736
 
@@ -781,7 +781,7 @@  discard block
 block discarded – undo
781 781
             'STS_ID',
782 782
             $this->get_model()->field_settings_for('STS_ID')->get_default_value()
783 783
         );
784
-        $current_status  = $this->status();
784
+        $current_status = $this->status();
785 785
         if (
786 786
             $original_status !== EEM_Payment::status_id_approved
787 787
             && $current_status === EEM_Payment::status_id_approved
Please login to merge, or discard this patch.
core/db_classes/EE_Price.class.php 1 patch
Indentation   +444 added lines, -444 removed lines patch added patch discarded remove patch
@@ -12,448 +12,448 @@
 block discarded – undo
12 12
  */
13 13
 class EE_Price extends EE_Soft_Delete_Base_Class
14 14
 {
15
-    /**
16
-     * @param array  $props_n_values          incoming values
17
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
18
-     *                                        used.)
19
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
20
-     *                                        date_format and the second value is the time format
21
-     * @return EE_Price
22
-     * @throws EE_Error
23
-     * @throws InvalidArgumentException
24
-     * @throws ReflectionException
25
-     * @throws InvalidDataTypeException
26
-     * @throws InvalidInterfaceException
27
-     */
28
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
29
-    {
30
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
31
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
32
-    }
33
-
34
-
35
-    /**
36
-     * @param array  $props_n_values  incoming values from the database
37
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
38
-     *                                the website will be used.
39
-     * @return EE_Price
40
-     * @throws EE_Error
41
-     * @throws InvalidArgumentException
42
-     * @throws ReflectionException
43
-     * @throws InvalidDataTypeException
44
-     * @throws InvalidInterfaceException
45
-     */
46
-    public static function new_instance_from_db($props_n_values = [], $timezone = '')
47
-    {
48
-        return new self($props_n_values, true, $timezone);
49
-    }
50
-
51
-
52
-    /**
53
-     * Set Price type ID
54
-     *
55
-     * @param int $PRT_ID
56
-     * @throws EE_Error
57
-     * @throws InvalidArgumentException
58
-     * @throws ReflectionException
59
-     * @throws InvalidDataTypeException
60
-     * @throws InvalidInterfaceException
61
-     */
62
-    public function set_type($PRT_ID = 0)
63
-    {
64
-        $this->set('PRT_ID', $PRT_ID);
65
-    }
66
-
67
-
68
-    /**
69
-     * Set Price Amount
70
-     *
71
-     * @param float $PRC_amount
72
-     * @throws EE_Error
73
-     * @throws InvalidArgumentException
74
-     * @throws ReflectionException
75
-     * @throws InvalidDataTypeException
76
-     * @throws InvalidInterfaceException
77
-     */
78
-    public function set_amount($PRC_amount = 0.00)
79
-    {
80
-        $this->set('PRC_amount', $PRC_amount);
81
-    }
82
-
83
-
84
-    /**
85
-     * Set Price Name
86
-     *
87
-     * @param string $PRC_name
88
-     * @throws EE_Error
89
-     * @throws InvalidArgumentException
90
-     * @throws ReflectionException
91
-     * @throws InvalidDataTypeException
92
-     * @throws InvalidInterfaceException
93
-     */
94
-    public function set_name($PRC_name = '')
95
-    {
96
-        $this->set('PRC_name', $PRC_name);
97
-    }
98
-
99
-
100
-    /**
101
-     * Set Price Description
102
-     *
103
-     * @param string $PRC_desc
104
-     * @throws EE_Error
105
-     * @throws InvalidArgumentException
106
-     * @throws ReflectionException
107
-     * @throws InvalidDataTypeException
108
-     * @throws InvalidInterfaceException
109
-     */
110
-    public function set_description($PRC_desc = '')
111
-    {
112
-        $this->Set('PRC_desc', $PRC_desc);
113
-    }
114
-
115
-
116
-    /**
117
-     * set is_default
118
-     *
119
-     * @param bool $PRC_is_default
120
-     * @throws EE_Error
121
-     * @throws InvalidArgumentException
122
-     * @throws ReflectionException
123
-     * @throws InvalidDataTypeException
124
-     * @throws InvalidInterfaceException
125
-     */
126
-    public function set_is_default($PRC_is_default = false)
127
-    {
128
-        $this->set('PRC_is_default', $PRC_is_default);
129
-    }
130
-
131
-
132
-    /**
133
-     * set deleted
134
-     *
135
-     * @param bool $PRC_deleted
136
-     * @throws EE_Error
137
-     * @throws InvalidArgumentException
138
-     * @throws ReflectionException
139
-     * @throws InvalidDataTypeException
140
-     * @throws InvalidInterfaceException
141
-     */
142
-    public function set_deleted($PRC_deleted = null)
143
-    {
144
-        $this->set('PRC_deleted', $PRC_deleted);
145
-    }
146
-
147
-
148
-    /**
149
-     * get Price type
150
-     *
151
-     * @return        int
152
-     * @throws EE_Error
153
-     * @throws InvalidArgumentException
154
-     * @throws ReflectionException
155
-     * @throws InvalidDataTypeException
156
-     * @throws InvalidInterfaceException
157
-     */
158
-    public function type()
159
-    {
160
-        return $this->get('PRT_ID');
161
-    }
162
-
163
-
164
-    /**
165
-     * get Price Amount
166
-     *
167
-     * @return        float
168
-     * @throws EE_Error
169
-     * @throws InvalidArgumentException
170
-     * @throws ReflectionException
171
-     * @throws InvalidDataTypeException
172
-     * @throws InvalidInterfaceException
173
-     */
174
-    public function amount()
175
-    {
176
-        return $this->get('PRC_amount');
177
-    }
178
-
179
-
180
-    /**
181
-     * get Price Name
182
-     *
183
-     * @return        string
184
-     * @throws EE_Error
185
-     * @throws InvalidArgumentException
186
-     * @throws ReflectionException
187
-     * @throws InvalidDataTypeException
188
-     * @throws InvalidInterfaceException
189
-     */
190
-    public function name()
191
-    {
192
-        return $this->get('PRC_name');
193
-    }
194
-
195
-
196
-    /**
197
-     * get Price description
198
-     *
199
-     * @return        string
200
-     * @throws EE_Error
201
-     * @throws InvalidArgumentException
202
-     * @throws ReflectionException
203
-     * @throws InvalidDataTypeException
204
-     * @throws InvalidInterfaceException
205
-     */
206
-    public function desc()
207
-    {
208
-        return $this->get('PRC_desc');
209
-    }
210
-
211
-
212
-    /**
213
-     * get overrides
214
-     *
215
-     * @return        int
216
-     * @throws EE_Error
217
-     * @throws InvalidArgumentException
218
-     * @throws ReflectionException
219
-     * @throws InvalidDataTypeException
220
-     * @throws InvalidInterfaceException
221
-     */
222
-    public function overrides()
223
-    {
224
-        return $this->get('PRC_overrides');
225
-    }
226
-
227
-
228
-    /**
229
-     * get order
230
-     *
231
-     * @return int
232
-     * @throws EE_Error
233
-     * @throws InvalidArgumentException
234
-     * @throws ReflectionException
235
-     * @throws InvalidDataTypeException
236
-     * @throws InvalidInterfaceException
237
-     */
238
-    public function order()
239
-    {
240
-        return $this->get('PRC_order');
241
-    }
242
-
243
-
244
-    /**
245
-     * get the author of the price
246
-     *
247
-     * @return int
248
-     * @throws EE_Error
249
-     * @throws InvalidArgumentException
250
-     * @throws ReflectionException
251
-     * @throws InvalidDataTypeException
252
-     * @throws InvalidInterfaceException
253
-     * @since 4.5.0
254
-     */
255
-    public function wp_user()
256
-    {
257
-        return $this->get('PRC_wp_user');
258
-    }
259
-
260
-
261
-    /**
262
-     * get is_default
263
-     *
264
-     * @return bool
265
-     * @throws EE_Error
266
-     * @throws InvalidArgumentException
267
-     * @throws ReflectionException
268
-     * @throws InvalidDataTypeException
269
-     * @throws InvalidInterfaceException
270
-     */
271
-    public function is_default()
272
-    {
273
-        return $this->get('PRC_is_default');
274
-    }
275
-
276
-
277
-    /**
278
-     * get deleted
279
-     *
280
-     * @return bool
281
-     * @throws EE_Error
282
-     * @throws InvalidArgumentException
283
-     * @throws ReflectionException
284
-     * @throws InvalidDataTypeException
285
-     * @throws InvalidInterfaceException
286
-     */
287
-    public function deleted()
288
-    {
289
-        return $this->get('PRC_deleted');
290
-    }
291
-
292
-
293
-    /**
294
-     * @return bool
295
-     * @throws EE_Error
296
-     * @throws InvalidArgumentException
297
-     * @throws ReflectionException
298
-     * @throws InvalidDataTypeException
299
-     * @throws InvalidInterfaceException
300
-     */
301
-    public function parent()
302
-    {
303
-        return $this->get('PRC_parent');
304
-    }
305
-
306
-
307
-    // some helper methods for getting info on the price_type for this price
308
-
309
-
310
-    /**
311
-     * return whether the price is a base price or not
312
-     *
313
-     * @return bool
314
-     * @throws EE_Error
315
-     * @throws InvalidArgumentException
316
-     * @throws InvalidDataTypeException
317
-     * @throws InvalidInterfaceException
318
-     * @throws ReflectionException
319
-     */
320
-    public function is_base_price(): bool
321
-    {
322
-        $price_type = $this->type_obj();
323
-        return $price_type instanceof EE_Price_Type ? $price_type->is_base_price() : false;
324
-    }
325
-
326
-
327
-    /**
328
-     * @return EE_Base_Class|EE_Price_Type
329
-     * @throws EE_Error
330
-     * @throws InvalidArgumentException
331
-     * @throws ReflectionException
332
-     * @throws InvalidDataTypeException
333
-     * @throws InvalidInterfaceException
334
-     */
335
-    public function type_obj()
336
-    {
337
-        return $this->get_first_related('Price_Type');
338
-    }
339
-
340
-
341
-    /**
342
-     * @return int
343
-     * @throws EE_Error
344
-     * @throws InvalidArgumentException
345
-     * @throws ReflectionException
346
-     * @throws InvalidDataTypeException
347
-     * @throws InvalidInterfaceException
348
-     */
349
-    public function type_order()
350
-    {
351
-        return $this->get_first_related('Price_Type')->order();
352
-    }
353
-
354
-
355
-    /**
356
-     * Simply indicates whether this price increases or decreases the total
357
-     *
358
-     * @return bool true = discount, otherwise adds to the total
359
-     * @throws EE_Error
360
-     * @throws InvalidArgumentException
361
-     * @throws ReflectionException
362
-     * @throws InvalidDataTypeException
363
-     * @throws InvalidInterfaceException
364
-     */
365
-    public function is_discount(): bool
366
-    {
367
-        $price_type = $this->type_obj();
368
-        return $price_type instanceof EE_Price_Type ? $price_type->is_discount() : false;
369
-    }
370
-
371
-
372
-    /**
373
-     * whether the price is a percentage or not
374
-     *
375
-     * @return bool
376
-     * @throws EE_Error
377
-     * @throws InvalidArgumentException
378
-     * @throws InvalidDataTypeException
379
-     * @throws InvalidInterfaceException
380
-     * @throws ReflectionException
381
-     */
382
-    public function is_percent(): bool
383
-    {
384
-        $price_type = $this->type_obj();
385
-        return $price_type instanceof EE_Price_Type ? $price_type->is_percent() : false;
386
-    }
387
-
388
-
389
-    /**
390
-     * whether the price is a percentage or not
391
-     *
392
-     * @return bool
393
-     * @throws EE_Error
394
-     * @throws InvalidArgumentException
395
-     * @throws ReflectionException
396
-     * @throws InvalidDataTypeException
397
-     * @throws InvalidInterfaceException
398
-     */
399
-    public function is_surcharge(): bool
400
-    {
401
-        $price_type = $this->type_obj();
402
-        return $price_type instanceof EE_Price_Type ? $price_type->is_surcharge() : false;
403
-    }
404
-
405
-
406
-
407
-    /**
408
-     * whether the price is a percentage or not
409
-     *
410
-     * @return bool
411
-     * @throws EE_Error
412
-     * @throws InvalidArgumentException
413
-     * @throws ReflectionException
414
-     * @throws InvalidDataTypeException
415
-     * @throws InvalidInterfaceException
416
-     */
417
-    public function is_tax(): bool
418
-    {
419
-        $price_type = $this->type_obj();
420
-        return $price_type instanceof EE_Price_Type ? $price_type->is_tax() : false;
421
-    }
422
-
423
-
424
-    /**
425
-     * return pretty price dependant on whether its a dollar or percent.
426
-     *
427
-     * @return string
428
-     * @throws EE_Error
429
-     * @throws InvalidArgumentException
430
-     * @throws ReflectionException
431
-     * @throws InvalidDataTypeException
432
-     * @throws InvalidInterfaceException
433
-     * @since 4.4.0
434
-     */
435
-    public function pretty_price()
436
-    {
437
-        return ! $this->is_percent()
438
-            ? $this->get_pretty('PRC_amount')
439
-            : $this->get('PRC_amount') . '%';
440
-    }
441
-
442
-
443
-    /**
444
-     * @return mixed
445
-     * @throws EE_Error
446
-     * @throws InvalidArgumentException
447
-     * @throws ReflectionException
448
-     * @throws InvalidDataTypeException
449
-     * @throws InvalidInterfaceException
450
-     */
451
-    public function get_price_without_currency_symbol()
452
-    {
453
-        return str_replace(
454
-            EE_Registry::instance()->CFG->currency->sign,
455
-            '',
456
-            $this->get_pretty('PRC_amount')
457
-        );
458
-    }
15
+	/**
16
+	 * @param array  $props_n_values          incoming values
17
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
18
+	 *                                        used.)
19
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
20
+	 *                                        date_format and the second value is the time format
21
+	 * @return EE_Price
22
+	 * @throws EE_Error
23
+	 * @throws InvalidArgumentException
24
+	 * @throws ReflectionException
25
+	 * @throws InvalidDataTypeException
26
+	 * @throws InvalidInterfaceException
27
+	 */
28
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
29
+	{
30
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
31
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
32
+	}
33
+
34
+
35
+	/**
36
+	 * @param array  $props_n_values  incoming values from the database
37
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
38
+	 *                                the website will be used.
39
+	 * @return EE_Price
40
+	 * @throws EE_Error
41
+	 * @throws InvalidArgumentException
42
+	 * @throws ReflectionException
43
+	 * @throws InvalidDataTypeException
44
+	 * @throws InvalidInterfaceException
45
+	 */
46
+	public static function new_instance_from_db($props_n_values = [], $timezone = '')
47
+	{
48
+		return new self($props_n_values, true, $timezone);
49
+	}
50
+
51
+
52
+	/**
53
+	 * Set Price type ID
54
+	 *
55
+	 * @param int $PRT_ID
56
+	 * @throws EE_Error
57
+	 * @throws InvalidArgumentException
58
+	 * @throws ReflectionException
59
+	 * @throws InvalidDataTypeException
60
+	 * @throws InvalidInterfaceException
61
+	 */
62
+	public function set_type($PRT_ID = 0)
63
+	{
64
+		$this->set('PRT_ID', $PRT_ID);
65
+	}
66
+
67
+
68
+	/**
69
+	 * Set Price Amount
70
+	 *
71
+	 * @param float $PRC_amount
72
+	 * @throws EE_Error
73
+	 * @throws InvalidArgumentException
74
+	 * @throws ReflectionException
75
+	 * @throws InvalidDataTypeException
76
+	 * @throws InvalidInterfaceException
77
+	 */
78
+	public function set_amount($PRC_amount = 0.00)
79
+	{
80
+		$this->set('PRC_amount', $PRC_amount);
81
+	}
82
+
83
+
84
+	/**
85
+	 * Set Price Name
86
+	 *
87
+	 * @param string $PRC_name
88
+	 * @throws EE_Error
89
+	 * @throws InvalidArgumentException
90
+	 * @throws ReflectionException
91
+	 * @throws InvalidDataTypeException
92
+	 * @throws InvalidInterfaceException
93
+	 */
94
+	public function set_name($PRC_name = '')
95
+	{
96
+		$this->set('PRC_name', $PRC_name);
97
+	}
98
+
99
+
100
+	/**
101
+	 * Set Price Description
102
+	 *
103
+	 * @param string $PRC_desc
104
+	 * @throws EE_Error
105
+	 * @throws InvalidArgumentException
106
+	 * @throws ReflectionException
107
+	 * @throws InvalidDataTypeException
108
+	 * @throws InvalidInterfaceException
109
+	 */
110
+	public function set_description($PRC_desc = '')
111
+	{
112
+		$this->Set('PRC_desc', $PRC_desc);
113
+	}
114
+
115
+
116
+	/**
117
+	 * set is_default
118
+	 *
119
+	 * @param bool $PRC_is_default
120
+	 * @throws EE_Error
121
+	 * @throws InvalidArgumentException
122
+	 * @throws ReflectionException
123
+	 * @throws InvalidDataTypeException
124
+	 * @throws InvalidInterfaceException
125
+	 */
126
+	public function set_is_default($PRC_is_default = false)
127
+	{
128
+		$this->set('PRC_is_default', $PRC_is_default);
129
+	}
130
+
131
+
132
+	/**
133
+	 * set deleted
134
+	 *
135
+	 * @param bool $PRC_deleted
136
+	 * @throws EE_Error
137
+	 * @throws InvalidArgumentException
138
+	 * @throws ReflectionException
139
+	 * @throws InvalidDataTypeException
140
+	 * @throws InvalidInterfaceException
141
+	 */
142
+	public function set_deleted($PRC_deleted = null)
143
+	{
144
+		$this->set('PRC_deleted', $PRC_deleted);
145
+	}
146
+
147
+
148
+	/**
149
+	 * get Price type
150
+	 *
151
+	 * @return        int
152
+	 * @throws EE_Error
153
+	 * @throws InvalidArgumentException
154
+	 * @throws ReflectionException
155
+	 * @throws InvalidDataTypeException
156
+	 * @throws InvalidInterfaceException
157
+	 */
158
+	public function type()
159
+	{
160
+		return $this->get('PRT_ID');
161
+	}
162
+
163
+
164
+	/**
165
+	 * get Price Amount
166
+	 *
167
+	 * @return        float
168
+	 * @throws EE_Error
169
+	 * @throws InvalidArgumentException
170
+	 * @throws ReflectionException
171
+	 * @throws InvalidDataTypeException
172
+	 * @throws InvalidInterfaceException
173
+	 */
174
+	public function amount()
175
+	{
176
+		return $this->get('PRC_amount');
177
+	}
178
+
179
+
180
+	/**
181
+	 * get Price Name
182
+	 *
183
+	 * @return        string
184
+	 * @throws EE_Error
185
+	 * @throws InvalidArgumentException
186
+	 * @throws ReflectionException
187
+	 * @throws InvalidDataTypeException
188
+	 * @throws InvalidInterfaceException
189
+	 */
190
+	public function name()
191
+	{
192
+		return $this->get('PRC_name');
193
+	}
194
+
195
+
196
+	/**
197
+	 * get Price description
198
+	 *
199
+	 * @return        string
200
+	 * @throws EE_Error
201
+	 * @throws InvalidArgumentException
202
+	 * @throws ReflectionException
203
+	 * @throws InvalidDataTypeException
204
+	 * @throws InvalidInterfaceException
205
+	 */
206
+	public function desc()
207
+	{
208
+		return $this->get('PRC_desc');
209
+	}
210
+
211
+
212
+	/**
213
+	 * get overrides
214
+	 *
215
+	 * @return        int
216
+	 * @throws EE_Error
217
+	 * @throws InvalidArgumentException
218
+	 * @throws ReflectionException
219
+	 * @throws InvalidDataTypeException
220
+	 * @throws InvalidInterfaceException
221
+	 */
222
+	public function overrides()
223
+	{
224
+		return $this->get('PRC_overrides');
225
+	}
226
+
227
+
228
+	/**
229
+	 * get order
230
+	 *
231
+	 * @return int
232
+	 * @throws EE_Error
233
+	 * @throws InvalidArgumentException
234
+	 * @throws ReflectionException
235
+	 * @throws InvalidDataTypeException
236
+	 * @throws InvalidInterfaceException
237
+	 */
238
+	public function order()
239
+	{
240
+		return $this->get('PRC_order');
241
+	}
242
+
243
+
244
+	/**
245
+	 * get the author of the price
246
+	 *
247
+	 * @return int
248
+	 * @throws EE_Error
249
+	 * @throws InvalidArgumentException
250
+	 * @throws ReflectionException
251
+	 * @throws InvalidDataTypeException
252
+	 * @throws InvalidInterfaceException
253
+	 * @since 4.5.0
254
+	 */
255
+	public function wp_user()
256
+	{
257
+		return $this->get('PRC_wp_user');
258
+	}
259
+
260
+
261
+	/**
262
+	 * get is_default
263
+	 *
264
+	 * @return bool
265
+	 * @throws EE_Error
266
+	 * @throws InvalidArgumentException
267
+	 * @throws ReflectionException
268
+	 * @throws InvalidDataTypeException
269
+	 * @throws InvalidInterfaceException
270
+	 */
271
+	public function is_default()
272
+	{
273
+		return $this->get('PRC_is_default');
274
+	}
275
+
276
+
277
+	/**
278
+	 * get deleted
279
+	 *
280
+	 * @return bool
281
+	 * @throws EE_Error
282
+	 * @throws InvalidArgumentException
283
+	 * @throws ReflectionException
284
+	 * @throws InvalidDataTypeException
285
+	 * @throws InvalidInterfaceException
286
+	 */
287
+	public function deleted()
288
+	{
289
+		return $this->get('PRC_deleted');
290
+	}
291
+
292
+
293
+	/**
294
+	 * @return bool
295
+	 * @throws EE_Error
296
+	 * @throws InvalidArgumentException
297
+	 * @throws ReflectionException
298
+	 * @throws InvalidDataTypeException
299
+	 * @throws InvalidInterfaceException
300
+	 */
301
+	public function parent()
302
+	{
303
+		return $this->get('PRC_parent');
304
+	}
305
+
306
+
307
+	// some helper methods for getting info on the price_type for this price
308
+
309
+
310
+	/**
311
+	 * return whether the price is a base price or not
312
+	 *
313
+	 * @return bool
314
+	 * @throws EE_Error
315
+	 * @throws InvalidArgumentException
316
+	 * @throws InvalidDataTypeException
317
+	 * @throws InvalidInterfaceException
318
+	 * @throws ReflectionException
319
+	 */
320
+	public function is_base_price(): bool
321
+	{
322
+		$price_type = $this->type_obj();
323
+		return $price_type instanceof EE_Price_Type ? $price_type->is_base_price() : false;
324
+	}
325
+
326
+
327
+	/**
328
+	 * @return EE_Base_Class|EE_Price_Type
329
+	 * @throws EE_Error
330
+	 * @throws InvalidArgumentException
331
+	 * @throws ReflectionException
332
+	 * @throws InvalidDataTypeException
333
+	 * @throws InvalidInterfaceException
334
+	 */
335
+	public function type_obj()
336
+	{
337
+		return $this->get_first_related('Price_Type');
338
+	}
339
+
340
+
341
+	/**
342
+	 * @return int
343
+	 * @throws EE_Error
344
+	 * @throws InvalidArgumentException
345
+	 * @throws ReflectionException
346
+	 * @throws InvalidDataTypeException
347
+	 * @throws InvalidInterfaceException
348
+	 */
349
+	public function type_order()
350
+	{
351
+		return $this->get_first_related('Price_Type')->order();
352
+	}
353
+
354
+
355
+	/**
356
+	 * Simply indicates whether this price increases or decreases the total
357
+	 *
358
+	 * @return bool true = discount, otherwise adds to the total
359
+	 * @throws EE_Error
360
+	 * @throws InvalidArgumentException
361
+	 * @throws ReflectionException
362
+	 * @throws InvalidDataTypeException
363
+	 * @throws InvalidInterfaceException
364
+	 */
365
+	public function is_discount(): bool
366
+	{
367
+		$price_type = $this->type_obj();
368
+		return $price_type instanceof EE_Price_Type ? $price_type->is_discount() : false;
369
+	}
370
+
371
+
372
+	/**
373
+	 * whether the price is a percentage or not
374
+	 *
375
+	 * @return bool
376
+	 * @throws EE_Error
377
+	 * @throws InvalidArgumentException
378
+	 * @throws InvalidDataTypeException
379
+	 * @throws InvalidInterfaceException
380
+	 * @throws ReflectionException
381
+	 */
382
+	public function is_percent(): bool
383
+	{
384
+		$price_type = $this->type_obj();
385
+		return $price_type instanceof EE_Price_Type ? $price_type->is_percent() : false;
386
+	}
387
+
388
+
389
+	/**
390
+	 * whether the price is a percentage or not
391
+	 *
392
+	 * @return bool
393
+	 * @throws EE_Error
394
+	 * @throws InvalidArgumentException
395
+	 * @throws ReflectionException
396
+	 * @throws InvalidDataTypeException
397
+	 * @throws InvalidInterfaceException
398
+	 */
399
+	public function is_surcharge(): bool
400
+	{
401
+		$price_type = $this->type_obj();
402
+		return $price_type instanceof EE_Price_Type ? $price_type->is_surcharge() : false;
403
+	}
404
+
405
+
406
+
407
+	/**
408
+	 * whether the price is a percentage or not
409
+	 *
410
+	 * @return bool
411
+	 * @throws EE_Error
412
+	 * @throws InvalidArgumentException
413
+	 * @throws ReflectionException
414
+	 * @throws InvalidDataTypeException
415
+	 * @throws InvalidInterfaceException
416
+	 */
417
+	public function is_tax(): bool
418
+	{
419
+		$price_type = $this->type_obj();
420
+		return $price_type instanceof EE_Price_Type ? $price_type->is_tax() : false;
421
+	}
422
+
423
+
424
+	/**
425
+	 * return pretty price dependant on whether its a dollar or percent.
426
+	 *
427
+	 * @return string
428
+	 * @throws EE_Error
429
+	 * @throws InvalidArgumentException
430
+	 * @throws ReflectionException
431
+	 * @throws InvalidDataTypeException
432
+	 * @throws InvalidInterfaceException
433
+	 * @since 4.4.0
434
+	 */
435
+	public function pretty_price()
436
+	{
437
+		return ! $this->is_percent()
438
+			? $this->get_pretty('PRC_amount')
439
+			: $this->get('PRC_amount') . '%';
440
+	}
441
+
442
+
443
+	/**
444
+	 * @return mixed
445
+	 * @throws EE_Error
446
+	 * @throws InvalidArgumentException
447
+	 * @throws ReflectionException
448
+	 * @throws InvalidDataTypeException
449
+	 * @throws InvalidInterfaceException
450
+	 */
451
+	public function get_price_without_currency_symbol()
452
+	{
453
+		return str_replace(
454
+			EE_Registry::instance()->CFG->currency->sign,
455
+			'',
456
+			$this->get_pretty('PRC_amount')
457
+		);
458
+	}
459 459
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Question.class.php 2 patches
Indentation   +669 added lines, -669 removed lines patch added patch discarded remove patch
@@ -12,673 +12,673 @@
 block discarded – undo
12 12
  */
13 13
 class EE_Question extends EE_Soft_Delete_Base_Class implements EEI_Duplicatable
14 14
 {
15
-    /**
16
-     * @param array  $props_n_values          incoming values
17
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
18
-     *                                        used.)
19
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
20
-     *                                        date_format and the second value is the time format
21
-     * @return EE_Question
22
-     */
23
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
24
-    {
25
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
26
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
27
-    }
28
-
29
-
30
-    /**
31
-     * @param array  $props_n_values  incoming values from the database
32
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
33
-     *                                the website will be used.
34
-     * @return EE_Question
35
-     */
36
-    public static function new_instance_from_db($props_n_values = [], $timezone = '')
37
-    {
38
-        return new self($props_n_values, true, $timezone);
39
-    }
40
-
41
-
42
-    /**
43
-     *        Set    Question display text
44
-     *
45
-     * @access        public
46
-     * @param string $QST_display_text
47
-     */
48
-    public function set_display_text($QST_display_text = '')
49
-    {
50
-        $this->set('QST_display_text', $QST_display_text);
51
-    }
52
-
53
-
54
-    /**
55
-     *        Set    Question admin text
56
-     *
57
-     * @access        public
58
-     * @param string $QST_admin_label
59
-     */
60
-    public function set_admin_label($QST_admin_label = '')
61
-    {
62
-        $this->set('QST_admin_label', $QST_admin_label);
63
-    }
64
-
65
-
66
-    /**
67
-     *        Set    system name
68
-     *
69
-     * @access        public
70
-     * @param mixed $QST_system
71
-     */
72
-    public function set_system_ID($QST_system = '')
73
-    {
74
-        $this->set('QST_system', $QST_system);
75
-    }
76
-
77
-
78
-    /**
79
-     *        Set    question's type
80
-     *
81
-     * @access        public
82
-     * @param string $QST_type
83
-     */
84
-    public function set_question_type($QST_type = '')
85
-    {
86
-        $this->set('QST_type', $QST_type);
87
-    }
88
-
89
-
90
-    /**
91
-     *        Sets whether this question must be answered when presented in a form
92
-     *
93
-     * @access        public
94
-     * @param bool $QST_required
95
-     */
96
-    public function set_required($QST_required = false)
97
-    {
98
-        $this->set('QST_required', $QST_required);
99
-    }
100
-
101
-
102
-    /**
103
-     *        Set    Question display text
104
-     *
105
-     * @access        public
106
-     * @param string $QST_required_text
107
-     */
108
-    public function set_required_text($QST_required_text = '')
109
-    {
110
-        $this->set('QST_required_text', $QST_required_text);
111
-    }
112
-
113
-
114
-    /**
115
-     *        Sets the order of this question when placed in a sequence of questions
116
-     *
117
-     * @access        public
118
-     * @param int $QST_order
119
-     */
120
-    public function set_order($QST_order = 0)
121
-    {
122
-        $this->set('QST_order', $QST_order);
123
-    }
124
-
125
-
126
-    /**
127
-     *        Sets whether the question is admin-only
128
-     *
129
-     * @access        public
130
-     * @param bool $QST_admin_only
131
-     */
132
-    public function set_admin_only($QST_admin_only = false)
133
-    {
134
-        $this->set('QST_admin_only', $QST_admin_only);
135
-    }
136
-
137
-
138
-    /**
139
-     *        Sets the wordpress user ID on the question
140
-     *
141
-     * @access        public
142
-     * @param int $QST_wp_user
143
-     */
144
-    public function set_wp_user($QST_wp_user = 1)
145
-    {
146
-        $this->set('QST_wp_user', $QST_wp_user);
147
-    }
148
-
149
-
150
-    /**
151
-     *        Sets whether the question has been deleted
152
-     *        (we use this boolean instead of actually
153
-     *        deleting it because when users delete this question
154
-     *        they really want to remove the question from future
155
-     *        forms, BUT keep their old answers which depend
156
-     *        on this record actually existing.
157
-     *
158
-     * @access        public
159
-     * @param bool $QST_deleted
160
-     */
161
-    public function set_deleted($QST_deleted = false)
162
-    {
163
-        $this->set('QST_deleted', $QST_deleted);
164
-    }
165
-
166
-
167
-    /**
168
-     * returns the text for displaying the question to users
169
-     *
170
-     * @access public
171
-     * @return string
172
-     */
173
-    public function display_text()
174
-    {
175
-        return $this->get('QST_display_text');
176
-    }
177
-
178
-
179
-    /**
180
-     * returns the text for the administrative label
181
-     *
182
-     * @access public
183
-     * @return string
184
-     */
185
-    public function admin_label()
186
-    {
187
-        return $this->get('QST_admin_label');
188
-    }
189
-
190
-
191
-    /**
192
-     * returns the attendee column name for this question
193
-     *
194
-     * @access public
195
-     * @return string
196
-     */
197
-    public function system_ID()
198
-    {
199
-        return $this->get('QST_system');
200
-    }
201
-
202
-
203
-    /**
204
-     * returns either a string of 'text', 'textfield', etc.
205
-     *
206
-     * @access public
207
-     * @return boolean
208
-     */
209
-    public function required()
210
-    {
211
-        return $this->get('QST_required');
212
-    }
213
-
214
-
215
-    /**
216
-     * returns the text which should be displayed when a user
217
-     * doesn't answer this question in a form
218
-     *
219
-     * @access public
220
-     * @return string
221
-     */
222
-    public function required_text()
223
-    {
224
-        return $this->get('QST_required_text');
225
-    }
226
-
227
-
228
-    /**
229
-     * returns the type of this question
230
-     *
231
-     * @access public
232
-     * @return string
233
-     */
234
-    public function type()
235
-    {
236
-        return $this->get('QST_type');
237
-    }
238
-
239
-
240
-    /**
241
-     * returns an integer showing where this question should
242
-     * be placed in a sequence of questions
243
-     *
244
-     * @access public
245
-     * @return int
246
-     */
247
-    public function order()
248
-    {
249
-        return $this->get('QST_order');
250
-    }
251
-
252
-
253
-    /**
254
-     * returns whether this question should only appears to admins,
255
-     * or to everyone
256
-     *
257
-     * @access public
258
-     * @return boolean
259
-     */
260
-    public function admin_only()
261
-    {
262
-        return $this->get('QST_admin_only');
263
-    }
264
-
265
-
266
-    /**
267
-     * returns the id the wordpress user who created this question
268
-     *
269
-     * @access public
270
-     * @return int
271
-     */
272
-    public function wp_user()
273
-    {
274
-        return $this->get('QST_wp_user');
275
-    }
276
-
277
-
278
-    /**
279
-     * returns whether this question has been marked as 'deleted'
280
-     *
281
-     * @access public
282
-     * @return boolean
283
-     */
284
-    public function deleted()
285
-    {
286
-        return $this->get('QST_deleted');
287
-    }
288
-
289
-
290
-    /**
291
-     * Gets an array of related EE_Answer  to this EE_Question
292
-     *
293
-     * @return EE_Answer[]
294
-     */
295
-    public function answers()
296
-    {
297
-        return $this->get_many_related('Answer');
298
-    }
299
-
300
-
301
-    /**
302
-     * Boolean check for if there are answers on this question in th db
303
-     *
304
-     * @return boolean true = has answers, false = no answers.
305
-     */
306
-    public function has_answers()
307
-    {
308
-        return $this->count_related('Answer') > 0 ? true : false;
309
-    }
310
-
311
-
312
-    /**
313
-     * gets an array of EE_Question_Group which relate to this question
314
-     *
315
-     * @return EE_Question_Group[]
316
-     */
317
-    public function question_groups()
318
-    {
319
-        return $this->get_many_related('Question_Group');
320
-    }
321
-
322
-
323
-    /**
324
-     * Returns all the options for this question. By default, it returns only the not-yet-deleted ones.
325
-     *
326
-     * @param boolean      $notDeletedOptionsOnly            1
327
-     *                                                       whether to return ALL options, or only the ones which have
328
-     *                                                       not yet been deleleted
329
-     * @param string|array $selected_value_to_always_include , when retrieving options to an ANSWERED question,
330
-     *                                                       we want to usually only show non-deleted options AND the
331
-     *                                                       value that was selected for the answer, whether it was
332
-     *                                                       trashed or not.
333
-     * @return EE_Question_Option[]
334
-     */
335
-    public function options($notDeletedOptionsOnly = true, $selected_value_to_always_include = null)
336
-    {
337
-        if (! $this->ID()) {
338
-            return [];
339
-        }
340
-        $query_params = [];
341
-        if ($selected_value_to_always_include) {
342
-            if (is_array($selected_value_to_always_include)) {
343
-                $query_params[0]['OR*options-query']['QSO_value'] = ['IN', $selected_value_to_always_include];
344
-            } else {
345
-                $query_params[0]['OR*options-query']['QSO_value'] = $selected_value_to_always_include;
346
-            }
347
-        }
348
-        if ($notDeletedOptionsOnly) {
349
-            $query_params[0]['OR*options-query']['QSO_deleted'] = false;
350
-        }
351
-        // order by QSO_order
352
-        $query_params['order_by'] = ['QSO_order' => 'ASC'];
353
-        return $this->get_many_related('Question_Option', $query_params);
354
-    }
355
-
356
-
357
-    /**
358
-     * returns an array of EE_Question_Options which relate to this question
359
-     *
360
-     * @return \EE_Question_Option[]
361
-     */
362
-    public function temp_options()
363
-    {
364
-        return $this->_model_relations['Question_Option'];
365
-    }
366
-
367
-
368
-    /**
369
-     * Adds an option for this question. Note: if the option were previously associated with a different
370
-     * Question, that relationship will be overwritten.
371
-     *
372
-     * @param EE_Question_Option $option
373
-     * @return boolean success
374
-     */
375
-    public function add_option(EE_Question_Option $option)
376
-    {
377
-        return $this->_add_relation_to($option, 'Question_Option');
378
-    }
379
-
380
-
381
-    /**
382
-     * Adds an option directly to this question without saving to the db
383
-     *
384
-     * @param EE_Question_Option $option
385
-     * @return boolean success
386
-     */
387
-    public function add_temp_option(EE_Question_Option $option)
388
-    {
389
-        $this->_model_relations['Question_Option'][] = $option;
390
-        return true;
391
-    }
392
-
393
-
394
-    /**
395
-     * Marks the option as deleted.
396
-     *
397
-     * @param EE_Question_Option $option
398
-     * @return boolean success
399
-     */
400
-    public function remove_option(EE_Question_Option $option)
401
-    {
402
-        return $this->_remove_relation_to($option, 'Question_Option');
403
-    }
404
-
405
-
406
-    /**
407
-     * @return bool
408
-     */
409
-    public function is_system_question()
410
-    {
411
-        $system_ID = $this->get('QST_system');
412
-        return ! empty($system_ID) ? true : false;
413
-    }
414
-
415
-
416
-    /**
417
-     * The purpose of this method is set the question order this question order to be the max out of all questions
418
-     *
419
-     * @access public
420
-     * @return void
421
-     */
422
-    public function set_order_to_latest()
423
-    {
424
-        $latest_order = $this->get_model()->get_latest_question_order();
425
-        $latest_order++;
426
-        $this->set('QST_order', $latest_order);
427
-    }
428
-
429
-
430
-    /**
431
-     * Retrieves the list of allowed question types from the model.
432
-     *
433
-     * @return string[]
434
-     */
435
-    private function _allowed_question_types()
436
-    {
437
-        $questionModel = $this->get_model();
438
-        /* @var $questionModel EEM_Question */
439
-        return $questionModel->allowed_question_types();
440
-    }
441
-
442
-
443
-    /**
444
-     * Duplicates this question and its question options
445
-     *
446
-     * @return \EE_Question
447
-     */
448
-    public function duplicate($options = [])
449
-    {
450
-        $new_question = clone $this;
451
-        $new_question->set('QST_ID', null);
452
-        $new_question->set_display_text(
453
-            sprintf(esc_html__('%s **Duplicate**', 'event_espresso'), $this->display_text())
454
-        );
455
-        $new_question->set_admin_label(sprintf(esc_html__('%s **Duplicate**', 'event_espresso'), $this->admin_label()));
456
-        $new_question->set_system_ID(null);
457
-        $new_question->set_wp_user(get_current_user_id());
458
-        // if we're duplicating a trashed question, assume we don't want the new one to be trashed
459
-        $new_question->set_deleted(false);
460
-        $success = $new_question->save();
461
-        if ($success) {
462
-            // we don't totally want to duplicate the question options, because we want them to be for the NEW question
463
-            foreach ($this->options() as $question_option) {
464
-                $question_option->duplicate(['QST_ID' => $new_question->ID()]);
465
-            }
466
-            return $new_question;
467
-        } else {
468
-            return null;
469
-        }
470
-    }
471
-
472
-
473
-    /**
474
-     * Returns the question's maximum allowed response size
475
-     *
476
-     * @return int|float
477
-     */
478
-    public function max()
479
-    {
480
-        return $this->get('QST_max');
481
-    }
482
-
483
-
484
-    /**
485
-     * Sets the question's maximum allowed response size
486
-     *
487
-     * @param int|float $new_max
488
-     * @return void
489
-     */
490
-    public function set_max($new_max)
491
-    {
492
-        $this->set('QST_max', $new_max);
493
-    }
494
-
495
-
496
-    /**
497
-     * Creates a form input from this question which can be used in HTML forms
498
-     *
499
-     * @param EE_Registration $registration
500
-     * @param EE_Answer       $answer
501
-     * @param array           $input_constructor_args
502
-     * @return EE_Form_Input_Base
503
-     */
504
-    public function generate_form_input($registration = null, $answer = null, $input_constructor_args = [])
505
-    {
506
-        $identifier = $this->is_system_question() ? $this->system_ID() : $this->ID();
507
-
508
-        $input_constructor_args = array_merge(
509
-            [
510
-                'required'                          => $this->required() ? true : false,
511
-                'html_label_text'                   => $this->display_text(),
512
-                'required_validation_error_message' => $this->required_text(),
513
-            ],
514
-            $input_constructor_args
515
-        );
516
-        if (! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
517
-            $answer = EEM_Answer::instance()->get_registration_question_answer_object($registration, $this->ID());
518
-        }
519
-        // has this question been answered ?
520
-        if (
521
-            $answer instanceof EE_Answer
522
-            && $answer->value() !== ''
523
-        ) {
524
-            // answer gets htmlspecialchars called on it, undo that please
525
-            // because the form input's display strategy may call esc_attr too
526
-            // which also does html special characters
527
-            $values_with_html_special_chars = $answer->value();
528
-            if (is_array($values_with_html_special_chars)) {
529
-                $default_value = array_map('htmlspecialchars_decode', $values_with_html_special_chars);
530
-            } else {
531
-                $default_value = htmlspecialchars_decode($values_with_html_special_chars);
532
-            }
533
-            $input_constructor_args['default'] = $default_value;
534
-        }
535
-        $max_max_for_question = EEM_Question::instance()->absolute_max_for_system_question($this->system_ID());
536
-        if (
537
-            in_array(
538
-                $this->type(),
539
-                EEM_Question::instance()->questionTypesWithMaxLength(),
540
-                true
541
-            )
542
-        ) {
543
-            $input_constructor_args['validation_strategies'][] = new EE_Max_Length_Validation_Strategy(
544
-                null,
545
-                min($max_max_for_question, $this->max())
546
-            );
547
-        }
548
-        $input_constructor_args = apply_filters(
549
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__input_constructor_args',
550
-            $input_constructor_args,
551
-            $registration,
552
-            $this,
553
-            $answer
554
-        );
555
-
556
-        $result = null;
557
-        switch ($this->type()) {
558
-            // Text
559
-            case EEM_Question::QST_type_text:
560
-                $result = new EE_Text_Input($input_constructor_args);
561
-                break;
562
-            // Textarea
563
-            case EEM_Question::QST_type_textarea:
564
-                $result = new EE_Text_Area_Input($input_constructor_args);
565
-                break;
566
-            // Radio Buttons
567
-            case EEM_Question::QST_type_radio:
568
-                $result = new EE_Radio_Button_Input($this->options(), $input_constructor_args);
569
-                break;
570
-            // Dropdown
571
-            case EEM_Question::QST_type_dropdown:
572
-                $result = new EE_Select_Input($this->options(), $input_constructor_args);
573
-                break;
574
-            // State Dropdown
575
-            case EEM_Question::QST_type_state:
576
-                $state_options = apply_filters(
577
-                    'FHEE__EE_Question__generate_form_input__state_options',
578
-                    null,
579
-                    $this,
580
-                    $registration,
581
-                    $answer
582
-                );
583
-                $result        = new EE_State_Select_Input($state_options, $input_constructor_args);
584
-                break;
585
-            // Country Dropdown
586
-            case EEM_Question::QST_type_country:
587
-                $country_options = apply_filters(
588
-                    'FHEE__EE_Question__generate_form_input__country_options',
589
-                    null,
590
-                    $this,
591
-                    $registration,
592
-                    $answer
593
-                );
594
-                $result          = new EE_Country_Select_Input($country_options, $input_constructor_args);
595
-                break;
596
-            // Checkboxes
597
-            case EEM_Question::QST_type_checkbox:
598
-                $result = new EE_Checkbox_Multi_Input($this->options(), $input_constructor_args);
599
-                break;
600
-            // Date
601
-            case EEM_Question::QST_type_date:
602
-                $result = new EE_Datepicker_Input($input_constructor_args);
603
-                break;
604
-            case EEM_Question::QST_type_html_textarea:
605
-                $input_constructor_args['validation_strategies'][] = new EE_Simple_HTML_Validation_Strategy();
606
-                $result                                            = new EE_Text_Area_Input($input_constructor_args);
607
-                $result->remove_validation_strategy('EE_Plaintext_Validation_Strategy');
608
-                break;
609
-            case EEM_Question::QST_type_email:
610
-                $result = new EE_Email_Input($input_constructor_args);
611
-                break;
612
-            // Email confirm
613
-            case EEM_Question::QST_type_email_confirm:
614
-                $result = new EE_Email_Confirm_Input($input_constructor_args);
615
-                break;
616
-            case EEM_Question::QST_type_us_phone:
617
-                $result = new EE_Phone_Input($input_constructor_args);
618
-                break;
619
-            case EEM_Question::QST_type_int:
620
-                $result = new EE_Integer_Input($input_constructor_args);
621
-                break;
622
-            case EEM_Question::QST_type_decimal:
623
-                $result = new EE_Float_Input($input_constructor_args);
624
-                break;
625
-            case EEM_Question::QST_type_url:
626
-                $input_constructor_args['validation_strategies'][] =
627
-                    LoaderFactory::getLoader()->getNew('EE_URL_Validation_Strategy');
628
-                $result                                            = new EE_Text_Input($input_constructor_args);
629
-                break;
630
-            case EEM_Question::QST_type_year:
631
-                $result = new EE_Year_Input(
632
-                    $input_constructor_args,
633
-                    apply_filters(
634
-                        'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__four_digit',
635
-                        true,
636
-                        $this
637
-                    ),
638
-                    apply_filters(
639
-                        'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__early_range',
640
-                        100,
641
-                        $this
642
-                    ),
643
-                    apply_filters(
644
-                        'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__end_range',
645
-                        100,
646
-                        $this
647
-                    )
648
-                );
649
-                break;
650
-            case EEM_Question::QST_type_multi_select:
651
-                $result = new EE_Select_Multiple_Input($this->options(), $input_constructor_args);
652
-                break;
653
-            // fallback
654
-            default:
655
-                $default_input = apply_filters(
656
-                    'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__default',
657
-                    null,
658
-                    $this->type(),
659
-                    $this,
660
-                    $input_constructor_args
661
-                );
662
-                if (! $default_input) {
663
-                    $default_input = new EE_Text_Input($input_constructor_args);
664
-                }
665
-                $result = $default_input;
666
-        }
667
-        return apply_filters('FHEE__EE_Question__generate_form_input__return', $result, $registration, $this, $answer);
668
-    }
669
-
670
-
671
-    /**
672
-     * Returns whether or not this question type should have question option entries
673
-     *
674
-     * @return bool
675
-     */
676
-    public function should_have_question_options()
677
-    {
678
-        return in_array(
679
-            $this->type(),
680
-            $this->_model->question_types_with_options(),
681
-            true
682
-        );
683
-    }
15
+	/**
16
+	 * @param array  $props_n_values          incoming values
17
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
18
+	 *                                        used.)
19
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
20
+	 *                                        date_format and the second value is the time format
21
+	 * @return EE_Question
22
+	 */
23
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
24
+	{
25
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
26
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
27
+	}
28
+
29
+
30
+	/**
31
+	 * @param array  $props_n_values  incoming values from the database
32
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
33
+	 *                                the website will be used.
34
+	 * @return EE_Question
35
+	 */
36
+	public static function new_instance_from_db($props_n_values = [], $timezone = '')
37
+	{
38
+		return new self($props_n_values, true, $timezone);
39
+	}
40
+
41
+
42
+	/**
43
+	 *        Set    Question display text
44
+	 *
45
+	 * @access        public
46
+	 * @param string $QST_display_text
47
+	 */
48
+	public function set_display_text($QST_display_text = '')
49
+	{
50
+		$this->set('QST_display_text', $QST_display_text);
51
+	}
52
+
53
+
54
+	/**
55
+	 *        Set    Question admin text
56
+	 *
57
+	 * @access        public
58
+	 * @param string $QST_admin_label
59
+	 */
60
+	public function set_admin_label($QST_admin_label = '')
61
+	{
62
+		$this->set('QST_admin_label', $QST_admin_label);
63
+	}
64
+
65
+
66
+	/**
67
+	 *        Set    system name
68
+	 *
69
+	 * @access        public
70
+	 * @param mixed $QST_system
71
+	 */
72
+	public function set_system_ID($QST_system = '')
73
+	{
74
+		$this->set('QST_system', $QST_system);
75
+	}
76
+
77
+
78
+	/**
79
+	 *        Set    question's type
80
+	 *
81
+	 * @access        public
82
+	 * @param string $QST_type
83
+	 */
84
+	public function set_question_type($QST_type = '')
85
+	{
86
+		$this->set('QST_type', $QST_type);
87
+	}
88
+
89
+
90
+	/**
91
+	 *        Sets whether this question must be answered when presented in a form
92
+	 *
93
+	 * @access        public
94
+	 * @param bool $QST_required
95
+	 */
96
+	public function set_required($QST_required = false)
97
+	{
98
+		$this->set('QST_required', $QST_required);
99
+	}
100
+
101
+
102
+	/**
103
+	 *        Set    Question display text
104
+	 *
105
+	 * @access        public
106
+	 * @param string $QST_required_text
107
+	 */
108
+	public function set_required_text($QST_required_text = '')
109
+	{
110
+		$this->set('QST_required_text', $QST_required_text);
111
+	}
112
+
113
+
114
+	/**
115
+	 *        Sets the order of this question when placed in a sequence of questions
116
+	 *
117
+	 * @access        public
118
+	 * @param int $QST_order
119
+	 */
120
+	public function set_order($QST_order = 0)
121
+	{
122
+		$this->set('QST_order', $QST_order);
123
+	}
124
+
125
+
126
+	/**
127
+	 *        Sets whether the question is admin-only
128
+	 *
129
+	 * @access        public
130
+	 * @param bool $QST_admin_only
131
+	 */
132
+	public function set_admin_only($QST_admin_only = false)
133
+	{
134
+		$this->set('QST_admin_only', $QST_admin_only);
135
+	}
136
+
137
+
138
+	/**
139
+	 *        Sets the wordpress user ID on the question
140
+	 *
141
+	 * @access        public
142
+	 * @param int $QST_wp_user
143
+	 */
144
+	public function set_wp_user($QST_wp_user = 1)
145
+	{
146
+		$this->set('QST_wp_user', $QST_wp_user);
147
+	}
148
+
149
+
150
+	/**
151
+	 *        Sets whether the question has been deleted
152
+	 *        (we use this boolean instead of actually
153
+	 *        deleting it because when users delete this question
154
+	 *        they really want to remove the question from future
155
+	 *        forms, BUT keep their old answers which depend
156
+	 *        on this record actually existing.
157
+	 *
158
+	 * @access        public
159
+	 * @param bool $QST_deleted
160
+	 */
161
+	public function set_deleted($QST_deleted = false)
162
+	{
163
+		$this->set('QST_deleted', $QST_deleted);
164
+	}
165
+
166
+
167
+	/**
168
+	 * returns the text for displaying the question to users
169
+	 *
170
+	 * @access public
171
+	 * @return string
172
+	 */
173
+	public function display_text()
174
+	{
175
+		return $this->get('QST_display_text');
176
+	}
177
+
178
+
179
+	/**
180
+	 * returns the text for the administrative label
181
+	 *
182
+	 * @access public
183
+	 * @return string
184
+	 */
185
+	public function admin_label()
186
+	{
187
+		return $this->get('QST_admin_label');
188
+	}
189
+
190
+
191
+	/**
192
+	 * returns the attendee column name for this question
193
+	 *
194
+	 * @access public
195
+	 * @return string
196
+	 */
197
+	public function system_ID()
198
+	{
199
+		return $this->get('QST_system');
200
+	}
201
+
202
+
203
+	/**
204
+	 * returns either a string of 'text', 'textfield', etc.
205
+	 *
206
+	 * @access public
207
+	 * @return boolean
208
+	 */
209
+	public function required()
210
+	{
211
+		return $this->get('QST_required');
212
+	}
213
+
214
+
215
+	/**
216
+	 * returns the text which should be displayed when a user
217
+	 * doesn't answer this question in a form
218
+	 *
219
+	 * @access public
220
+	 * @return string
221
+	 */
222
+	public function required_text()
223
+	{
224
+		return $this->get('QST_required_text');
225
+	}
226
+
227
+
228
+	/**
229
+	 * returns the type of this question
230
+	 *
231
+	 * @access public
232
+	 * @return string
233
+	 */
234
+	public function type()
235
+	{
236
+		return $this->get('QST_type');
237
+	}
238
+
239
+
240
+	/**
241
+	 * returns an integer showing where this question should
242
+	 * be placed in a sequence of questions
243
+	 *
244
+	 * @access public
245
+	 * @return int
246
+	 */
247
+	public function order()
248
+	{
249
+		return $this->get('QST_order');
250
+	}
251
+
252
+
253
+	/**
254
+	 * returns whether this question should only appears to admins,
255
+	 * or to everyone
256
+	 *
257
+	 * @access public
258
+	 * @return boolean
259
+	 */
260
+	public function admin_only()
261
+	{
262
+		return $this->get('QST_admin_only');
263
+	}
264
+
265
+
266
+	/**
267
+	 * returns the id the wordpress user who created this question
268
+	 *
269
+	 * @access public
270
+	 * @return int
271
+	 */
272
+	public function wp_user()
273
+	{
274
+		return $this->get('QST_wp_user');
275
+	}
276
+
277
+
278
+	/**
279
+	 * returns whether this question has been marked as 'deleted'
280
+	 *
281
+	 * @access public
282
+	 * @return boolean
283
+	 */
284
+	public function deleted()
285
+	{
286
+		return $this->get('QST_deleted');
287
+	}
288
+
289
+
290
+	/**
291
+	 * Gets an array of related EE_Answer  to this EE_Question
292
+	 *
293
+	 * @return EE_Answer[]
294
+	 */
295
+	public function answers()
296
+	{
297
+		return $this->get_many_related('Answer');
298
+	}
299
+
300
+
301
+	/**
302
+	 * Boolean check for if there are answers on this question in th db
303
+	 *
304
+	 * @return boolean true = has answers, false = no answers.
305
+	 */
306
+	public function has_answers()
307
+	{
308
+		return $this->count_related('Answer') > 0 ? true : false;
309
+	}
310
+
311
+
312
+	/**
313
+	 * gets an array of EE_Question_Group which relate to this question
314
+	 *
315
+	 * @return EE_Question_Group[]
316
+	 */
317
+	public function question_groups()
318
+	{
319
+		return $this->get_many_related('Question_Group');
320
+	}
321
+
322
+
323
+	/**
324
+	 * Returns all the options for this question. By default, it returns only the not-yet-deleted ones.
325
+	 *
326
+	 * @param boolean      $notDeletedOptionsOnly            1
327
+	 *                                                       whether to return ALL options, or only the ones which have
328
+	 *                                                       not yet been deleleted
329
+	 * @param string|array $selected_value_to_always_include , when retrieving options to an ANSWERED question,
330
+	 *                                                       we want to usually only show non-deleted options AND the
331
+	 *                                                       value that was selected for the answer, whether it was
332
+	 *                                                       trashed or not.
333
+	 * @return EE_Question_Option[]
334
+	 */
335
+	public function options($notDeletedOptionsOnly = true, $selected_value_to_always_include = null)
336
+	{
337
+		if (! $this->ID()) {
338
+			return [];
339
+		}
340
+		$query_params = [];
341
+		if ($selected_value_to_always_include) {
342
+			if (is_array($selected_value_to_always_include)) {
343
+				$query_params[0]['OR*options-query']['QSO_value'] = ['IN', $selected_value_to_always_include];
344
+			} else {
345
+				$query_params[0]['OR*options-query']['QSO_value'] = $selected_value_to_always_include;
346
+			}
347
+		}
348
+		if ($notDeletedOptionsOnly) {
349
+			$query_params[0]['OR*options-query']['QSO_deleted'] = false;
350
+		}
351
+		// order by QSO_order
352
+		$query_params['order_by'] = ['QSO_order' => 'ASC'];
353
+		return $this->get_many_related('Question_Option', $query_params);
354
+	}
355
+
356
+
357
+	/**
358
+	 * returns an array of EE_Question_Options which relate to this question
359
+	 *
360
+	 * @return \EE_Question_Option[]
361
+	 */
362
+	public function temp_options()
363
+	{
364
+		return $this->_model_relations['Question_Option'];
365
+	}
366
+
367
+
368
+	/**
369
+	 * Adds an option for this question. Note: if the option were previously associated with a different
370
+	 * Question, that relationship will be overwritten.
371
+	 *
372
+	 * @param EE_Question_Option $option
373
+	 * @return boolean success
374
+	 */
375
+	public function add_option(EE_Question_Option $option)
376
+	{
377
+		return $this->_add_relation_to($option, 'Question_Option');
378
+	}
379
+
380
+
381
+	/**
382
+	 * Adds an option directly to this question without saving to the db
383
+	 *
384
+	 * @param EE_Question_Option $option
385
+	 * @return boolean success
386
+	 */
387
+	public function add_temp_option(EE_Question_Option $option)
388
+	{
389
+		$this->_model_relations['Question_Option'][] = $option;
390
+		return true;
391
+	}
392
+
393
+
394
+	/**
395
+	 * Marks the option as deleted.
396
+	 *
397
+	 * @param EE_Question_Option $option
398
+	 * @return boolean success
399
+	 */
400
+	public function remove_option(EE_Question_Option $option)
401
+	{
402
+		return $this->_remove_relation_to($option, 'Question_Option');
403
+	}
404
+
405
+
406
+	/**
407
+	 * @return bool
408
+	 */
409
+	public function is_system_question()
410
+	{
411
+		$system_ID = $this->get('QST_system');
412
+		return ! empty($system_ID) ? true : false;
413
+	}
414
+
415
+
416
+	/**
417
+	 * The purpose of this method is set the question order this question order to be the max out of all questions
418
+	 *
419
+	 * @access public
420
+	 * @return void
421
+	 */
422
+	public function set_order_to_latest()
423
+	{
424
+		$latest_order = $this->get_model()->get_latest_question_order();
425
+		$latest_order++;
426
+		$this->set('QST_order', $latest_order);
427
+	}
428
+
429
+
430
+	/**
431
+	 * Retrieves the list of allowed question types from the model.
432
+	 *
433
+	 * @return string[]
434
+	 */
435
+	private function _allowed_question_types()
436
+	{
437
+		$questionModel = $this->get_model();
438
+		/* @var $questionModel EEM_Question */
439
+		return $questionModel->allowed_question_types();
440
+	}
441
+
442
+
443
+	/**
444
+	 * Duplicates this question and its question options
445
+	 *
446
+	 * @return \EE_Question
447
+	 */
448
+	public function duplicate($options = [])
449
+	{
450
+		$new_question = clone $this;
451
+		$new_question->set('QST_ID', null);
452
+		$new_question->set_display_text(
453
+			sprintf(esc_html__('%s **Duplicate**', 'event_espresso'), $this->display_text())
454
+		);
455
+		$new_question->set_admin_label(sprintf(esc_html__('%s **Duplicate**', 'event_espresso'), $this->admin_label()));
456
+		$new_question->set_system_ID(null);
457
+		$new_question->set_wp_user(get_current_user_id());
458
+		// if we're duplicating a trashed question, assume we don't want the new one to be trashed
459
+		$new_question->set_deleted(false);
460
+		$success = $new_question->save();
461
+		if ($success) {
462
+			// we don't totally want to duplicate the question options, because we want them to be for the NEW question
463
+			foreach ($this->options() as $question_option) {
464
+				$question_option->duplicate(['QST_ID' => $new_question->ID()]);
465
+			}
466
+			return $new_question;
467
+		} else {
468
+			return null;
469
+		}
470
+	}
471
+
472
+
473
+	/**
474
+	 * Returns the question's maximum allowed response size
475
+	 *
476
+	 * @return int|float
477
+	 */
478
+	public function max()
479
+	{
480
+		return $this->get('QST_max');
481
+	}
482
+
483
+
484
+	/**
485
+	 * Sets the question's maximum allowed response size
486
+	 *
487
+	 * @param int|float $new_max
488
+	 * @return void
489
+	 */
490
+	public function set_max($new_max)
491
+	{
492
+		$this->set('QST_max', $new_max);
493
+	}
494
+
495
+
496
+	/**
497
+	 * Creates a form input from this question which can be used in HTML forms
498
+	 *
499
+	 * @param EE_Registration $registration
500
+	 * @param EE_Answer       $answer
501
+	 * @param array           $input_constructor_args
502
+	 * @return EE_Form_Input_Base
503
+	 */
504
+	public function generate_form_input($registration = null, $answer = null, $input_constructor_args = [])
505
+	{
506
+		$identifier = $this->is_system_question() ? $this->system_ID() : $this->ID();
507
+
508
+		$input_constructor_args = array_merge(
509
+			[
510
+				'required'                          => $this->required() ? true : false,
511
+				'html_label_text'                   => $this->display_text(),
512
+				'required_validation_error_message' => $this->required_text(),
513
+			],
514
+			$input_constructor_args
515
+		);
516
+		if (! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
517
+			$answer = EEM_Answer::instance()->get_registration_question_answer_object($registration, $this->ID());
518
+		}
519
+		// has this question been answered ?
520
+		if (
521
+			$answer instanceof EE_Answer
522
+			&& $answer->value() !== ''
523
+		) {
524
+			// answer gets htmlspecialchars called on it, undo that please
525
+			// because the form input's display strategy may call esc_attr too
526
+			// which also does html special characters
527
+			$values_with_html_special_chars = $answer->value();
528
+			if (is_array($values_with_html_special_chars)) {
529
+				$default_value = array_map('htmlspecialchars_decode', $values_with_html_special_chars);
530
+			} else {
531
+				$default_value = htmlspecialchars_decode($values_with_html_special_chars);
532
+			}
533
+			$input_constructor_args['default'] = $default_value;
534
+		}
535
+		$max_max_for_question = EEM_Question::instance()->absolute_max_for_system_question($this->system_ID());
536
+		if (
537
+			in_array(
538
+				$this->type(),
539
+				EEM_Question::instance()->questionTypesWithMaxLength(),
540
+				true
541
+			)
542
+		) {
543
+			$input_constructor_args['validation_strategies'][] = new EE_Max_Length_Validation_Strategy(
544
+				null,
545
+				min($max_max_for_question, $this->max())
546
+			);
547
+		}
548
+		$input_constructor_args = apply_filters(
549
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__input_constructor_args',
550
+			$input_constructor_args,
551
+			$registration,
552
+			$this,
553
+			$answer
554
+		);
555
+
556
+		$result = null;
557
+		switch ($this->type()) {
558
+			// Text
559
+			case EEM_Question::QST_type_text:
560
+				$result = new EE_Text_Input($input_constructor_args);
561
+				break;
562
+			// Textarea
563
+			case EEM_Question::QST_type_textarea:
564
+				$result = new EE_Text_Area_Input($input_constructor_args);
565
+				break;
566
+			// Radio Buttons
567
+			case EEM_Question::QST_type_radio:
568
+				$result = new EE_Radio_Button_Input($this->options(), $input_constructor_args);
569
+				break;
570
+			// Dropdown
571
+			case EEM_Question::QST_type_dropdown:
572
+				$result = new EE_Select_Input($this->options(), $input_constructor_args);
573
+				break;
574
+			// State Dropdown
575
+			case EEM_Question::QST_type_state:
576
+				$state_options = apply_filters(
577
+					'FHEE__EE_Question__generate_form_input__state_options',
578
+					null,
579
+					$this,
580
+					$registration,
581
+					$answer
582
+				);
583
+				$result        = new EE_State_Select_Input($state_options, $input_constructor_args);
584
+				break;
585
+			// Country Dropdown
586
+			case EEM_Question::QST_type_country:
587
+				$country_options = apply_filters(
588
+					'FHEE__EE_Question__generate_form_input__country_options',
589
+					null,
590
+					$this,
591
+					$registration,
592
+					$answer
593
+				);
594
+				$result          = new EE_Country_Select_Input($country_options, $input_constructor_args);
595
+				break;
596
+			// Checkboxes
597
+			case EEM_Question::QST_type_checkbox:
598
+				$result = new EE_Checkbox_Multi_Input($this->options(), $input_constructor_args);
599
+				break;
600
+			// Date
601
+			case EEM_Question::QST_type_date:
602
+				$result = new EE_Datepicker_Input($input_constructor_args);
603
+				break;
604
+			case EEM_Question::QST_type_html_textarea:
605
+				$input_constructor_args['validation_strategies'][] = new EE_Simple_HTML_Validation_Strategy();
606
+				$result                                            = new EE_Text_Area_Input($input_constructor_args);
607
+				$result->remove_validation_strategy('EE_Plaintext_Validation_Strategy');
608
+				break;
609
+			case EEM_Question::QST_type_email:
610
+				$result = new EE_Email_Input($input_constructor_args);
611
+				break;
612
+			// Email confirm
613
+			case EEM_Question::QST_type_email_confirm:
614
+				$result = new EE_Email_Confirm_Input($input_constructor_args);
615
+				break;
616
+			case EEM_Question::QST_type_us_phone:
617
+				$result = new EE_Phone_Input($input_constructor_args);
618
+				break;
619
+			case EEM_Question::QST_type_int:
620
+				$result = new EE_Integer_Input($input_constructor_args);
621
+				break;
622
+			case EEM_Question::QST_type_decimal:
623
+				$result = new EE_Float_Input($input_constructor_args);
624
+				break;
625
+			case EEM_Question::QST_type_url:
626
+				$input_constructor_args['validation_strategies'][] =
627
+					LoaderFactory::getLoader()->getNew('EE_URL_Validation_Strategy');
628
+				$result                                            = new EE_Text_Input($input_constructor_args);
629
+				break;
630
+			case EEM_Question::QST_type_year:
631
+				$result = new EE_Year_Input(
632
+					$input_constructor_args,
633
+					apply_filters(
634
+						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__four_digit',
635
+						true,
636
+						$this
637
+					),
638
+					apply_filters(
639
+						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__early_range',
640
+						100,
641
+						$this
642
+					),
643
+					apply_filters(
644
+						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__end_range',
645
+						100,
646
+						$this
647
+					)
648
+				);
649
+				break;
650
+			case EEM_Question::QST_type_multi_select:
651
+				$result = new EE_Select_Multiple_Input($this->options(), $input_constructor_args);
652
+				break;
653
+			// fallback
654
+			default:
655
+				$default_input = apply_filters(
656
+					'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__default',
657
+					null,
658
+					$this->type(),
659
+					$this,
660
+					$input_constructor_args
661
+				);
662
+				if (! $default_input) {
663
+					$default_input = new EE_Text_Input($input_constructor_args);
664
+				}
665
+				$result = $default_input;
666
+		}
667
+		return apply_filters('FHEE__EE_Question__generate_form_input__return', $result, $registration, $this, $answer);
668
+	}
669
+
670
+
671
+	/**
672
+	 * Returns whether or not this question type should have question option entries
673
+	 *
674
+	 * @return bool
675
+	 */
676
+	public function should_have_question_options()
677
+	{
678
+		return in_array(
679
+			$this->type(),
680
+			$this->_model->question_types_with_options(),
681
+			true
682
+		);
683
+	}
684 684
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
      */
335 335
     public function options($notDeletedOptionsOnly = true, $selected_value_to_always_include = null)
336 336
     {
337
-        if (! $this->ID()) {
337
+        if ( ! $this->ID()) {
338 338
             return [];
339 339
         }
340 340
         $query_params = [];
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
             ],
514 514
             $input_constructor_args
515 515
         );
516
-        if (! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
516
+        if ( ! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
517 517
             $answer = EEM_Answer::instance()->get_registration_question_answer_object($registration, $this->ID());
518 518
         }
519 519
         // has this question been answered ?
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
                     $registration,
581 581
                     $answer
582 582
                 );
583
-                $result        = new EE_State_Select_Input($state_options, $input_constructor_args);
583
+                $result = new EE_State_Select_Input($state_options, $input_constructor_args);
584 584
                 break;
585 585
             // Country Dropdown
586 586
             case EEM_Question::QST_type_country:
@@ -591,7 +591,7 @@  discard block
 block discarded – undo
591 591
                     $registration,
592 592
                     $answer
593 593
                 );
594
-                $result          = new EE_Country_Select_Input($country_options, $input_constructor_args);
594
+                $result = new EE_Country_Select_Input($country_options, $input_constructor_args);
595 595
                 break;
596 596
             // Checkboxes
597 597
             case EEM_Question::QST_type_checkbox:
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
                     $this,
660 660
                     $input_constructor_args
661 661
                 );
662
-                if (! $default_input) {
662
+                if ( ! $default_input) {
663 663
                     $default_input = new EE_Text_Input($input_constructor_args);
664 664
                 }
665 665
                 $result = $default_input;
Please login to merge, or discard this patch.