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