Completed
Branch BUG/3575-event-deletion-previe... (bbeda1)
by
unknown
06:40 queued 04:49
created
core/services/notifications/PersistentAdminNoticeManager.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
      */
86 86
     public function setReturnUrl($return_url)
87 87
     {
88
-        if (! is_string($return_url)) {
88
+        if ( ! is_string($return_url)) {
89 89
             throw new InvalidDataTypeException('$return_url', $return_url, 'string');
90 90
         }
91 91
         $this->return_url = $return_url;
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
      */
103 103
     protected function getPersistentAdminNoticeCollection()
104 104
     {
105
-        if (! $this->notice_collection instanceof Collection) {
105
+        if ( ! $this->notice_collection instanceof Collection) {
106 106
             $this->notice_collection = new Collection(
107 107
                 'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
108 108
             );
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
     protected function retrieveStoredNotices()
126 126
     {
127 127
         $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
128
-        if (! empty($persistent_admin_notices)) {
128
+        if ( ! empty($persistent_admin_notices)) {
129 129
             foreach ($persistent_admin_notices as $name => $details) {
130 130
                 if (is_array($details)) {
131 131
                     if (
@@ -247,14 +247,14 @@  discard block
 block discarded – undo
247 247
     {
248 248
         wp_register_script(
249 249
             'espresso_core',
250
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
250
+            EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
251 251
             array('jquery'),
252 252
             EVENT_ESPRESSO_VERSION,
253 253
             true
254 254
         );
255 255
         wp_register_script(
256 256
             'ee_error_js',
257
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
257
+            EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js',
258 258
             array('espresso_core'),
259 259
             EVENT_ESPRESSO_VERSION,
260 260
             true
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
         // used in template
286 286
         $persistent_admin_notice_name = $persistent_admin_notice->getName();
287 287
         $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
288
-        require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
288
+        require EE_TEMPLATES.'/notifications/persistent_admin_notice.template.php';
289 289
     }
290 290
 
291 291
 
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
     {
311 311
         $pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
312 312
         $this->notice_collection = $this->getPersistentAdminNoticeCollection();
313
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
313
+        if ( ! empty($pan_name) && $this->notice_collection->has($pan_name)) {
314 314
             /** @var PersistentAdminNotice $persistent_admin_notice */
315 315
             $persistent_admin_notice = $this->notice_collection->get($pan_name);
316 316
             $persistent_admin_notice->setDismissed(true);
@@ -360,10 +360,10 @@  discard block
 block discarded – undo
360 360
             foreach ($this->notice_collection as $persistent_admin_notice) {
361 361
                 // are we deleting this notice ?
362 362
                 if ($persistent_admin_notice->getPurge()) {
363
-                    unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
363
+                    unset($persistent_admin_notices[$persistent_admin_notice->getName()]);
364 364
                 } else {
365 365
                     /** @var PersistentAdminNotice $persistent_admin_notice */
366
-                    $persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
366
+                    $persistent_admin_notices[$persistent_admin_notice->getName()] = array(
367 367
                         'message'     => $persistent_admin_notice->getMessage(),
368 368
                         'capability'  => $persistent_admin_notice->getCapability(),
369 369
                         'cap_context' => $persistent_admin_notice->getCapContext(),
Please login to merge, or discard this patch.
Indentation   +385 added lines, -385 removed lines patch added patch discarded remove patch
@@ -31,389 +31,389 @@
 block discarded – undo
31 31
 class PersistentAdminNoticeManager
32 32
 {
33 33
 
34
-    const WP_OPTION_KEY = 'ee_pers_admin_notices';
35
-
36
-    /**
37
-     * @var Collection|PersistentAdminNotice[] $notice_collection
38
-     */
39
-    private $notice_collection;
40
-
41
-    /**
42
-     * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
43
-     * persistent admin notice was displayed, and ultimately dismissed from.
44
-     *
45
-     * @var string $return_url
46
-     */
47
-    private $return_url;
48
-
49
-    /**
50
-     * @var CapabilitiesChecker $capabilities_checker
51
-     */
52
-    private $capabilities_checker;
53
-
54
-    /**
55
-     * @var RequestInterface $request
56
-     */
57
-    private $request;
58
-
59
-
60
-    /**
61
-     * PersistentAdminNoticeManager constructor
62
-     *
63
-     * @param string              $return_url where to  redirect to after dismissing notices
64
-     * @param CapabilitiesChecker $capabilities_checker
65
-     * @param RequestInterface          $request
66
-     * @throws InvalidDataTypeException
67
-     */
68
-    public function __construct($return_url = '', CapabilitiesChecker $capabilities_checker, RequestInterface $request)
69
-    {
70
-        $this->setReturnUrl($return_url);
71
-        $this->capabilities_checker = $capabilities_checker;
72
-        $this->request = $request;
73
-        // setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
74
-        // and we want to retrieve and generate any nag notices at the last possible moment
75
-        add_action('admin_notices', array($this, 'displayNotices'), 9);
76
-        add_action('network_admin_notices', array($this, 'displayNotices'), 9);
77
-        add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
78
-        add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
79
-    }
80
-
81
-
82
-    /**
83
-     * @param string $return_url
84
-     * @throws InvalidDataTypeException
85
-     */
86
-    public function setReturnUrl($return_url)
87
-    {
88
-        if (! is_string($return_url)) {
89
-            throw new InvalidDataTypeException('$return_url', $return_url, 'string');
90
-        }
91
-        $this->return_url = $return_url;
92
-    }
93
-
94
-
95
-    /**
96
-     * @return Collection
97
-     * @throws InvalidEntityException
98
-     * @throws InvalidInterfaceException
99
-     * @throws InvalidDataTypeException
100
-     * @throws DomainException
101
-     * @throws DuplicateCollectionIdentifierException
102
-     */
103
-    protected function getPersistentAdminNoticeCollection()
104
-    {
105
-        if (! $this->notice_collection instanceof Collection) {
106
-            $this->notice_collection = new Collection(
107
-                'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
108
-            );
109
-            $this->retrieveStoredNotices();
110
-            $this->registerNotices();
111
-        }
112
-        return $this->notice_collection;
113
-    }
114
-
115
-
116
-    /**
117
-     * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
118
-     *
119
-     * @return void
120
-     * @throws InvalidEntityException
121
-     * @throws DomainException
122
-     * @throws InvalidDataTypeException
123
-     * @throws DuplicateCollectionIdentifierException
124
-     */
125
-    protected function retrieveStoredNotices()
126
-    {
127
-        $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
128
-        if (! empty($persistent_admin_notices)) {
129
-            foreach ($persistent_admin_notices as $name => $details) {
130
-                if (is_array($details)) {
131
-                    if (
132
-                        ! isset(
133
-                            $details['message'],
134
-                            $details['capability'],
135
-                            $details['cap_context'],
136
-                            $details['dismissed']
137
-                        )
138
-                    ) {
139
-                        throw new DomainException(
140
-                            sprintf(
141
-                                esc_html__(
142
-                                    'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
143
-                                    'event_espresso'
144
-                                ),
145
-                                $name
146
-                            )
147
-                        );
148
-                    }
149
-                    // new format for nag notices
150
-                    $this->notice_collection->add(
151
-                        new PersistentAdminNotice(
152
-                            $name,
153
-                            $details['message'],
154
-                            false,
155
-                            $details['capability'],
156
-                            $details['cap_context'],
157
-                            $details['dismissed']
158
-                        ),
159
-                        sanitize_key($name)
160
-                    );
161
-                } else {
162
-                    try {
163
-                        // old nag notices, that we want to convert to the new format
164
-                        $this->notice_collection->add(
165
-                            new PersistentAdminNotice(
166
-                                $name,
167
-                                (string) $details,
168
-                                false,
169
-                                '',
170
-                                '',
171
-                                empty($details)
172
-                            ),
173
-                            sanitize_key($name)
174
-                        );
175
-                    } catch (Exception $e) {
176
-                        EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
177
-                    }
178
-                }
179
-                // each notice will self register when the action hook in registerNotices is triggered
180
-            }
181
-        }
182
-    }
183
-
184
-
185
-    /**
186
-     * exposes the Persistent Admin Notice Collection via an action
187
-     * so that PersistentAdminNotice objects can be added and/or removed
188
-     * without compromising the actual collection like a filter would
189
-     */
190
-    protected function registerNotices()
191
-    {
192
-        do_action(
193
-            'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
194
-            $this->notice_collection
195
-        );
196
-    }
197
-
198
-
199
-    /**
200
-     * @throws DomainException
201
-     * @throws InvalidClassException
202
-     * @throws InvalidDataTypeException
203
-     * @throws InvalidInterfaceException
204
-     * @throws InvalidEntityException
205
-     * @throws DuplicateCollectionIdentifierException
206
-     */
207
-    public function displayNotices()
208
-    {
209
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
210
-        if ($this->notice_collection->hasObjects()) {
211
-            $enqueue_assets = false;
212
-            // and display notices
213
-            foreach ($this->notice_collection as $persistent_admin_notice) {
214
-                /** @var PersistentAdminNotice $persistent_admin_notice */
215
-                // don't display notices that have already been dismissed
216
-                if ($persistent_admin_notice->getDismissed()) {
217
-                    continue;
218
-                }
219
-                try {
220
-                    $this->capabilities_checker->processCapCheck(
221
-                        $persistent_admin_notice->getCapCheck()
222
-                    );
223
-                } catch (InsufficientPermissionsException $e) {
224
-                    // user does not have required cap, so skip to next notice
225
-                    // and just eat the exception - nom nom nom nom
226
-                    continue;
227
-                }
228
-                if ($persistent_admin_notice->getMessage() === '') {
229
-                    continue;
230
-                }
231
-                $this->displayPersistentAdminNotice($persistent_admin_notice);
232
-                $enqueue_assets = true;
233
-            }
234
-            if ($enqueue_assets) {
235
-                $this->enqueueAssets();
236
-            }
237
-        }
238
-    }
239
-
240
-
241
-    /**
242
-     * does what it's named
243
-     *
244
-     * @return void
245
-     */
246
-    public function enqueueAssets()
247
-    {
248
-        wp_register_script(
249
-            'espresso_core',
250
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
251
-            array('jquery'),
252
-            EVENT_ESPRESSO_VERSION,
253
-            true
254
-        );
255
-        wp_register_script(
256
-            'ee_error_js',
257
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
258
-            array('espresso_core'),
259
-            EVENT_ESPRESSO_VERSION,
260
-            true
261
-        );
262
-        wp_localize_script(
263
-            'ee_error_js',
264
-            'ee_dismiss',
265
-            array(
266
-                'return_url'    => urlencode($this->return_url),
267
-                'ajax_url'      => WP_AJAX_URL,
268
-                'unknown_error' => wp_strip_all_tags(
269
-                    __(
270
-                        'An unknown error has occurred on the server while attempting to dismiss this notice.',
271
-                        'event_espresso'
272
-                    )
273
-                ),
274
-            )
275
-        );
276
-        wp_enqueue_script('ee_error_js');
277
-    }
278
-
279
-
280
-    /**
281
-     * displayPersistentAdminNoticeHtml
282
-     *
283
-     * @param  PersistentAdminNotice $persistent_admin_notice
284
-     */
285
-    protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
286
-    {
287
-        // used in template
288
-        $persistent_admin_notice_name = $persistent_admin_notice->getName();
289
-        $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
290
-        require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
291
-    }
292
-
293
-
294
-    /**
295
-     * dismissNotice
296
-     *
297
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
298
-     * @param bool   $purge    if true, then delete it from the db
299
-     * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
300
-     * @return void
301
-     * @throws InvalidEntityException
302
-     * @throws InvalidInterfaceException
303
-     * @throws InvalidDataTypeException
304
-     * @throws DomainException
305
-     * @throws InvalidArgumentException
306
-     * @throws InvalidArgumentException
307
-     * @throws InvalidArgumentException
308
-     * @throws InvalidArgumentException
309
-     * @throws DuplicateCollectionIdentifierException
310
-     */
311
-    public function dismissNotice($pan_name = '', $purge = false, $return = false)
312
-    {
313
-        $pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
314
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
315
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
316
-            /** @var PersistentAdminNotice $persistent_admin_notice */
317
-            $persistent_admin_notice = $this->notice_collection->get($pan_name);
318
-            $persistent_admin_notice->setDismissed(true);
319
-            $persistent_admin_notice->setPurge($purge);
320
-            $this->saveNotices();
321
-        }
322
-        if ($return) {
323
-            return;
324
-        }
325
-        if ($this->request->isAjax()) {
326
-            // grab any notices and concatenate into string
327
-            echo wp_json_encode(
328
-                array(
329
-                    'errors' => implode('<br />', EE_Error::get_notices(false)),
330
-                )
331
-            );
332
-            exit();
333
-        }
334
-        // save errors to a transient to be displayed on next request (after redirect)
335
-        EE_Error::get_notices(false, true);
336
-        wp_safe_redirect(
337
-            urldecode(
338
-                $this->request->getRequestParam('return_url', '')
339
-            )
340
-        );
341
-    }
342
-
343
-
344
-    /**
345
-     * saveNotices
346
-     *
347
-     * @throws DomainException
348
-     * @throws InvalidDataTypeException
349
-     * @throws InvalidInterfaceException
350
-     * @throws InvalidEntityException
351
-     * @throws DuplicateCollectionIdentifierException
352
-     */
353
-    public function saveNotices()
354
-    {
355
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
356
-        if ($this->notice_collection->hasObjects()) {
357
-            $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
358
-            // maybe initialize persistent_admin_notices
359
-            if (empty($persistent_admin_notices)) {
360
-                add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
361
-            }
362
-            foreach ($this->notice_collection as $persistent_admin_notice) {
363
-                // are we deleting this notice ?
364
-                if ($persistent_admin_notice->getPurge()) {
365
-                    unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
366
-                } else {
367
-                    /** @var PersistentAdminNotice $persistent_admin_notice */
368
-                    $persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
369
-                        'message'     => $persistent_admin_notice->getMessage(),
370
-                        'capability'  => $persistent_admin_notice->getCapability(),
371
-                        'cap_context' => $persistent_admin_notice->getCapContext(),
372
-                        'dismissed'   => $persistent_admin_notice->getDismissed(),
373
-                    );
374
-                }
375
-            }
376
-            update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
377
-        }
378
-    }
379
-
380
-
381
-    /**
382
-     * @throws DomainException
383
-     * @throws InvalidDataTypeException
384
-     * @throws InvalidEntityException
385
-     * @throws InvalidInterfaceException
386
-     * @throws DuplicateCollectionIdentifierException
387
-     */
388
-    public function registerAndSaveNotices()
389
-    {
390
-        $this->getPersistentAdminNoticeCollection();
391
-        $this->registerNotices();
392
-        $this->saveNotices();
393
-        add_filter(
394
-            'PersistentAdminNoticeManager__registerAndSaveNotices__complete',
395
-            '__return_true'
396
-        );
397
-    }
398
-
399
-
400
-    /**
401
-     * @throws DomainException
402
-     * @throws InvalidDataTypeException
403
-     * @throws InvalidEntityException
404
-     * @throws InvalidInterfaceException
405
-     * @throws InvalidArgumentException
406
-     * @throws DuplicateCollectionIdentifierException
407
-     */
408
-    public static function loadRegisterAndSaveNotices()
409
-    {
410
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
411
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
412
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
413
-        );
414
-        // if shutdown has already run, then call registerAndSaveNotices() manually
415
-        if (did_action('shutdown')) {
416
-            $persistent_admin_notice_manager->registerAndSaveNotices();
417
-        }
418
-    }
34
+	const WP_OPTION_KEY = 'ee_pers_admin_notices';
35
+
36
+	/**
37
+	 * @var Collection|PersistentAdminNotice[] $notice_collection
38
+	 */
39
+	private $notice_collection;
40
+
41
+	/**
42
+	 * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
43
+	 * persistent admin notice was displayed, and ultimately dismissed from.
44
+	 *
45
+	 * @var string $return_url
46
+	 */
47
+	private $return_url;
48
+
49
+	/**
50
+	 * @var CapabilitiesChecker $capabilities_checker
51
+	 */
52
+	private $capabilities_checker;
53
+
54
+	/**
55
+	 * @var RequestInterface $request
56
+	 */
57
+	private $request;
58
+
59
+
60
+	/**
61
+	 * PersistentAdminNoticeManager constructor
62
+	 *
63
+	 * @param string              $return_url where to  redirect to after dismissing notices
64
+	 * @param CapabilitiesChecker $capabilities_checker
65
+	 * @param RequestInterface          $request
66
+	 * @throws InvalidDataTypeException
67
+	 */
68
+	public function __construct($return_url = '', CapabilitiesChecker $capabilities_checker, RequestInterface $request)
69
+	{
70
+		$this->setReturnUrl($return_url);
71
+		$this->capabilities_checker = $capabilities_checker;
72
+		$this->request = $request;
73
+		// setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
74
+		// and we want to retrieve and generate any nag notices at the last possible moment
75
+		add_action('admin_notices', array($this, 'displayNotices'), 9);
76
+		add_action('network_admin_notices', array($this, 'displayNotices'), 9);
77
+		add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
78
+		add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
79
+	}
80
+
81
+
82
+	/**
83
+	 * @param string $return_url
84
+	 * @throws InvalidDataTypeException
85
+	 */
86
+	public function setReturnUrl($return_url)
87
+	{
88
+		if (! is_string($return_url)) {
89
+			throw new InvalidDataTypeException('$return_url', $return_url, 'string');
90
+		}
91
+		$this->return_url = $return_url;
92
+	}
93
+
94
+
95
+	/**
96
+	 * @return Collection
97
+	 * @throws InvalidEntityException
98
+	 * @throws InvalidInterfaceException
99
+	 * @throws InvalidDataTypeException
100
+	 * @throws DomainException
101
+	 * @throws DuplicateCollectionIdentifierException
102
+	 */
103
+	protected function getPersistentAdminNoticeCollection()
104
+	{
105
+		if (! $this->notice_collection instanceof Collection) {
106
+			$this->notice_collection = new Collection(
107
+				'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
108
+			);
109
+			$this->retrieveStoredNotices();
110
+			$this->registerNotices();
111
+		}
112
+		return $this->notice_collection;
113
+	}
114
+
115
+
116
+	/**
117
+	 * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
118
+	 *
119
+	 * @return void
120
+	 * @throws InvalidEntityException
121
+	 * @throws DomainException
122
+	 * @throws InvalidDataTypeException
123
+	 * @throws DuplicateCollectionIdentifierException
124
+	 */
125
+	protected function retrieveStoredNotices()
126
+	{
127
+		$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
128
+		if (! empty($persistent_admin_notices)) {
129
+			foreach ($persistent_admin_notices as $name => $details) {
130
+				if (is_array($details)) {
131
+					if (
132
+						! isset(
133
+							$details['message'],
134
+							$details['capability'],
135
+							$details['cap_context'],
136
+							$details['dismissed']
137
+						)
138
+					) {
139
+						throw new DomainException(
140
+							sprintf(
141
+								esc_html__(
142
+									'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
143
+									'event_espresso'
144
+								),
145
+								$name
146
+							)
147
+						);
148
+					}
149
+					// new format for nag notices
150
+					$this->notice_collection->add(
151
+						new PersistentAdminNotice(
152
+							$name,
153
+							$details['message'],
154
+							false,
155
+							$details['capability'],
156
+							$details['cap_context'],
157
+							$details['dismissed']
158
+						),
159
+						sanitize_key($name)
160
+					);
161
+				} else {
162
+					try {
163
+						// old nag notices, that we want to convert to the new format
164
+						$this->notice_collection->add(
165
+							new PersistentAdminNotice(
166
+								$name,
167
+								(string) $details,
168
+								false,
169
+								'',
170
+								'',
171
+								empty($details)
172
+							),
173
+							sanitize_key($name)
174
+						);
175
+					} catch (Exception $e) {
176
+						EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
177
+					}
178
+				}
179
+				// each notice will self register when the action hook in registerNotices is triggered
180
+			}
181
+		}
182
+	}
183
+
184
+
185
+	/**
186
+	 * exposes the Persistent Admin Notice Collection via an action
187
+	 * so that PersistentAdminNotice objects can be added and/or removed
188
+	 * without compromising the actual collection like a filter would
189
+	 */
190
+	protected function registerNotices()
191
+	{
192
+		do_action(
193
+			'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
194
+			$this->notice_collection
195
+		);
196
+	}
197
+
198
+
199
+	/**
200
+	 * @throws DomainException
201
+	 * @throws InvalidClassException
202
+	 * @throws InvalidDataTypeException
203
+	 * @throws InvalidInterfaceException
204
+	 * @throws InvalidEntityException
205
+	 * @throws DuplicateCollectionIdentifierException
206
+	 */
207
+	public function displayNotices()
208
+	{
209
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
210
+		if ($this->notice_collection->hasObjects()) {
211
+			$enqueue_assets = false;
212
+			// and display notices
213
+			foreach ($this->notice_collection as $persistent_admin_notice) {
214
+				/** @var PersistentAdminNotice $persistent_admin_notice */
215
+				// don't display notices that have already been dismissed
216
+				if ($persistent_admin_notice->getDismissed()) {
217
+					continue;
218
+				}
219
+				try {
220
+					$this->capabilities_checker->processCapCheck(
221
+						$persistent_admin_notice->getCapCheck()
222
+					);
223
+				} catch (InsufficientPermissionsException $e) {
224
+					// user does not have required cap, so skip to next notice
225
+					// and just eat the exception - nom nom nom nom
226
+					continue;
227
+				}
228
+				if ($persistent_admin_notice->getMessage() === '') {
229
+					continue;
230
+				}
231
+				$this->displayPersistentAdminNotice($persistent_admin_notice);
232
+				$enqueue_assets = true;
233
+			}
234
+			if ($enqueue_assets) {
235
+				$this->enqueueAssets();
236
+			}
237
+		}
238
+	}
239
+
240
+
241
+	/**
242
+	 * does what it's named
243
+	 *
244
+	 * @return void
245
+	 */
246
+	public function enqueueAssets()
247
+	{
248
+		wp_register_script(
249
+			'espresso_core',
250
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
251
+			array('jquery'),
252
+			EVENT_ESPRESSO_VERSION,
253
+			true
254
+		);
255
+		wp_register_script(
256
+			'ee_error_js',
257
+			EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
258
+			array('espresso_core'),
259
+			EVENT_ESPRESSO_VERSION,
260
+			true
261
+		);
262
+		wp_localize_script(
263
+			'ee_error_js',
264
+			'ee_dismiss',
265
+			array(
266
+				'return_url'    => urlencode($this->return_url),
267
+				'ajax_url'      => WP_AJAX_URL,
268
+				'unknown_error' => wp_strip_all_tags(
269
+					__(
270
+						'An unknown error has occurred on the server while attempting to dismiss this notice.',
271
+						'event_espresso'
272
+					)
273
+				),
274
+			)
275
+		);
276
+		wp_enqueue_script('ee_error_js');
277
+	}
278
+
279
+
280
+	/**
281
+	 * displayPersistentAdminNoticeHtml
282
+	 *
283
+	 * @param  PersistentAdminNotice $persistent_admin_notice
284
+	 */
285
+	protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
286
+	{
287
+		// used in template
288
+		$persistent_admin_notice_name = $persistent_admin_notice->getName();
289
+		$persistent_admin_notice_message = $persistent_admin_notice->getMessage();
290
+		require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
291
+	}
292
+
293
+
294
+	/**
295
+	 * dismissNotice
296
+	 *
297
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
298
+	 * @param bool   $purge    if true, then delete it from the db
299
+	 * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
300
+	 * @return void
301
+	 * @throws InvalidEntityException
302
+	 * @throws InvalidInterfaceException
303
+	 * @throws InvalidDataTypeException
304
+	 * @throws DomainException
305
+	 * @throws InvalidArgumentException
306
+	 * @throws InvalidArgumentException
307
+	 * @throws InvalidArgumentException
308
+	 * @throws InvalidArgumentException
309
+	 * @throws DuplicateCollectionIdentifierException
310
+	 */
311
+	public function dismissNotice($pan_name = '', $purge = false, $return = false)
312
+	{
313
+		$pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
314
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
315
+		if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
316
+			/** @var PersistentAdminNotice $persistent_admin_notice */
317
+			$persistent_admin_notice = $this->notice_collection->get($pan_name);
318
+			$persistent_admin_notice->setDismissed(true);
319
+			$persistent_admin_notice->setPurge($purge);
320
+			$this->saveNotices();
321
+		}
322
+		if ($return) {
323
+			return;
324
+		}
325
+		if ($this->request->isAjax()) {
326
+			// grab any notices and concatenate into string
327
+			echo wp_json_encode(
328
+				array(
329
+					'errors' => implode('<br />', EE_Error::get_notices(false)),
330
+				)
331
+			);
332
+			exit();
333
+		}
334
+		// save errors to a transient to be displayed on next request (after redirect)
335
+		EE_Error::get_notices(false, true);
336
+		wp_safe_redirect(
337
+			urldecode(
338
+				$this->request->getRequestParam('return_url', '')
339
+			)
340
+		);
341
+	}
342
+
343
+
344
+	/**
345
+	 * saveNotices
346
+	 *
347
+	 * @throws DomainException
348
+	 * @throws InvalidDataTypeException
349
+	 * @throws InvalidInterfaceException
350
+	 * @throws InvalidEntityException
351
+	 * @throws DuplicateCollectionIdentifierException
352
+	 */
353
+	public function saveNotices()
354
+	{
355
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
356
+		if ($this->notice_collection->hasObjects()) {
357
+			$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
358
+			// maybe initialize persistent_admin_notices
359
+			if (empty($persistent_admin_notices)) {
360
+				add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
361
+			}
362
+			foreach ($this->notice_collection as $persistent_admin_notice) {
363
+				// are we deleting this notice ?
364
+				if ($persistent_admin_notice->getPurge()) {
365
+					unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
366
+				} else {
367
+					/** @var PersistentAdminNotice $persistent_admin_notice */
368
+					$persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
369
+						'message'     => $persistent_admin_notice->getMessage(),
370
+						'capability'  => $persistent_admin_notice->getCapability(),
371
+						'cap_context' => $persistent_admin_notice->getCapContext(),
372
+						'dismissed'   => $persistent_admin_notice->getDismissed(),
373
+					);
374
+				}
375
+			}
376
+			update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
377
+		}
378
+	}
379
+
380
+
381
+	/**
382
+	 * @throws DomainException
383
+	 * @throws InvalidDataTypeException
384
+	 * @throws InvalidEntityException
385
+	 * @throws InvalidInterfaceException
386
+	 * @throws DuplicateCollectionIdentifierException
387
+	 */
388
+	public function registerAndSaveNotices()
389
+	{
390
+		$this->getPersistentAdminNoticeCollection();
391
+		$this->registerNotices();
392
+		$this->saveNotices();
393
+		add_filter(
394
+			'PersistentAdminNoticeManager__registerAndSaveNotices__complete',
395
+			'__return_true'
396
+		);
397
+	}
398
+
399
+
400
+	/**
401
+	 * @throws DomainException
402
+	 * @throws InvalidDataTypeException
403
+	 * @throws InvalidEntityException
404
+	 * @throws InvalidInterfaceException
405
+	 * @throws InvalidArgumentException
406
+	 * @throws DuplicateCollectionIdentifierException
407
+	 */
408
+	public static function loadRegisterAndSaveNotices()
409
+	{
410
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
411
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
412
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
413
+		);
414
+		// if shutdown has already run, then call registerAndSaveNotices() manually
415
+		if (did_action('shutdown')) {
416
+			$persistent_admin_notice_manager->registerAndSaveNotices();
417
+		}
418
+	}
419 419
 }
Please login to merge, or discard this patch.
core/services/database/TableAnalysis.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
     public function ensureTableNameHasPrefix($table_name)
33 33
     {
34 34
         global $wpdb;
35
-        return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix . $table_name;
35
+        return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix.$table_name;
36 36
     }
37 37
 
38 38
 
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
         $wpdb->last_error = $old_error;
82 82
         $EZSQL_ERROR = $ezsql_error_cache;
83 83
         // if there was a table doesn't exist error
84
-        if (! empty($new_error)) {
84
+        if ( ! empty($new_error)) {
85 85
             if (
86 86
                 in_array(
87 87
                     \EEH_Activation::last_wpdb_error_code(),
Please login to merge, or discard this patch.
Indentation   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -14,132 +14,132 @@
 block discarded – undo
14 14
 class TableAnalysis extends \EE_Base
15 15
 {
16 16
 
17
-    /**
18
-     * The maximum number of characters that can be indexed on a column using utf8mb4 collation,
19
-     * see https://events.codebasehq.com/redirect?https://make.wordpress.org/core/2015/04/02/the-utf8mb4-upgrade/
20
-     */
21
-    const INDEX_COLUMN_SIZE = 191;
17
+	/**
18
+	 * The maximum number of characters that can be indexed on a column using utf8mb4 collation,
19
+	 * see https://events.codebasehq.com/redirect?https://make.wordpress.org/core/2015/04/02/the-utf8mb4-upgrade/
20
+	 */
21
+	const INDEX_COLUMN_SIZE = 191;
22 22
 
23
-    /**
24
-     * Returns the table name which will definitely have the wpdb prefix on the front,
25
-     * except if it currently has the wpdb->base_prefix on the front, in which case
26
-     * it will have the wpdb->base_prefix on it
27
-     *
28
-     * @global \wpdb $wpdb
29
-     * @param string $table_name
30
-     * @return string $tableName, having ensured it has the wpdb prefix on the front
31
-     */
32
-    public function ensureTableNameHasPrefix($table_name)
33
-    {
34
-        global $wpdb;
35
-        return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix . $table_name;
36
-    }
23
+	/**
24
+	 * Returns the table name which will definitely have the wpdb prefix on the front,
25
+	 * except if it currently has the wpdb->base_prefix on the front, in which case
26
+	 * it will have the wpdb->base_prefix on it
27
+	 *
28
+	 * @global \wpdb $wpdb
29
+	 * @param string $table_name
30
+	 * @return string $tableName, having ensured it has the wpdb prefix on the front
31
+	 */
32
+	public function ensureTableNameHasPrefix($table_name)
33
+	{
34
+		global $wpdb;
35
+		return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix . $table_name;
36
+	}
37 37
 
38 38
 
39
-    /**
40
-     * Indicates whether or not the table has any entries. $table_name can
41
-     * optionally start with $wpdb->prefix or not
42
-     *
43
-     * @global \wpdb $wpdb
44
-     * @param string $table_name
45
-     * @return bool
46
-     */
47
-    public function tableIsEmpty($table_name)
48
-    {
49
-        global $wpdb;
50
-        $table_name = $this->ensureTableNameHasPrefix($table_name);
51
-        if ($this->tableExists($table_name)) {
52
-            $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
53
-            return absint($count) === 0 ? true : false;
54
-        }
55
-        return false;
56
-    }
39
+	/**
40
+	 * Indicates whether or not the table has any entries. $table_name can
41
+	 * optionally start with $wpdb->prefix or not
42
+	 *
43
+	 * @global \wpdb $wpdb
44
+	 * @param string $table_name
45
+	 * @return bool
46
+	 */
47
+	public function tableIsEmpty($table_name)
48
+	{
49
+		global $wpdb;
50
+		$table_name = $this->ensureTableNameHasPrefix($table_name);
51
+		if ($this->tableExists($table_name)) {
52
+			$count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
53
+			return absint($count) === 0 ? true : false;
54
+		}
55
+		return false;
56
+	}
57 57
 
58 58
 
59
-    /**
60
-     * Indicates whether or not the table exists. $table_name can optionally
61
-     * have the $wpdb->prefix on the beginning, or not.
62
-     *
63
-     * @global \wpdb $wpdb
64
-     * @global array EZSQL_Error
65
-     * @param        $table_name
66
-     * @return bool
67
-     */
68
-    public function tableExists($table_name)
69
-    {
70
-        global $wpdb, $EZSQL_ERROR;
71
-        $table_name = $this->ensureTableNameHasPrefix($table_name);
72
-        // ignore if this causes an sql error
73
-        $old_error = $wpdb->last_error;
74
-        $old_suppress_errors = $wpdb->suppress_errors();
75
-        $old_show_errors_value = $wpdb->show_errors(false);
76
-        $ezsql_error_cache = $EZSQL_ERROR;
77
-        $wpdb->get_results("SELECT * from $table_name LIMIT 1");
78
-        $wpdb->show_errors($old_show_errors_value);
79
-        $wpdb->suppress_errors($old_suppress_errors);
80
-        $new_error = $wpdb->last_error;
81
-        $wpdb->last_error = $old_error;
82
-        $EZSQL_ERROR = $ezsql_error_cache;
83
-        // if there was a table doesn't exist error
84
-        if (! empty($new_error)) {
85
-            if (
86
-                in_array(
87
-                    \EEH_Activation::last_wpdb_error_code(),
88
-                    array(
89
-                    1051, // bad table
90
-                    1109, // unknown table
91
-                    117, // no such table
92
-                    )
93
-                )
94
-                ||
95
-                preg_match(
96
-                    '~^Table .* doesn\'t exist~',
97
-                    $new_error
98
-                ) // in case not using mysql and error codes aren't reliable, just check for this error string
99
-            ) {
100
-                return false;
101
-            } else {
102
-                // log this because that's weird. Just use the normal PHP error log
103
-                error_log(
104
-                    sprintf(
105
-                        esc_html__(
106
-                            'Event Espresso error detected when checking if table existed: %1$s (it wasn\'t just that the table didn\'t exist either)',
107
-                            'event_espresso'
108
-                        ),
109
-                        $new_error
110
-                    )
111
-                );
112
-            }
113
-        }
114
-        return true;
115
-    }
59
+	/**
60
+	 * Indicates whether or not the table exists. $table_name can optionally
61
+	 * have the $wpdb->prefix on the beginning, or not.
62
+	 *
63
+	 * @global \wpdb $wpdb
64
+	 * @global array EZSQL_Error
65
+	 * @param        $table_name
66
+	 * @return bool
67
+	 */
68
+	public function tableExists($table_name)
69
+	{
70
+		global $wpdb, $EZSQL_ERROR;
71
+		$table_name = $this->ensureTableNameHasPrefix($table_name);
72
+		// ignore if this causes an sql error
73
+		$old_error = $wpdb->last_error;
74
+		$old_suppress_errors = $wpdb->suppress_errors();
75
+		$old_show_errors_value = $wpdb->show_errors(false);
76
+		$ezsql_error_cache = $EZSQL_ERROR;
77
+		$wpdb->get_results("SELECT * from $table_name LIMIT 1");
78
+		$wpdb->show_errors($old_show_errors_value);
79
+		$wpdb->suppress_errors($old_suppress_errors);
80
+		$new_error = $wpdb->last_error;
81
+		$wpdb->last_error = $old_error;
82
+		$EZSQL_ERROR = $ezsql_error_cache;
83
+		// if there was a table doesn't exist error
84
+		if (! empty($new_error)) {
85
+			if (
86
+				in_array(
87
+					\EEH_Activation::last_wpdb_error_code(),
88
+					array(
89
+					1051, // bad table
90
+					1109, // unknown table
91
+					117, // no such table
92
+					)
93
+				)
94
+				||
95
+				preg_match(
96
+					'~^Table .* doesn\'t exist~',
97
+					$new_error
98
+				) // in case not using mysql and error codes aren't reliable, just check for this error string
99
+			) {
100
+				return false;
101
+			} else {
102
+				// log this because that's weird. Just use the normal PHP error log
103
+				error_log(
104
+					sprintf(
105
+						esc_html__(
106
+							'Event Espresso error detected when checking if table existed: %1$s (it wasn\'t just that the table didn\'t exist either)',
107
+							'event_espresso'
108
+						),
109
+						$new_error
110
+					)
111
+				);
112
+			}
113
+		}
114
+		return true;
115
+	}
116 116
 
117 117
 
118
-    /**
119
-     * @param $table_name
120
-     * @param $index_name
121
-     * @return array of columns used on that index, Each entry is an object with the following properties {
122
-     * @type string Table
123
-     * @type string Non_unique "0" or "1"
124
-     * @type string Key_name
125
-     * @type string Seq_in_index
126
-     * @type string Column_name
127
-     * @type string Collation
128
-     * @type string Cardinality
129
-     * @type string Sub_part on a column, usually this is just the number of characters from this column to use in
130
-     *       indexing
131
-     * @type string|null Packed
132
-     * @type string Null
133
-     * @type string Index_type
134
-     * @type string Comment
135
-     * @type string Index_comment
136
-     * }
137
-     */
138
-    public function showIndexes($table_name, $index_name)
139
-    {
140
-        global $wpdb;
141
-        $table_name = $this->ensureTableNameHasPrefix($table_name);
142
-        $index_exists_query = "SHOW INDEX FROM {$table_name} WHERE Key_name = '{$index_name}'";
143
-        return $wpdb->get_results($index_exists_query);
144
-    }
118
+	/**
119
+	 * @param $table_name
120
+	 * @param $index_name
121
+	 * @return array of columns used on that index, Each entry is an object with the following properties {
122
+	 * @type string Table
123
+	 * @type string Non_unique "0" or "1"
124
+	 * @type string Key_name
125
+	 * @type string Seq_in_index
126
+	 * @type string Column_name
127
+	 * @type string Collation
128
+	 * @type string Cardinality
129
+	 * @type string Sub_part on a column, usually this is just the number of characters from this column to use in
130
+	 *       indexing
131
+	 * @type string|null Packed
132
+	 * @type string Null
133
+	 * @type string Index_type
134
+	 * @type string Comment
135
+	 * @type string Index_comment
136
+	 * }
137
+	 */
138
+	public function showIndexes($table_name, $index_name)
139
+	{
140
+		global $wpdb;
141
+		$table_name = $this->ensureTableNameHasPrefix($table_name);
142
+		$index_exists_query = "SHOW INDEX FROM {$table_name} WHERE Key_name = '{$index_name}'";
143
+		return $wpdb->get_results($index_exists_query);
144
+	}
145 145
 }
Please login to merge, or discard this patch.
core/services/cache/TransientCacheStorage.php 2 patches
Indentation   +363 added lines, -363 removed lines patch added patch discarded remove patch
@@ -16,367 +16,367 @@
 block discarded – undo
16 16
 class TransientCacheStorage implements CacheStorageInterface
17 17
 {
18 18
 
19
-    /**
20
-     * wp-option option_name for tracking transients
21
-     *
22
-     * @type string
23
-     */
24
-    const TRANSIENT_SCHEDULE_OPTIONS_KEY = 'ee_transient_schedule';
25
-
26
-    /**
27
-     * @var int $current_time
28
-     */
29
-    private $current_time;
30
-
31
-    /**
32
-     * how often to perform transient cleanup
33
-     *
34
-     * @var string $transient_cleanup_frequency
35
-     */
36
-    private $transient_cleanup_frequency;
37
-
38
-    /**
39
-     * options for how often to perform transient cleanup
40
-     *
41
-     * @var array $transient_cleanup_frequency_options
42
-     */
43
-    private $transient_cleanup_frequency_options = array();
44
-
45
-    /**
46
-     * @var array $transients
47
-     */
48
-    private $transients;
49
-
50
-
51
-    /**
52
-     * TransientCacheStorage constructor.
53
-     */
54
-    public function __construct()
55
-    {
56
-        $this->transient_cleanup_frequency = $this->setTransientCleanupFrequency();
57
-        // round current time down to closest 5 minutes to simplify scheduling
58
-        $this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
59
-        $this->transients = (array) get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
60
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
61
-            add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
62
-        }
63
-    }
64
-
65
-
66
-    /**
67
-     * Sets how often transient cleanup occurs
68
-     *
69
-     * @return string
70
-     */
71
-    private function setTransientCleanupFrequency()
72
-    {
73
-        // sets how often transients are cleaned up
74
-        $this->transient_cleanup_frequency_options = apply_filters(
75
-            'FHEE__TransientCacheStorage__transient_cleanup_schedule_options',
76
-            array(
77
-                'off',
78
-                '15-minutes',
79
-                'hour',
80
-                '12-hours',
81
-                'day',
82
-            )
83
-        );
84
-        $transient_cleanup_frequency = apply_filters(
85
-            'FHEE__TransientCacheStorage__transient_cleanup_schedule',
86
-            'hour'
87
-        );
88
-        return in_array(
89
-            $transient_cleanup_frequency,
90
-            $this->transient_cleanup_frequency_options,
91
-            true
92
-        )
93
-            ? $transient_cleanup_frequency
94
-            : 'hour';
95
-    }
96
-
97
-
98
-    /**
99
-     * we need to be able to round timestamps off to match the set transient cleanup frequency
100
-     * so if a transient is set to expire at 1:17 pm for example, and our cleanup schedule is every hour,
101
-     * then that timestamp needs to be rounded up to 2:00 pm so that it is removed
102
-     * during the next scheduled cleanup after its expiration.
103
-     * We also round off the current time timestamp to the closest 5 minutes
104
-     * just to make the timestamps a little easier to round which helps with debugging.
105
-     *
106
-     * @param int    $timestamp [required]
107
-     * @param string $cleanup_frequency
108
-     * @param bool   $round_up
109
-     * @return int
110
-     */
111
-    private function roundTimestamp($timestamp, $cleanup_frequency = 'hour', $round_up = true)
112
-    {
113
-        $cleanup_frequency = $cleanup_frequency ? $cleanup_frequency : $this->transient_cleanup_frequency;
114
-        // in order to round the time to the closest xx minutes (or hours),
115
-        // we take the minutes (or hours) portion of the timestamp and divide it by xx,
116
-        // round down to a whole number, then multiply by xx to bring us almost back up to where we were
117
-        // why round down ? so the minutes (or hours) don't go over 60 (or 24)
118
-        // and bump the hour, which could bump the day, which could bump the month, etc,
119
-        // which would be bad because we don't always want to round up,
120
-        // but when we do we can easily achieve that by simply adding the desired offset,
121
-        $minutes = '00';
122
-        $hours = 'H';
123
-        switch ($cleanup_frequency) {
124
-            case '5-minutes':
125
-                $minutes = floor((int) date('i', $timestamp) / 5) * 5;
126
-                $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
127
-                $offset = MINUTE_IN_SECONDS * 5;
128
-                break;
129
-            case '15-minutes':
130
-                $minutes = floor((int) date('i', $timestamp) / 15) * 15;
131
-                $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
132
-                $offset = MINUTE_IN_SECONDS * 15;
133
-                break;
134
-            case '12-hours':
135
-                $hours = floor((int) date('H', $timestamp) / 12) * 12;
136
-                $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
137
-                $offset = HOUR_IN_SECONDS * 12;
138
-                break;
139
-            case 'day':
140
-                $hours = '03'; // run cleanup at 3:00 am (or first site hit after that)
141
-                $offset = DAY_IN_SECONDS;
142
-                break;
143
-            case 'hour':
144
-            default:
145
-                $offset = HOUR_IN_SECONDS;
146
-                break;
147
-        }
148
-        $rounded_timestamp = (int) strtotime(date("Y-m-d {$hours}:{$minutes}:00", $timestamp));
149
-        $rounded_timestamp += $round_up ? $offset : 0;
150
-        return apply_filters(
151
-            'FHEE__TransientCacheStorage__roundTimestamp__timestamp',
152
-            $rounded_timestamp,
153
-            $timestamp,
154
-            $cleanup_frequency,
155
-            $round_up
156
-        );
157
-    }
158
-
159
-
160
-    /**
161
-     * Saves supplied data to a transient
162
-     * if an expiration is set, then it automatically schedules the transient for cleanup
163
-     *
164
-     * @param string $transient_key [required]
165
-     * @param string $data          [required]
166
-     * @param int    $expiration    number of seconds until the cache expires
167
-     * @return bool
168
-     */
169
-    public function add($transient_key, $data, $expiration = 0)
170
-    {
171
-        $expiration = (int) abs($expiration);
172
-        $saved = set_transient($transient_key, $data, $expiration);
173
-        if ($saved && $expiration) {
174
-            $this->scheduleTransientCleanup($transient_key, $expiration);
175
-        }
176
-        return $saved;
177
-    }
178
-
179
-
180
-    /**
181
-     * retrieves transient data
182
-     * automatically triggers early cache refresh for standard cache items
183
-     * in order to avoid cache stampedes on busy sites.
184
-     * For non-standard cache items like PHP Session data where early refreshing is not wanted,
185
-     * the $standard_cache parameter should be set to false when retrieving data
186
-     *
187
-     * @param string $transient_key [required]
188
-     * @param bool   $standard_cache
189
-     * @return mixed|null
190
-     */
191
-    public function get($transient_key, $standard_cache = true)
192
-    {
193
-        if (isset($this->transients[ $transient_key ])) {
194
-            // to avoid cache stampedes (AKA:dogpiles) for standard cache items,
195
-            // check if known cache expires within the next minute,
196
-            // and if so, remove it from our tracking and and return nothing.
197
-            // this should trigger the cache content to be regenerated during this request,
198
-            // while allowing any following requests to still access the existing cache
199
-            // until it gets replaced with the refreshed content
200
-            if (
201
-                $standard_cache
202
-                && $this->transients[ $transient_key ] - time() <= MINUTE_IN_SECONDS
203
-            ) {
204
-                unset($this->transients[ $transient_key ]);
205
-                $this->updateTransients();
206
-                return null;
207
-            }
208
-
209
-            // for non standard cache items, remove the key from our tracking,
210
-            // but proceed to retrieve the transient so that it also gets removed from the db
211
-            if ($this->transients[ $transient_key ] <= time()) {
212
-                unset($this->transients[ $transient_key ]);
213
-                $this->updateTransients();
214
-            }
215
-        }
216
-
217
-        $content = get_transient($transient_key);
218
-        return $content !== false ? $content : null;
219
-    }
220
-
221
-
222
-    /**
223
-     * delete a single transient and remove tracking
224
-     *
225
-     * @param string $transient_key [required] full or partial transient key to be deleted
226
-     */
227
-    public function delete($transient_key)
228
-    {
229
-        $this->deleteMany(array($transient_key));
230
-    }
231
-
232
-
233
-    /**
234
-     * delete multiple transients and remove tracking
235
-     *
236
-     * @param array $transient_keys [required] array of full or partial transient keys to be deleted
237
-     * @param bool  $force_delete   [optional] if true, then will not check incoming keys against those being tracked
238
-     *                              and proceed directly to deleting those entries from the cache storage
239
-     */
240
-    public function deleteMany(array $transient_keys, $force_delete = false)
241
-    {
242
-        $full_transient_keys = $force_delete ? $transient_keys : array();
243
-        if (empty($full_transient_keys)) {
244
-            foreach ($this->transients as $transient_key => $expiration) {
245
-                foreach ($transient_keys as $transient_key_to_delete) {
246
-                    if (strpos($transient_key, $transient_key_to_delete) !== false) {
247
-                        $full_transient_keys[] = $transient_key;
248
-                    }
249
-                }
250
-            }
251
-        }
252
-        if ($this->deleteTransientKeys($full_transient_keys)) {
253
-            $this->updateTransients();
254
-        }
255
-    }
256
-
257
-
258
-    /**
259
-     * sorts transients numerically by timestamp
260
-     * then saves the transient schedule to a WP option
261
-     */
262
-    private function updateTransients()
263
-    {
264
-        asort($this->transients, SORT_NUMERIC);
265
-        update_option(
266
-            TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY,
267
-            $this->transients
268
-        );
269
-    }
270
-
271
-
272
-    /**
273
-     * schedules a transient for cleanup by adding it to the transient tracking
274
-     *
275
-     * @param string $transient_key [required]
276
-     * @param int    $expiration    [required]
277
-     */
278
-    private function scheduleTransientCleanup($transient_key, $expiration)
279
-    {
280
-        // make sure a valid future timestamp is set
281
-        $expiration += $expiration < time() ? time() : 0;
282
-        // and round to the closest 15 minutes
283
-        $expiration = $this->roundTimestamp($expiration);
284
-        // save transients to clear using their ID as the key to avoid duplicates
285
-        $this->transients[ $transient_key ] = $expiration;
286
-        $this->updateTransients();
287
-    }
288
-
289
-
290
-    /**
291
-     * Since our tracked transients are sorted by their timestamps
292
-     * we can grab the first transient and see when it is scheduled for cleanup.
293
-     * If that timestamp is less than or equal to the current time,
294
-     * then cleanup is triggered
295
-     */
296
-    public function checkTransientCleanupSchedule()
297
-    {
298
-        if (empty($this->transients)) {
299
-            return;
300
-        }
301
-        // when do we run the next cleanup job?
302
-        reset($this->transients);
303
-        $next_scheduled_cleanup = current($this->transients);
304
-        // if the next cleanup job is scheduled for the current hour
305
-        if ($next_scheduled_cleanup <= $this->current_time) {
306
-            if ($this->cleanupExpiredTransients()) {
307
-                $this->updateTransients();
308
-            }
309
-        }
310
-    }
311
-
312
-
313
-    /**
314
-     * loops through the array of tracked transients,
315
-     * compiles a list of those that have expired, and sends that list off for deletion.
316
-     * Also removes any bad records from the transients array
317
-     *
318
-     * @return bool
319
-     */
320
-    private function cleanupExpiredTransients()
321
-    {
322
-        $update = false;
323
-        // filter the query limit. Set to 0 to turn off garbage collection
324
-        $limit = (int) abs(
325
-            apply_filters(
326
-                'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
327
-                50
328
-            )
329
-        );
330
-        // non-zero LIMIT means take out the trash
331
-        if ($limit) {
332
-            $transient_keys = array();
333
-            foreach ($this->transients as $transient_key => $expiration) {
334
-                if ($expiration > $this->current_time) {
335
-                    continue;
336
-                }
337
-                if (! $expiration || ! $transient_key) {
338
-                    unset($this->transients[ $transient_key ]);
339
-                    $update = true;
340
-                    continue;
341
-                }
342
-                $transient_keys[] = $transient_key;
343
-            }
344
-            // delete expired keys, but maintain value of $update if nothing is deleted
345
-            $update = $this->deleteTransientKeys($transient_keys, $limit) ? true : $update;
346
-            do_action('FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
347
-        }
348
-        return $update;
349
-    }
350
-
351
-
352
-    /**
353
-     * calls delete_transient() on each transient key provided, up to the specified limit
354
-     *
355
-     * @param array $transient_keys [required]
356
-     * @param int   $limit
357
-     * @return bool
358
-     */
359
-    private function deleteTransientKeys(array $transient_keys, $limit = 50)
360
-    {
361
-        if (empty($transient_keys)) {
362
-            return false;
363
-        }
364
-        $counter = 0;
365
-        foreach ($transient_keys as $transient_key) {
366
-            if ($counter === $limit) {
367
-                break;
368
-            }
369
-            // remove any transient prefixes
370
-            $transient_key = strpos($transient_key, '_transient_timeout_') === 0
371
-                ? str_replace('_transient_timeout_', '', $transient_key)
372
-                : $transient_key;
373
-            $transient_key = strpos($transient_key, '_transient_') === 0
374
-                ? str_replace('_transient_', '', $transient_key)
375
-                : $transient_key;
376
-            delete_transient($transient_key);
377
-            unset($this->transients[ $transient_key ]);
378
-            $counter++;
379
-        }
380
-        return $counter > 0;
381
-    }
19
+	/**
20
+	 * wp-option option_name for tracking transients
21
+	 *
22
+	 * @type string
23
+	 */
24
+	const TRANSIENT_SCHEDULE_OPTIONS_KEY = 'ee_transient_schedule';
25
+
26
+	/**
27
+	 * @var int $current_time
28
+	 */
29
+	private $current_time;
30
+
31
+	/**
32
+	 * how often to perform transient cleanup
33
+	 *
34
+	 * @var string $transient_cleanup_frequency
35
+	 */
36
+	private $transient_cleanup_frequency;
37
+
38
+	/**
39
+	 * options for how often to perform transient cleanup
40
+	 *
41
+	 * @var array $transient_cleanup_frequency_options
42
+	 */
43
+	private $transient_cleanup_frequency_options = array();
44
+
45
+	/**
46
+	 * @var array $transients
47
+	 */
48
+	private $transients;
49
+
50
+
51
+	/**
52
+	 * TransientCacheStorage constructor.
53
+	 */
54
+	public function __construct()
55
+	{
56
+		$this->transient_cleanup_frequency = $this->setTransientCleanupFrequency();
57
+		// round current time down to closest 5 minutes to simplify scheduling
58
+		$this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
59
+		$this->transients = (array) get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
60
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
61
+			add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
62
+		}
63
+	}
64
+
65
+
66
+	/**
67
+	 * Sets how often transient cleanup occurs
68
+	 *
69
+	 * @return string
70
+	 */
71
+	private function setTransientCleanupFrequency()
72
+	{
73
+		// sets how often transients are cleaned up
74
+		$this->transient_cleanup_frequency_options = apply_filters(
75
+			'FHEE__TransientCacheStorage__transient_cleanup_schedule_options',
76
+			array(
77
+				'off',
78
+				'15-minutes',
79
+				'hour',
80
+				'12-hours',
81
+				'day',
82
+			)
83
+		);
84
+		$transient_cleanup_frequency = apply_filters(
85
+			'FHEE__TransientCacheStorage__transient_cleanup_schedule',
86
+			'hour'
87
+		);
88
+		return in_array(
89
+			$transient_cleanup_frequency,
90
+			$this->transient_cleanup_frequency_options,
91
+			true
92
+		)
93
+			? $transient_cleanup_frequency
94
+			: 'hour';
95
+	}
96
+
97
+
98
+	/**
99
+	 * we need to be able to round timestamps off to match the set transient cleanup frequency
100
+	 * so if a transient is set to expire at 1:17 pm for example, and our cleanup schedule is every hour,
101
+	 * then that timestamp needs to be rounded up to 2:00 pm so that it is removed
102
+	 * during the next scheduled cleanup after its expiration.
103
+	 * We also round off the current time timestamp to the closest 5 minutes
104
+	 * just to make the timestamps a little easier to round which helps with debugging.
105
+	 *
106
+	 * @param int    $timestamp [required]
107
+	 * @param string $cleanup_frequency
108
+	 * @param bool   $round_up
109
+	 * @return int
110
+	 */
111
+	private function roundTimestamp($timestamp, $cleanup_frequency = 'hour', $round_up = true)
112
+	{
113
+		$cleanup_frequency = $cleanup_frequency ? $cleanup_frequency : $this->transient_cleanup_frequency;
114
+		// in order to round the time to the closest xx minutes (or hours),
115
+		// we take the minutes (or hours) portion of the timestamp and divide it by xx,
116
+		// round down to a whole number, then multiply by xx to bring us almost back up to where we were
117
+		// why round down ? so the minutes (or hours) don't go over 60 (or 24)
118
+		// and bump the hour, which could bump the day, which could bump the month, etc,
119
+		// which would be bad because we don't always want to round up,
120
+		// but when we do we can easily achieve that by simply adding the desired offset,
121
+		$minutes = '00';
122
+		$hours = 'H';
123
+		switch ($cleanup_frequency) {
124
+			case '5-minutes':
125
+				$minutes = floor((int) date('i', $timestamp) / 5) * 5;
126
+				$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
127
+				$offset = MINUTE_IN_SECONDS * 5;
128
+				break;
129
+			case '15-minutes':
130
+				$minutes = floor((int) date('i', $timestamp) / 15) * 15;
131
+				$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
132
+				$offset = MINUTE_IN_SECONDS * 15;
133
+				break;
134
+			case '12-hours':
135
+				$hours = floor((int) date('H', $timestamp) / 12) * 12;
136
+				$hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
137
+				$offset = HOUR_IN_SECONDS * 12;
138
+				break;
139
+			case 'day':
140
+				$hours = '03'; // run cleanup at 3:00 am (or first site hit after that)
141
+				$offset = DAY_IN_SECONDS;
142
+				break;
143
+			case 'hour':
144
+			default:
145
+				$offset = HOUR_IN_SECONDS;
146
+				break;
147
+		}
148
+		$rounded_timestamp = (int) strtotime(date("Y-m-d {$hours}:{$minutes}:00", $timestamp));
149
+		$rounded_timestamp += $round_up ? $offset : 0;
150
+		return apply_filters(
151
+			'FHEE__TransientCacheStorage__roundTimestamp__timestamp',
152
+			$rounded_timestamp,
153
+			$timestamp,
154
+			$cleanup_frequency,
155
+			$round_up
156
+		);
157
+	}
158
+
159
+
160
+	/**
161
+	 * Saves supplied data to a transient
162
+	 * if an expiration is set, then it automatically schedules the transient for cleanup
163
+	 *
164
+	 * @param string $transient_key [required]
165
+	 * @param string $data          [required]
166
+	 * @param int    $expiration    number of seconds until the cache expires
167
+	 * @return bool
168
+	 */
169
+	public function add($transient_key, $data, $expiration = 0)
170
+	{
171
+		$expiration = (int) abs($expiration);
172
+		$saved = set_transient($transient_key, $data, $expiration);
173
+		if ($saved && $expiration) {
174
+			$this->scheduleTransientCleanup($transient_key, $expiration);
175
+		}
176
+		return $saved;
177
+	}
178
+
179
+
180
+	/**
181
+	 * retrieves transient data
182
+	 * automatically triggers early cache refresh for standard cache items
183
+	 * in order to avoid cache stampedes on busy sites.
184
+	 * For non-standard cache items like PHP Session data where early refreshing is not wanted,
185
+	 * the $standard_cache parameter should be set to false when retrieving data
186
+	 *
187
+	 * @param string $transient_key [required]
188
+	 * @param bool   $standard_cache
189
+	 * @return mixed|null
190
+	 */
191
+	public function get($transient_key, $standard_cache = true)
192
+	{
193
+		if (isset($this->transients[ $transient_key ])) {
194
+			// to avoid cache stampedes (AKA:dogpiles) for standard cache items,
195
+			// check if known cache expires within the next minute,
196
+			// and if so, remove it from our tracking and and return nothing.
197
+			// this should trigger the cache content to be regenerated during this request,
198
+			// while allowing any following requests to still access the existing cache
199
+			// until it gets replaced with the refreshed content
200
+			if (
201
+				$standard_cache
202
+				&& $this->transients[ $transient_key ] - time() <= MINUTE_IN_SECONDS
203
+			) {
204
+				unset($this->transients[ $transient_key ]);
205
+				$this->updateTransients();
206
+				return null;
207
+			}
208
+
209
+			// for non standard cache items, remove the key from our tracking,
210
+			// but proceed to retrieve the transient so that it also gets removed from the db
211
+			if ($this->transients[ $transient_key ] <= time()) {
212
+				unset($this->transients[ $transient_key ]);
213
+				$this->updateTransients();
214
+			}
215
+		}
216
+
217
+		$content = get_transient($transient_key);
218
+		return $content !== false ? $content : null;
219
+	}
220
+
221
+
222
+	/**
223
+	 * delete a single transient and remove tracking
224
+	 *
225
+	 * @param string $transient_key [required] full or partial transient key to be deleted
226
+	 */
227
+	public function delete($transient_key)
228
+	{
229
+		$this->deleteMany(array($transient_key));
230
+	}
231
+
232
+
233
+	/**
234
+	 * delete multiple transients and remove tracking
235
+	 *
236
+	 * @param array $transient_keys [required] array of full or partial transient keys to be deleted
237
+	 * @param bool  $force_delete   [optional] if true, then will not check incoming keys against those being tracked
238
+	 *                              and proceed directly to deleting those entries from the cache storage
239
+	 */
240
+	public function deleteMany(array $transient_keys, $force_delete = false)
241
+	{
242
+		$full_transient_keys = $force_delete ? $transient_keys : array();
243
+		if (empty($full_transient_keys)) {
244
+			foreach ($this->transients as $transient_key => $expiration) {
245
+				foreach ($transient_keys as $transient_key_to_delete) {
246
+					if (strpos($transient_key, $transient_key_to_delete) !== false) {
247
+						$full_transient_keys[] = $transient_key;
248
+					}
249
+				}
250
+			}
251
+		}
252
+		if ($this->deleteTransientKeys($full_transient_keys)) {
253
+			$this->updateTransients();
254
+		}
255
+	}
256
+
257
+
258
+	/**
259
+	 * sorts transients numerically by timestamp
260
+	 * then saves the transient schedule to a WP option
261
+	 */
262
+	private function updateTransients()
263
+	{
264
+		asort($this->transients, SORT_NUMERIC);
265
+		update_option(
266
+			TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY,
267
+			$this->transients
268
+		);
269
+	}
270
+
271
+
272
+	/**
273
+	 * schedules a transient for cleanup by adding it to the transient tracking
274
+	 *
275
+	 * @param string $transient_key [required]
276
+	 * @param int    $expiration    [required]
277
+	 */
278
+	private function scheduleTransientCleanup($transient_key, $expiration)
279
+	{
280
+		// make sure a valid future timestamp is set
281
+		$expiration += $expiration < time() ? time() : 0;
282
+		// and round to the closest 15 minutes
283
+		$expiration = $this->roundTimestamp($expiration);
284
+		// save transients to clear using their ID as the key to avoid duplicates
285
+		$this->transients[ $transient_key ] = $expiration;
286
+		$this->updateTransients();
287
+	}
288
+
289
+
290
+	/**
291
+	 * Since our tracked transients are sorted by their timestamps
292
+	 * we can grab the first transient and see when it is scheduled for cleanup.
293
+	 * If that timestamp is less than or equal to the current time,
294
+	 * then cleanup is triggered
295
+	 */
296
+	public function checkTransientCleanupSchedule()
297
+	{
298
+		if (empty($this->transients)) {
299
+			return;
300
+		}
301
+		// when do we run the next cleanup job?
302
+		reset($this->transients);
303
+		$next_scheduled_cleanup = current($this->transients);
304
+		// if the next cleanup job is scheduled for the current hour
305
+		if ($next_scheduled_cleanup <= $this->current_time) {
306
+			if ($this->cleanupExpiredTransients()) {
307
+				$this->updateTransients();
308
+			}
309
+		}
310
+	}
311
+
312
+
313
+	/**
314
+	 * loops through the array of tracked transients,
315
+	 * compiles a list of those that have expired, and sends that list off for deletion.
316
+	 * Also removes any bad records from the transients array
317
+	 *
318
+	 * @return bool
319
+	 */
320
+	private function cleanupExpiredTransients()
321
+	{
322
+		$update = false;
323
+		// filter the query limit. Set to 0 to turn off garbage collection
324
+		$limit = (int) abs(
325
+			apply_filters(
326
+				'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
327
+				50
328
+			)
329
+		);
330
+		// non-zero LIMIT means take out the trash
331
+		if ($limit) {
332
+			$transient_keys = array();
333
+			foreach ($this->transients as $transient_key => $expiration) {
334
+				if ($expiration > $this->current_time) {
335
+					continue;
336
+				}
337
+				if (! $expiration || ! $transient_key) {
338
+					unset($this->transients[ $transient_key ]);
339
+					$update = true;
340
+					continue;
341
+				}
342
+				$transient_keys[] = $transient_key;
343
+			}
344
+			// delete expired keys, but maintain value of $update if nothing is deleted
345
+			$update = $this->deleteTransientKeys($transient_keys, $limit) ? true : $update;
346
+			do_action('FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
347
+		}
348
+		return $update;
349
+	}
350
+
351
+
352
+	/**
353
+	 * calls delete_transient() on each transient key provided, up to the specified limit
354
+	 *
355
+	 * @param array $transient_keys [required]
356
+	 * @param int   $limit
357
+	 * @return bool
358
+	 */
359
+	private function deleteTransientKeys(array $transient_keys, $limit = 50)
360
+	{
361
+		if (empty($transient_keys)) {
362
+			return false;
363
+		}
364
+		$counter = 0;
365
+		foreach ($transient_keys as $transient_key) {
366
+			if ($counter === $limit) {
367
+				break;
368
+			}
369
+			// remove any transient prefixes
370
+			$transient_key = strpos($transient_key, '_transient_timeout_') === 0
371
+				? str_replace('_transient_timeout_', '', $transient_key)
372
+				: $transient_key;
373
+			$transient_key = strpos($transient_key, '_transient_') === 0
374
+				? str_replace('_transient_', '', $transient_key)
375
+				: $transient_key;
376
+			delete_transient($transient_key);
377
+			unset($this->transients[ $transient_key ]);
378
+			$counter++;
379
+		}
380
+		return $counter > 0;
381
+	}
382 382
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
         // round current time down to closest 5 minutes to simplify scheduling
58 58
         $this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
59 59
         $this->transients = (array) get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
60
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
60
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
61 61
             add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
62 62
         }
63 63
     }
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
      */
191 191
     public function get($transient_key, $standard_cache = true)
192 192
     {
193
-        if (isset($this->transients[ $transient_key ])) {
193
+        if (isset($this->transients[$transient_key])) {
194 194
             // to avoid cache stampedes (AKA:dogpiles) for standard cache items,
195 195
             // check if known cache expires within the next minute,
196 196
             // and if so, remove it from our tracking and and return nothing.
@@ -199,17 +199,17 @@  discard block
 block discarded – undo
199 199
             // until it gets replaced with the refreshed content
200 200
             if (
201 201
                 $standard_cache
202
-                && $this->transients[ $transient_key ] - time() <= MINUTE_IN_SECONDS
202
+                && $this->transients[$transient_key] - time() <= MINUTE_IN_SECONDS
203 203
             ) {
204
-                unset($this->transients[ $transient_key ]);
204
+                unset($this->transients[$transient_key]);
205 205
                 $this->updateTransients();
206 206
                 return null;
207 207
             }
208 208
 
209 209
             // for non standard cache items, remove the key from our tracking,
210 210
             // but proceed to retrieve the transient so that it also gets removed from the db
211
-            if ($this->transients[ $transient_key ] <= time()) {
212
-                unset($this->transients[ $transient_key ]);
211
+            if ($this->transients[$transient_key] <= time()) {
212
+                unset($this->transients[$transient_key]);
213 213
                 $this->updateTransients();
214 214
             }
215 215
         }
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
         // and round to the closest 15 minutes
283 283
         $expiration = $this->roundTimestamp($expiration);
284 284
         // save transients to clear using their ID as the key to avoid duplicates
285
-        $this->transients[ $transient_key ] = $expiration;
285
+        $this->transients[$transient_key] = $expiration;
286 286
         $this->updateTransients();
287 287
     }
288 288
 
@@ -334,8 +334,8 @@  discard block
 block discarded – undo
334 334
                 if ($expiration > $this->current_time) {
335 335
                     continue;
336 336
                 }
337
-                if (! $expiration || ! $transient_key) {
338
-                    unset($this->transients[ $transient_key ]);
337
+                if ( ! $expiration || ! $transient_key) {
338
+                    unset($this->transients[$transient_key]);
339 339
                     $update = true;
340 340
                     continue;
341 341
                 }
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
                 ? str_replace('_transient_', '', $transient_key)
375 375
                 : $transient_key;
376 376
             delete_transient($transient_key);
377
-            unset($this->transients[ $transient_key ]);
377
+            unset($this->transients[$transient_key]);
378 378
             $counter++;
379 379
         }
380 380
         return $counter > 0;
Please login to merge, or discard this patch.
core/services/request/middleware/DetectLogin.php 1 patch
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -16,29 +16,29 @@
 block discarded – undo
16 16
 class DetectLogin extends Middleware
17 17
 {
18 18
 
19
-    /**
20
-     * converts a Request to a Response
21
-     *
22
-     * @param RequestInterface  $request
23
-     * @param ResponseInterface $response
24
-     * @return ResponseInterface
25
-     */
26
-    public function handleRequest(RequestInterface $request, ResponseInterface $response)
27
-    {
28
-        $this->request = $request;
29
-        $this->response = $response;
30
-        global $pagenow;
31
-        if (
32
-            in_array(
33
-                $pagenow,
34
-                array('wp-login.php', 'wp-register.php'),
35
-                true
36
-            )
37
-            && ! filter_var($request->getRequestParam('ee_load_on_login'), FILTER_VALIDATE_BOOLEAN)
38
-        ) {
39
-            $this->response->terminateRequest();
40
-        }
41
-        $this->response = $this->processRequestStack($this->request, $this->response);
42
-        return $this->response;
43
-    }
19
+	/**
20
+	 * converts a Request to a Response
21
+	 *
22
+	 * @param RequestInterface  $request
23
+	 * @param ResponseInterface $response
24
+	 * @return ResponseInterface
25
+	 */
26
+	public function handleRequest(RequestInterface $request, ResponseInterface $response)
27
+	{
28
+		$this->request = $request;
29
+		$this->response = $response;
30
+		global $pagenow;
31
+		if (
32
+			in_array(
33
+				$pagenow,
34
+				array('wp-login.php', 'wp-register.php'),
35
+				true
36
+			)
37
+			&& ! filter_var($request->getRequestParam('ee_load_on_login'), FILTER_VALIDATE_BOOLEAN)
38
+		) {
39
+			$this->response->terminateRequest();
40
+		}
41
+		$this->response = $this->processRequestStack($this->request, $this->response);
42
+		return $this->response;
43
+	}
44 44
 }
Please login to merge, or discard this patch.
core/services/container/DependencyInjector.php 2 patches
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -21,216 +21,216 @@
 block discarded – undo
21 21
 class DependencyInjector implements InjectorInterface
22 22
 {
23 23
 
24
-    /**
25
-     * @var CoffeePotInterface $coffee_pot
26
-     */
27
-    private $coffee_pot;
28
-
29
-    /**
30
-     * @var EEH_Array $array_helper
31
-     */
32
-    private $array_helper;
33
-
34
-    /**
35
-     * @var ReflectionClass[] $reflectors
36
-     */
37
-    private $reflectors;
38
-
39
-    /**
40
-     * @var ReflectionMethod[] $constructors
41
-     */
42
-    private $constructors;
43
-
44
-    /**
45
-     * @var ReflectionParameter[] $parameters
46
-     */
47
-    private $parameters;
48
-
49
-
50
-    /**
51
-     * DependencyInjector constructor
52
-     *
53
-     * @param CoffeePotInterface $coffee_pot
54
-     * @param EEH_Array          $array_helper
55
-     */
56
-    public function __construct(CoffeePotInterface $coffee_pot, EEH_Array $array_helper)
57
-    {
58
-        $this->coffee_pot = $coffee_pot;
59
-        $this->array_helper = $array_helper;
60
-    }
61
-
62
-
63
-    /**
64
-     * getReflectionClass
65
-     * checks if a ReflectionClass object has already been generated for a class
66
-     * and returns that instead of creating a new one
67
-     *
68
-     * @param string $class_name
69
-     * @return ReflectionClass
70
-     */
71
-    public function getReflectionClass($class_name)
72
-    {
73
-        if (
74
-            ! isset($this->reflectors[ $class_name ])
75
-            || ! $this->reflectors[ $class_name ] instanceof ReflectionClass
76
-        ) {
77
-            $this->reflectors[ $class_name ] = new ReflectionClass($class_name);
78
-        }
79
-        return $this->reflectors[ $class_name ];
80
-    }
81
-
82
-
83
-    /**
84
-     * getConstructor
85
-     * checks if a ReflectionMethod object has already been generated for the class constructor
86
-     * and returns that instead of creating a new one
87
-     *
88
-     * @param ReflectionClass $reflector
89
-     * @return ReflectionMethod
90
-     */
91
-    protected function getConstructor(ReflectionClass $reflector)
92
-    {
93
-        if (
94
-            ! isset($this->constructors[ $reflector->getName() ])
95
-            || ! $this->constructors[ $reflector->getName() ] instanceof ReflectionMethod
96
-        ) {
97
-            $this->constructors[ $reflector->getName() ] = $reflector->getConstructor();
98
-        }
99
-        return $this->constructors[ $reflector->getName() ];
100
-    }
101
-
102
-
103
-    /**
104
-     * getParameters
105
-     * checks if an array of ReflectionParameter objects has already been generated for the class constructor
106
-     * and returns that instead of creating a new one
107
-     *
108
-     * @param ReflectionMethod $constructor
109
-     * @return ReflectionParameter[]
110
-     */
111
-    protected function getParameters(ReflectionMethod $constructor)
112
-    {
113
-        if (! isset($this->parameters[ $constructor->class ])) {
114
-            $this->parameters[ $constructor->class ] = $constructor->getParameters();
115
-        }
116
-        return $this->parameters[ $constructor->class ];
117
-    }
118
-
119
-
120
-    /**
121
-     * resolveDependencies
122
-     * examines the constructor for the requested class to determine
123
-     * if any dependencies exist, and if they can be injected.
124
-     * If so, then those classes will be added to the array of arguments passed to the constructor
125
-     * PLZ NOTE: this is achieved by type hinting the constructor params
126
-     * For example:
127
-     *        if attempting to load a class "Foo" with the following constructor:
128
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
129
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
130
-     *        but only IF they are NOT already present in the incoming arguments array,
131
-     *        and the correct classes can be loaded
132
-     *
133
-     * @param RecipeInterface $recipe
134
-     * @param ReflectionClass $reflector
135
-     * @param array           $arguments
136
-     * @return array
137
-     * @throws UnexpectedValueException
138
-     */
139
-    public function resolveDependencies(RecipeInterface $recipe, ReflectionClass $reflector, $arguments = array())
140
-    {
141
-        // if arguments array is numerically and sequentially indexed, then we want it to remain as is,
142
-        // else wrap it in an additional array so that it doesn't get split into multiple parameters
143
-        $arguments = $this->array_helper->is_array_numerically_and_sequentially_indexed($arguments)
144
-            ? $arguments
145
-            : array($arguments);
146
-        $resolved_parameters = array();
147
-        // let's examine the constructor
148
-        // let's examine the constructor
149
-        $constructor = $this->getConstructor($reflector);
150
-        // whu? huh? nothing?
151
-        if (! $constructor) {
152
-            return $arguments;
153
-        }
154
-        // get constructor parameters
155
-        $params = $this->getParameters($constructor);
156
-        if (empty($params)) {
157
-            return $resolved_parameters;
158
-        }
159
-        $ingredients = $recipe->ingredients();
160
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
161
-        $argument_keys = array_keys($arguments);
162
-        // now loop thru all of the constructors expected parameters
163
-        foreach ($params as $index => $param) {
164
-            if (! $param instanceof ReflectionParameter) {
165
-                continue;
166
-            }
167
-            // is this a dependency for a specific class ?
168
-            $param_class = $param->getClass() ? $param->getClass()->name : '';
169
-            $param_name = $param->getName() ? $param->getName() : '';
170
-            if (
24
+	/**
25
+	 * @var CoffeePotInterface $coffee_pot
26
+	 */
27
+	private $coffee_pot;
28
+
29
+	/**
30
+	 * @var EEH_Array $array_helper
31
+	 */
32
+	private $array_helper;
33
+
34
+	/**
35
+	 * @var ReflectionClass[] $reflectors
36
+	 */
37
+	private $reflectors;
38
+
39
+	/**
40
+	 * @var ReflectionMethod[] $constructors
41
+	 */
42
+	private $constructors;
43
+
44
+	/**
45
+	 * @var ReflectionParameter[] $parameters
46
+	 */
47
+	private $parameters;
48
+
49
+
50
+	/**
51
+	 * DependencyInjector constructor
52
+	 *
53
+	 * @param CoffeePotInterface $coffee_pot
54
+	 * @param EEH_Array          $array_helper
55
+	 */
56
+	public function __construct(CoffeePotInterface $coffee_pot, EEH_Array $array_helper)
57
+	{
58
+		$this->coffee_pot = $coffee_pot;
59
+		$this->array_helper = $array_helper;
60
+	}
61
+
62
+
63
+	/**
64
+	 * getReflectionClass
65
+	 * checks if a ReflectionClass object has already been generated for a class
66
+	 * and returns that instead of creating a new one
67
+	 *
68
+	 * @param string $class_name
69
+	 * @return ReflectionClass
70
+	 */
71
+	public function getReflectionClass($class_name)
72
+	{
73
+		if (
74
+			! isset($this->reflectors[ $class_name ])
75
+			|| ! $this->reflectors[ $class_name ] instanceof ReflectionClass
76
+		) {
77
+			$this->reflectors[ $class_name ] = new ReflectionClass($class_name);
78
+		}
79
+		return $this->reflectors[ $class_name ];
80
+	}
81
+
82
+
83
+	/**
84
+	 * getConstructor
85
+	 * checks if a ReflectionMethod object has already been generated for the class constructor
86
+	 * and returns that instead of creating a new one
87
+	 *
88
+	 * @param ReflectionClass $reflector
89
+	 * @return ReflectionMethod
90
+	 */
91
+	protected function getConstructor(ReflectionClass $reflector)
92
+	{
93
+		if (
94
+			! isset($this->constructors[ $reflector->getName() ])
95
+			|| ! $this->constructors[ $reflector->getName() ] instanceof ReflectionMethod
96
+		) {
97
+			$this->constructors[ $reflector->getName() ] = $reflector->getConstructor();
98
+		}
99
+		return $this->constructors[ $reflector->getName() ];
100
+	}
101
+
102
+
103
+	/**
104
+	 * getParameters
105
+	 * checks if an array of ReflectionParameter objects has already been generated for the class constructor
106
+	 * and returns that instead of creating a new one
107
+	 *
108
+	 * @param ReflectionMethod $constructor
109
+	 * @return ReflectionParameter[]
110
+	 */
111
+	protected function getParameters(ReflectionMethod $constructor)
112
+	{
113
+		if (! isset($this->parameters[ $constructor->class ])) {
114
+			$this->parameters[ $constructor->class ] = $constructor->getParameters();
115
+		}
116
+		return $this->parameters[ $constructor->class ];
117
+	}
118
+
119
+
120
+	/**
121
+	 * resolveDependencies
122
+	 * examines the constructor for the requested class to determine
123
+	 * if any dependencies exist, and if they can be injected.
124
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
125
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
126
+	 * For example:
127
+	 *        if attempting to load a class "Foo" with the following constructor:
128
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
129
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
130
+	 *        but only IF they are NOT already present in the incoming arguments array,
131
+	 *        and the correct classes can be loaded
132
+	 *
133
+	 * @param RecipeInterface $recipe
134
+	 * @param ReflectionClass $reflector
135
+	 * @param array           $arguments
136
+	 * @return array
137
+	 * @throws UnexpectedValueException
138
+	 */
139
+	public function resolveDependencies(RecipeInterface $recipe, ReflectionClass $reflector, $arguments = array())
140
+	{
141
+		// if arguments array is numerically and sequentially indexed, then we want it to remain as is,
142
+		// else wrap it in an additional array so that it doesn't get split into multiple parameters
143
+		$arguments = $this->array_helper->is_array_numerically_and_sequentially_indexed($arguments)
144
+			? $arguments
145
+			: array($arguments);
146
+		$resolved_parameters = array();
147
+		// let's examine the constructor
148
+		// let's examine the constructor
149
+		$constructor = $this->getConstructor($reflector);
150
+		// whu? huh? nothing?
151
+		if (! $constructor) {
152
+			return $arguments;
153
+		}
154
+		// get constructor parameters
155
+		$params = $this->getParameters($constructor);
156
+		if (empty($params)) {
157
+			return $resolved_parameters;
158
+		}
159
+		$ingredients = $recipe->ingredients();
160
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
161
+		$argument_keys = array_keys($arguments);
162
+		// now loop thru all of the constructors expected parameters
163
+		foreach ($params as $index => $param) {
164
+			if (! $param instanceof ReflectionParameter) {
165
+				continue;
166
+			}
167
+			// is this a dependency for a specific class ?
168
+			$param_class = $param->getClass() ? $param->getClass()->name : '';
169
+			$param_name = $param->getName() ? $param->getName() : '';
170
+			if (
171 171
 // param is not a class but is specified in the list of ingredients for this Recipe
172
-                is_string($param_name) && isset($ingredients[ $param_name ])
173
-            ) {
174
-                // attempt to inject the dependency
175
-                $resolved_parameters[ $index ] = $ingredients[ $param_name ];
176
-            } elseif (
172
+				is_string($param_name) && isset($ingredients[ $param_name ])
173
+			) {
174
+				// attempt to inject the dependency
175
+				$resolved_parameters[ $index ] = $ingredients[ $param_name ];
176
+			} elseif (
177 177
 // param is specified in the list of ingredients for this Recipe
178
-                isset($ingredients[ $param_class ])
179
-            ) { // attempt to inject the dependency
180
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $ingredients[ $param_class ]);
181
-            } elseif (
178
+				isset($ingredients[ $param_class ])
179
+			) { // attempt to inject the dependency
180
+				$resolved_parameters[ $index ] = $this->injectDependency($reflector, $ingredients[ $param_class ]);
181
+			} elseif (
182 182
 // param is not even a class
183
-                empty($param_class)
184
-                // and something already exists in the incoming arguments for this param
185
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
186
-            ) {
187
-                // add parameter from incoming arguments
188
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
189
-            } elseif (
183
+				empty($param_class)
184
+				// and something already exists in the incoming arguments for this param
185
+				&& isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
186
+			) {
187
+				// add parameter from incoming arguments
188
+				$resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
189
+			} elseif (
190 190
 // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
191
-                ! empty($param_class)
192
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
193
-                && $arguments[ $argument_keys[ $index ] ] instanceof $param_class
194
-            ) {
195
-                // add parameter from incoming arguments
196
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
197
-            } elseif (
191
+				! empty($param_class)
192
+				&& isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
193
+				&& $arguments[ $argument_keys[ $index ] ] instanceof $param_class
194
+			) {
195
+				// add parameter from incoming arguments
196
+				$resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
197
+			} elseif (
198 198
 // parameter is type hinted as a class, and should be injected
199
-                ! empty($param_class)
200
-            ) {
201
-                // attempt to inject the dependency
202
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $param_class);
203
-            } elseif ($param->isOptional()) {
204
-                $resolved_parameters[ $index ] = $param->getDefaultValue();
205
-            } else {
206
-                $resolved_parameters[ $index ] = null;
207
-            }
208
-        }
209
-        return $resolved_parameters;
210
-    }
211
-
212
-
213
-    /**
214
-     * @param ReflectionClass $reflector
215
-     * @param string          $param_class
216
-     * @return mixed
217
-     * @throws UnexpectedValueException
218
-     */
219
-    private function injectDependency(ReflectionClass $reflector, $param_class)
220
-    {
221
-        $dependency = $this->coffee_pot->brew($param_class);
222
-        if (! $dependency instanceof $param_class) {
223
-            throw new UnexpectedValueException(
224
-                sprintf(
225
-                    esc_html__(
226
-                        'Could not resolve dependency for "%1$s" for the "%2$s" class constructor.',
227
-                        'event_espresso'
228
-                    ),
229
-                    $param_class,
230
-                    $reflector->getName()
231
-                )
232
-            );
233
-        }
234
-        return $dependency;
235
-    }
199
+				! empty($param_class)
200
+			) {
201
+				// attempt to inject the dependency
202
+				$resolved_parameters[ $index ] = $this->injectDependency($reflector, $param_class);
203
+			} elseif ($param->isOptional()) {
204
+				$resolved_parameters[ $index ] = $param->getDefaultValue();
205
+			} else {
206
+				$resolved_parameters[ $index ] = null;
207
+			}
208
+		}
209
+		return $resolved_parameters;
210
+	}
211
+
212
+
213
+	/**
214
+	 * @param ReflectionClass $reflector
215
+	 * @param string          $param_class
216
+	 * @return mixed
217
+	 * @throws UnexpectedValueException
218
+	 */
219
+	private function injectDependency(ReflectionClass $reflector, $param_class)
220
+	{
221
+		$dependency = $this->coffee_pot->brew($param_class);
222
+		if (! $dependency instanceof $param_class) {
223
+			throw new UnexpectedValueException(
224
+				sprintf(
225
+					esc_html__(
226
+						'Could not resolve dependency for "%1$s" for the "%2$s" class constructor.',
227
+						'event_espresso'
228
+					),
229
+					$param_class,
230
+					$reflector->getName()
231
+				)
232
+			);
233
+		}
234
+		return $dependency;
235
+	}
236 236
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -71,12 +71,12 @@  discard block
 block discarded – undo
71 71
     public function getReflectionClass($class_name)
72 72
     {
73 73
         if (
74
-            ! isset($this->reflectors[ $class_name ])
75
-            || ! $this->reflectors[ $class_name ] instanceof ReflectionClass
74
+            ! isset($this->reflectors[$class_name])
75
+            || ! $this->reflectors[$class_name] instanceof ReflectionClass
76 76
         ) {
77
-            $this->reflectors[ $class_name ] = new ReflectionClass($class_name);
77
+            $this->reflectors[$class_name] = new ReflectionClass($class_name);
78 78
         }
79
-        return $this->reflectors[ $class_name ];
79
+        return $this->reflectors[$class_name];
80 80
     }
81 81
 
82 82
 
@@ -91,12 +91,12 @@  discard block
 block discarded – undo
91 91
     protected function getConstructor(ReflectionClass $reflector)
92 92
     {
93 93
         if (
94
-            ! isset($this->constructors[ $reflector->getName() ])
95
-            || ! $this->constructors[ $reflector->getName() ] instanceof ReflectionMethod
94
+            ! isset($this->constructors[$reflector->getName()])
95
+            || ! $this->constructors[$reflector->getName()] instanceof ReflectionMethod
96 96
         ) {
97
-            $this->constructors[ $reflector->getName() ] = $reflector->getConstructor();
97
+            $this->constructors[$reflector->getName()] = $reflector->getConstructor();
98 98
         }
99
-        return $this->constructors[ $reflector->getName() ];
99
+        return $this->constructors[$reflector->getName()];
100 100
     }
101 101
 
102 102
 
@@ -110,10 +110,10 @@  discard block
 block discarded – undo
110 110
      */
111 111
     protected function getParameters(ReflectionMethod $constructor)
112 112
     {
113
-        if (! isset($this->parameters[ $constructor->class ])) {
114
-            $this->parameters[ $constructor->class ] = $constructor->getParameters();
113
+        if ( ! isset($this->parameters[$constructor->class])) {
114
+            $this->parameters[$constructor->class] = $constructor->getParameters();
115 115
         }
116
-        return $this->parameters[ $constructor->class ];
116
+        return $this->parameters[$constructor->class];
117 117
     }
118 118
 
119 119
 
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
         // let's examine the constructor
149 149
         $constructor = $this->getConstructor($reflector);
150 150
         // whu? huh? nothing?
151
-        if (! $constructor) {
151
+        if ( ! $constructor) {
152 152
             return $arguments;
153 153
         }
154 154
         // get constructor parameters
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
         $argument_keys = array_keys($arguments);
162 162
         // now loop thru all of the constructors expected parameters
163 163
         foreach ($params as $index => $param) {
164
-            if (! $param instanceof ReflectionParameter) {
164
+            if ( ! $param instanceof ReflectionParameter) {
165 165
                 continue;
166 166
             }
167 167
             // is this a dependency for a specific class ?
@@ -169,41 +169,41 @@  discard block
 block discarded – undo
169 169
             $param_name = $param->getName() ? $param->getName() : '';
170 170
             if (
171 171
 // param is not a class but is specified in the list of ingredients for this Recipe
172
-                is_string($param_name) && isset($ingredients[ $param_name ])
172
+                is_string($param_name) && isset($ingredients[$param_name])
173 173
             ) {
174 174
                 // attempt to inject the dependency
175
-                $resolved_parameters[ $index ] = $ingredients[ $param_name ];
175
+                $resolved_parameters[$index] = $ingredients[$param_name];
176 176
             } elseif (
177 177
 // param is specified in the list of ingredients for this Recipe
178
-                isset($ingredients[ $param_class ])
178
+                isset($ingredients[$param_class])
179 179
             ) { // attempt to inject the dependency
180
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $ingredients[ $param_class ]);
180
+                $resolved_parameters[$index] = $this->injectDependency($reflector, $ingredients[$param_class]);
181 181
             } elseif (
182 182
 // param is not even a class
183 183
                 empty($param_class)
184 184
                 // and something already exists in the incoming arguments for this param
185
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
185
+                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
186 186
             ) {
187 187
                 // add parameter from incoming arguments
188
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
188
+                $resolved_parameters[$index] = $arguments[$argument_keys[$index]];
189 189
             } elseif (
190 190
 // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
191 191
                 ! empty($param_class)
192
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
193
-                && $arguments[ $argument_keys[ $index ] ] instanceof $param_class
192
+                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
193
+                && $arguments[$argument_keys[$index]] instanceof $param_class
194 194
             ) {
195 195
                 // add parameter from incoming arguments
196
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
196
+                $resolved_parameters[$index] = $arguments[$argument_keys[$index]];
197 197
             } elseif (
198 198
 // parameter is type hinted as a class, and should be injected
199 199
                 ! empty($param_class)
200 200
             ) {
201 201
                 // attempt to inject the dependency
202
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $param_class);
202
+                $resolved_parameters[$index] = $this->injectDependency($reflector, $param_class);
203 203
             } elseif ($param->isOptional()) {
204
-                $resolved_parameters[ $index ] = $param->getDefaultValue();
204
+                $resolved_parameters[$index] = $param->getDefaultValue();
205 205
             } else {
206
-                $resolved_parameters[ $index ] = null;
206
+                $resolved_parameters[$index] = null;
207 207
             }
208 208
         }
209 209
         return $resolved_parameters;
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
     private function injectDependency(ReflectionClass $reflector, $param_class)
220 220
     {
221 221
         $dependency = $this->coffee_pot->brew($param_class);
222
-        if (! $dependency instanceof $param_class) {
222
+        if ( ! $dependency instanceof $param_class) {
223 223
             throw new UnexpectedValueException(
224 224
                 sprintf(
225 225
                     esc_html__(
Please login to merge, or discard this patch.
core/db_classes/EE_Question_Option.class.php 1 patch
Indentation   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -10,222 +10,222 @@
 block discarded – undo
10 10
 class EE_Question_Option extends EE_Soft_Delete_Base_Class implements EEI_Duplicatable
11 11
 {
12 12
 
13
-    /**
14
-     * Question Option Opt Group Name
15
-     *
16
-     * @access protected
17
-     * @var string
18
-     */
19
-    protected $_QSO_opt_group = null;
20
-
21
-
22
-    /**
23
-     *
24
-     * @param array  $props_n_values          incoming values
25
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
26
-     *                                        used.)
27
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
28
-     *                                        date_format and the second value is the time format
29
-     * @return EE_Attendee
30
-     */
31
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
32
-    {
33
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
34
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
35
-    }
36
-
37
-
38
-    /**
39
-     * @param array  $props_n_values  incoming values from the database
40
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
41
-     *                                the website will be used.
42
-     * @return EE_Attendee
43
-     */
44
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
45
-    {
46
-        return new self($props_n_values, true, $timezone);
47
-    }
48
-
49
-
50
-    /**
51
-     * Sets the option's key value
52
-     *
53
-     * @param string $value
54
-     * @return bool success
55
-     */
56
-    public function set_value($value)
57
-    {
58
-        $this->set('QSO_value', $value);
59
-    }
60
-
61
-
62
-    /**
63
-     * Sets the option's Display Text
64
-     *
65
-     * @param string $text
66
-     * @return bool success
67
-     */
68
-    public function set_desc($text)
69
-    {
70
-        $this->set('QSO_desc', $text);
71
-    }
72
-
73
-
74
-    /**
75
-     * Sets the order for this option
76
-     *
77
-     * @access public
78
-     * @param integer $order
79
-     * @return bool      $success
80
-     */
81
-    public function set_order($order)
82
-    {
83
-        $this->set('QSO_order', $order);
84
-    }
85
-
86
-
87
-    /**
88
-     * Sets the ID of the related question
89
-     *
90
-     * @param int $question_ID
91
-     * @return bool success
92
-     */
93
-    public function set_question_ID($question_ID)
94
-    {
95
-        $this->set('QST_ID', $question_ID);
96
-    }
97
-
98
-
99
-    /**
100
-     * Sets the option's opt_group
101
-     *
102
-     * @param string $text
103
-     * @return bool success
104
-     */
105
-    public function set_opt_group($text)
106
-    {
107
-        return $this->_QSO_opt_group = $text;
108
-    }
109
-
110
-
111
-    /**
112
-     * Gets the option's key value
113
-     *
114
-     * @return string
115
-     */
116
-    public function value()
117
-    {
118
-        return $this->get('QSO_value');
119
-    }
120
-
121
-
122
-    /**
123
-     * Gets the option's display text
124
-     *
125
-     * @return string
126
-     */
127
-    public function desc()
128
-    {
129
-        return $this->get('QSO_desc');
130
-    }
131
-
132
-
133
-    /**
134
-     * Returns whether this option has been deleted or not
135
-     *
136
-     * @return boolean
137
-     */
138
-    public function deleted()
139
-    {
140
-        return $this->get('QSO_deleted');
141
-    }
142
-
143
-
144
-    /**
145
-     * Returns the order or the Question Option
146
-     *
147
-     * @access public
148
-     * @return integer
149
-     */
150
-    public function order()
151
-    {
152
-        return $this->get('QSO_option');
153
-    }
154
-
155
-
156
-    /**
157
-     * Gets the related question's ID
158
-     *
159
-     * @return int
160
-     */
161
-    public function question_ID()
162
-    {
163
-        return $this->get('QST_ID');
164
-    }
165
-
166
-
167
-    /**
168
-     * Returns the question related to this question option
169
-     *
170
-     * @return EE_Question
171
-     */
172
-    public function question()
173
-    {
174
-        return $this->get_first_related('Question');
175
-    }
176
-
177
-
178
-    /**
179
-     * Gets the option's opt_group
180
-     *
181
-     * @return string
182
-     */
183
-    public function opt_group()
184
-    {
185
-        return $this->_QSO_opt_group;
186
-    }
187
-
188
-    /**
189
-     * Duplicates this question option. By default the new question option will be for the same question,
190
-     * but that can be overriden by setting the 'QST_ID' option
191
-     *
192
-     * @param array $options {
193
-     * @type int    $QST_ID  the QST_ID attribute of this question option, otherwise it will be for the same question
194
-     *                       as the original
195
-     */
196
-    public function duplicate($options = array())
197
-    {
198
-        $new_question_option = clone $this;
199
-        $new_question_option->set('QSO_ID', null);
200
-        if (
201
-            array_key_exists(
202
-                'QST_ID',
203
-                $options
204
-            )
205
-        ) {// use array_key_exists instead of isset because NULL might be a valid value
206
-            $new_question_option->set_question_ID($options['QST_ID']);
207
-        }
208
-        $new_question_option->save();
209
-    }
210
-
211
-    /**
212
-     * Gets the QSO_system value
213
-     *
214
-     * @return string|null
215
-     */
216
-    public function system()
217
-    {
218
-        return $this->get('QSO_system');
219
-    }
220
-
221
-    /**
222
-     * Sets QSO_system
223
-     *
224
-     * @param string $QSO_system
225
-     * @return bool
226
-     */
227
-    public function set_system($QSO_system)
228
-    {
229
-        return $this->set('QSO_system', $QSO_system);
230
-    }
13
+	/**
14
+	 * Question Option Opt Group Name
15
+	 *
16
+	 * @access protected
17
+	 * @var string
18
+	 */
19
+	protected $_QSO_opt_group = null;
20
+
21
+
22
+	/**
23
+	 *
24
+	 * @param array  $props_n_values          incoming values
25
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
26
+	 *                                        used.)
27
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
28
+	 *                                        date_format and the second value is the time format
29
+	 * @return EE_Attendee
30
+	 */
31
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
32
+	{
33
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
34
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
35
+	}
36
+
37
+
38
+	/**
39
+	 * @param array  $props_n_values  incoming values from the database
40
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
41
+	 *                                the website will be used.
42
+	 * @return EE_Attendee
43
+	 */
44
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
45
+	{
46
+		return new self($props_n_values, true, $timezone);
47
+	}
48
+
49
+
50
+	/**
51
+	 * Sets the option's key value
52
+	 *
53
+	 * @param string $value
54
+	 * @return bool success
55
+	 */
56
+	public function set_value($value)
57
+	{
58
+		$this->set('QSO_value', $value);
59
+	}
60
+
61
+
62
+	/**
63
+	 * Sets the option's Display Text
64
+	 *
65
+	 * @param string $text
66
+	 * @return bool success
67
+	 */
68
+	public function set_desc($text)
69
+	{
70
+		$this->set('QSO_desc', $text);
71
+	}
72
+
73
+
74
+	/**
75
+	 * Sets the order for this option
76
+	 *
77
+	 * @access public
78
+	 * @param integer $order
79
+	 * @return bool      $success
80
+	 */
81
+	public function set_order($order)
82
+	{
83
+		$this->set('QSO_order', $order);
84
+	}
85
+
86
+
87
+	/**
88
+	 * Sets the ID of the related question
89
+	 *
90
+	 * @param int $question_ID
91
+	 * @return bool success
92
+	 */
93
+	public function set_question_ID($question_ID)
94
+	{
95
+		$this->set('QST_ID', $question_ID);
96
+	}
97
+
98
+
99
+	/**
100
+	 * Sets the option's opt_group
101
+	 *
102
+	 * @param string $text
103
+	 * @return bool success
104
+	 */
105
+	public function set_opt_group($text)
106
+	{
107
+		return $this->_QSO_opt_group = $text;
108
+	}
109
+
110
+
111
+	/**
112
+	 * Gets the option's key value
113
+	 *
114
+	 * @return string
115
+	 */
116
+	public function value()
117
+	{
118
+		return $this->get('QSO_value');
119
+	}
120
+
121
+
122
+	/**
123
+	 * Gets the option's display text
124
+	 *
125
+	 * @return string
126
+	 */
127
+	public function desc()
128
+	{
129
+		return $this->get('QSO_desc');
130
+	}
131
+
132
+
133
+	/**
134
+	 * Returns whether this option has been deleted or not
135
+	 *
136
+	 * @return boolean
137
+	 */
138
+	public function deleted()
139
+	{
140
+		return $this->get('QSO_deleted');
141
+	}
142
+
143
+
144
+	/**
145
+	 * Returns the order or the Question Option
146
+	 *
147
+	 * @access public
148
+	 * @return integer
149
+	 */
150
+	public function order()
151
+	{
152
+		return $this->get('QSO_option');
153
+	}
154
+
155
+
156
+	/**
157
+	 * Gets the related question's ID
158
+	 *
159
+	 * @return int
160
+	 */
161
+	public function question_ID()
162
+	{
163
+		return $this->get('QST_ID');
164
+	}
165
+
166
+
167
+	/**
168
+	 * Returns the question related to this question option
169
+	 *
170
+	 * @return EE_Question
171
+	 */
172
+	public function question()
173
+	{
174
+		return $this->get_first_related('Question');
175
+	}
176
+
177
+
178
+	/**
179
+	 * Gets the option's opt_group
180
+	 *
181
+	 * @return string
182
+	 */
183
+	public function opt_group()
184
+	{
185
+		return $this->_QSO_opt_group;
186
+	}
187
+
188
+	/**
189
+	 * Duplicates this question option. By default the new question option will be for the same question,
190
+	 * but that can be overriden by setting the 'QST_ID' option
191
+	 *
192
+	 * @param array $options {
193
+	 * @type int    $QST_ID  the QST_ID attribute of this question option, otherwise it will be for the same question
194
+	 *                       as the original
195
+	 */
196
+	public function duplicate($options = array())
197
+	{
198
+		$new_question_option = clone $this;
199
+		$new_question_option->set('QSO_ID', null);
200
+		if (
201
+			array_key_exists(
202
+				'QST_ID',
203
+				$options
204
+			)
205
+		) {// use array_key_exists instead of isset because NULL might be a valid value
206
+			$new_question_option->set_question_ID($options['QST_ID']);
207
+		}
208
+		$new_question_option->save();
209
+	}
210
+
211
+	/**
212
+	 * Gets the QSO_system value
213
+	 *
214
+	 * @return string|null
215
+	 */
216
+	public function system()
217
+	{
218
+		return $this->get('QSO_system');
219
+	}
220
+
221
+	/**
222
+	 * Sets QSO_system
223
+	 *
224
+	 * @param string $QSO_system
225
+	 * @return bool
226
+	 */
227
+	public function set_system($QSO_system)
228
+	{
229
+		return $this->set('QSO_system', $QSO_system);
230
+	}
231 231
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Datetime.class.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
             $date_or_time,
534 534
             $echo
535 535
         );
536
-        if (! $echo) {
536
+        if ( ! $echo) {
537 537
             return $dtt;
538 538
         }
539 539
         return '';
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
             '&nbsp;',
636 636
             $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
637 637
         );
638
-        return $start !== $end ? $start . $conjunction . $end : $start;
638
+        return $start !== $end ? $start.$conjunction.$end : $start;
639 639
     }
640 640
 
641 641
 
@@ -743,7 +743,7 @@  discard block
 block discarded – undo
743 743
             '&nbsp;',
744 744
             $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
745 745
         );
746
-        return $start !== $end ? $start . $conjunction . $end : $start;
746
+        return $start !== $end ? $start.$conjunction.$end : $start;
747 747
     }
748 748
 
749 749
 
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
     ) {
789 789
         $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
790 790
         $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
791
-        $full_format = $dt_format . $separator . $tm_format;
791
+        $full_format = $dt_format.$separator.$tm_format;
792 792
         // the range output depends on various conditions
793 793
         switch (true) {
794 794
             // start date timestamp and end date timestamp are the same.
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
         // tickets remaining available for purchase
1030 1030
         // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1031 1031
         $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1032
-        if (! $consider_tickets) {
1032
+        if ( ! $consider_tickets) {
1033 1033
             return $dtt_remaining;
1034 1034
         }
1035 1035
         $tickets_remaining = $this->tickets_remaining();
@@ -1053,7 +1053,7 @@  discard block
 block discarded – undo
1053 1053
     {
1054 1054
         $sum = 0;
1055 1055
         $tickets = $this->tickets($query_params);
1056
-        if (! empty($tickets)) {
1056
+        if ( ! empty($tickets)) {
1057 1057
             foreach ($tickets as $ticket) {
1058 1058
                 if ($ticket instanceof EE_Ticket) {
1059 1059
                     // get the actual amount of tickets that can be sold
@@ -1204,7 +1204,7 @@  discard block
 block discarded – undo
1204 1204
     {
1205 1205
         if ($use_dtt_name) {
1206 1206
             $dtt_name = $this->name();
1207
-            if (! empty($dtt_name)) {
1207
+            if ( ! empty($dtt_name)) {
1208 1208
                 return $dtt_name;
1209 1209
             }
1210 1210
         }
@@ -1212,14 +1212,14 @@  discard block
 block discarded – undo
1212 1212
         if (
1213 1213
             date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1214 1214
         ) {
1215
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
+            $display_date = $this->start_date('M j\, Y g:i a').' - '.$this->end_date('M j\, Y g:i a');
1216 1216
             // next condition is if its the same month but different day
1217 1217
         } else {
1218 1218
             if (
1219 1219
                 date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1220 1220
                 && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1221 1221
             ) {
1222
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
+                $display_date = $this->start_date('M j\, g:i a').' - '.$this->end_date('M j\, g:i a Y');
1223 1223
             } else {
1224 1224
                 $display_date = $this->start_date('F j\, Y')
1225 1225
                                 . ' @ '
Please login to merge, or discard this patch.
Indentation   +1404 added lines, -1404 removed lines patch added patch discarded remove patch
@@ -13,1412 +13,1412 @@
 block discarded – undo
13 13
 class EE_Datetime extends EE_Soft_Delete_Base_Class
14 14
 {
15 15
 
16
-    /**
17
-     * constant used by get_active_status, indicates datetime has no more available spaces
18
-     */
19
-    const sold_out = 'DTS';
20
-
21
-    /**
22
-     * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
23
-     */
24
-    const active = 'DTA';
25
-
26
-    /**
27
-     * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
28
-     * expired
29
-     */
30
-    const upcoming = 'DTU';
31
-
32
-    /**
33
-     * Datetime is postponed
34
-     */
35
-    const postponed = 'DTP';
36
-
37
-    /**
38
-     * Datetime is cancelled
39
-     */
40
-    const cancelled = 'DTC';
41
-
42
-    /**
43
-     * constant used by get_active_status, indicates datetime has expired (event is over)
44
-     */
45
-    const expired = 'DTE';
46
-
47
-    /**
48
-     * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
49
-     */
50
-    const inactive = 'DTI';
51
-
52
-
53
-    /**
54
-     * @param array  $props_n_values    incoming values
55
-     * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
56
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
57
-     *                                  and the second value is the time format
58
-     * @return EE_Datetime
59
-     * @throws ReflectionException
60
-     * @throws InvalidArgumentException
61
-     * @throws InvalidInterfaceException
62
-     * @throws InvalidDataTypeException
63
-     * @throws EE_Error
64
-     */
65
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
66
-    {
67
-        $has_object = parent::_check_for_object(
68
-            $props_n_values,
69
-            __CLASS__,
70
-            $timezone,
71
-            $date_formats
72
-        );
73
-        return $has_object
74
-            ? $has_object
75
-            : new self($props_n_values, false, $timezone, $date_formats);
76
-    }
77
-
78
-
79
-    /**
80
-     * @param array  $props_n_values  incoming values from the database
81
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
-     *                                the website will be used.
83
-     * @return EE_Datetime
84
-     * @throws ReflectionException
85
-     * @throws InvalidArgumentException
86
-     * @throws InvalidInterfaceException
87
-     * @throws InvalidDataTypeException
88
-     * @throws EE_Error
89
-     */
90
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
91
-    {
92
-        return new self($props_n_values, true, $timezone);
93
-    }
94
-
95
-
96
-    /**
97
-     * @param $name
98
-     * @throws ReflectionException
99
-     * @throws InvalidArgumentException
100
-     * @throws InvalidInterfaceException
101
-     * @throws InvalidDataTypeException
102
-     * @throws EE_Error
103
-     */
104
-    public function set_name($name)
105
-    {
106
-        $this->set('DTT_name', $name);
107
-    }
108
-
109
-
110
-    /**
111
-     * @param $description
112
-     * @throws ReflectionException
113
-     * @throws InvalidArgumentException
114
-     * @throws InvalidInterfaceException
115
-     * @throws InvalidDataTypeException
116
-     * @throws EE_Error
117
-     */
118
-    public function set_description($description)
119
-    {
120
-        $this->set('DTT_description', $description);
121
-    }
122
-
123
-
124
-    /**
125
-     * Set event start date
126
-     * set the start date for an event
127
-     *
128
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
129
-     * @throws ReflectionException
130
-     * @throws InvalidArgumentException
131
-     * @throws InvalidInterfaceException
132
-     * @throws InvalidDataTypeException
133
-     * @throws EE_Error
134
-     */
135
-    public function set_start_date($date)
136
-    {
137
-        $this->_set_date_for($date, 'DTT_EVT_start');
138
-    }
139
-
140
-
141
-    /**
142
-     * Set event start time
143
-     * set the start time for an event
144
-     *
145
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
146
-     * @throws ReflectionException
147
-     * @throws InvalidArgumentException
148
-     * @throws InvalidInterfaceException
149
-     * @throws InvalidDataTypeException
150
-     * @throws EE_Error
151
-     */
152
-    public function set_start_time($time)
153
-    {
154
-        $this->_set_time_for($time, 'DTT_EVT_start');
155
-    }
156
-
157
-
158
-    /**
159
-     * Set event end date
160
-     * set the end date for an event
161
-     *
162
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
163
-     * @throws ReflectionException
164
-     * @throws InvalidArgumentException
165
-     * @throws InvalidInterfaceException
166
-     * @throws InvalidDataTypeException
167
-     * @throws EE_Error
168
-     */
169
-    public function set_end_date($date)
170
-    {
171
-        $this->_set_date_for($date, 'DTT_EVT_end');
172
-    }
173
-
174
-
175
-    /**
176
-     * Set event end time
177
-     * set the end time for an event
178
-     *
179
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
180
-     * @throws ReflectionException
181
-     * @throws InvalidArgumentException
182
-     * @throws InvalidInterfaceException
183
-     * @throws InvalidDataTypeException
184
-     * @throws EE_Error
185
-     */
186
-    public function set_end_time($time)
187
-    {
188
-        $this->_set_time_for($time, 'DTT_EVT_end');
189
-    }
190
-
191
-
192
-    /**
193
-     * Set registration limit
194
-     * set the maximum number of attendees that can be registered for this datetime slot
195
-     *
196
-     * @param int $reg_limit
197
-     * @throws ReflectionException
198
-     * @throws InvalidArgumentException
199
-     * @throws InvalidInterfaceException
200
-     * @throws InvalidDataTypeException
201
-     * @throws EE_Error
202
-     */
203
-    public function set_reg_limit($reg_limit)
204
-    {
205
-        $this->set('DTT_reg_limit', $reg_limit);
206
-    }
207
-
208
-
209
-    /**
210
-     * get the number of tickets sold for this datetime slot
211
-     *
212
-     * @return mixed int on success, FALSE on fail
213
-     * @throws ReflectionException
214
-     * @throws InvalidArgumentException
215
-     * @throws InvalidInterfaceException
216
-     * @throws InvalidDataTypeException
217
-     * @throws EE_Error
218
-     */
219
-    public function sold()
220
-    {
221
-        return $this->get_raw('DTT_sold');
222
-    }
223
-
224
-
225
-    /**
226
-     * @param int $sold
227
-     * @throws ReflectionException
228
-     * @throws InvalidArgumentException
229
-     * @throws InvalidInterfaceException
230
-     * @throws InvalidDataTypeException
231
-     * @throws EE_Error
232
-     */
233
-    public function set_sold($sold)
234
-    {
235
-        // sold can not go below zero
236
-        $sold = max(0, $sold);
237
-        $this->set('DTT_sold', $sold);
238
-    }
239
-
240
-
241
-    /**
242
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
243
-     * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
244
-     *
245
-     * @param int $qty
246
-     * @param boolean $also_decrease_reserved
247
-     * @return boolean indicating success
248
-     * @throws ReflectionException
249
-     * @throws InvalidArgumentException
250
-     * @throws InvalidInterfaceException
251
-     * @throws InvalidDataTypeException
252
-     * @throws EE_Error
253
-     */
254
-    public function increaseSold($qty = 1, $also_decrease_reserved = true)
255
-    {
256
-        $qty = absint($qty);
257
-        if ($also_decrease_reserved) {
258
-            $success = $this->adjustNumericFieldsInDb(
259
-                [
260
-                    'DTT_reserved' => $qty * -1,
261
-                    'DTT_sold' => $qty
262
-                ]
263
-            );
264
-        } else {
265
-            $success = $this->adjustNumericFieldsInDb(
266
-                [
267
-                    'DTT_sold' => $qty
268
-                ]
269
-            );
270
-        }
271
-
272
-        do_action(
273
-            'AHEE__EE_Datetime__increase_sold',
274
-            $this,
275
-            $qty,
276
-            $this->sold(),
277
-            $success
278
-        );
279
-        return $success;
280
-    }
281
-
282
-
283
-    /**
284
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
285
-     * to save afterwards.)
286
-     *
287
-     * @param int $qty
288
-     * @return boolean indicating success
289
-     * @throws ReflectionException
290
-     * @throws InvalidArgumentException
291
-     * @throws InvalidInterfaceException
292
-     * @throws InvalidDataTypeException
293
-     * @throws EE_Error
294
-     */
295
-    public function decreaseSold($qty = 1)
296
-    {
297
-        $qty = absint($qty);
298
-        $success = $this->adjustNumericFieldsInDb(
299
-            [
300
-                'DTT_sold' => $qty * -1
301
-            ]
302
-        );
303
-        do_action(
304
-            'AHEE__EE_Datetime__decrease_sold',
305
-            $this,
306
-            $qty,
307
-            $this->sold(),
308
-            $success
309
-        );
310
-        return $success;
311
-    }
312
-
313
-
314
-    /**
315
-     * Gets qty of reserved tickets for this datetime
316
-     *
317
-     * @return int
318
-     * @throws ReflectionException
319
-     * @throws InvalidArgumentException
320
-     * @throws InvalidInterfaceException
321
-     * @throws InvalidDataTypeException
322
-     * @throws EE_Error
323
-     */
324
-    public function reserved()
325
-    {
326
-        return $this->get_raw('DTT_reserved');
327
-    }
328
-
329
-
330
-    /**
331
-     * Sets qty of reserved tickets for this datetime
332
-     *
333
-     * @param int $reserved
334
-     * @throws ReflectionException
335
-     * @throws InvalidArgumentException
336
-     * @throws InvalidInterfaceException
337
-     * @throws InvalidDataTypeException
338
-     * @throws EE_Error
339
-     */
340
-    public function set_reserved($reserved)
341
-    {
342
-        // reserved can not go below zero
343
-        $reserved = max(0, (int) $reserved);
344
-        $this->set('DTT_reserved', $reserved);
345
-    }
346
-
347
-
348
-    /**
349
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
350
-     *
351
-     * @param int $qty
352
-     * @return boolean indicating success
353
-     * @throws ReflectionException
354
-     * @throws InvalidArgumentException
355
-     * @throws InvalidInterfaceException
356
-     * @throws InvalidDataTypeException
357
-     * @throws EE_Error
358
-     */
359
-    public function increaseReserved($qty = 1)
360
-    {
361
-        $qty = absint($qty);
362
-        $success = $this->incrementFieldConditionallyInDb(
363
-            'DTT_reserved',
364
-            'DTT_sold',
365
-            'DTT_reg_limit',
366
-            $qty
367
-        );
368
-        do_action(
369
-            'AHEE__EE_Datetime__increase_reserved',
370
-            $this,
371
-            $qty,
372
-            $this->reserved(),
373
-            $success
374
-        );
375
-        return $success;
376
-    }
377
-
378
-
379
-    /**
380
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
381
-     *
382
-     * @param int $qty
383
-     * @return boolean indicating success
384
-     * @throws ReflectionException
385
-     * @throws InvalidArgumentException
386
-     * @throws InvalidInterfaceException
387
-     * @throws InvalidDataTypeException
388
-     * @throws EE_Error
389
-     */
390
-    public function decreaseReserved($qty = 1)
391
-    {
392
-        $qty = absint($qty);
393
-        $success = $this->adjustNumericFieldsInDb(
394
-            [
395
-                'DTT_reserved' => $qty * -1
396
-            ]
397
-        );
398
-        do_action(
399
-            'AHEE__EE_Datetime__decrease_reserved',
400
-            $this,
401
-            $qty,
402
-            $this->reserved(),
403
-            $success
404
-        );
405
-        return $success;
406
-    }
407
-
408
-
409
-    /**
410
-     * total sold and reserved tickets
411
-     *
412
-     * @return int
413
-     * @throws ReflectionException
414
-     * @throws InvalidArgumentException
415
-     * @throws InvalidInterfaceException
416
-     * @throws InvalidDataTypeException
417
-     * @throws EE_Error
418
-     */
419
-    public function sold_and_reserved()
420
-    {
421
-        return $this->sold() + $this->reserved();
422
-    }
423
-
424
-
425
-    /**
426
-     * returns the datetime name
427
-     *
428
-     * @return string
429
-     * @throws ReflectionException
430
-     * @throws InvalidArgumentException
431
-     * @throws InvalidInterfaceException
432
-     * @throws InvalidDataTypeException
433
-     * @throws EE_Error
434
-     */
435
-    public function name()
436
-    {
437
-        return $this->get('DTT_name');
438
-    }
439
-
440
-
441
-    /**
442
-     * returns the datetime description
443
-     *
444
-     * @return string
445
-     * @throws ReflectionException
446
-     * @throws InvalidArgumentException
447
-     * @throws InvalidInterfaceException
448
-     * @throws InvalidDataTypeException
449
-     * @throws EE_Error
450
-     */
451
-    public function description()
452
-    {
453
-        return $this->get('DTT_description');
454
-    }
455
-
456
-
457
-    /**
458
-     * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
459
-     *
460
-     * @return boolean  TRUE if is primary, FALSE if not.
461
-     * @throws ReflectionException
462
-     * @throws InvalidArgumentException
463
-     * @throws InvalidInterfaceException
464
-     * @throws InvalidDataTypeException
465
-     * @throws EE_Error
466
-     */
467
-    public function is_primary()
468
-    {
469
-        return $this->get('DTT_is_primary');
470
-    }
471
-
472
-
473
-    /**
474
-     * This helper simply returns the order for the datetime
475
-     *
476
-     * @return int  The order of the datetime for this event.
477
-     * @throws ReflectionException
478
-     * @throws InvalidArgumentException
479
-     * @throws InvalidInterfaceException
480
-     * @throws InvalidDataTypeException
481
-     * @throws EE_Error
482
-     */
483
-    public function order()
484
-    {
485
-        return $this->get('DTT_order');
486
-    }
487
-
488
-
489
-    /**
490
-     * This helper simply returns the parent id for the datetime
491
-     *
492
-     * @return int
493
-     * @throws ReflectionException
494
-     * @throws InvalidArgumentException
495
-     * @throws InvalidInterfaceException
496
-     * @throws InvalidDataTypeException
497
-     * @throws EE_Error
498
-     */
499
-    public function parent()
500
-    {
501
-        return $this->get('DTT_parent');
502
-    }
503
-
504
-
505
-    /**
506
-     * show date and/or time
507
-     *
508
-     * @param string $date_or_time    whether to display a date or time or both
509
-     * @param string $start_or_end    whether to display start or end datetimes
510
-     * @param string $dt_frmt
511
-     * @param string $tm_frmt
512
-     * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
513
-     *                                otherwise we use the standard formats)
514
-     * @return string|bool  string on success, FALSE on fail
515
-     * @throws ReflectionException
516
-     * @throws InvalidArgumentException
517
-     * @throws InvalidInterfaceException
518
-     * @throws InvalidDataTypeException
519
-     * @throws EE_Error
520
-     */
521
-    private function _show_datetime(
522
-        $date_or_time = null,
523
-        $start_or_end = 'start',
524
-        $dt_frmt = '',
525
-        $tm_frmt = '',
526
-        $echo = false
527
-    ) {
528
-        $field_name = "DTT_EVT_{$start_or_end}";
529
-        $dtt = $this->_get_datetime(
530
-            $field_name,
531
-            $dt_frmt,
532
-            $tm_frmt,
533
-            $date_or_time,
534
-            $echo
535
-        );
536
-        if (! $echo) {
537
-            return $dtt;
538
-        }
539
-        return '';
540
-    }
541
-
542
-
543
-    /**
544
-     * get event start date.  Provide either the date format, or NULL to re-use the
545
-     * last-used format, or '' to use the default date format
546
-     *
547
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
548
-     * @return mixed            string on success, FALSE on fail
549
-     * @throws ReflectionException
550
-     * @throws InvalidArgumentException
551
-     * @throws InvalidInterfaceException
552
-     * @throws InvalidDataTypeException
553
-     * @throws EE_Error
554
-     */
555
-    public function start_date($dt_frmt = '')
556
-    {
557
-        return $this->_show_datetime('D', 'start', $dt_frmt);
558
-    }
559
-
560
-
561
-    /**
562
-     * Echoes start_date()
563
-     *
564
-     * @param string $dt_frmt
565
-     * @throws ReflectionException
566
-     * @throws InvalidArgumentException
567
-     * @throws InvalidInterfaceException
568
-     * @throws InvalidDataTypeException
569
-     * @throws EE_Error
570
-     */
571
-    public function e_start_date($dt_frmt = '')
572
-    {
573
-        $this->_show_datetime('D', 'start', $dt_frmt, null, true);
574
-    }
575
-
576
-
577
-    /**
578
-     * get end date. Provide either the date format, or NULL to re-use the
579
-     * last-used format, or '' to use the default date format
580
-     *
581
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
582
-     * @return mixed            string on success, FALSE on fail
583
-     * @throws ReflectionException
584
-     * @throws InvalidArgumentException
585
-     * @throws InvalidInterfaceException
586
-     * @throws InvalidDataTypeException
587
-     * @throws EE_Error
588
-     */
589
-    public function end_date($dt_frmt = '')
590
-    {
591
-        return $this->_show_datetime('D', 'end', $dt_frmt);
592
-    }
593
-
594
-
595
-    /**
596
-     * Echoes the end date. See end_date()
597
-     *
598
-     * @param string $dt_frmt
599
-     * @throws ReflectionException
600
-     * @throws InvalidArgumentException
601
-     * @throws InvalidInterfaceException
602
-     * @throws InvalidDataTypeException
603
-     * @throws EE_Error
604
-     */
605
-    public function e_end_date($dt_frmt = '')
606
-    {
607
-        $this->_show_datetime('D', 'end', $dt_frmt, null, true);
608
-    }
609
-
610
-
611
-    /**
612
-     * get date_range - meaning the start AND end date
613
-     *
614
-     * @access public
615
-     * @param string $dt_frmt     string representation of date format defaults to WP settings
616
-     * @param string $conjunction conjunction junction what's your function ?
617
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
618
-     * @return mixed              string on success, FALSE on fail
619
-     * @throws ReflectionException
620
-     * @throws InvalidArgumentException
621
-     * @throws InvalidInterfaceException
622
-     * @throws InvalidDataTypeException
623
-     * @throws EE_Error
624
-     */
625
-    public function date_range($dt_frmt = '', $conjunction = ' - ')
626
-    {
627
-        $dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
628
-        $start = str_replace(
629
-            ' ',
630
-            '&nbsp;',
631
-            $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
632
-        );
633
-        $end = str_replace(
634
-            ' ',
635
-            '&nbsp;',
636
-            $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
637
-        );
638
-        return $start !== $end ? $start . $conjunction . $end : $start;
639
-    }
640
-
641
-
642
-    /**
643
-     * @param string $dt_frmt
644
-     * @param string $conjunction
645
-     * @throws ReflectionException
646
-     * @throws InvalidArgumentException
647
-     * @throws InvalidInterfaceException
648
-     * @throws InvalidDataTypeException
649
-     * @throws EE_Error
650
-     */
651
-    public function e_date_range($dt_frmt = '', $conjunction = ' - ')
652
-    {
653
-        echo $this->date_range($dt_frmt, $conjunction); // sanitized
654
-    }
655
-
656
-
657
-    /**
658
-     * get start time
659
-     *
660
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
661
-     * @return mixed        string on success, FALSE on fail
662
-     * @throws ReflectionException
663
-     * @throws InvalidArgumentException
664
-     * @throws InvalidInterfaceException
665
-     * @throws InvalidDataTypeException
666
-     * @throws EE_Error
667
-     */
668
-    public function start_time($tm_format = '')
669
-    {
670
-        return $this->_show_datetime('T', 'start', null, $tm_format);
671
-    }
672
-
673
-
674
-    /**
675
-     * @param string $tm_format
676
-     * @throws ReflectionException
677
-     * @throws InvalidArgumentException
678
-     * @throws InvalidInterfaceException
679
-     * @throws InvalidDataTypeException
680
-     * @throws EE_Error
681
-     */
682
-    public function e_start_time($tm_format = '')
683
-    {
684
-        $this->_show_datetime('T', 'start', null, $tm_format, true);
685
-    }
686
-
687
-
688
-    /**
689
-     * get end time
690
-     *
691
-     * @param string $tm_format string representation of time format defaults to 'g:i a'
692
-     * @return mixed                string on success, FALSE on fail
693
-     * @throws ReflectionException
694
-     * @throws InvalidArgumentException
695
-     * @throws InvalidInterfaceException
696
-     * @throws InvalidDataTypeException
697
-     * @throws EE_Error
698
-     */
699
-    public function end_time($tm_format = '')
700
-    {
701
-        return $this->_show_datetime('T', 'end', null, $tm_format);
702
-    }
703
-
704
-
705
-    /**
706
-     * @param string $tm_format
707
-     * @throws ReflectionException
708
-     * @throws InvalidArgumentException
709
-     * @throws InvalidInterfaceException
710
-     * @throws InvalidDataTypeException
711
-     * @throws EE_Error
712
-     */
713
-    public function e_end_time($tm_format = '')
714
-    {
715
-        $this->_show_datetime('T', 'end', null, $tm_format, true);
716
-    }
717
-
718
-
719
-    /**
720
-     * get time_range
721
-     *
722
-     * @access public
723
-     * @param string $tm_format   string representation of time format defaults to 'g:i a'
724
-     * @param string $conjunction conjunction junction what's your function ?
725
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
726
-     * @return mixed              string on success, FALSE on fail
727
-     * @throws ReflectionException
728
-     * @throws InvalidArgumentException
729
-     * @throws InvalidInterfaceException
730
-     * @throws InvalidDataTypeException
731
-     * @throws EE_Error
732
-     */
733
-    public function time_range($tm_format = '', $conjunction = ' - ')
734
-    {
735
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
736
-        $start = str_replace(
737
-            ' ',
738
-            '&nbsp;',
739
-            $this->get_i18n_datetime('DTT_EVT_start', $tm_format)
740
-        );
741
-        $end = str_replace(
742
-            ' ',
743
-            '&nbsp;',
744
-            $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
745
-        );
746
-        return $start !== $end ? $start . $conjunction . $end : $start;
747
-    }
748
-
749
-
750
-    /**
751
-     * @param string $tm_format
752
-     * @param string $conjunction
753
-     * @throws ReflectionException
754
-     * @throws InvalidArgumentException
755
-     * @throws InvalidInterfaceException
756
-     * @throws InvalidDataTypeException
757
-     * @throws EE_Error
758
-     */
759
-    public function e_time_range($tm_format = '', $conjunction = ' - ')
760
-    {
761
-        echo $this->time_range($tm_format, $conjunction); // sanitized
762
-    }
763
-
764
-
765
-    /**
766
-     * This returns a range representation of the date and times.
767
-     * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
768
-     * Also, the return value is localized.
769
-     *
770
-     * @param string $dt_format
771
-     * @param string $tm_format
772
-     * @param string $conjunction used between two different dates or times.
773
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
774
-     * @param string $separator   used between the date and time formats.
775
-     *                            ex: Dec 1, 2016{$separator}2pm
776
-     * @return string
777
-     * @throws ReflectionException
778
-     * @throws InvalidArgumentException
779
-     * @throws InvalidInterfaceException
780
-     * @throws InvalidDataTypeException
781
-     * @throws EE_Error
782
-     */
783
-    public function date_and_time_range(
784
-        $dt_format = '',
785
-        $tm_format = '',
786
-        $conjunction = ' - ',
787
-        $separator = ' '
788
-    ) {
789
-        $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
790
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
791
-        $full_format = $dt_format . $separator . $tm_format;
792
-        // the range output depends on various conditions
793
-        switch (true) {
794
-            // start date timestamp and end date timestamp are the same.
795
-            case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
796
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
797
-                break;
798
-            // start and end date are the same but times are different
799
-            case ($this->start_date() === $this->end_date()):
800
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
801
-                          . $conjunction
802
-                          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
803
-                break;
804
-            // all other conditions
805
-            default:
806
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
807
-                          . $conjunction
808
-                          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
809
-                break;
810
-        }
811
-        return $output;
812
-    }
813
-
814
-
815
-    /**
816
-     * This echos the results of date and time range.
817
-     *
818
-     * @see date_and_time_range() for more details on purpose.
819
-     * @param string $dt_format
820
-     * @param string $tm_format
821
-     * @param string $conjunction
822
-     * @return void
823
-     * @throws ReflectionException
824
-     * @throws InvalidArgumentException
825
-     * @throws InvalidInterfaceException
826
-     * @throws InvalidDataTypeException
827
-     * @throws EE_Error
828
-     */
829
-    public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
830
-    {
831
-        echo $this->date_and_time_range($dt_format, $tm_format, $conjunction); // sanitized
832
-    }
833
-
834
-
835
-    /**
836
-     * get start date and start time
837
-     *
838
-     * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
839
-     * @param    string $tm_format - string representation of time format defaults to 'g:i a'
840
-     * @return    mixed    string on success, FALSE on fail
841
-     * @throws ReflectionException
842
-     * @throws InvalidArgumentException
843
-     * @throws InvalidInterfaceException
844
-     * @throws InvalidDataTypeException
845
-     * @throws EE_Error
846
-     */
847
-    public function start_date_and_time($dt_format = '', $tm_format = '')
848
-    {
849
-        return $this->_show_datetime('', 'start', $dt_format, $tm_format);
850
-    }
851
-
852
-
853
-    /**
854
-     * @param string $dt_frmt
855
-     * @param string $tm_format
856
-     * @throws ReflectionException
857
-     * @throws InvalidArgumentException
858
-     * @throws InvalidInterfaceException
859
-     * @throws InvalidDataTypeException
860
-     * @throws EE_Error
861
-     */
862
-    public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
863
-    {
864
-        $this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
865
-    }
866
-
867
-
868
-    /**
869
-     * Shows the length of the event (start to end time).
870
-     * Can be shown in 'seconds','minutes','hours', or 'days'.
871
-     * By default, rounds up. (So if you use 'days', and then event
872
-     * only occurs for 1 hour, it will return 1 day).
873
-     *
874
-     * @param string $units 'seconds','minutes','hours','days'
875
-     * @param bool   $round_up
876
-     * @return float|int|mixed
877
-     * @throws ReflectionException
878
-     * @throws InvalidArgumentException
879
-     * @throws InvalidInterfaceException
880
-     * @throws InvalidDataTypeException
881
-     * @throws EE_Error
882
-     */
883
-    public function length($units = 'seconds', $round_up = false)
884
-    {
885
-        $start = $this->get_raw('DTT_EVT_start');
886
-        $end = $this->get_raw('DTT_EVT_end');
887
-        $length_in_units = $end - $start;
888
-        switch ($units) {
889
-            // NOTE: We purposefully don't use "break;" in order to chain the divisions
890
-            /** @noinspection PhpMissingBreakStatementInspection */
891
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
892
-            case 'days':
893
-                $length_in_units /= 24;
894
-            /** @noinspection PhpMissingBreakStatementInspection */
895
-            case 'hours':
896
-                // fall through is intentional
897
-                $length_in_units /= 60;
898
-            /** @noinspection PhpMissingBreakStatementInspection */
899
-            case 'minutes':
900
-                // fall through is intentional
901
-                $length_in_units /= 60;
902
-            case 'seconds':
903
-            default:
904
-                $length_in_units = ceil($length_in_units);
905
-        }
906
-        // phpcs:enable
907
-        if ($round_up) {
908
-            $length_in_units = max($length_in_units, 1);
909
-        }
910
-        return $length_in_units;
911
-    }
912
-
913
-
914
-    /**
915
-     *        get end date and time
916
-     *
917
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
918
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
919
-     * @return    mixed                string on success, FALSE on fail
920
-     * @throws ReflectionException
921
-     * @throws InvalidArgumentException
922
-     * @throws InvalidInterfaceException
923
-     * @throws InvalidDataTypeException
924
-     * @throws EE_Error
925
-     */
926
-    public function end_date_and_time($dt_frmt = '', $tm_format = '')
927
-    {
928
-        return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
929
-    }
930
-
931
-
932
-    /**
933
-     * @param string $dt_frmt
934
-     * @param string $tm_format
935
-     * @throws ReflectionException
936
-     * @throws InvalidArgumentException
937
-     * @throws InvalidInterfaceException
938
-     * @throws InvalidDataTypeException
939
-     * @throws EE_Error
940
-     */
941
-    public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
942
-    {
943
-        $this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
944
-    }
945
-
946
-
947
-    /**
948
-     *        get start timestamp
949
-     *
950
-     * @return        int
951
-     * @throws ReflectionException
952
-     * @throws InvalidArgumentException
953
-     * @throws InvalidInterfaceException
954
-     * @throws InvalidDataTypeException
955
-     * @throws EE_Error
956
-     */
957
-    public function start()
958
-    {
959
-        return $this->get_raw('DTT_EVT_start');
960
-    }
961
-
962
-
963
-    /**
964
-     *        get end timestamp
965
-     *
966
-     * @return        int
967
-     * @throws ReflectionException
968
-     * @throws InvalidArgumentException
969
-     * @throws InvalidInterfaceException
970
-     * @throws InvalidDataTypeException
971
-     * @throws EE_Error
972
-     */
973
-    public function end()
974
-    {
975
-        return $this->get_raw('DTT_EVT_end');
976
-    }
977
-
978
-
979
-    /**
980
-     *    get the registration limit for this datetime slot
981
-     *
982
-     * @return        mixed        int on success, FALSE on fail
983
-     * @throws ReflectionException
984
-     * @throws InvalidArgumentException
985
-     * @throws InvalidInterfaceException
986
-     * @throws InvalidDataTypeException
987
-     * @throws EE_Error
988
-     */
989
-    public function reg_limit()
990
-    {
991
-        return $this->get_raw('DTT_reg_limit');
992
-    }
993
-
994
-
995
-    /**
996
-     *    have the tickets sold for this datetime, met or exceed the registration limit ?
997
-     *
998
-     * @return        boolean
999
-     * @throws ReflectionException
1000
-     * @throws InvalidArgumentException
1001
-     * @throws InvalidInterfaceException
1002
-     * @throws InvalidDataTypeException
1003
-     * @throws EE_Error
1004
-     */
1005
-    public function sold_out()
1006
-    {
1007
-        return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1008
-    }
1009
-
1010
-
1011
-    /**
1012
-     * return the total number of spaces remaining at this venue.
1013
-     * This only takes the venue's capacity into account, NOT the tickets available for sale
1014
-     *
1015
-     * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1016
-     *                               Because if all tickets attached to this datetime have no spaces left,
1017
-     *                               then this datetime IS effectively sold out.
1018
-     *                               However, there are cases where we just want to know the spaces
1019
-     *                               remaining for this particular datetime, hence the flag.
1020
-     * @return int
1021
-     * @throws ReflectionException
1022
-     * @throws InvalidArgumentException
1023
-     * @throws InvalidInterfaceException
1024
-     * @throws InvalidDataTypeException
1025
-     * @throws EE_Error
1026
-     */
1027
-    public function spaces_remaining($consider_tickets = false)
1028
-    {
1029
-        // tickets remaining available for purchase
1030
-        // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1031
-        $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1032
-        if (! $consider_tickets) {
1033
-            return $dtt_remaining;
1034
-        }
1035
-        $tickets_remaining = $this->tickets_remaining();
1036
-        return min($dtt_remaining, $tickets_remaining);
1037
-    }
1038
-
1039
-
1040
-    /**
1041
-     * Counts the total tickets available
1042
-     * (from all the different types of tickets which are available for this datetime).
1043
-     *
1044
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1045
-     * @return int
1046
-     * @throws ReflectionException
1047
-     * @throws InvalidArgumentException
1048
-     * @throws InvalidInterfaceException
1049
-     * @throws InvalidDataTypeException
1050
-     * @throws EE_Error
1051
-     */
1052
-    public function tickets_remaining($query_params = array())
1053
-    {
1054
-        $sum = 0;
1055
-        $tickets = $this->tickets($query_params);
1056
-        if (! empty($tickets)) {
1057
-            foreach ($tickets as $ticket) {
1058
-                if ($ticket instanceof EE_Ticket) {
1059
-                    // get the actual amount of tickets that can be sold
1060
-                    $qty = $ticket->qty('saleable');
1061
-                    if ($qty === EE_INF) {
1062
-                        return EE_INF;
1063
-                    }
1064
-                    // no negative ticket quantities plz
1065
-                    if ($qty > 0) {
1066
-                        $sum += $qty;
1067
-                    }
1068
-                }
1069
-            }
1070
-        }
1071
-        return $sum;
1072
-    }
1073
-
1074
-
1075
-    /**
1076
-     * Gets the count of all the tickets available at this datetime (not ticket types)
1077
-     * before any were sold
1078
-     *
1079
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1080
-     * @return int
1081
-     * @throws ReflectionException
1082
-     * @throws InvalidArgumentException
1083
-     * @throws InvalidInterfaceException
1084
-     * @throws InvalidDataTypeException
1085
-     * @throws EE_Error
1086
-     */
1087
-    public function sum_tickets_initially_available($query_params = array())
1088
-    {
1089
-        return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1090
-    }
1091
-
1092
-
1093
-    /**
1094
-     * Returns the lesser-of-the two: spaces remaining at this datetime, or
1095
-     * the total tickets remaining (a sum of the tickets remaining for each ticket type
1096
-     * that is available for this datetime).
1097
-     *
1098
-     * @return int
1099
-     * @throws ReflectionException
1100
-     * @throws InvalidArgumentException
1101
-     * @throws InvalidInterfaceException
1102
-     * @throws InvalidDataTypeException
1103
-     * @throws EE_Error
1104
-     */
1105
-    public function total_tickets_available_at_this_datetime()
1106
-    {
1107
-        return $this->spaces_remaining(true);
1108
-    }
1109
-
1110
-
1111
-    /**
1112
-     * This simply compares the internal dtt for the given string with NOW
1113
-     * and determines if the date is upcoming or not.
1114
-     *
1115
-     * @access public
1116
-     * @return boolean
1117
-     * @throws ReflectionException
1118
-     * @throws InvalidArgumentException
1119
-     * @throws InvalidInterfaceException
1120
-     * @throws InvalidDataTypeException
1121
-     * @throws EE_Error
1122
-     */
1123
-    public function is_upcoming()
1124
-    {
1125
-        return ($this->get_raw('DTT_EVT_start') > time());
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * This simply compares the internal datetime for the given string with NOW
1131
-     * and returns if the date is active (i.e. start and end time)
1132
-     *
1133
-     * @return boolean
1134
-     * @throws ReflectionException
1135
-     * @throws InvalidArgumentException
1136
-     * @throws InvalidInterfaceException
1137
-     * @throws InvalidDataTypeException
1138
-     * @throws EE_Error
1139
-     */
1140
-    public function is_active()
1141
-    {
1142
-        return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1143
-    }
1144
-
1145
-
1146
-    /**
1147
-     * This simply compares the internal dtt for the given string with NOW
1148
-     * and determines if the date is expired or not.
1149
-     *
1150
-     * @return boolean
1151
-     * @throws ReflectionException
1152
-     * @throws InvalidArgumentException
1153
-     * @throws InvalidInterfaceException
1154
-     * @throws InvalidDataTypeException
1155
-     * @throws EE_Error
1156
-     */
1157
-    public function is_expired()
1158
-    {
1159
-        return ($this->get_raw('DTT_EVT_end') < time());
1160
-    }
1161
-
1162
-
1163
-    /**
1164
-     * This returns the active status for whether an event is active, upcoming, or expired
1165
-     *
1166
-     * @return int return value will be one of the EE_Datetime status constants.
1167
-     * @throws ReflectionException
1168
-     * @throws InvalidArgumentException
1169
-     * @throws InvalidInterfaceException
1170
-     * @throws InvalidDataTypeException
1171
-     * @throws EE_Error
1172
-     */
1173
-    public function get_active_status()
1174
-    {
1175
-        $total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1176
-        if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1177
-            return EE_Datetime::sold_out;
1178
-        }
1179
-        if ($this->is_expired()) {
1180
-            return EE_Datetime::expired;
1181
-        }
1182
-        if ($this->is_upcoming()) {
1183
-            return EE_Datetime::upcoming;
1184
-        }
1185
-        if ($this->is_active()) {
1186
-            return EE_Datetime::active;
1187
-        }
1188
-        return null;
1189
-    }
1190
-
1191
-
1192
-    /**
1193
-     * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1194
-     *
1195
-     * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1196
-     * @return string
1197
-     * @throws ReflectionException
1198
-     * @throws InvalidArgumentException
1199
-     * @throws InvalidInterfaceException
1200
-     * @throws InvalidDataTypeException
1201
-     * @throws EE_Error
1202
-     */
1203
-    public function get_dtt_display_name($use_dtt_name = false)
1204
-    {
1205
-        if ($use_dtt_name) {
1206
-            $dtt_name = $this->name();
1207
-            if (! empty($dtt_name)) {
1208
-                return $dtt_name;
1209
-            }
1210
-        }
1211
-        // first condition is to see if the months are different
1212
-        if (
1213
-            date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1214
-        ) {
1215
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1216
-            // next condition is if its the same month but different day
1217
-        } else {
1218
-            if (
1219
-                date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1220
-                && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1221
-            ) {
1222
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1223
-            } else {
1224
-                $display_date = $this->start_date('F j\, Y')
1225
-                                . ' @ '
1226
-                                . $this->start_date('g:i a')
1227
-                                . ' - '
1228
-                                . $this->end_date('g:i a');
1229
-            }
1230
-        }
1231
-        return $display_date;
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     * Gets all the tickets for this datetime
1237
-     *
1238
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1239
-     * @return EE_Base_Class[]|EE_Ticket[]
1240
-     * @throws ReflectionException
1241
-     * @throws InvalidArgumentException
1242
-     * @throws InvalidInterfaceException
1243
-     * @throws InvalidDataTypeException
1244
-     * @throws EE_Error
1245
-     */
1246
-    public function tickets($query_params = array())
1247
-    {
1248
-        return $this->get_many_related('Ticket', $query_params);
1249
-    }
1250
-
1251
-
1252
-    /**
1253
-     * Gets all the ticket types currently available for purchase
1254
-     *
1255
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1256
-     * @return EE_Ticket[]
1257
-     * @throws ReflectionException
1258
-     * @throws InvalidArgumentException
1259
-     * @throws InvalidInterfaceException
1260
-     * @throws InvalidDataTypeException
1261
-     * @throws EE_Error
1262
-     */
1263
-    public function ticket_types_available_for_purchase($query_params = array())
1264
-    {
1265
-        // first check if datetime is valid
1266
-        if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1267
-            return array();
1268
-        }
1269
-        if (empty($query_params)) {
1270
-            $query_params = array(
1271
-                array(
1272
-                    'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1273
-                    'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1274
-                    'TKT_deleted'    => false,
1275
-                ),
1276
-            );
1277
-        }
1278
-        return $this->tickets($query_params);
1279
-    }
1280
-
1281
-
1282
-    /**
1283
-     * @return EE_Base_Class|EE_Event
1284
-     * @throws ReflectionException
1285
-     * @throws InvalidArgumentException
1286
-     * @throws InvalidInterfaceException
1287
-     * @throws InvalidDataTypeException
1288
-     * @throws EE_Error
1289
-     */
1290
-    public function event()
1291
-    {
1292
-        return $this->get_first_related('Event');
1293
-    }
1294
-
1295
-
1296
-    /**
1297
-     * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1298
-     * (via the tickets).
1299
-     *
1300
-     * @return int
1301
-     * @throws ReflectionException
1302
-     * @throws InvalidArgumentException
1303
-     * @throws InvalidInterfaceException
1304
-     * @throws InvalidDataTypeException
1305
-     * @throws EE_Error
1306
-     */
1307
-    public function update_sold()
1308
-    {
1309
-        $count_regs_for_this_datetime = EEM_Registration::instance()->count(
1310
-            array(
1311
-                array(
1312
-                    'STS_ID'                 => EEM_Registration::status_id_approved,
1313
-                    'REG_deleted'            => 0,
1314
-                    'Ticket.Datetime.DTT_ID' => $this->ID(),
1315
-                ),
1316
-            )
1317
-        );
1318
-        $this->set_sold($count_regs_for_this_datetime);
1319
-        $this->save();
1320
-        return $count_regs_for_this_datetime;
1321
-    }
1322
-
1323
-
1324
-    /*******************************************************************
16
+	/**
17
+	 * constant used by get_active_status, indicates datetime has no more available spaces
18
+	 */
19
+	const sold_out = 'DTS';
20
+
21
+	/**
22
+	 * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
23
+	 */
24
+	const active = 'DTA';
25
+
26
+	/**
27
+	 * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
28
+	 * expired
29
+	 */
30
+	const upcoming = 'DTU';
31
+
32
+	/**
33
+	 * Datetime is postponed
34
+	 */
35
+	const postponed = 'DTP';
36
+
37
+	/**
38
+	 * Datetime is cancelled
39
+	 */
40
+	const cancelled = 'DTC';
41
+
42
+	/**
43
+	 * constant used by get_active_status, indicates datetime has expired (event is over)
44
+	 */
45
+	const expired = 'DTE';
46
+
47
+	/**
48
+	 * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
49
+	 */
50
+	const inactive = 'DTI';
51
+
52
+
53
+	/**
54
+	 * @param array  $props_n_values    incoming values
55
+	 * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
56
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
57
+	 *                                  and the second value is the time format
58
+	 * @return EE_Datetime
59
+	 * @throws ReflectionException
60
+	 * @throws InvalidArgumentException
61
+	 * @throws InvalidInterfaceException
62
+	 * @throws InvalidDataTypeException
63
+	 * @throws EE_Error
64
+	 */
65
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
66
+	{
67
+		$has_object = parent::_check_for_object(
68
+			$props_n_values,
69
+			__CLASS__,
70
+			$timezone,
71
+			$date_formats
72
+		);
73
+		return $has_object
74
+			? $has_object
75
+			: new self($props_n_values, false, $timezone, $date_formats);
76
+	}
77
+
78
+
79
+	/**
80
+	 * @param array  $props_n_values  incoming values from the database
81
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
+	 *                                the website will be used.
83
+	 * @return EE_Datetime
84
+	 * @throws ReflectionException
85
+	 * @throws InvalidArgumentException
86
+	 * @throws InvalidInterfaceException
87
+	 * @throws InvalidDataTypeException
88
+	 * @throws EE_Error
89
+	 */
90
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
91
+	{
92
+		return new self($props_n_values, true, $timezone);
93
+	}
94
+
95
+
96
+	/**
97
+	 * @param $name
98
+	 * @throws ReflectionException
99
+	 * @throws InvalidArgumentException
100
+	 * @throws InvalidInterfaceException
101
+	 * @throws InvalidDataTypeException
102
+	 * @throws EE_Error
103
+	 */
104
+	public function set_name($name)
105
+	{
106
+		$this->set('DTT_name', $name);
107
+	}
108
+
109
+
110
+	/**
111
+	 * @param $description
112
+	 * @throws ReflectionException
113
+	 * @throws InvalidArgumentException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws InvalidDataTypeException
116
+	 * @throws EE_Error
117
+	 */
118
+	public function set_description($description)
119
+	{
120
+		$this->set('DTT_description', $description);
121
+	}
122
+
123
+
124
+	/**
125
+	 * Set event start date
126
+	 * set the start date for an event
127
+	 *
128
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
129
+	 * @throws ReflectionException
130
+	 * @throws InvalidArgumentException
131
+	 * @throws InvalidInterfaceException
132
+	 * @throws InvalidDataTypeException
133
+	 * @throws EE_Error
134
+	 */
135
+	public function set_start_date($date)
136
+	{
137
+		$this->_set_date_for($date, 'DTT_EVT_start');
138
+	}
139
+
140
+
141
+	/**
142
+	 * Set event start time
143
+	 * set the start time for an event
144
+	 *
145
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
146
+	 * @throws ReflectionException
147
+	 * @throws InvalidArgumentException
148
+	 * @throws InvalidInterfaceException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws EE_Error
151
+	 */
152
+	public function set_start_time($time)
153
+	{
154
+		$this->_set_time_for($time, 'DTT_EVT_start');
155
+	}
156
+
157
+
158
+	/**
159
+	 * Set event end date
160
+	 * set the end date for an event
161
+	 *
162
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
163
+	 * @throws ReflectionException
164
+	 * @throws InvalidArgumentException
165
+	 * @throws InvalidInterfaceException
166
+	 * @throws InvalidDataTypeException
167
+	 * @throws EE_Error
168
+	 */
169
+	public function set_end_date($date)
170
+	{
171
+		$this->_set_date_for($date, 'DTT_EVT_end');
172
+	}
173
+
174
+
175
+	/**
176
+	 * Set event end time
177
+	 * set the end time for an event
178
+	 *
179
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
180
+	 * @throws ReflectionException
181
+	 * @throws InvalidArgumentException
182
+	 * @throws InvalidInterfaceException
183
+	 * @throws InvalidDataTypeException
184
+	 * @throws EE_Error
185
+	 */
186
+	public function set_end_time($time)
187
+	{
188
+		$this->_set_time_for($time, 'DTT_EVT_end');
189
+	}
190
+
191
+
192
+	/**
193
+	 * Set registration limit
194
+	 * set the maximum number of attendees that can be registered for this datetime slot
195
+	 *
196
+	 * @param int $reg_limit
197
+	 * @throws ReflectionException
198
+	 * @throws InvalidArgumentException
199
+	 * @throws InvalidInterfaceException
200
+	 * @throws InvalidDataTypeException
201
+	 * @throws EE_Error
202
+	 */
203
+	public function set_reg_limit($reg_limit)
204
+	{
205
+		$this->set('DTT_reg_limit', $reg_limit);
206
+	}
207
+
208
+
209
+	/**
210
+	 * get the number of tickets sold for this datetime slot
211
+	 *
212
+	 * @return mixed int on success, FALSE on fail
213
+	 * @throws ReflectionException
214
+	 * @throws InvalidArgumentException
215
+	 * @throws InvalidInterfaceException
216
+	 * @throws InvalidDataTypeException
217
+	 * @throws EE_Error
218
+	 */
219
+	public function sold()
220
+	{
221
+		return $this->get_raw('DTT_sold');
222
+	}
223
+
224
+
225
+	/**
226
+	 * @param int $sold
227
+	 * @throws ReflectionException
228
+	 * @throws InvalidArgumentException
229
+	 * @throws InvalidInterfaceException
230
+	 * @throws InvalidDataTypeException
231
+	 * @throws EE_Error
232
+	 */
233
+	public function set_sold($sold)
234
+	{
235
+		// sold can not go below zero
236
+		$sold = max(0, $sold);
237
+		$this->set('DTT_sold', $sold);
238
+	}
239
+
240
+
241
+	/**
242
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
243
+	 * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
244
+	 *
245
+	 * @param int $qty
246
+	 * @param boolean $also_decrease_reserved
247
+	 * @return boolean indicating success
248
+	 * @throws ReflectionException
249
+	 * @throws InvalidArgumentException
250
+	 * @throws InvalidInterfaceException
251
+	 * @throws InvalidDataTypeException
252
+	 * @throws EE_Error
253
+	 */
254
+	public function increaseSold($qty = 1, $also_decrease_reserved = true)
255
+	{
256
+		$qty = absint($qty);
257
+		if ($also_decrease_reserved) {
258
+			$success = $this->adjustNumericFieldsInDb(
259
+				[
260
+					'DTT_reserved' => $qty * -1,
261
+					'DTT_sold' => $qty
262
+				]
263
+			);
264
+		} else {
265
+			$success = $this->adjustNumericFieldsInDb(
266
+				[
267
+					'DTT_sold' => $qty
268
+				]
269
+			);
270
+		}
271
+
272
+		do_action(
273
+			'AHEE__EE_Datetime__increase_sold',
274
+			$this,
275
+			$qty,
276
+			$this->sold(),
277
+			$success
278
+		);
279
+		return $success;
280
+	}
281
+
282
+
283
+	/**
284
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
285
+	 * to save afterwards.)
286
+	 *
287
+	 * @param int $qty
288
+	 * @return boolean indicating success
289
+	 * @throws ReflectionException
290
+	 * @throws InvalidArgumentException
291
+	 * @throws InvalidInterfaceException
292
+	 * @throws InvalidDataTypeException
293
+	 * @throws EE_Error
294
+	 */
295
+	public function decreaseSold($qty = 1)
296
+	{
297
+		$qty = absint($qty);
298
+		$success = $this->adjustNumericFieldsInDb(
299
+			[
300
+				'DTT_sold' => $qty * -1
301
+			]
302
+		);
303
+		do_action(
304
+			'AHEE__EE_Datetime__decrease_sold',
305
+			$this,
306
+			$qty,
307
+			$this->sold(),
308
+			$success
309
+		);
310
+		return $success;
311
+	}
312
+
313
+
314
+	/**
315
+	 * Gets qty of reserved tickets for this datetime
316
+	 *
317
+	 * @return int
318
+	 * @throws ReflectionException
319
+	 * @throws InvalidArgumentException
320
+	 * @throws InvalidInterfaceException
321
+	 * @throws InvalidDataTypeException
322
+	 * @throws EE_Error
323
+	 */
324
+	public function reserved()
325
+	{
326
+		return $this->get_raw('DTT_reserved');
327
+	}
328
+
329
+
330
+	/**
331
+	 * Sets qty of reserved tickets for this datetime
332
+	 *
333
+	 * @param int $reserved
334
+	 * @throws ReflectionException
335
+	 * @throws InvalidArgumentException
336
+	 * @throws InvalidInterfaceException
337
+	 * @throws InvalidDataTypeException
338
+	 * @throws EE_Error
339
+	 */
340
+	public function set_reserved($reserved)
341
+	{
342
+		// reserved can not go below zero
343
+		$reserved = max(0, (int) $reserved);
344
+		$this->set('DTT_reserved', $reserved);
345
+	}
346
+
347
+
348
+	/**
349
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
350
+	 *
351
+	 * @param int $qty
352
+	 * @return boolean indicating success
353
+	 * @throws ReflectionException
354
+	 * @throws InvalidArgumentException
355
+	 * @throws InvalidInterfaceException
356
+	 * @throws InvalidDataTypeException
357
+	 * @throws EE_Error
358
+	 */
359
+	public function increaseReserved($qty = 1)
360
+	{
361
+		$qty = absint($qty);
362
+		$success = $this->incrementFieldConditionallyInDb(
363
+			'DTT_reserved',
364
+			'DTT_sold',
365
+			'DTT_reg_limit',
366
+			$qty
367
+		);
368
+		do_action(
369
+			'AHEE__EE_Datetime__increase_reserved',
370
+			$this,
371
+			$qty,
372
+			$this->reserved(),
373
+			$success
374
+		);
375
+		return $success;
376
+	}
377
+
378
+
379
+	/**
380
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
381
+	 *
382
+	 * @param int $qty
383
+	 * @return boolean indicating success
384
+	 * @throws ReflectionException
385
+	 * @throws InvalidArgumentException
386
+	 * @throws InvalidInterfaceException
387
+	 * @throws InvalidDataTypeException
388
+	 * @throws EE_Error
389
+	 */
390
+	public function decreaseReserved($qty = 1)
391
+	{
392
+		$qty = absint($qty);
393
+		$success = $this->adjustNumericFieldsInDb(
394
+			[
395
+				'DTT_reserved' => $qty * -1
396
+			]
397
+		);
398
+		do_action(
399
+			'AHEE__EE_Datetime__decrease_reserved',
400
+			$this,
401
+			$qty,
402
+			$this->reserved(),
403
+			$success
404
+		);
405
+		return $success;
406
+	}
407
+
408
+
409
+	/**
410
+	 * total sold and reserved tickets
411
+	 *
412
+	 * @return int
413
+	 * @throws ReflectionException
414
+	 * @throws InvalidArgumentException
415
+	 * @throws InvalidInterfaceException
416
+	 * @throws InvalidDataTypeException
417
+	 * @throws EE_Error
418
+	 */
419
+	public function sold_and_reserved()
420
+	{
421
+		return $this->sold() + $this->reserved();
422
+	}
423
+
424
+
425
+	/**
426
+	 * returns the datetime name
427
+	 *
428
+	 * @return string
429
+	 * @throws ReflectionException
430
+	 * @throws InvalidArgumentException
431
+	 * @throws InvalidInterfaceException
432
+	 * @throws InvalidDataTypeException
433
+	 * @throws EE_Error
434
+	 */
435
+	public function name()
436
+	{
437
+		return $this->get('DTT_name');
438
+	}
439
+
440
+
441
+	/**
442
+	 * returns the datetime description
443
+	 *
444
+	 * @return string
445
+	 * @throws ReflectionException
446
+	 * @throws InvalidArgumentException
447
+	 * @throws InvalidInterfaceException
448
+	 * @throws InvalidDataTypeException
449
+	 * @throws EE_Error
450
+	 */
451
+	public function description()
452
+	{
453
+		return $this->get('DTT_description');
454
+	}
455
+
456
+
457
+	/**
458
+	 * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
459
+	 *
460
+	 * @return boolean  TRUE if is primary, FALSE if not.
461
+	 * @throws ReflectionException
462
+	 * @throws InvalidArgumentException
463
+	 * @throws InvalidInterfaceException
464
+	 * @throws InvalidDataTypeException
465
+	 * @throws EE_Error
466
+	 */
467
+	public function is_primary()
468
+	{
469
+		return $this->get('DTT_is_primary');
470
+	}
471
+
472
+
473
+	/**
474
+	 * This helper simply returns the order for the datetime
475
+	 *
476
+	 * @return int  The order of the datetime for this event.
477
+	 * @throws ReflectionException
478
+	 * @throws InvalidArgumentException
479
+	 * @throws InvalidInterfaceException
480
+	 * @throws InvalidDataTypeException
481
+	 * @throws EE_Error
482
+	 */
483
+	public function order()
484
+	{
485
+		return $this->get('DTT_order');
486
+	}
487
+
488
+
489
+	/**
490
+	 * This helper simply returns the parent id for the datetime
491
+	 *
492
+	 * @return int
493
+	 * @throws ReflectionException
494
+	 * @throws InvalidArgumentException
495
+	 * @throws InvalidInterfaceException
496
+	 * @throws InvalidDataTypeException
497
+	 * @throws EE_Error
498
+	 */
499
+	public function parent()
500
+	{
501
+		return $this->get('DTT_parent');
502
+	}
503
+
504
+
505
+	/**
506
+	 * show date and/or time
507
+	 *
508
+	 * @param string $date_or_time    whether to display a date or time or both
509
+	 * @param string $start_or_end    whether to display start or end datetimes
510
+	 * @param string $dt_frmt
511
+	 * @param string $tm_frmt
512
+	 * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
513
+	 *                                otherwise we use the standard formats)
514
+	 * @return string|bool  string on success, FALSE on fail
515
+	 * @throws ReflectionException
516
+	 * @throws InvalidArgumentException
517
+	 * @throws InvalidInterfaceException
518
+	 * @throws InvalidDataTypeException
519
+	 * @throws EE_Error
520
+	 */
521
+	private function _show_datetime(
522
+		$date_or_time = null,
523
+		$start_or_end = 'start',
524
+		$dt_frmt = '',
525
+		$tm_frmt = '',
526
+		$echo = false
527
+	) {
528
+		$field_name = "DTT_EVT_{$start_or_end}";
529
+		$dtt = $this->_get_datetime(
530
+			$field_name,
531
+			$dt_frmt,
532
+			$tm_frmt,
533
+			$date_or_time,
534
+			$echo
535
+		);
536
+		if (! $echo) {
537
+			return $dtt;
538
+		}
539
+		return '';
540
+	}
541
+
542
+
543
+	/**
544
+	 * get event start date.  Provide either the date format, or NULL to re-use the
545
+	 * last-used format, or '' to use the default date format
546
+	 *
547
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
548
+	 * @return mixed            string on success, FALSE on fail
549
+	 * @throws ReflectionException
550
+	 * @throws InvalidArgumentException
551
+	 * @throws InvalidInterfaceException
552
+	 * @throws InvalidDataTypeException
553
+	 * @throws EE_Error
554
+	 */
555
+	public function start_date($dt_frmt = '')
556
+	{
557
+		return $this->_show_datetime('D', 'start', $dt_frmt);
558
+	}
559
+
560
+
561
+	/**
562
+	 * Echoes start_date()
563
+	 *
564
+	 * @param string $dt_frmt
565
+	 * @throws ReflectionException
566
+	 * @throws InvalidArgumentException
567
+	 * @throws InvalidInterfaceException
568
+	 * @throws InvalidDataTypeException
569
+	 * @throws EE_Error
570
+	 */
571
+	public function e_start_date($dt_frmt = '')
572
+	{
573
+		$this->_show_datetime('D', 'start', $dt_frmt, null, true);
574
+	}
575
+
576
+
577
+	/**
578
+	 * get end date. Provide either the date format, or NULL to re-use the
579
+	 * last-used format, or '' to use the default date format
580
+	 *
581
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
582
+	 * @return mixed            string on success, FALSE on fail
583
+	 * @throws ReflectionException
584
+	 * @throws InvalidArgumentException
585
+	 * @throws InvalidInterfaceException
586
+	 * @throws InvalidDataTypeException
587
+	 * @throws EE_Error
588
+	 */
589
+	public function end_date($dt_frmt = '')
590
+	{
591
+		return $this->_show_datetime('D', 'end', $dt_frmt);
592
+	}
593
+
594
+
595
+	/**
596
+	 * Echoes the end date. See end_date()
597
+	 *
598
+	 * @param string $dt_frmt
599
+	 * @throws ReflectionException
600
+	 * @throws InvalidArgumentException
601
+	 * @throws InvalidInterfaceException
602
+	 * @throws InvalidDataTypeException
603
+	 * @throws EE_Error
604
+	 */
605
+	public function e_end_date($dt_frmt = '')
606
+	{
607
+		$this->_show_datetime('D', 'end', $dt_frmt, null, true);
608
+	}
609
+
610
+
611
+	/**
612
+	 * get date_range - meaning the start AND end date
613
+	 *
614
+	 * @access public
615
+	 * @param string $dt_frmt     string representation of date format defaults to WP settings
616
+	 * @param string $conjunction conjunction junction what's your function ?
617
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
618
+	 * @return mixed              string on success, FALSE on fail
619
+	 * @throws ReflectionException
620
+	 * @throws InvalidArgumentException
621
+	 * @throws InvalidInterfaceException
622
+	 * @throws InvalidDataTypeException
623
+	 * @throws EE_Error
624
+	 */
625
+	public function date_range($dt_frmt = '', $conjunction = ' - ')
626
+	{
627
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
628
+		$start = str_replace(
629
+			' ',
630
+			'&nbsp;',
631
+			$this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
632
+		);
633
+		$end = str_replace(
634
+			' ',
635
+			'&nbsp;',
636
+			$this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
637
+		);
638
+		return $start !== $end ? $start . $conjunction . $end : $start;
639
+	}
640
+
641
+
642
+	/**
643
+	 * @param string $dt_frmt
644
+	 * @param string $conjunction
645
+	 * @throws ReflectionException
646
+	 * @throws InvalidArgumentException
647
+	 * @throws InvalidInterfaceException
648
+	 * @throws InvalidDataTypeException
649
+	 * @throws EE_Error
650
+	 */
651
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ')
652
+	{
653
+		echo $this->date_range($dt_frmt, $conjunction); // sanitized
654
+	}
655
+
656
+
657
+	/**
658
+	 * get start time
659
+	 *
660
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
661
+	 * @return mixed        string on success, FALSE on fail
662
+	 * @throws ReflectionException
663
+	 * @throws InvalidArgumentException
664
+	 * @throws InvalidInterfaceException
665
+	 * @throws InvalidDataTypeException
666
+	 * @throws EE_Error
667
+	 */
668
+	public function start_time($tm_format = '')
669
+	{
670
+		return $this->_show_datetime('T', 'start', null, $tm_format);
671
+	}
672
+
673
+
674
+	/**
675
+	 * @param string $tm_format
676
+	 * @throws ReflectionException
677
+	 * @throws InvalidArgumentException
678
+	 * @throws InvalidInterfaceException
679
+	 * @throws InvalidDataTypeException
680
+	 * @throws EE_Error
681
+	 */
682
+	public function e_start_time($tm_format = '')
683
+	{
684
+		$this->_show_datetime('T', 'start', null, $tm_format, true);
685
+	}
686
+
687
+
688
+	/**
689
+	 * get end time
690
+	 *
691
+	 * @param string $tm_format string representation of time format defaults to 'g:i a'
692
+	 * @return mixed                string on success, FALSE on fail
693
+	 * @throws ReflectionException
694
+	 * @throws InvalidArgumentException
695
+	 * @throws InvalidInterfaceException
696
+	 * @throws InvalidDataTypeException
697
+	 * @throws EE_Error
698
+	 */
699
+	public function end_time($tm_format = '')
700
+	{
701
+		return $this->_show_datetime('T', 'end', null, $tm_format);
702
+	}
703
+
704
+
705
+	/**
706
+	 * @param string $tm_format
707
+	 * @throws ReflectionException
708
+	 * @throws InvalidArgumentException
709
+	 * @throws InvalidInterfaceException
710
+	 * @throws InvalidDataTypeException
711
+	 * @throws EE_Error
712
+	 */
713
+	public function e_end_time($tm_format = '')
714
+	{
715
+		$this->_show_datetime('T', 'end', null, $tm_format, true);
716
+	}
717
+
718
+
719
+	/**
720
+	 * get time_range
721
+	 *
722
+	 * @access public
723
+	 * @param string $tm_format   string representation of time format defaults to 'g:i a'
724
+	 * @param string $conjunction conjunction junction what's your function ?
725
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
726
+	 * @return mixed              string on success, FALSE on fail
727
+	 * @throws ReflectionException
728
+	 * @throws InvalidArgumentException
729
+	 * @throws InvalidInterfaceException
730
+	 * @throws InvalidDataTypeException
731
+	 * @throws EE_Error
732
+	 */
733
+	public function time_range($tm_format = '', $conjunction = ' - ')
734
+	{
735
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
736
+		$start = str_replace(
737
+			' ',
738
+			'&nbsp;',
739
+			$this->get_i18n_datetime('DTT_EVT_start', $tm_format)
740
+		);
741
+		$end = str_replace(
742
+			' ',
743
+			'&nbsp;',
744
+			$this->get_i18n_datetime('DTT_EVT_end', $tm_format)
745
+		);
746
+		return $start !== $end ? $start . $conjunction . $end : $start;
747
+	}
748
+
749
+
750
+	/**
751
+	 * @param string $tm_format
752
+	 * @param string $conjunction
753
+	 * @throws ReflectionException
754
+	 * @throws InvalidArgumentException
755
+	 * @throws InvalidInterfaceException
756
+	 * @throws InvalidDataTypeException
757
+	 * @throws EE_Error
758
+	 */
759
+	public function e_time_range($tm_format = '', $conjunction = ' - ')
760
+	{
761
+		echo $this->time_range($tm_format, $conjunction); // sanitized
762
+	}
763
+
764
+
765
+	/**
766
+	 * This returns a range representation of the date and times.
767
+	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
768
+	 * Also, the return value is localized.
769
+	 *
770
+	 * @param string $dt_format
771
+	 * @param string $tm_format
772
+	 * @param string $conjunction used between two different dates or times.
773
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
774
+	 * @param string $separator   used between the date and time formats.
775
+	 *                            ex: Dec 1, 2016{$separator}2pm
776
+	 * @return string
777
+	 * @throws ReflectionException
778
+	 * @throws InvalidArgumentException
779
+	 * @throws InvalidInterfaceException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws EE_Error
782
+	 */
783
+	public function date_and_time_range(
784
+		$dt_format = '',
785
+		$tm_format = '',
786
+		$conjunction = ' - ',
787
+		$separator = ' '
788
+	) {
789
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
790
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
791
+		$full_format = $dt_format . $separator . $tm_format;
792
+		// the range output depends on various conditions
793
+		switch (true) {
794
+			// start date timestamp and end date timestamp are the same.
795
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
796
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
797
+				break;
798
+			// start and end date are the same but times are different
799
+			case ($this->start_date() === $this->end_date()):
800
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
801
+						  . $conjunction
802
+						  . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
803
+				break;
804
+			// all other conditions
805
+			default:
806
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
807
+						  . $conjunction
808
+						  . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
809
+				break;
810
+		}
811
+		return $output;
812
+	}
813
+
814
+
815
+	/**
816
+	 * This echos the results of date and time range.
817
+	 *
818
+	 * @see date_and_time_range() for more details on purpose.
819
+	 * @param string $dt_format
820
+	 * @param string $tm_format
821
+	 * @param string $conjunction
822
+	 * @return void
823
+	 * @throws ReflectionException
824
+	 * @throws InvalidArgumentException
825
+	 * @throws InvalidInterfaceException
826
+	 * @throws InvalidDataTypeException
827
+	 * @throws EE_Error
828
+	 */
829
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
830
+	{
831
+		echo $this->date_and_time_range($dt_format, $tm_format, $conjunction); // sanitized
832
+	}
833
+
834
+
835
+	/**
836
+	 * get start date and start time
837
+	 *
838
+	 * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
839
+	 * @param    string $tm_format - string representation of time format defaults to 'g:i a'
840
+	 * @return    mixed    string on success, FALSE on fail
841
+	 * @throws ReflectionException
842
+	 * @throws InvalidArgumentException
843
+	 * @throws InvalidInterfaceException
844
+	 * @throws InvalidDataTypeException
845
+	 * @throws EE_Error
846
+	 */
847
+	public function start_date_and_time($dt_format = '', $tm_format = '')
848
+	{
849
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
850
+	}
851
+
852
+
853
+	/**
854
+	 * @param string $dt_frmt
855
+	 * @param string $tm_format
856
+	 * @throws ReflectionException
857
+	 * @throws InvalidArgumentException
858
+	 * @throws InvalidInterfaceException
859
+	 * @throws InvalidDataTypeException
860
+	 * @throws EE_Error
861
+	 */
862
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
863
+	{
864
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
865
+	}
866
+
867
+
868
+	/**
869
+	 * Shows the length of the event (start to end time).
870
+	 * Can be shown in 'seconds','minutes','hours', or 'days'.
871
+	 * By default, rounds up. (So if you use 'days', and then event
872
+	 * only occurs for 1 hour, it will return 1 day).
873
+	 *
874
+	 * @param string $units 'seconds','minutes','hours','days'
875
+	 * @param bool   $round_up
876
+	 * @return float|int|mixed
877
+	 * @throws ReflectionException
878
+	 * @throws InvalidArgumentException
879
+	 * @throws InvalidInterfaceException
880
+	 * @throws InvalidDataTypeException
881
+	 * @throws EE_Error
882
+	 */
883
+	public function length($units = 'seconds', $round_up = false)
884
+	{
885
+		$start = $this->get_raw('DTT_EVT_start');
886
+		$end = $this->get_raw('DTT_EVT_end');
887
+		$length_in_units = $end - $start;
888
+		switch ($units) {
889
+			// NOTE: We purposefully don't use "break;" in order to chain the divisions
890
+			/** @noinspection PhpMissingBreakStatementInspection */
891
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
892
+			case 'days':
893
+				$length_in_units /= 24;
894
+			/** @noinspection PhpMissingBreakStatementInspection */
895
+			case 'hours':
896
+				// fall through is intentional
897
+				$length_in_units /= 60;
898
+			/** @noinspection PhpMissingBreakStatementInspection */
899
+			case 'minutes':
900
+				// fall through is intentional
901
+				$length_in_units /= 60;
902
+			case 'seconds':
903
+			default:
904
+				$length_in_units = ceil($length_in_units);
905
+		}
906
+		// phpcs:enable
907
+		if ($round_up) {
908
+			$length_in_units = max($length_in_units, 1);
909
+		}
910
+		return $length_in_units;
911
+	}
912
+
913
+
914
+	/**
915
+	 *        get end date and time
916
+	 *
917
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
918
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
919
+	 * @return    mixed                string on success, FALSE on fail
920
+	 * @throws ReflectionException
921
+	 * @throws InvalidArgumentException
922
+	 * @throws InvalidInterfaceException
923
+	 * @throws InvalidDataTypeException
924
+	 * @throws EE_Error
925
+	 */
926
+	public function end_date_and_time($dt_frmt = '', $tm_format = '')
927
+	{
928
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
929
+	}
930
+
931
+
932
+	/**
933
+	 * @param string $dt_frmt
934
+	 * @param string $tm_format
935
+	 * @throws ReflectionException
936
+	 * @throws InvalidArgumentException
937
+	 * @throws InvalidInterfaceException
938
+	 * @throws InvalidDataTypeException
939
+	 * @throws EE_Error
940
+	 */
941
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
942
+	{
943
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
944
+	}
945
+
946
+
947
+	/**
948
+	 *        get start timestamp
949
+	 *
950
+	 * @return        int
951
+	 * @throws ReflectionException
952
+	 * @throws InvalidArgumentException
953
+	 * @throws InvalidInterfaceException
954
+	 * @throws InvalidDataTypeException
955
+	 * @throws EE_Error
956
+	 */
957
+	public function start()
958
+	{
959
+		return $this->get_raw('DTT_EVT_start');
960
+	}
961
+
962
+
963
+	/**
964
+	 *        get end timestamp
965
+	 *
966
+	 * @return        int
967
+	 * @throws ReflectionException
968
+	 * @throws InvalidArgumentException
969
+	 * @throws InvalidInterfaceException
970
+	 * @throws InvalidDataTypeException
971
+	 * @throws EE_Error
972
+	 */
973
+	public function end()
974
+	{
975
+		return $this->get_raw('DTT_EVT_end');
976
+	}
977
+
978
+
979
+	/**
980
+	 *    get the registration limit for this datetime slot
981
+	 *
982
+	 * @return        mixed        int on success, FALSE on fail
983
+	 * @throws ReflectionException
984
+	 * @throws InvalidArgumentException
985
+	 * @throws InvalidInterfaceException
986
+	 * @throws InvalidDataTypeException
987
+	 * @throws EE_Error
988
+	 */
989
+	public function reg_limit()
990
+	{
991
+		return $this->get_raw('DTT_reg_limit');
992
+	}
993
+
994
+
995
+	/**
996
+	 *    have the tickets sold for this datetime, met or exceed the registration limit ?
997
+	 *
998
+	 * @return        boolean
999
+	 * @throws ReflectionException
1000
+	 * @throws InvalidArgumentException
1001
+	 * @throws InvalidInterfaceException
1002
+	 * @throws InvalidDataTypeException
1003
+	 * @throws EE_Error
1004
+	 */
1005
+	public function sold_out()
1006
+	{
1007
+		return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1008
+	}
1009
+
1010
+
1011
+	/**
1012
+	 * return the total number of spaces remaining at this venue.
1013
+	 * This only takes the venue's capacity into account, NOT the tickets available for sale
1014
+	 *
1015
+	 * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1016
+	 *                               Because if all tickets attached to this datetime have no spaces left,
1017
+	 *                               then this datetime IS effectively sold out.
1018
+	 *                               However, there are cases where we just want to know the spaces
1019
+	 *                               remaining for this particular datetime, hence the flag.
1020
+	 * @return int
1021
+	 * @throws ReflectionException
1022
+	 * @throws InvalidArgumentException
1023
+	 * @throws InvalidInterfaceException
1024
+	 * @throws InvalidDataTypeException
1025
+	 * @throws EE_Error
1026
+	 */
1027
+	public function spaces_remaining($consider_tickets = false)
1028
+	{
1029
+		// tickets remaining available for purchase
1030
+		// no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1031
+		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1032
+		if (! $consider_tickets) {
1033
+			return $dtt_remaining;
1034
+		}
1035
+		$tickets_remaining = $this->tickets_remaining();
1036
+		return min($dtt_remaining, $tickets_remaining);
1037
+	}
1038
+
1039
+
1040
+	/**
1041
+	 * Counts the total tickets available
1042
+	 * (from all the different types of tickets which are available for this datetime).
1043
+	 *
1044
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1045
+	 * @return int
1046
+	 * @throws ReflectionException
1047
+	 * @throws InvalidArgumentException
1048
+	 * @throws InvalidInterfaceException
1049
+	 * @throws InvalidDataTypeException
1050
+	 * @throws EE_Error
1051
+	 */
1052
+	public function tickets_remaining($query_params = array())
1053
+	{
1054
+		$sum = 0;
1055
+		$tickets = $this->tickets($query_params);
1056
+		if (! empty($tickets)) {
1057
+			foreach ($tickets as $ticket) {
1058
+				if ($ticket instanceof EE_Ticket) {
1059
+					// get the actual amount of tickets that can be sold
1060
+					$qty = $ticket->qty('saleable');
1061
+					if ($qty === EE_INF) {
1062
+						return EE_INF;
1063
+					}
1064
+					// no negative ticket quantities plz
1065
+					if ($qty > 0) {
1066
+						$sum += $qty;
1067
+					}
1068
+				}
1069
+			}
1070
+		}
1071
+		return $sum;
1072
+	}
1073
+
1074
+
1075
+	/**
1076
+	 * Gets the count of all the tickets available at this datetime (not ticket types)
1077
+	 * before any were sold
1078
+	 *
1079
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1080
+	 * @return int
1081
+	 * @throws ReflectionException
1082
+	 * @throws InvalidArgumentException
1083
+	 * @throws InvalidInterfaceException
1084
+	 * @throws InvalidDataTypeException
1085
+	 * @throws EE_Error
1086
+	 */
1087
+	public function sum_tickets_initially_available($query_params = array())
1088
+	{
1089
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1090
+	}
1091
+
1092
+
1093
+	/**
1094
+	 * Returns the lesser-of-the two: spaces remaining at this datetime, or
1095
+	 * the total tickets remaining (a sum of the tickets remaining for each ticket type
1096
+	 * that is available for this datetime).
1097
+	 *
1098
+	 * @return int
1099
+	 * @throws ReflectionException
1100
+	 * @throws InvalidArgumentException
1101
+	 * @throws InvalidInterfaceException
1102
+	 * @throws InvalidDataTypeException
1103
+	 * @throws EE_Error
1104
+	 */
1105
+	public function total_tickets_available_at_this_datetime()
1106
+	{
1107
+		return $this->spaces_remaining(true);
1108
+	}
1109
+
1110
+
1111
+	/**
1112
+	 * This simply compares the internal dtt for the given string with NOW
1113
+	 * and determines if the date is upcoming or not.
1114
+	 *
1115
+	 * @access public
1116
+	 * @return boolean
1117
+	 * @throws ReflectionException
1118
+	 * @throws InvalidArgumentException
1119
+	 * @throws InvalidInterfaceException
1120
+	 * @throws InvalidDataTypeException
1121
+	 * @throws EE_Error
1122
+	 */
1123
+	public function is_upcoming()
1124
+	{
1125
+		return ($this->get_raw('DTT_EVT_start') > time());
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * This simply compares the internal datetime for the given string with NOW
1131
+	 * and returns if the date is active (i.e. start and end time)
1132
+	 *
1133
+	 * @return boolean
1134
+	 * @throws ReflectionException
1135
+	 * @throws InvalidArgumentException
1136
+	 * @throws InvalidInterfaceException
1137
+	 * @throws InvalidDataTypeException
1138
+	 * @throws EE_Error
1139
+	 */
1140
+	public function is_active()
1141
+	{
1142
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1143
+	}
1144
+
1145
+
1146
+	/**
1147
+	 * This simply compares the internal dtt for the given string with NOW
1148
+	 * and determines if the date is expired or not.
1149
+	 *
1150
+	 * @return boolean
1151
+	 * @throws ReflectionException
1152
+	 * @throws InvalidArgumentException
1153
+	 * @throws InvalidInterfaceException
1154
+	 * @throws InvalidDataTypeException
1155
+	 * @throws EE_Error
1156
+	 */
1157
+	public function is_expired()
1158
+	{
1159
+		return ($this->get_raw('DTT_EVT_end') < time());
1160
+	}
1161
+
1162
+
1163
+	/**
1164
+	 * This returns the active status for whether an event is active, upcoming, or expired
1165
+	 *
1166
+	 * @return int return value will be one of the EE_Datetime status constants.
1167
+	 * @throws ReflectionException
1168
+	 * @throws InvalidArgumentException
1169
+	 * @throws InvalidInterfaceException
1170
+	 * @throws InvalidDataTypeException
1171
+	 * @throws EE_Error
1172
+	 */
1173
+	public function get_active_status()
1174
+	{
1175
+		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1176
+		if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1177
+			return EE_Datetime::sold_out;
1178
+		}
1179
+		if ($this->is_expired()) {
1180
+			return EE_Datetime::expired;
1181
+		}
1182
+		if ($this->is_upcoming()) {
1183
+			return EE_Datetime::upcoming;
1184
+		}
1185
+		if ($this->is_active()) {
1186
+			return EE_Datetime::active;
1187
+		}
1188
+		return null;
1189
+	}
1190
+
1191
+
1192
+	/**
1193
+	 * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1194
+	 *
1195
+	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1196
+	 * @return string
1197
+	 * @throws ReflectionException
1198
+	 * @throws InvalidArgumentException
1199
+	 * @throws InvalidInterfaceException
1200
+	 * @throws InvalidDataTypeException
1201
+	 * @throws EE_Error
1202
+	 */
1203
+	public function get_dtt_display_name($use_dtt_name = false)
1204
+	{
1205
+		if ($use_dtt_name) {
1206
+			$dtt_name = $this->name();
1207
+			if (! empty($dtt_name)) {
1208
+				return $dtt_name;
1209
+			}
1210
+		}
1211
+		// first condition is to see if the months are different
1212
+		if (
1213
+			date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1214
+		) {
1215
+			$display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1216
+			// next condition is if its the same month but different day
1217
+		} else {
1218
+			if (
1219
+				date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1220
+				&& date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1221
+			) {
1222
+				$display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1223
+			} else {
1224
+				$display_date = $this->start_date('F j\, Y')
1225
+								. ' @ '
1226
+								. $this->start_date('g:i a')
1227
+								. ' - '
1228
+								. $this->end_date('g:i a');
1229
+			}
1230
+		}
1231
+		return $display_date;
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 * Gets all the tickets for this datetime
1237
+	 *
1238
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1239
+	 * @return EE_Base_Class[]|EE_Ticket[]
1240
+	 * @throws ReflectionException
1241
+	 * @throws InvalidArgumentException
1242
+	 * @throws InvalidInterfaceException
1243
+	 * @throws InvalidDataTypeException
1244
+	 * @throws EE_Error
1245
+	 */
1246
+	public function tickets($query_params = array())
1247
+	{
1248
+		return $this->get_many_related('Ticket', $query_params);
1249
+	}
1250
+
1251
+
1252
+	/**
1253
+	 * Gets all the ticket types currently available for purchase
1254
+	 *
1255
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1256
+	 * @return EE_Ticket[]
1257
+	 * @throws ReflectionException
1258
+	 * @throws InvalidArgumentException
1259
+	 * @throws InvalidInterfaceException
1260
+	 * @throws InvalidDataTypeException
1261
+	 * @throws EE_Error
1262
+	 */
1263
+	public function ticket_types_available_for_purchase($query_params = array())
1264
+	{
1265
+		// first check if datetime is valid
1266
+		if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1267
+			return array();
1268
+		}
1269
+		if (empty($query_params)) {
1270
+			$query_params = array(
1271
+				array(
1272
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1273
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1274
+					'TKT_deleted'    => false,
1275
+				),
1276
+			);
1277
+		}
1278
+		return $this->tickets($query_params);
1279
+	}
1280
+
1281
+
1282
+	/**
1283
+	 * @return EE_Base_Class|EE_Event
1284
+	 * @throws ReflectionException
1285
+	 * @throws InvalidArgumentException
1286
+	 * @throws InvalidInterfaceException
1287
+	 * @throws InvalidDataTypeException
1288
+	 * @throws EE_Error
1289
+	 */
1290
+	public function event()
1291
+	{
1292
+		return $this->get_first_related('Event');
1293
+	}
1294
+
1295
+
1296
+	/**
1297
+	 * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1298
+	 * (via the tickets).
1299
+	 *
1300
+	 * @return int
1301
+	 * @throws ReflectionException
1302
+	 * @throws InvalidArgumentException
1303
+	 * @throws InvalidInterfaceException
1304
+	 * @throws InvalidDataTypeException
1305
+	 * @throws EE_Error
1306
+	 */
1307
+	public function update_sold()
1308
+	{
1309
+		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
1310
+			array(
1311
+				array(
1312
+					'STS_ID'                 => EEM_Registration::status_id_approved,
1313
+					'REG_deleted'            => 0,
1314
+					'Ticket.Datetime.DTT_ID' => $this->ID(),
1315
+				),
1316
+			)
1317
+		);
1318
+		$this->set_sold($count_regs_for_this_datetime);
1319
+		$this->save();
1320
+		return $count_regs_for_this_datetime;
1321
+	}
1322
+
1323
+
1324
+	/*******************************************************************
1325 1325
      ***********************  DEPRECATED METHODS  **********************
1326 1326
      *******************************************************************/
1327 1327
 
1328 1328
 
1329
-    /**
1330
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
1331
-     *
1332
-     * @deprecated 4.9.80.p
1333
-     * @param int $qty
1334
-     * @return boolean
1335
-     * @throws ReflectionException
1336
-     * @throws InvalidArgumentException
1337
-     * @throws InvalidInterfaceException
1338
-     * @throws InvalidDataTypeException
1339
-     * @throws EE_Error
1340
-     */
1341
-    public function increase_sold($qty = 1)
1342
-    {
1343
-        EE_Error::doing_it_wrong(
1344
-            __FUNCTION__,
1345
-            esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1346
-            '4.9.80.p',
1347
-            '5.0.0.p'
1348
-        );
1349
-        return $this->increaseSold($qty);
1350
-    }
1351
-
1352
-
1353
-    /**
1354
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1355
-     * to save afterwards.)
1356
-     *
1357
-     * @deprecated 4.9.80.p
1358
-     * @param int $qty
1359
-     * @return boolean
1360
-     * @throws ReflectionException
1361
-     * @throws InvalidArgumentException
1362
-     * @throws InvalidInterfaceException
1363
-     * @throws InvalidDataTypeException
1364
-     * @throws EE_Error
1365
-     */
1366
-    public function decrease_sold($qty = 1)
1367
-    {
1368
-        EE_Error::doing_it_wrong(
1369
-            __FUNCTION__,
1370
-            esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1371
-            '4.9.80.p',
1372
-            '5.0.0.p'
1373
-        );
1374
-        return $this->decreaseSold($qty);
1375
-    }
1376
-
1377
-
1378
-    /**
1379
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1380
-     *
1381
-     * @deprecated 4.9.80.p
1382
-     * @param int $qty
1383
-     * @return boolean indicating success
1384
-     * @throws ReflectionException
1385
-     * @throws InvalidArgumentException
1386
-     * @throws InvalidInterfaceException
1387
-     * @throws InvalidDataTypeException
1388
-     * @throws EE_Error
1389
-     */
1390
-    public function increase_reserved($qty = 1)
1391
-    {
1392
-        EE_Error::doing_it_wrong(
1393
-            __FUNCTION__,
1394
-            esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1395
-            '4.9.80.p',
1396
-            '5.0.0.p'
1397
-        );
1398
-        return $this->increaseReserved($qty);
1399
-    }
1400
-
1401
-
1402
-    /**
1403
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1404
-     *
1405
-     * @deprecated 4.9.80.p
1406
-     * @param int $qty
1407
-     * @return boolean
1408
-     * @throws ReflectionException
1409
-     * @throws InvalidArgumentException
1410
-     * @throws InvalidInterfaceException
1411
-     * @throws InvalidDataTypeException
1412
-     * @throws EE_Error
1413
-     */
1414
-    public function decrease_reserved($qty = 1)
1415
-    {
1416
-        EE_Error::doing_it_wrong(
1417
-            __FUNCTION__,
1418
-            esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1419
-            '4.9.80.p',
1420
-            '5.0.0.p'
1421
-        );
1422
-        return $this->decreaseReserved($qty);
1423
-    }
1329
+	/**
1330
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
1331
+	 *
1332
+	 * @deprecated 4.9.80.p
1333
+	 * @param int $qty
1334
+	 * @return boolean
1335
+	 * @throws ReflectionException
1336
+	 * @throws InvalidArgumentException
1337
+	 * @throws InvalidInterfaceException
1338
+	 * @throws InvalidDataTypeException
1339
+	 * @throws EE_Error
1340
+	 */
1341
+	public function increase_sold($qty = 1)
1342
+	{
1343
+		EE_Error::doing_it_wrong(
1344
+			__FUNCTION__,
1345
+			esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1346
+			'4.9.80.p',
1347
+			'5.0.0.p'
1348
+		);
1349
+		return $this->increaseSold($qty);
1350
+	}
1351
+
1352
+
1353
+	/**
1354
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1355
+	 * to save afterwards.)
1356
+	 *
1357
+	 * @deprecated 4.9.80.p
1358
+	 * @param int $qty
1359
+	 * @return boolean
1360
+	 * @throws ReflectionException
1361
+	 * @throws InvalidArgumentException
1362
+	 * @throws InvalidInterfaceException
1363
+	 * @throws InvalidDataTypeException
1364
+	 * @throws EE_Error
1365
+	 */
1366
+	public function decrease_sold($qty = 1)
1367
+	{
1368
+		EE_Error::doing_it_wrong(
1369
+			__FUNCTION__,
1370
+			esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1371
+			'4.9.80.p',
1372
+			'5.0.0.p'
1373
+		);
1374
+		return $this->decreaseSold($qty);
1375
+	}
1376
+
1377
+
1378
+	/**
1379
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1380
+	 *
1381
+	 * @deprecated 4.9.80.p
1382
+	 * @param int $qty
1383
+	 * @return boolean indicating success
1384
+	 * @throws ReflectionException
1385
+	 * @throws InvalidArgumentException
1386
+	 * @throws InvalidInterfaceException
1387
+	 * @throws InvalidDataTypeException
1388
+	 * @throws EE_Error
1389
+	 */
1390
+	public function increase_reserved($qty = 1)
1391
+	{
1392
+		EE_Error::doing_it_wrong(
1393
+			__FUNCTION__,
1394
+			esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1395
+			'4.9.80.p',
1396
+			'5.0.0.p'
1397
+		);
1398
+		return $this->increaseReserved($qty);
1399
+	}
1400
+
1401
+
1402
+	/**
1403
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1404
+	 *
1405
+	 * @deprecated 4.9.80.p
1406
+	 * @param int $qty
1407
+	 * @return boolean
1408
+	 * @throws ReflectionException
1409
+	 * @throws InvalidArgumentException
1410
+	 * @throws InvalidInterfaceException
1411
+	 * @throws InvalidDataTypeException
1412
+	 * @throws EE_Error
1413
+	 */
1414
+	public function decrease_reserved($qty = 1)
1415
+	{
1416
+		EE_Error::doing_it_wrong(
1417
+			__FUNCTION__,
1418
+			esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1419
+			'4.9.80.p',
1420
+			'5.0.0.p'
1421
+		);
1422
+		return $this->decreaseReserved($qty);
1423
+	}
1424 1424
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 2 patches
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
     {
120 120
         switch ($field_name) {
121 121
             case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
122
+                if ( ! empty($field_value) && $this->reg_code() === null) {
123 123
                     $this->set_reg_code($field_value, $use_default);
124 124
                 }
125 125
                 break;
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
     public function event()
407 407
     {
408 408
         $event = $this->get_first_related('Event');
409
-        if (! $event instanceof \EE_Event) {
409
+        if ( ! $event instanceof \EE_Event) {
410 410
             throw new EntityNotFoundException('Event ID', $this->event_ID());
411 411
         }
412 412
         return $event;
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
     {
450 450
         // reserved ticket and datetime counts will be decremented as sold counts are incremented
451 451
         // so stop tracking that this reg has a ticket reserved
452
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
452
+        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:".__LINE__.')');
453 453
         $ticket = $this->ticket();
454 454
         $ticket->increaseSold();
455 455
         // possibly set event status to sold out
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
                 && $update_ticket
505 505
             ) {
506 506
                 $ticket = $this->ticket();
507
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
507
+                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:".__LINE__.')');
508 508
                 $ticket->save();
509 509
             }
510 510
         }
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
                 && $update_ticket
537 537
             ) {
538 538
                 $ticket = $this->ticket();
539
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
539
+                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:".__LINE__.')');
540 540
             }
541 541
         }
542 542
     }
@@ -1211,7 +1211,7 @@  discard block
 block discarded – undo
1211 1211
                     : '';
1212 1212
                 break;
1213 1213
         }
1214
-        return $icon . $status[ $this->status_ID() ];
1214
+        return $icon.$status[$this->status_ID()];
1215 1215
     }
1216 1216
 
1217 1217
 
@@ -1455,7 +1455,7 @@  discard block
 block discarded – undo
1455 1455
     {
1456 1456
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1457 1457
 
1458
-        if (! $DTT_ID) {
1458
+        if ( ! $DTT_ID) {
1459 1459
             return false;
1460 1460
         }
1461 1461
 
@@ -1463,7 +1463,7 @@  discard block
 block discarded – undo
1463 1463
 
1464 1464
         // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1465 1465
         // check-in or not.
1466
-        if (! $max_uses || $max_uses === EE_INF) {
1466
+        if ( ! $max_uses || $max_uses === EE_INF) {
1467 1467
             return true;
1468 1468
         }
1469 1469
 
@@ -1523,7 +1523,7 @@  discard block
 block discarded – undo
1523 1523
             $datetime = $this->get_latest_related_datetime();
1524 1524
             $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1525 1525
             // verify the registration can checkin for the given DTT_ID
1526
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1526
+        } elseif ( ! $this->can_checkin($DTT_ID, $verify)) {
1527 1527
             EE_Error::add_error(
1528 1528
                 sprintf(
1529 1529
                     esc_html__(
@@ -1546,7 +1546,7 @@  discard block
 block discarded – undo
1546 1546
         );
1547 1547
         // start by getting the current status so we know what status we'll be changing to.
1548 1548
         $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1549
-        $status_to = $status_paths[ $cur_status ];
1549
+        $status_to = $status_paths[$cur_status];
1550 1550
         // database only records true for checked IN or false for checked OUT
1551 1551
         // no record ( null ) means checked in NEVER, but we obviously don't save that
1552 1552
         $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
@@ -1714,7 +1714,7 @@  discard block
 block discarded – undo
1714 1714
     public function transaction()
1715 1715
     {
1716 1716
         $transaction = $this->get_first_related('Transaction');
1717
-        if (! $transaction instanceof \EE_Transaction) {
1717
+        if ( ! $transaction instanceof \EE_Transaction) {
1718 1718
             throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1719 1719
         }
1720 1720
         return $transaction;
@@ -1768,11 +1768,11 @@  discard block
 block discarded – undo
1768 1768
             );
1769 1769
             return;
1770 1770
         }
1771
-        if (! $this->reg_code()) {
1771
+        if ( ! $this->reg_code()) {
1772 1772
             parent::set('REG_code', $REG_code, $use_default);
1773 1773
         } else {
1774 1774
             EE_Error::doing_it_wrong(
1775
-                __CLASS__ . '::' . __FUNCTION__,
1775
+                __CLASS__.'::'.__FUNCTION__,
1776 1776
                 esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1777 1777
                 '4.6.0'
1778 1778
             );
@@ -1924,7 +1924,7 @@  discard block
 block discarded – undo
1924 1924
                 break;
1925 1925
             }
1926 1926
         }
1927
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1927
+        if ( ! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1928 1928
             throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1929 1929
         }
1930 1930
         return $line_item;
Please login to merge, or discard this patch.
Indentation   +2113 added lines, -2113 removed lines patch added patch discarded remove patch
@@ -17,2117 +17,2117 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * Used to reference when a registration has never been checked in.
22
-     *
23
-     * @deprecated use \EE_Checkin::status_checked_never instead
24
-     * @type int
25
-     */
26
-    const checkin_status_never = 2;
27
-
28
-    /**
29
-     * Used to reference when a registration has been checked in.
30
-     *
31
-     * @deprecated use \EE_Checkin::status_checked_in instead
32
-     * @type int
33
-     */
34
-    const checkin_status_in = 1;
35
-
36
-
37
-    /**
38
-     * Used to reference when a registration has been checked out.
39
-     *
40
-     * @deprecated use \EE_Checkin::status_checked_out instead
41
-     * @type int
42
-     */
43
-    const checkin_status_out = 0;
44
-
45
-
46
-    /**
47
-     * extra meta key for tracking reg status os trashed registrations
48
-     *
49
-     * @type string
50
-     */
51
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
-
53
-
54
-    /**
55
-     * extra meta key for tracking if registration has reserved ticket
56
-     *
57
-     * @type string
58
-     */
59
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
-
61
-
62
-    /**
63
-     * @param array  $props_n_values          incoming values
64
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
-     *                                        used.)
66
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
-     *                                        date_format and the second value is the time format
68
-     * @return EE_Registration
69
-     * @throws EE_Error
70
-     */
71
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
72
-    {
73
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param array  $props_n_values  incoming values from the database
80
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
-     *                                the website will be used.
82
-     * @return EE_Registration
83
-     */
84
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
85
-    {
86
-        return new self($props_n_values, true, $timezone);
87
-    }
88
-
89
-
90
-    /**
91
-     *        Set Event ID
92
-     *
93
-     * @param        int $EVT_ID Event ID
94
-     * @throws EE_Error
95
-     * @throws RuntimeException
96
-     */
97
-    public function set_event($EVT_ID = 0)
98
-    {
99
-        $this->set('EVT_ID', $EVT_ID);
100
-    }
101
-
102
-
103
-    /**
104
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
-     * be routed to internal methods
106
-     *
107
-     * @param string $field_name
108
-     * @param mixed  $field_value
109
-     * @param bool   $use_default
110
-     * @throws EE_Error
111
-     * @throws EntityNotFoundException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidDataTypeException
114
-     * @throws InvalidInterfaceException
115
-     * @throws ReflectionException
116
-     * @throws RuntimeException
117
-     */
118
-    public function set($field_name, $field_value, $use_default = false)
119
-    {
120
-        switch ($field_name) {
121
-            case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
123
-                    $this->set_reg_code($field_value, $use_default);
124
-                }
125
-                break;
126
-            case 'STS_ID':
127
-                $this->set_status($field_value, $use_default);
128
-                break;
129
-            default:
130
-                parent::set($field_name, $field_value, $use_default);
131
-        }
132
-    }
133
-
134
-
135
-    /**
136
-     * Set Status ID
137
-     * updates the registration status and ALSO...
138
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
-     *
141
-     * @param string                $new_STS_ID
142
-     * @param boolean               $use_default
143
-     * @param ContextInterface|null $context
144
-     * @return bool
145
-     * @throws DomainException
146
-     * @throws EE_Error
147
-     * @throws EntityNotFoundException
148
-     * @throws InvalidArgumentException
149
-     * @throws InvalidDataTypeException
150
-     * @throws InvalidInterfaceException
151
-     * @throws ReflectionException
152
-     * @throws RuntimeException
153
-     * @throws UnexpectedEntityException
154
-     */
155
-    public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
156
-    {
157
-        // get current REG_Status
158
-        $old_STS_ID = $this->status_ID();
159
-        // if status has changed
160
-        if (
161
-            $old_STS_ID !== $new_STS_ID // and that status has actually changed
162
-            && ! empty($old_STS_ID) // and that old status is actually set
163
-            && ! empty($new_STS_ID) // as well as the new status
164
-            && $this->ID() // ensure registration is in the db
165
-        ) {
166
-            // update internal status first
167
-            parent::set('STS_ID', $new_STS_ID, $use_default);
168
-            // THEN handle other changes that occur when reg status changes
169
-            // TO approved
170
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
171
-                // reserve a space by incrementing ticket and datetime sold values
172
-                $this->reserveRegistrationSpace();
173
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
174
-                // OR FROM  approved
175
-            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
176
-                // release a space by decrementing ticket and datetime sold values
177
-                $this->releaseRegistrationSpace();
178
-                do_action(
179
-                    'AHEE__EE_Registration__set_status__from_approved',
180
-                    $this,
181
-                    $old_STS_ID,
182
-                    $new_STS_ID,
183
-                    $context
184
-                );
185
-            }
186
-            // update status
187
-            parent::set('STS_ID', $new_STS_ID, $use_default);
188
-            $this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
189
-            if ($this->statusChangeUpdatesTransaction($context)) {
190
-                $this->updateTransactionAfterStatusChange();
191
-            }
192
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
193
-            return true;
194
-        }
195
-        // even though the old value matches the new value, it's still good to
196
-        // allow the parent set method to have a say
197
-        parent::set('STS_ID', $new_STS_ID, $use_default);
198
-        return true;
199
-    }
200
-
201
-
202
-    /**
203
-     * update REGs and TXN when cancelled or declined registrations involved
204
-     *
205
-     * @param string                $new_STS_ID
206
-     * @param string                $old_STS_ID
207
-     * @param ContextInterface|null $context
208
-     * @throws EE_Error
209
-     * @throws InvalidArgumentException
210
-     * @throws InvalidDataTypeException
211
-     * @throws InvalidInterfaceException
212
-     * @throws ReflectionException
213
-     * @throws RuntimeException
214
-     */
215
-    private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
216
-    {
217
-        // these reg statuses should not be considered in any calculations involving monies owing
218
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
219
-        // true if registration has been cancelled or declined
220
-        $this->updateIfCanceled(
221
-            $closed_reg_statuses,
222
-            $new_STS_ID,
223
-            $old_STS_ID,
224
-            $context
225
-        );
226
-        $this->updateIfReinstated(
227
-            $closed_reg_statuses,
228
-            $new_STS_ID,
229
-            $old_STS_ID,
230
-            $context
231
-        );
232
-    }
233
-
234
-
235
-    /**
236
-     * update REGs and TXN when cancelled or declined registrations involved
237
-     *
238
-     * @param array                 $closed_reg_statuses
239
-     * @param string                $new_STS_ID
240
-     * @param string                $old_STS_ID
241
-     * @param ContextInterface|null $context
242
-     * @throws EE_Error
243
-     * @throws InvalidArgumentException
244
-     * @throws InvalidDataTypeException
245
-     * @throws InvalidInterfaceException
246
-     * @throws ReflectionException
247
-     * @throws RuntimeException
248
-     */
249
-    private function updateIfCanceled(
250
-        array $closed_reg_statuses,
251
-        $new_STS_ID,
252
-        $old_STS_ID,
253
-        ContextInterface $context = null
254
-    ) {
255
-        // true if registration has been cancelled or declined
256
-        if (
257
-            in_array($new_STS_ID, $closed_reg_statuses, true)
258
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
259
-        ) {
260
-            /** @type EE_Registration_Processor $registration_processor */
261
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
262
-            /** @type EE_Transaction_Processor $transaction_processor */
263
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
264
-            // cancelled or declined registration
265
-            $registration_processor->update_registration_after_being_canceled_or_declined(
266
-                $this,
267
-                $closed_reg_statuses
268
-            );
269
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
270
-                $this,
271
-                $closed_reg_statuses,
272
-                false
273
-            );
274
-            do_action(
275
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
276
-                $this,
277
-                $old_STS_ID,
278
-                $new_STS_ID,
279
-                $context
280
-            );
281
-            return;
282
-        }
283
-    }
284
-
285
-
286
-    /**
287
-     * update REGs and TXN when cancelled or declined registrations involved
288
-     *
289
-     * @param array                 $closed_reg_statuses
290
-     * @param string                $new_STS_ID
291
-     * @param string                $old_STS_ID
292
-     * @param ContextInterface|null $context
293
-     * @throws EE_Error
294
-     * @throws InvalidArgumentException
295
-     * @throws InvalidDataTypeException
296
-     * @throws InvalidInterfaceException
297
-     * @throws ReflectionException
298
-     */
299
-    private function updateIfReinstated(
300
-        array $closed_reg_statuses,
301
-        $new_STS_ID,
302
-        $old_STS_ID,
303
-        ContextInterface $context = null
304
-    ) {
305
-        // true if reinstating cancelled or declined registration
306
-        if (
307
-            in_array($old_STS_ID, $closed_reg_statuses, true)
308
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
309
-        ) {
310
-            /** @type EE_Registration_Processor $registration_processor */
311
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
312
-            /** @type EE_Transaction_Processor $transaction_processor */
313
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
314
-            // reinstating cancelled or declined registration
315
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
316
-                $this,
317
-                $closed_reg_statuses
318
-            );
319
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
320
-                $this,
321
-                $closed_reg_statuses,
322
-                false
323
-            );
324
-            do_action(
325
-                'AHEE__EE_Registration__set_status__after_reinstated',
326
-                $this,
327
-                $old_STS_ID,
328
-                $new_STS_ID,
329
-                $context
330
-            );
331
-        }
332
-    }
333
-
334
-
335
-    /**
336
-     * @param ContextInterface|null $context
337
-     * @return bool
338
-     */
339
-    private function statusChangeUpdatesTransaction(ContextInterface $context = null)
340
-    {
341
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
342
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
343
-            array('spco_reg_step_attendee_information_process_registrations'),
344
-            $context,
345
-            $this
346
-        );
347
-        return ! (
348
-            $context instanceof ContextInterface
349
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
350
-        );
351
-    }
352
-
353
-
354
-    /**
355
-     * @throws EE_Error
356
-     * @throws EntityNotFoundException
357
-     * @throws InvalidArgumentException
358
-     * @throws InvalidDataTypeException
359
-     * @throws InvalidInterfaceException
360
-     * @throws ReflectionException
361
-     * @throws RuntimeException
362
-     */
363
-    private function updateTransactionAfterStatusChange()
364
-    {
365
-        /** @type EE_Transaction_Payments $transaction_payments */
366
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
367
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
368
-        $this->transaction()->update_status_based_on_total_paid(true);
369
-    }
370
-
371
-
372
-    /**
373
-     *        get Status ID
374
-     */
375
-    public function status_ID()
376
-    {
377
-        return $this->get('STS_ID');
378
-    }
379
-
380
-
381
-    /**
382
-     * Gets the ticket this registration is for
383
-     *
384
-     * @param boolean $include_archived whether to include archived tickets or not.
385
-     *
386
-     * @return EE_Ticket|EE_Base_Class
387
-     * @throws EE_Error
388
-     */
389
-    public function ticket($include_archived = true)
390
-    {
391
-        $query_params = array();
392
-        if ($include_archived) {
393
-            $query_params['default_where_conditions'] = 'none';
394
-        }
395
-        return $this->get_first_related('Ticket', $query_params);
396
-    }
397
-
398
-
399
-    /**
400
-     * Gets the event this registration is for
401
-     *
402
-     * @return EE_Event
403
-     * @throws EE_Error
404
-     * @throws EntityNotFoundException
405
-     */
406
-    public function event()
407
-    {
408
-        $event = $this->get_first_related('Event');
409
-        if (! $event instanceof \EE_Event) {
410
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
411
-        }
412
-        return $event;
413
-    }
414
-
415
-
416
-    /**
417
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
418
-     * with the author of the event this registration is for.
419
-     *
420
-     * @since 4.5.0
421
-     * @return int
422
-     * @throws EE_Error
423
-     * @throws EntityNotFoundException
424
-     */
425
-    public function wp_user()
426
-    {
427
-        $event = $this->event();
428
-        if ($event instanceof EE_Event) {
429
-            return $event->wp_user();
430
-        }
431
-        return 0;
432
-    }
433
-
434
-
435
-    /**
436
-     * increments this registration's related ticket sold and corresponding datetime sold values
437
-     *
438
-     * @return void
439
-     * @throws DomainException
440
-     * @throws EE_Error
441
-     * @throws EntityNotFoundException
442
-     * @throws InvalidArgumentException
443
-     * @throws InvalidDataTypeException
444
-     * @throws InvalidInterfaceException
445
-     * @throws ReflectionException
446
-     * @throws UnexpectedEntityException
447
-     */
448
-    private function reserveRegistrationSpace()
449
-    {
450
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
451
-        // so stop tracking that this reg has a ticket reserved
452
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
453
-        $ticket = $this->ticket();
454
-        $ticket->increaseSold();
455
-        // possibly set event status to sold out
456
-        $this->event()->perform_sold_out_status_check();
457
-    }
458
-
459
-
460
-    /**
461
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
462
-     *
463
-     * @return void
464
-     * @throws DomainException
465
-     * @throws EE_Error
466
-     * @throws EntityNotFoundException
467
-     * @throws InvalidArgumentException
468
-     * @throws InvalidDataTypeException
469
-     * @throws InvalidInterfaceException
470
-     * @throws ReflectionException
471
-     * @throws UnexpectedEntityException
472
-     */
473
-    private function releaseRegistrationSpace()
474
-    {
475
-        $ticket = $this->ticket();
476
-        $ticket->decreaseSold();
477
-        // possibly change event status from sold out back to previous status
478
-        $this->event()->perform_sold_out_status_check();
479
-    }
480
-
481
-
482
-    /**
483
-     * tracks this registration's ticket reservation in extra meta
484
-     * and can increment related ticket reserved and corresponding datetime reserved values
485
-     *
486
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
487
-     * @return void
488
-     * @throws EE_Error
489
-     * @throws InvalidArgumentException
490
-     * @throws InvalidDataTypeException
491
-     * @throws InvalidInterfaceException
492
-     * @throws ReflectionException
493
-     */
494
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
495
-    {
496
-        // only reserve ticket if space is not currently reserved
497
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
498
-            $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
499
-            // IMPORTANT !!!
500
-            // although checking $update_ticket first would be more efficient,
501
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
502
-            if (
503
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
504
-                && $update_ticket
505
-            ) {
506
-                $ticket = $this->ticket();
507
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
508
-                $ticket->save();
509
-            }
510
-        }
511
-    }
512
-
513
-
514
-    /**
515
-     * stops tracking this registration's ticket reservation in extra meta
516
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
517
-     *
518
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
519
-     * @return void
520
-     * @throws EE_Error
521
-     * @throws InvalidArgumentException
522
-     * @throws InvalidDataTypeException
523
-     * @throws InvalidInterfaceException
524
-     * @throws ReflectionException
525
-     */
526
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
527
-    {
528
-        // only release ticket if space is currently reserved
529
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
530
-            $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
531
-            // IMPORTANT !!!
532
-            // although checking $update_ticket first would be more efficient,
533
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
534
-            if (
535
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
536
-                && $update_ticket
537
-            ) {
538
-                $ticket = $this->ticket();
539
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
540
-            }
541
-        }
542
-    }
543
-
544
-
545
-    /**
546
-     * Set Attendee ID
547
-     *
548
-     * @param        int $ATT_ID Attendee ID
549
-     * @throws EE_Error
550
-     * @throws RuntimeException
551
-     */
552
-    public function set_attendee_id($ATT_ID = 0)
553
-    {
554
-        $this->set('ATT_ID', $ATT_ID);
555
-    }
556
-
557
-
558
-    /**
559
-     *        Set Transaction ID
560
-     *
561
-     * @param        int $TXN_ID Transaction ID
562
-     * @throws EE_Error
563
-     * @throws RuntimeException
564
-     */
565
-    public function set_transaction_id($TXN_ID = 0)
566
-    {
567
-        $this->set('TXN_ID', $TXN_ID);
568
-    }
569
-
570
-
571
-    /**
572
-     *        Set Session
573
-     *
574
-     * @param    string $REG_session PHP Session ID
575
-     * @throws EE_Error
576
-     * @throws RuntimeException
577
-     */
578
-    public function set_session($REG_session = '')
579
-    {
580
-        $this->set('REG_session', $REG_session);
581
-    }
582
-
583
-
584
-    /**
585
-     *        Set Registration URL Link
586
-     *
587
-     * @param    string $REG_url_link Registration URL Link
588
-     * @throws EE_Error
589
-     * @throws RuntimeException
590
-     */
591
-    public function set_reg_url_link($REG_url_link = '')
592
-    {
593
-        $this->set('REG_url_link', $REG_url_link);
594
-    }
595
-
596
-
597
-    /**
598
-     *        Set Attendee Counter
599
-     *
600
-     * @param        int $REG_count Primary Attendee
601
-     * @throws EE_Error
602
-     * @throws RuntimeException
603
-     */
604
-    public function set_count($REG_count = 1)
605
-    {
606
-        $this->set('REG_count', $REG_count);
607
-    }
608
-
609
-
610
-    /**
611
-     *        Set Group Size
612
-     *
613
-     * @param        boolean $REG_group_size Group Registration
614
-     * @throws EE_Error
615
-     * @throws RuntimeException
616
-     */
617
-    public function set_group_size($REG_group_size = false)
618
-    {
619
-        $this->set('REG_group_size', $REG_group_size);
620
-    }
621
-
622
-
623
-    /**
624
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
625
-     *    EEM_Registration::status_id_not_approved
626
-     *
627
-     * @return        boolean
628
-     */
629
-    public function is_not_approved()
630
-    {
631
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
632
-    }
633
-
634
-
635
-    /**
636
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
637
-     *    EEM_Registration::status_id_pending_payment
638
-     *
639
-     * @return        boolean
640
-     */
641
-    public function is_pending_payment()
642
-    {
643
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
644
-    }
645
-
646
-
647
-    /**
648
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
649
-     *
650
-     * @return        boolean
651
-     */
652
-    public function is_approved()
653
-    {
654
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
655
-    }
656
-
657
-
658
-    /**
659
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
660
-     *
661
-     * @return        boolean
662
-     */
663
-    public function is_cancelled()
664
-    {
665
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
666
-    }
667
-
668
-
669
-    /**
670
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
671
-     *
672
-     * @return        boolean
673
-     */
674
-    public function is_declined()
675
-    {
676
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
677
-    }
678
-
679
-
680
-    /**
681
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
682
-     *    EEM_Registration::status_id_incomplete
683
-     *
684
-     * @return        boolean
685
-     */
686
-    public function is_incomplete()
687
-    {
688
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
689
-    }
690
-
691
-
692
-    /**
693
-     *        Set Registration Date
694
-     *
695
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
696
-     *                                                 Date
697
-     * @throws EE_Error
698
-     * @throws RuntimeException
699
-     */
700
-    public function set_reg_date($REG_date = false)
701
-    {
702
-        $this->set('REG_date', $REG_date);
703
-    }
704
-
705
-
706
-    /**
707
-     *    Set final price owing for this registration after all ticket/price modifications
708
-     *
709
-     * @access    public
710
-     * @param    float $REG_final_price
711
-     * @throws EE_Error
712
-     * @throws RuntimeException
713
-     */
714
-    public function set_final_price($REG_final_price = 0.00)
715
-    {
716
-        $this->set('REG_final_price', $REG_final_price);
717
-    }
718
-
719
-
720
-    /**
721
-     *    Set amount paid towards this registration's final price
722
-     *
723
-     * @access    public
724
-     * @param    float $REG_paid
725
-     * @throws EE_Error
726
-     * @throws RuntimeException
727
-     */
728
-    public function set_paid($REG_paid = 0.00)
729
-    {
730
-        $this->set('REG_paid', $REG_paid);
731
-    }
732
-
733
-
734
-    /**
735
-     *        Attendee Is Going
736
-     *
737
-     * @param        boolean $REG_att_is_going Attendee Is Going
738
-     * @throws EE_Error
739
-     * @throws RuntimeException
740
-     */
741
-    public function set_att_is_going($REG_att_is_going = false)
742
-    {
743
-        $this->set('REG_att_is_going', $REG_att_is_going);
744
-    }
745
-
746
-
747
-    /**
748
-     * Gets the related attendee
749
-     *
750
-     * @return EE_Attendee
751
-     * @throws EE_Error
752
-     */
753
-    public function attendee()
754
-    {
755
-        return $this->get_first_related('Attendee');
756
-    }
757
-
758
-    /**
759
-     * Gets the name of the attendee.
760
-     * @since 4.10.12.p
761
-     * @param bool $apply_html_entities set to true if you want to use HTML entities.
762
-     * @return string
763
-     * @throws EE_Error
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     * @throws ReflectionException
768
-     */
769
-    public function attendeeName($apply_html_entities = false)
770
-    {
771
-        $attendee = $this->get_first_related('Attendee');
772
-        if ($attendee instanceof EE_Attendee) {
773
-            $attendee_name = $attendee->full_name($apply_html_entities);
774
-        } else {
775
-            $attendee_name = esc_html__('Unknown', 'event_espresso');
776
-        }
777
-        return $attendee_name;
778
-    }
779
-
780
-
781
-    /**
782
-     *        get Event ID
783
-     */
784
-    public function event_ID()
785
-    {
786
-        return $this->get('EVT_ID');
787
-    }
788
-
789
-
790
-    /**
791
-     *        get Event ID
792
-     */
793
-    public function event_name()
794
-    {
795
-        $event = $this->event_obj();
796
-        if ($event) {
797
-            return $event->name();
798
-        } else {
799
-            return null;
800
-        }
801
-    }
802
-
803
-
804
-    /**
805
-     * Fetches the event this registration is for
806
-     *
807
-     * @return EE_Event
808
-     * @throws EE_Error
809
-     */
810
-    public function event_obj()
811
-    {
812
-        return $this->get_first_related('Event');
813
-    }
814
-
815
-
816
-    /**
817
-     *        get Attendee ID
818
-     */
819
-    public function attendee_ID()
820
-    {
821
-        return $this->get('ATT_ID');
822
-    }
823
-
824
-
825
-    /**
826
-     *        get PHP Session ID
827
-     */
828
-    public function session_ID()
829
-    {
830
-        return $this->get('REG_session');
831
-    }
832
-
833
-
834
-    /**
835
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
836
-     *
837
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
838
-     * @return string
839
-     */
840
-    public function receipt_url($messenger = 'html')
841
-    {
842
-
843
-        /**
844
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
845
-         * already in use on old system.  If there is then we just return the standard url for it.
846
-         *
847
-         * @since 4.5.0
848
-         */
849
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
850
-        $has_custom = EEH_Template::locate_template(
851
-            $template_relative_path,
852
-            array(),
853
-            true,
854
-            true,
855
-            true
856
-        );
857
-
858
-        if ($has_custom) {
859
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
860
-        }
861
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
862
-    }
863
-
864
-
865
-    /**
866
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
867
-     *
868
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
869
-     * @return string
870
-     * @throws EE_Error
871
-     */
872
-    public function invoice_url($messenger = 'html')
873
-    {
874
-        /**
875
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
876
-         * already in use on old system.  If there is then we just return the standard url for it.
877
-         *
878
-         * @since 4.5.0
879
-         */
880
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
881
-        $has_custom = EEH_Template::locate_template(
882
-            $template_relative_path,
883
-            array(),
884
-            true,
885
-            true,
886
-            true
887
-        );
888
-
889
-        if ($has_custom) {
890
-            if ($messenger == 'html') {
891
-                return $this->invoice_url('launch');
892
-            }
893
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
894
-
895
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
896
-            if ($messenger == 'html') {
897
-                $query_args['html'] = true;
898
-            }
899
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
900
-        }
901
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
902
-    }
903
-
904
-
905
-    /**
906
-     * get Registration URL Link
907
-     *
908
-     * @access public
909
-     * @return string
910
-     * @throws EE_Error
911
-     */
912
-    public function reg_url_link()
913
-    {
914
-        return (string) $this->get('REG_url_link');
915
-    }
916
-
917
-
918
-    /**
919
-     * Echoes out invoice_url()
920
-     *
921
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
922
-     * @return void
923
-     * @throws EE_Error
924
-     */
925
-    public function e_invoice_url($type = 'launch')
926
-    {
927
-        echo esc_url_raw($this->invoice_url($type));
928
-    }
929
-
930
-
931
-    /**
932
-     * Echoes out payment_overview_url
933
-     */
934
-    public function e_payment_overview_url()
935
-    {
936
-        echo esc_url_raw($this->payment_overview_url());
937
-    }
938
-
939
-
940
-    /**
941
-     * Gets the URL for the checkout payment options reg step
942
-     * with this registration's REG_url_link added as a query parameter
943
-     *
944
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
945
-     *                            payment overview url.
946
-     * @return string
947
-     * @throws InvalidInterfaceException
948
-     * @throws InvalidDataTypeException
949
-     * @throws EE_Error
950
-     * @throws InvalidArgumentException
951
-     */
952
-    public function payment_overview_url($clear_session = false)
953
-    {
954
-        return add_query_arg(
955
-            (array) apply_filters(
956
-                'FHEE__EE_Registration__payment_overview_url__query_args',
957
-                array(
958
-                    'e_reg_url_link' => $this->reg_url_link(),
959
-                    'step'           => 'payment_options',
960
-                    'revisit'        => true,
961
-                    'clear_session'  => (bool) $clear_session,
962
-                ),
963
-                $this
964
-            ),
965
-            EE_Registry::instance()->CFG->core->reg_page_url()
966
-        );
967
-    }
968
-
969
-
970
-    /**
971
-     * Gets the URL for the checkout attendee information reg step
972
-     * with this registration's REG_url_link added as a query parameter
973
-     *
974
-     * @return string
975
-     * @throws InvalidInterfaceException
976
-     * @throws InvalidDataTypeException
977
-     * @throws EE_Error
978
-     * @throws InvalidArgumentException
979
-     */
980
-    public function edit_attendee_information_url()
981
-    {
982
-        return add_query_arg(
983
-            (array) apply_filters(
984
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
985
-                array(
986
-                    'e_reg_url_link' => $this->reg_url_link(),
987
-                    'step'           => 'attendee_information',
988
-                    'revisit'        => true,
989
-                ),
990
-                $this
991
-            ),
992
-            EE_Registry::instance()->CFG->core->reg_page_url()
993
-        );
994
-    }
995
-
996
-
997
-    /**
998
-     * Simply generates and returns the appropriate admin_url link to edit this registration
999
-     *
1000
-     * @return string
1001
-     * @throws EE_Error
1002
-     */
1003
-    public function get_admin_edit_url()
1004
-    {
1005
-        return EEH_URL::add_query_args_and_nonce(
1006
-            array(
1007
-                'page'    => 'espresso_registrations',
1008
-                'action'  => 'view_registration',
1009
-                '_REG_ID' => $this->ID(),
1010
-            ),
1011
-            admin_url('admin.php')
1012
-        );
1013
-    }
1014
-
1015
-
1016
-    /**
1017
-     *    is_primary_registrant?
1018
-     */
1019
-    public function is_primary_registrant()
1020
-    {
1021
-        return $this->get('REG_count') === 1 ? true : false;
1022
-    }
1023
-
1024
-
1025
-    /**
1026
-     * This returns the primary registration object for this registration group (which may be this object).
1027
-     *
1028
-     * @return EE_Registration
1029
-     * @throws EE_Error
1030
-     */
1031
-    public function get_primary_registration()
1032
-    {
1033
-        if ($this->is_primary_registrant()) {
1034
-            return $this;
1035
-        }
1036
-
1037
-        // k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1038
-        /** @var EE_Registration $primary_registrant */
1039
-        $primary_registrant = EEM_Registration::instance()->get_one(
1040
-            array(
1041
-                array(
1042
-                    'TXN_ID'    => $this->transaction_ID(),
1043
-                    'REG_count' => 1,
1044
-                ),
1045
-            )
1046
-        );
1047
-        return $primary_registrant;
1048
-    }
1049
-
1050
-
1051
-    /**
1052
-     *        get  Attendee Number
1053
-     *
1054
-     * @access        public
1055
-     */
1056
-    public function count()
1057
-    {
1058
-        return $this->get('REG_count');
1059
-    }
1060
-
1061
-
1062
-    /**
1063
-     *        get Group Size
1064
-     */
1065
-    public function group_size()
1066
-    {
1067
-        return $this->get('REG_group_size');
1068
-    }
1069
-
1070
-
1071
-    /**
1072
-     *        get Registration Date
1073
-     */
1074
-    public function date()
1075
-    {
1076
-        return $this->get('REG_date');
1077
-    }
1078
-
1079
-
1080
-    /**
1081
-     * gets a pretty date
1082
-     *
1083
-     * @param string $date_format
1084
-     * @param string $time_format
1085
-     * @return string
1086
-     * @throws EE_Error
1087
-     */
1088
-    public function pretty_date($date_format = null, $time_format = null)
1089
-    {
1090
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     * final_price
1096
-     * the registration's share of the transaction total, so that the
1097
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1098
-     *
1099
-     * @return float
1100
-     * @throws EE_Error
1101
-     */
1102
-    public function final_price()
1103
-    {
1104
-        return $this->get('REG_final_price');
1105
-    }
1106
-
1107
-
1108
-    /**
1109
-     * pretty_final_price
1110
-     *  final price as formatted string, with correct decimal places and currency symbol
1111
-     *
1112
-     * @return string
1113
-     * @throws EE_Error
1114
-     */
1115
-    public function pretty_final_price()
1116
-    {
1117
-        return $this->get_pretty('REG_final_price');
1118
-    }
1119
-
1120
-
1121
-    /**
1122
-     * get paid (yeah)
1123
-     *
1124
-     * @return float
1125
-     * @throws EE_Error
1126
-     */
1127
-    public function paid()
1128
-    {
1129
-        return $this->get('REG_paid');
1130
-    }
1131
-
1132
-
1133
-    /**
1134
-     * pretty_paid
1135
-     *
1136
-     * @return float
1137
-     * @throws EE_Error
1138
-     */
1139
-    public function pretty_paid()
1140
-    {
1141
-        return $this->get_pretty('REG_paid');
1142
-    }
1143
-
1144
-
1145
-    /**
1146
-     * owes_monies_and_can_pay
1147
-     * whether or not this registration has monies owing and it's' status allows payment
1148
-     *
1149
-     * @param array $requires_payment
1150
-     * @return bool
1151
-     * @throws EE_Error
1152
-     */
1153
-    public function owes_monies_and_can_pay($requires_payment = array())
1154
-    {
1155
-        // these reg statuses require payment (if event is not free)
1156
-        $requires_payment = ! empty($requires_payment)
1157
-            ? $requires_payment
1158
-            : EEM_Registration::reg_statuses_that_allow_payment();
1159
-        if (
1160
-            in_array($this->status_ID(), $requires_payment) &&
1161
-            $this->final_price() != 0 &&
1162
-            $this->final_price() != $this->paid()
1163
-        ) {
1164
-            return true;
1165
-        } else {
1166
-            return false;
1167
-        }
1168
-    }
1169
-
1170
-
1171
-    /**
1172
-     * Prints out the return value of $this->pretty_status()
1173
-     *
1174
-     * @param bool $show_icons
1175
-     * @return void
1176
-     * @throws EE_Error
1177
-     */
1178
-    public function e_pretty_status($show_icons = false)
1179
-    {
1180
-        echo $this->pretty_status($show_icons); // already escaped
1181
-    }
1182
-
1183
-
1184
-    /**
1185
-     * Returns a nice version of the status for displaying to customers
1186
-     *
1187
-     * @param bool $show_icons
1188
-     * @return string
1189
-     * @throws EE_Error
1190
-     */
1191
-    public function pretty_status($show_icons = false)
1192
-    {
1193
-        $status = EEM_Status::instance()->localized_status(
1194
-            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1195
-            false,
1196
-            'sentence'
1197
-        );
1198
-        $icon = '';
1199
-        switch ($this->status_ID()) {
1200
-            case EEM_Registration::status_id_approved:
1201
-                $icon = $show_icons
1202
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1203
-                    : '';
1204
-                break;
1205
-            case EEM_Registration::status_id_pending_payment:
1206
-                $icon = $show_icons
1207
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1208
-                    : '';
1209
-                break;
1210
-            case EEM_Registration::status_id_not_approved:
1211
-                $icon = $show_icons
1212
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1213
-                    : '';
1214
-                break;
1215
-            case EEM_Registration::status_id_cancelled:
1216
-                $icon = $show_icons
1217
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1218
-                    : '';
1219
-                break;
1220
-            case EEM_Registration::status_id_incomplete:
1221
-                $icon = $show_icons
1222
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1223
-                    : '';
1224
-                break;
1225
-            case EEM_Registration::status_id_declined:
1226
-                $icon = $show_icons
1227
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1228
-                    : '';
1229
-                break;
1230
-            case EEM_Registration::status_id_wait_list:
1231
-                $icon = $show_icons
1232
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1233
-                    : '';
1234
-                break;
1235
-        }
1236
-        return $icon . $status[ $this->status_ID() ];
1237
-    }
1238
-
1239
-
1240
-    /**
1241
-     *        get Attendee Is Going
1242
-     */
1243
-    public function att_is_going()
1244
-    {
1245
-        return $this->get('REG_att_is_going');
1246
-    }
1247
-
1248
-
1249
-    /**
1250
-     * Gets related answers
1251
-     *
1252
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1253
-     * @return EE_Answer[]
1254
-     * @throws EE_Error
1255
-     */
1256
-    public function answers($query_params = null)
1257
-    {
1258
-        return $this->get_many_related('Answer', $query_params);
1259
-    }
1260
-
1261
-
1262
-    /**
1263
-     * Gets the registration's answer value to the specified question
1264
-     * (either the question's ID or a question object)
1265
-     *
1266
-     * @param EE_Question|int $question
1267
-     * @param bool            $pretty_value
1268
-     * @return array|string if pretty_value= true, the result will always be a string
1269
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1270
-     * will convert it into some kind of string)
1271
-     * @throws EE_Error
1272
-     */
1273
-    public function answer_value_to_question($question, $pretty_value = true)
1274
-    {
1275
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1276
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1277
-    }
1278
-
1279
-
1280
-    /**
1281
-     * question_groups
1282
-     * returns an array of EE_Question_Group objects for this registration
1283
-     *
1284
-     * @return EE_Question_Group[]
1285
-     * @throws EE_Error
1286
-     * @throws InvalidArgumentException
1287
-     * @throws InvalidDataTypeException
1288
-     * @throws InvalidInterfaceException
1289
-     * @throws ReflectionException
1290
-     */
1291
-    public function question_groups()
1292
-    {
1293
-        return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1294
-    }
1295
-
1296
-
1297
-    /**
1298
-     * count_question_groups
1299
-     * returns a count of the number of EE_Question_Group objects for this registration
1300
-     *
1301
-     * @return int
1302
-     * @throws EE_Error
1303
-     * @throws EntityNotFoundException
1304
-     * @throws InvalidArgumentException
1305
-     * @throws InvalidDataTypeException
1306
-     * @throws InvalidInterfaceException
1307
-     * @throws ReflectionException
1308
-     */
1309
-    public function count_question_groups()
1310
-    {
1311
-        return EEM_Event::instance()->count_related(
1312
-            $this->event_ID(),
1313
-            'Question_Group',
1314
-            [
1315
-                [
1316
-                    'Event_Question_Group.'
1317
-                    . EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1318
-                ]
1319
-            ]
1320
-        );
1321
-    }
1322
-
1323
-
1324
-    /**
1325
-     * Returns the registration date in the 'standard' string format
1326
-     * (function may be improved in the future to allow for different formats and timezones)
1327
-     *
1328
-     * @return string
1329
-     * @throws EE_Error
1330
-     */
1331
-    public function reg_date()
1332
-    {
1333
-        return $this->get_datetime('REG_date');
1334
-    }
1335
-
1336
-
1337
-    /**
1338
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1339
-     * the ticket this registration purchased, or the datetime they have registered
1340
-     * to attend)
1341
-     *
1342
-     * @return EE_Datetime_Ticket
1343
-     * @throws EE_Error
1344
-     */
1345
-    public function datetime_ticket()
1346
-    {
1347
-        return $this->get_first_related('Datetime_Ticket');
1348
-    }
1349
-
1350
-
1351
-    /**
1352
-     * Sets the registration's datetime_ticket.
1353
-     *
1354
-     * @param EE_Datetime_Ticket $datetime_ticket
1355
-     * @return EE_Datetime_Ticket
1356
-     * @throws EE_Error
1357
-     */
1358
-    public function set_datetime_ticket($datetime_ticket)
1359
-    {
1360
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1361
-    }
1362
-
1363
-    /**
1364
-     * Gets deleted
1365
-     *
1366
-     * @return bool
1367
-     * @throws EE_Error
1368
-     */
1369
-    public function deleted()
1370
-    {
1371
-        return $this->get('REG_deleted');
1372
-    }
1373
-
1374
-    /**
1375
-     * Sets deleted
1376
-     *
1377
-     * @param boolean $deleted
1378
-     * @return bool
1379
-     * @throws EE_Error
1380
-     * @throws RuntimeException
1381
-     */
1382
-    public function set_deleted($deleted)
1383
-    {
1384
-        if ($deleted) {
1385
-            $this->delete();
1386
-        } else {
1387
-            $this->restore();
1388
-        }
1389
-    }
1390
-
1391
-
1392
-    /**
1393
-     * Get the status object of this object
1394
-     *
1395
-     * @return EE_Status
1396
-     * @throws EE_Error
1397
-     */
1398
-    public function status_obj()
1399
-    {
1400
-        return $this->get_first_related('Status');
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * Returns the number of times this registration has checked into any of the datetimes
1406
-     * its available for
1407
-     *
1408
-     * @return int
1409
-     * @throws EE_Error
1410
-     */
1411
-    public function count_checkins()
1412
-    {
1413
-        return $this->get_model()->count_related($this, 'Checkin');
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1419
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1420
-     *
1421
-     * @return int
1422
-     * @throws EE_Error
1423
-     */
1424
-    public function count_checkins_not_checkedout()
1425
-    {
1426
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1427
-    }
1428
-
1429
-
1430
-    /**
1431
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1432
-     *
1433
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1434
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1435
-     *                                          consider registration status as well as datetime access.
1436
-     * @return bool
1437
-     * @throws EE_Error
1438
-     */
1439
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1440
-    {
1441
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1442
-
1443
-        // first check registration status
1444
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1445
-            return false;
1446
-        }
1447
-        // is there a datetime ticket that matches this dtt_ID?
1448
-        if (
1449
-            ! (EEM_Datetime_Ticket::instance()->exists(
1450
-                array(
1451
-                array(
1452
-                    'TKT_ID' => $this->get('TKT_ID'),
1453
-                    'DTT_ID' => $DTT_ID,
1454
-                ),
1455
-                )
1456
-            ))
1457
-        ) {
1458
-            return false;
1459
-        }
1460
-
1461
-        // final check is against TKT_uses
1462
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1463
-    }
1464
-
1465
-
1466
-    /**
1467
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1468
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1469
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1470
-     * then return false.  Otherwise return true.
1471
-     *
1472
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1473
-     * @return bool true means can checkin.  false means cannot checkin.
1474
-     * @throws EE_Error
1475
-     */
1476
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1477
-    {
1478
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1479
-
1480
-        if (! $DTT_ID) {
1481
-            return false;
1482
-        }
1483
-
1484
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1485
-
1486
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1487
-        // check-in or not.
1488
-        if (! $max_uses || $max_uses === EE_INF) {
1489
-            return true;
1490
-        }
1491
-
1492
-        // does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1493
-        // go ahead and toggle.
1494
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1495
-            return true;
1496
-        }
1497
-
1498
-        // made it here so the last check is whether the number of checkins per unique datetime on this registration
1499
-        // disallows further check-ins.
1500
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1501
-            array(
1502
-                array(
1503
-                    'REG_ID' => $this->ID(),
1504
-                    'CHK_in' => true,
1505
-                ),
1506
-            ),
1507
-            'DTT_ID',
1508
-            true
1509
-        );
1510
-        // checkins have already reached their max number of uses
1511
-        // so registrant can NOT checkin
1512
-        if ($count_unique_dtt_checkins >= $max_uses) {
1513
-            EE_Error::add_error(
1514
-                esc_html__(
1515
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1516
-                    'event_espresso'
1517
-                ),
1518
-                __FILE__,
1519
-                __FUNCTION__,
1520
-                __LINE__
1521
-            );
1522
-            return false;
1523
-        }
1524
-        return true;
1525
-    }
1526
-
1527
-
1528
-    /**
1529
-     * toggle Check-in status for this registration
1530
-     * Check-ins are toggled in the following order:
1531
-     * never checked in -> checked in
1532
-     * checked in -> checked out
1533
-     * checked out -> checked in
1534
-     *
1535
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1536
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1537
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1538
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1539
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1540
-     * @throws EE_Error
1541
-     */
1542
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1543
-    {
1544
-        if (empty($DTT_ID)) {
1545
-            $datetime = $this->get_latest_related_datetime();
1546
-            $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1547
-            // verify the registration can checkin for the given DTT_ID
1548
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1549
-            EE_Error::add_error(
1550
-                sprintf(
1551
-                    esc_html__(
1552
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1553
-                        'event_espresso'
1554
-                    ),
1555
-                    $this->ID(),
1556
-                    $DTT_ID
1557
-                ),
1558
-                __FILE__,
1559
-                __FUNCTION__,
1560
-                __LINE__
1561
-            );
1562
-            return false;
1563
-        }
1564
-        $status_paths = array(
1565
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1566
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1567
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1568
-        );
1569
-        // start by getting the current status so we know what status we'll be changing to.
1570
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1571
-        $status_to = $status_paths[ $cur_status ];
1572
-        // database only records true for checked IN or false for checked OUT
1573
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1574
-        $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1575
-        // add relation - note Check-ins are always creating new rows
1576
-        // because we are keeping track of Check-ins over time.
1577
-        // Eventually we'll probably want to show a list table
1578
-        // for the individual Check-ins so that they can be managed.
1579
-        $checkin = EE_Checkin::new_instance(
1580
-            array(
1581
-                'REG_ID' => $this->ID(),
1582
-                'DTT_ID' => $DTT_ID,
1583
-                'CHK_in' => $new_status,
1584
-            )
1585
-        );
1586
-        // if the record could not be saved then return false
1587
-        if ($checkin->save() === 0) {
1588
-            if (WP_DEBUG) {
1589
-                global $wpdb;
1590
-                $error = sprintf(
1591
-                    esc_html__(
1592
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1593
-                        'event_espresso'
1594
-                    ),
1595
-                    '<br />',
1596
-                    $wpdb->last_error
1597
-                );
1598
-            } else {
1599
-                $error = esc_html__(
1600
-                    'Registration check in update failed because of an unknown database error',
1601
-                    'event_espresso'
1602
-                );
1603
-            }
1604
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1605
-            return false;
1606
-        }
1607
-        // Fire a checked_in and checkout_out action.
1608
-        $checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1609
-        do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1610
-        return $status_to;
1611
-    }
1612
-
1613
-
1614
-    /**
1615
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1616
-     * "Latest" is defined by the `DTT_EVT_start` column.
1617
-     *
1618
-     * @return EE_Datetime|null
1619
-     * @throws EE_Error
1620
-     */
1621
-    public function get_latest_related_datetime()
1622
-    {
1623
-        return EEM_Datetime::instance()->get_one(
1624
-            array(
1625
-                array(
1626
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1627
-                ),
1628
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1629
-            )
1630
-        );
1631
-    }
1632
-
1633
-
1634
-    /**
1635
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1636
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1637
-     *
1638
-     * @throws EE_Error
1639
-     */
1640
-    public function get_earliest_related_datetime()
1641
-    {
1642
-        return EEM_Datetime::instance()->get_one(
1643
-            array(
1644
-                array(
1645
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1646
-                ),
1647
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1648
-            )
1649
-        );
1650
-    }
1651
-
1652
-
1653
-    /**
1654
-     * This method simply returns the check-in status for this registration and the given datetime.
1655
-     * If neither the datetime nor the checkin values are provided as arguments,
1656
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1657
-     *
1658
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1659
-     *                            (if empty we'll get the primary datetime for
1660
-     *                            this registration (via event) and use it's ID);
1661
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1662
-     *
1663
-     * @return int                Integer representing Check-in status.
1664
-     * @throws EE_Error
1665
-     */
1666
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1667
-    {
1668
-        $checkin_query_params = array(
1669
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1670
-        );
1671
-
1672
-        if ($DTT_ID > 0) {
1673
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1674
-        }
1675
-
1676
-        // get checkin object (if exists)
1677
-        $checkin = $checkin instanceof EE_Checkin
1678
-            ? $checkin
1679
-            : $this->get_first_related('Checkin', $checkin_query_params);
1680
-        if ($checkin instanceof EE_Checkin) {
1681
-            if ($checkin->get('CHK_in')) {
1682
-                return EE_Checkin::status_checked_in; // checked in
1683
-            }
1684
-            return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1685
-        }
1686
-        return EE_Checkin::status_checked_never; // never been checked in
1687
-    }
1688
-
1689
-
1690
-    /**
1691
-     * This method returns a localized message for the toggled Check-in message.
1692
-     *
1693
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1694
-     *                     then it is assumed Check-in for primary datetime was toggled.
1695
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1696
-     *                     message can be customized with the attendee name.
1697
-     * @return string internationalized message
1698
-     * @throws EE_Error
1699
-     */
1700
-    public function get_checkin_msg($DTT_ID, $error = false)
1701
-    {
1702
-        // let's get the attendee first so we can include the name of the attendee
1703
-        $attendee = $this->get_first_related('Attendee');
1704
-        if ($attendee instanceof EE_Attendee) {
1705
-            if ($error) {
1706
-                return sprintf(esc_html__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1707
-            }
1708
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1709
-            // what is the status message going to be?
1710
-            switch ($cur_status) {
1711
-                case EE_Checkin::status_checked_never:
1712
-                    return sprintf(
1713
-                        esc_html__("%s has been removed from Check-in records", "event_espresso"),
1714
-                        $attendee->full_name()
1715
-                    );
1716
-                    break;
1717
-                case EE_Checkin::status_checked_in:
1718
-                    return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1719
-                    break;
1720
-                case EE_Checkin::status_checked_out:
1721
-                    return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1722
-                    break;
1723
-            }
1724
-        }
1725
-        return esc_html__("The check-in status could not be determined.", "event_espresso");
1726
-    }
1727
-
1728
-
1729
-    /**
1730
-     * Returns the related EE_Transaction to this registration
1731
-     *
1732
-     * @return EE_Transaction
1733
-     * @throws EE_Error
1734
-     * @throws EntityNotFoundException
1735
-     */
1736
-    public function transaction()
1737
-    {
1738
-        $transaction = $this->get_first_related('Transaction');
1739
-        if (! $transaction instanceof \EE_Transaction) {
1740
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1741
-        }
1742
-        return $transaction;
1743
-    }
1744
-
1745
-
1746
-    /**
1747
-     *        get Registration Code
1748
-     */
1749
-    public function reg_code()
1750
-    {
1751
-        return $this->get('REG_code');
1752
-    }
1753
-
1754
-
1755
-    /**
1756
-     *        get Transaction ID
1757
-     */
1758
-    public function transaction_ID()
1759
-    {
1760
-        return $this->get('TXN_ID');
1761
-    }
1762
-
1763
-
1764
-    /**
1765
-     * @return int
1766
-     * @throws EE_Error
1767
-     */
1768
-    public function ticket_ID()
1769
-    {
1770
-        return $this->get('TKT_ID');
1771
-    }
1772
-
1773
-
1774
-    /**
1775
-     *        Set Registration Code
1776
-     *
1777
-     * @access    public
1778
-     * @param    string  $REG_code Registration Code
1779
-     * @param    boolean $use_default
1780
-     * @throws EE_Error
1781
-     */
1782
-    public function set_reg_code($REG_code, $use_default = false)
1783
-    {
1784
-        if (empty($REG_code)) {
1785
-            EE_Error::add_error(
1786
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
1787
-                __FILE__,
1788
-                __FUNCTION__,
1789
-                __LINE__
1790
-            );
1791
-            return;
1792
-        }
1793
-        if (! $this->reg_code()) {
1794
-            parent::set('REG_code', $REG_code, $use_default);
1795
-        } else {
1796
-            EE_Error::doing_it_wrong(
1797
-                __CLASS__ . '::' . __FUNCTION__,
1798
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1799
-                '4.6.0'
1800
-            );
1801
-        }
1802
-    }
1803
-
1804
-
1805
-    /**
1806
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1807
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1808
-     *    $registration->transaction()->registrations();
1809
-     *
1810
-     * @since 4.5.0
1811
-     * @return EE_Registration[] or empty array if this isn't a group registration.
1812
-     * @throws EE_Error
1813
-     */
1814
-    public function get_all_other_registrations_in_group()
1815
-    {
1816
-        if ($this->group_size() < 2) {
1817
-            return array();
1818
-        }
1819
-
1820
-        $query[0] = array(
1821
-            'TXN_ID' => $this->transaction_ID(),
1822
-            'REG_ID' => array('!=', $this->ID()),
1823
-            'TKT_ID' => $this->ticket_ID(),
1824
-        );
1825
-        /** @var EE_Registration[] $registrations */
1826
-        $registrations = $this->get_model()->get_all($query);
1827
-        return $registrations;
1828
-    }
1829
-
1830
-    /**
1831
-     * Return the link to the admin details for the object.
1832
-     *
1833
-     * @return string
1834
-     * @throws EE_Error
1835
-     */
1836
-    public function get_admin_details_link()
1837
-    {
1838
-        EE_Registry::instance()->load_helper('URL');
1839
-        return EEH_URL::add_query_args_and_nonce(
1840
-            array(
1841
-                'page'    => 'espresso_registrations',
1842
-                'action'  => 'view_registration',
1843
-                '_REG_ID' => $this->ID(),
1844
-            ),
1845
-            admin_url('admin.php')
1846
-        );
1847
-    }
1848
-
1849
-    /**
1850
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1851
-     *
1852
-     * @return string
1853
-     * @throws EE_Error
1854
-     */
1855
-    public function get_admin_edit_link()
1856
-    {
1857
-        return $this->get_admin_details_link();
1858
-    }
1859
-
1860
-    /**
1861
-     * Returns the link to a settings page for the object.
1862
-     *
1863
-     * @return string
1864
-     * @throws EE_Error
1865
-     */
1866
-    public function get_admin_settings_link()
1867
-    {
1868
-        return $this->get_admin_details_link();
1869
-    }
1870
-
1871
-    /**
1872
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1873
-     *
1874
-     * @return string
1875
-     */
1876
-    public function get_admin_overview_link()
1877
-    {
1878
-        EE_Registry::instance()->load_helper('URL');
1879
-        return EEH_URL::add_query_args_and_nonce(
1880
-            array(
1881
-                'page' => 'espresso_registrations',
1882
-            ),
1883
-            admin_url('admin.php')
1884
-        );
1885
-    }
1886
-
1887
-
1888
-    /**
1889
-     * @param array $query_params
1890
-     *
1891
-     * @return \EE_Registration[]
1892
-     * @throws EE_Error
1893
-     */
1894
-    public function payments($query_params = array())
1895
-    {
1896
-        return $this->get_many_related('Payment', $query_params);
1897
-    }
1898
-
1899
-
1900
-    /**
1901
-     * @param array $query_params
1902
-     *
1903
-     * @return \EE_Registration_Payment[]
1904
-     * @throws EE_Error
1905
-     */
1906
-    public function registration_payments($query_params = array())
1907
-    {
1908
-        return $this->get_many_related('Registration_Payment', $query_params);
1909
-    }
1910
-
1911
-
1912
-    /**
1913
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1914
-     * Note: if there are no payments on the registration there will be no payment method returned.
1915
-     *
1916
-     * @return EE_Payment_Method|null
1917
-     */
1918
-    public function payment_method()
1919
-    {
1920
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1921
-    }
1922
-
1923
-
1924
-    /**
1925
-     * @return \EE_Line_Item
1926
-     * @throws EntityNotFoundException
1927
-     * @throws EE_Error
1928
-     */
1929
-    public function ticket_line_item()
1930
-    {
1931
-        $ticket = $this->ticket();
1932
-        $transaction = $this->transaction();
1933
-        $line_item = null;
1934
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1935
-            $transaction->total_line_item(),
1936
-            'Ticket',
1937
-            array($ticket->ID())
1938
-        );
1939
-        foreach ($ticket_line_items as $ticket_line_item) {
1940
-            if (
1941
-                $ticket_line_item instanceof \EE_Line_Item
1942
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1943
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1944
-            ) {
1945
-                $line_item = $ticket_line_item;
1946
-                break;
1947
-            }
1948
-        }
1949
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1950
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1951
-        }
1952
-        return $line_item;
1953
-    }
1954
-
1955
-
1956
-    /**
1957
-     * Soft Deletes this model object.
1958
-     *
1959
-     * @return boolean | int
1960
-     * @throws RuntimeException
1961
-     * @throws EE_Error
1962
-     */
1963
-    public function delete()
1964
-    {
1965
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1966
-            $this->set_status(EEM_Registration::status_id_cancelled);
1967
-        }
1968
-        return parent::delete();
1969
-    }
1970
-
1971
-
1972
-    /**
1973
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1974
-     *
1975
-     * @throws EE_Error
1976
-     * @throws RuntimeException
1977
-     */
1978
-    public function restore()
1979
-    {
1980
-        $previous_status = $this->get_extra_meta(
1981
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1982
-            true,
1983
-            EEM_Registration::status_id_cancelled
1984
-        );
1985
-        if ($previous_status) {
1986
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1987
-            $this->set_status($previous_status);
1988
-        }
1989
-        return parent::restore();
1990
-    }
1991
-
1992
-
1993
-    /**
1994
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1995
-     *
1996
-     * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1997
-     *                                           depending on whether the reg status changes to or from "Approved"
1998
-     * @return boolean whether the Registration status was updated
1999
-     * @throws EE_Error
2000
-     * @throws RuntimeException
2001
-     */
2002
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2003
-    {
2004
-        $paid = $this->paid();
2005
-        $price = $this->final_price();
2006
-        switch (true) {
2007
-            // overpaid or paid
2008
-            case EEH_Money::compare_floats($paid, $price, '>'):
2009
-            case EEH_Money::compare_floats($paid, $price):
2010
-                $new_status = EEM_Registration::status_id_approved;
2011
-                break;
2012
-            //  underpaid
2013
-            case EEH_Money::compare_floats($paid, $price, '<'):
2014
-                $new_status = EEM_Registration::status_id_pending_payment;
2015
-                break;
2016
-            // uhhh Houston...
2017
-            default:
2018
-                throw new RuntimeException(
2019
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2020
-                );
2021
-        }
2022
-        if ($new_status !== $this->status_ID()) {
2023
-            if ($trigger_set_status_logic) {
2024
-                return $this->set_status($new_status);
2025
-            }
2026
-            parent::set('STS_ID', $new_status);
2027
-            return true;
2028
-        }
2029
-        return false;
2030
-    }
2031
-
2032
-
2033
-    /*************************** DEPRECATED ***************************/
2034
-
2035
-
2036
-    /**
2037
-     * @deprecated
2038
-     * @since     4.7.0
2039
-     * @access    public
2040
-     */
2041
-    public function price_paid()
2042
-    {
2043
-        EE_Error::doing_it_wrong(
2044
-            'EE_Registration::price_paid()',
2045
-            esc_html__(
2046
-                'This method is deprecated, please use EE_Registration::final_price() instead.',
2047
-                'event_espresso'
2048
-            ),
2049
-            '4.7.0'
2050
-        );
2051
-        return $this->final_price();
2052
-    }
2053
-
2054
-
2055
-    /**
2056
-     * @deprecated
2057
-     * @since     4.7.0
2058
-     * @access    public
2059
-     * @param    float $REG_final_price
2060
-     * @throws EE_Error
2061
-     * @throws RuntimeException
2062
-     */
2063
-    public function set_price_paid($REG_final_price = 0.00)
2064
-    {
2065
-        EE_Error::doing_it_wrong(
2066
-            'EE_Registration::set_price_paid()',
2067
-            esc_html__(
2068
-                'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2069
-                'event_espresso'
2070
-            ),
2071
-            '4.7.0'
2072
-        );
2073
-        $this->set_final_price($REG_final_price);
2074
-    }
2075
-
2076
-
2077
-    /**
2078
-     * @deprecated
2079
-     * @since 4.7.0
2080
-     * @return string
2081
-     * @throws EE_Error
2082
-     */
2083
-    public function pretty_price_paid()
2084
-    {
2085
-        EE_Error::doing_it_wrong(
2086
-            'EE_Registration::pretty_price_paid()',
2087
-            esc_html__(
2088
-                'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2089
-                'event_espresso'
2090
-            ),
2091
-            '4.7.0'
2092
-        );
2093
-        return $this->pretty_final_price();
2094
-    }
2095
-
2096
-
2097
-    /**
2098
-     * Gets the primary datetime related to this registration via the related Event to this registration
2099
-     *
2100
-     * @deprecated 4.9.17
2101
-     * @return EE_Datetime
2102
-     * @throws EE_Error
2103
-     * @throws EntityNotFoundException
2104
-     */
2105
-    public function get_related_primary_datetime()
2106
-    {
2107
-        EE_Error::doing_it_wrong(
2108
-            __METHOD__,
2109
-            esc_html__(
2110
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2111
-                'event_espresso'
2112
-            ),
2113
-            '4.9.17',
2114
-            '5.0.0'
2115
-        );
2116
-        return $this->event()->primary_datetime();
2117
-    }
2118
-
2119
-    /**
2120
-     * Returns the contact's name (or "Unknown" if there is no contact.)
2121
-     * @since 4.10.12.p
2122
-     * @return string
2123
-     * @throws EE_Error
2124
-     * @throws InvalidArgumentException
2125
-     * @throws InvalidDataTypeException
2126
-     * @throws InvalidInterfaceException
2127
-     * @throws ReflectionException
2128
-     */
2129
-    public function name()
2130
-    {
2131
-        return $this->attendeeName();
2132
-    }
20
+	/**
21
+	 * Used to reference when a registration has never been checked in.
22
+	 *
23
+	 * @deprecated use \EE_Checkin::status_checked_never instead
24
+	 * @type int
25
+	 */
26
+	const checkin_status_never = 2;
27
+
28
+	/**
29
+	 * Used to reference when a registration has been checked in.
30
+	 *
31
+	 * @deprecated use \EE_Checkin::status_checked_in instead
32
+	 * @type int
33
+	 */
34
+	const checkin_status_in = 1;
35
+
36
+
37
+	/**
38
+	 * Used to reference when a registration has been checked out.
39
+	 *
40
+	 * @deprecated use \EE_Checkin::status_checked_out instead
41
+	 * @type int
42
+	 */
43
+	const checkin_status_out = 0;
44
+
45
+
46
+	/**
47
+	 * extra meta key for tracking reg status os trashed registrations
48
+	 *
49
+	 * @type string
50
+	 */
51
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
52
+
53
+
54
+	/**
55
+	 * extra meta key for tracking if registration has reserved ticket
56
+	 *
57
+	 * @type string
58
+	 */
59
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
60
+
61
+
62
+	/**
63
+	 * @param array  $props_n_values          incoming values
64
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
65
+	 *                                        used.)
66
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
67
+	 *                                        date_format and the second value is the time format
68
+	 * @return EE_Registration
69
+	 * @throws EE_Error
70
+	 */
71
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
72
+	{
73
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
74
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param array  $props_n_values  incoming values from the database
80
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
+	 *                                the website will be used.
82
+	 * @return EE_Registration
83
+	 */
84
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
85
+	{
86
+		return new self($props_n_values, true, $timezone);
87
+	}
88
+
89
+
90
+	/**
91
+	 *        Set Event ID
92
+	 *
93
+	 * @param        int $EVT_ID Event ID
94
+	 * @throws EE_Error
95
+	 * @throws RuntimeException
96
+	 */
97
+	public function set_event($EVT_ID = 0)
98
+	{
99
+		$this->set('EVT_ID', $EVT_ID);
100
+	}
101
+
102
+
103
+	/**
104
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
105
+	 * be routed to internal methods
106
+	 *
107
+	 * @param string $field_name
108
+	 * @param mixed  $field_value
109
+	 * @param bool   $use_default
110
+	 * @throws EE_Error
111
+	 * @throws EntityNotFoundException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidDataTypeException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws ReflectionException
116
+	 * @throws RuntimeException
117
+	 */
118
+	public function set($field_name, $field_value, $use_default = false)
119
+	{
120
+		switch ($field_name) {
121
+			case 'REG_code':
122
+				if (! empty($field_value) && $this->reg_code() === null) {
123
+					$this->set_reg_code($field_value, $use_default);
124
+				}
125
+				break;
126
+			case 'STS_ID':
127
+				$this->set_status($field_value, $use_default);
128
+				break;
129
+			default:
130
+				parent::set($field_name, $field_value, $use_default);
131
+		}
132
+	}
133
+
134
+
135
+	/**
136
+	 * Set Status ID
137
+	 * updates the registration status and ALSO...
138
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
139
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
140
+	 *
141
+	 * @param string                $new_STS_ID
142
+	 * @param boolean               $use_default
143
+	 * @param ContextInterface|null $context
144
+	 * @return bool
145
+	 * @throws DomainException
146
+	 * @throws EE_Error
147
+	 * @throws EntityNotFoundException
148
+	 * @throws InvalidArgumentException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws InvalidInterfaceException
151
+	 * @throws ReflectionException
152
+	 * @throws RuntimeException
153
+	 * @throws UnexpectedEntityException
154
+	 */
155
+	public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
156
+	{
157
+		// get current REG_Status
158
+		$old_STS_ID = $this->status_ID();
159
+		// if status has changed
160
+		if (
161
+			$old_STS_ID !== $new_STS_ID // and that status has actually changed
162
+			&& ! empty($old_STS_ID) // and that old status is actually set
163
+			&& ! empty($new_STS_ID) // as well as the new status
164
+			&& $this->ID() // ensure registration is in the db
165
+		) {
166
+			// update internal status first
167
+			parent::set('STS_ID', $new_STS_ID, $use_default);
168
+			// THEN handle other changes that occur when reg status changes
169
+			// TO approved
170
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
171
+				// reserve a space by incrementing ticket and datetime sold values
172
+				$this->reserveRegistrationSpace();
173
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
174
+				// OR FROM  approved
175
+			} elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
176
+				// release a space by decrementing ticket and datetime sold values
177
+				$this->releaseRegistrationSpace();
178
+				do_action(
179
+					'AHEE__EE_Registration__set_status__from_approved',
180
+					$this,
181
+					$old_STS_ID,
182
+					$new_STS_ID,
183
+					$context
184
+				);
185
+			}
186
+			// update status
187
+			parent::set('STS_ID', $new_STS_ID, $use_default);
188
+			$this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
189
+			if ($this->statusChangeUpdatesTransaction($context)) {
190
+				$this->updateTransactionAfterStatusChange();
191
+			}
192
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
193
+			return true;
194
+		}
195
+		// even though the old value matches the new value, it's still good to
196
+		// allow the parent set method to have a say
197
+		parent::set('STS_ID', $new_STS_ID, $use_default);
198
+		return true;
199
+	}
200
+
201
+
202
+	/**
203
+	 * update REGs and TXN when cancelled or declined registrations involved
204
+	 *
205
+	 * @param string                $new_STS_ID
206
+	 * @param string                $old_STS_ID
207
+	 * @param ContextInterface|null $context
208
+	 * @throws EE_Error
209
+	 * @throws InvalidArgumentException
210
+	 * @throws InvalidDataTypeException
211
+	 * @throws InvalidInterfaceException
212
+	 * @throws ReflectionException
213
+	 * @throws RuntimeException
214
+	 */
215
+	private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
216
+	{
217
+		// these reg statuses should not be considered in any calculations involving monies owing
218
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
219
+		// true if registration has been cancelled or declined
220
+		$this->updateIfCanceled(
221
+			$closed_reg_statuses,
222
+			$new_STS_ID,
223
+			$old_STS_ID,
224
+			$context
225
+		);
226
+		$this->updateIfReinstated(
227
+			$closed_reg_statuses,
228
+			$new_STS_ID,
229
+			$old_STS_ID,
230
+			$context
231
+		);
232
+	}
233
+
234
+
235
+	/**
236
+	 * update REGs and TXN when cancelled or declined registrations involved
237
+	 *
238
+	 * @param array                 $closed_reg_statuses
239
+	 * @param string                $new_STS_ID
240
+	 * @param string                $old_STS_ID
241
+	 * @param ContextInterface|null $context
242
+	 * @throws EE_Error
243
+	 * @throws InvalidArgumentException
244
+	 * @throws InvalidDataTypeException
245
+	 * @throws InvalidInterfaceException
246
+	 * @throws ReflectionException
247
+	 * @throws RuntimeException
248
+	 */
249
+	private function updateIfCanceled(
250
+		array $closed_reg_statuses,
251
+		$new_STS_ID,
252
+		$old_STS_ID,
253
+		ContextInterface $context = null
254
+	) {
255
+		// true if registration has been cancelled or declined
256
+		if (
257
+			in_array($new_STS_ID, $closed_reg_statuses, true)
258
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
259
+		) {
260
+			/** @type EE_Registration_Processor $registration_processor */
261
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
262
+			/** @type EE_Transaction_Processor $transaction_processor */
263
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
264
+			// cancelled or declined registration
265
+			$registration_processor->update_registration_after_being_canceled_or_declined(
266
+				$this,
267
+				$closed_reg_statuses
268
+			);
269
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
270
+				$this,
271
+				$closed_reg_statuses,
272
+				false
273
+			);
274
+			do_action(
275
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
276
+				$this,
277
+				$old_STS_ID,
278
+				$new_STS_ID,
279
+				$context
280
+			);
281
+			return;
282
+		}
283
+	}
284
+
285
+
286
+	/**
287
+	 * update REGs and TXN when cancelled or declined registrations involved
288
+	 *
289
+	 * @param array                 $closed_reg_statuses
290
+	 * @param string                $new_STS_ID
291
+	 * @param string                $old_STS_ID
292
+	 * @param ContextInterface|null $context
293
+	 * @throws EE_Error
294
+	 * @throws InvalidArgumentException
295
+	 * @throws InvalidDataTypeException
296
+	 * @throws InvalidInterfaceException
297
+	 * @throws ReflectionException
298
+	 */
299
+	private function updateIfReinstated(
300
+		array $closed_reg_statuses,
301
+		$new_STS_ID,
302
+		$old_STS_ID,
303
+		ContextInterface $context = null
304
+	) {
305
+		// true if reinstating cancelled or declined registration
306
+		if (
307
+			in_array($old_STS_ID, $closed_reg_statuses, true)
308
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
309
+		) {
310
+			/** @type EE_Registration_Processor $registration_processor */
311
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
312
+			/** @type EE_Transaction_Processor $transaction_processor */
313
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
314
+			// reinstating cancelled or declined registration
315
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
316
+				$this,
317
+				$closed_reg_statuses
318
+			);
319
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
320
+				$this,
321
+				$closed_reg_statuses,
322
+				false
323
+			);
324
+			do_action(
325
+				'AHEE__EE_Registration__set_status__after_reinstated',
326
+				$this,
327
+				$old_STS_ID,
328
+				$new_STS_ID,
329
+				$context
330
+			);
331
+		}
332
+	}
333
+
334
+
335
+	/**
336
+	 * @param ContextInterface|null $context
337
+	 * @return bool
338
+	 */
339
+	private function statusChangeUpdatesTransaction(ContextInterface $context = null)
340
+	{
341
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
342
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
343
+			array('spco_reg_step_attendee_information_process_registrations'),
344
+			$context,
345
+			$this
346
+		);
347
+		return ! (
348
+			$context instanceof ContextInterface
349
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
350
+		);
351
+	}
352
+
353
+
354
+	/**
355
+	 * @throws EE_Error
356
+	 * @throws EntityNotFoundException
357
+	 * @throws InvalidArgumentException
358
+	 * @throws InvalidDataTypeException
359
+	 * @throws InvalidInterfaceException
360
+	 * @throws ReflectionException
361
+	 * @throws RuntimeException
362
+	 */
363
+	private function updateTransactionAfterStatusChange()
364
+	{
365
+		/** @type EE_Transaction_Payments $transaction_payments */
366
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
367
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
368
+		$this->transaction()->update_status_based_on_total_paid(true);
369
+	}
370
+
371
+
372
+	/**
373
+	 *        get Status ID
374
+	 */
375
+	public function status_ID()
376
+	{
377
+		return $this->get('STS_ID');
378
+	}
379
+
380
+
381
+	/**
382
+	 * Gets the ticket this registration is for
383
+	 *
384
+	 * @param boolean $include_archived whether to include archived tickets or not.
385
+	 *
386
+	 * @return EE_Ticket|EE_Base_Class
387
+	 * @throws EE_Error
388
+	 */
389
+	public function ticket($include_archived = true)
390
+	{
391
+		$query_params = array();
392
+		if ($include_archived) {
393
+			$query_params['default_where_conditions'] = 'none';
394
+		}
395
+		return $this->get_first_related('Ticket', $query_params);
396
+	}
397
+
398
+
399
+	/**
400
+	 * Gets the event this registration is for
401
+	 *
402
+	 * @return EE_Event
403
+	 * @throws EE_Error
404
+	 * @throws EntityNotFoundException
405
+	 */
406
+	public function event()
407
+	{
408
+		$event = $this->get_first_related('Event');
409
+		if (! $event instanceof \EE_Event) {
410
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
411
+		}
412
+		return $event;
413
+	}
414
+
415
+
416
+	/**
417
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
418
+	 * with the author of the event this registration is for.
419
+	 *
420
+	 * @since 4.5.0
421
+	 * @return int
422
+	 * @throws EE_Error
423
+	 * @throws EntityNotFoundException
424
+	 */
425
+	public function wp_user()
426
+	{
427
+		$event = $this->event();
428
+		if ($event instanceof EE_Event) {
429
+			return $event->wp_user();
430
+		}
431
+		return 0;
432
+	}
433
+
434
+
435
+	/**
436
+	 * increments this registration's related ticket sold and corresponding datetime sold values
437
+	 *
438
+	 * @return void
439
+	 * @throws DomainException
440
+	 * @throws EE_Error
441
+	 * @throws EntityNotFoundException
442
+	 * @throws InvalidArgumentException
443
+	 * @throws InvalidDataTypeException
444
+	 * @throws InvalidInterfaceException
445
+	 * @throws ReflectionException
446
+	 * @throws UnexpectedEntityException
447
+	 */
448
+	private function reserveRegistrationSpace()
449
+	{
450
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
451
+		// so stop tracking that this reg has a ticket reserved
452
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
453
+		$ticket = $this->ticket();
454
+		$ticket->increaseSold();
455
+		// possibly set event status to sold out
456
+		$this->event()->perform_sold_out_status_check();
457
+	}
458
+
459
+
460
+	/**
461
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
462
+	 *
463
+	 * @return void
464
+	 * @throws DomainException
465
+	 * @throws EE_Error
466
+	 * @throws EntityNotFoundException
467
+	 * @throws InvalidArgumentException
468
+	 * @throws InvalidDataTypeException
469
+	 * @throws InvalidInterfaceException
470
+	 * @throws ReflectionException
471
+	 * @throws UnexpectedEntityException
472
+	 */
473
+	private function releaseRegistrationSpace()
474
+	{
475
+		$ticket = $this->ticket();
476
+		$ticket->decreaseSold();
477
+		// possibly change event status from sold out back to previous status
478
+		$this->event()->perform_sold_out_status_check();
479
+	}
480
+
481
+
482
+	/**
483
+	 * tracks this registration's ticket reservation in extra meta
484
+	 * and can increment related ticket reserved and corresponding datetime reserved values
485
+	 *
486
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
487
+	 * @return void
488
+	 * @throws EE_Error
489
+	 * @throws InvalidArgumentException
490
+	 * @throws InvalidDataTypeException
491
+	 * @throws InvalidInterfaceException
492
+	 * @throws ReflectionException
493
+	 */
494
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
495
+	{
496
+		// only reserve ticket if space is not currently reserved
497
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
498
+			$this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
499
+			// IMPORTANT !!!
500
+			// although checking $update_ticket first would be more efficient,
501
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
502
+			if (
503
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
504
+				&& $update_ticket
505
+			) {
506
+				$ticket = $this->ticket();
507
+				$ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
508
+				$ticket->save();
509
+			}
510
+		}
511
+	}
512
+
513
+
514
+	/**
515
+	 * stops tracking this registration's ticket reservation in extra meta
516
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
517
+	 *
518
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
519
+	 * @return void
520
+	 * @throws EE_Error
521
+	 * @throws InvalidArgumentException
522
+	 * @throws InvalidDataTypeException
523
+	 * @throws InvalidInterfaceException
524
+	 * @throws ReflectionException
525
+	 */
526
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
527
+	{
528
+		// only release ticket if space is currently reserved
529
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
530
+			$this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
531
+			// IMPORTANT !!!
532
+			// although checking $update_ticket first would be more efficient,
533
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
534
+			if (
535
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
536
+				&& $update_ticket
537
+			) {
538
+				$ticket = $this->ticket();
539
+				$ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
540
+			}
541
+		}
542
+	}
543
+
544
+
545
+	/**
546
+	 * Set Attendee ID
547
+	 *
548
+	 * @param        int $ATT_ID Attendee ID
549
+	 * @throws EE_Error
550
+	 * @throws RuntimeException
551
+	 */
552
+	public function set_attendee_id($ATT_ID = 0)
553
+	{
554
+		$this->set('ATT_ID', $ATT_ID);
555
+	}
556
+
557
+
558
+	/**
559
+	 *        Set Transaction ID
560
+	 *
561
+	 * @param        int $TXN_ID Transaction ID
562
+	 * @throws EE_Error
563
+	 * @throws RuntimeException
564
+	 */
565
+	public function set_transaction_id($TXN_ID = 0)
566
+	{
567
+		$this->set('TXN_ID', $TXN_ID);
568
+	}
569
+
570
+
571
+	/**
572
+	 *        Set Session
573
+	 *
574
+	 * @param    string $REG_session PHP Session ID
575
+	 * @throws EE_Error
576
+	 * @throws RuntimeException
577
+	 */
578
+	public function set_session($REG_session = '')
579
+	{
580
+		$this->set('REG_session', $REG_session);
581
+	}
582
+
583
+
584
+	/**
585
+	 *        Set Registration URL Link
586
+	 *
587
+	 * @param    string $REG_url_link Registration URL Link
588
+	 * @throws EE_Error
589
+	 * @throws RuntimeException
590
+	 */
591
+	public function set_reg_url_link($REG_url_link = '')
592
+	{
593
+		$this->set('REG_url_link', $REG_url_link);
594
+	}
595
+
596
+
597
+	/**
598
+	 *        Set Attendee Counter
599
+	 *
600
+	 * @param        int $REG_count Primary Attendee
601
+	 * @throws EE_Error
602
+	 * @throws RuntimeException
603
+	 */
604
+	public function set_count($REG_count = 1)
605
+	{
606
+		$this->set('REG_count', $REG_count);
607
+	}
608
+
609
+
610
+	/**
611
+	 *        Set Group Size
612
+	 *
613
+	 * @param        boolean $REG_group_size Group Registration
614
+	 * @throws EE_Error
615
+	 * @throws RuntimeException
616
+	 */
617
+	public function set_group_size($REG_group_size = false)
618
+	{
619
+		$this->set('REG_group_size', $REG_group_size);
620
+	}
621
+
622
+
623
+	/**
624
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
625
+	 *    EEM_Registration::status_id_not_approved
626
+	 *
627
+	 * @return        boolean
628
+	 */
629
+	public function is_not_approved()
630
+	{
631
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
632
+	}
633
+
634
+
635
+	/**
636
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
637
+	 *    EEM_Registration::status_id_pending_payment
638
+	 *
639
+	 * @return        boolean
640
+	 */
641
+	public function is_pending_payment()
642
+	{
643
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
644
+	}
645
+
646
+
647
+	/**
648
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
649
+	 *
650
+	 * @return        boolean
651
+	 */
652
+	public function is_approved()
653
+	{
654
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
655
+	}
656
+
657
+
658
+	/**
659
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
660
+	 *
661
+	 * @return        boolean
662
+	 */
663
+	public function is_cancelled()
664
+	{
665
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
666
+	}
667
+
668
+
669
+	/**
670
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
671
+	 *
672
+	 * @return        boolean
673
+	 */
674
+	public function is_declined()
675
+	{
676
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
677
+	}
678
+
679
+
680
+	/**
681
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
682
+	 *    EEM_Registration::status_id_incomplete
683
+	 *
684
+	 * @return        boolean
685
+	 */
686
+	public function is_incomplete()
687
+	{
688
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
689
+	}
690
+
691
+
692
+	/**
693
+	 *        Set Registration Date
694
+	 *
695
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
696
+	 *                                                 Date
697
+	 * @throws EE_Error
698
+	 * @throws RuntimeException
699
+	 */
700
+	public function set_reg_date($REG_date = false)
701
+	{
702
+		$this->set('REG_date', $REG_date);
703
+	}
704
+
705
+
706
+	/**
707
+	 *    Set final price owing for this registration after all ticket/price modifications
708
+	 *
709
+	 * @access    public
710
+	 * @param    float $REG_final_price
711
+	 * @throws EE_Error
712
+	 * @throws RuntimeException
713
+	 */
714
+	public function set_final_price($REG_final_price = 0.00)
715
+	{
716
+		$this->set('REG_final_price', $REG_final_price);
717
+	}
718
+
719
+
720
+	/**
721
+	 *    Set amount paid towards this registration's final price
722
+	 *
723
+	 * @access    public
724
+	 * @param    float $REG_paid
725
+	 * @throws EE_Error
726
+	 * @throws RuntimeException
727
+	 */
728
+	public function set_paid($REG_paid = 0.00)
729
+	{
730
+		$this->set('REG_paid', $REG_paid);
731
+	}
732
+
733
+
734
+	/**
735
+	 *        Attendee Is Going
736
+	 *
737
+	 * @param        boolean $REG_att_is_going Attendee Is Going
738
+	 * @throws EE_Error
739
+	 * @throws RuntimeException
740
+	 */
741
+	public function set_att_is_going($REG_att_is_going = false)
742
+	{
743
+		$this->set('REG_att_is_going', $REG_att_is_going);
744
+	}
745
+
746
+
747
+	/**
748
+	 * Gets the related attendee
749
+	 *
750
+	 * @return EE_Attendee
751
+	 * @throws EE_Error
752
+	 */
753
+	public function attendee()
754
+	{
755
+		return $this->get_first_related('Attendee');
756
+	}
757
+
758
+	/**
759
+	 * Gets the name of the attendee.
760
+	 * @since 4.10.12.p
761
+	 * @param bool $apply_html_entities set to true if you want to use HTML entities.
762
+	 * @return string
763
+	 * @throws EE_Error
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 * @throws ReflectionException
768
+	 */
769
+	public function attendeeName($apply_html_entities = false)
770
+	{
771
+		$attendee = $this->get_first_related('Attendee');
772
+		if ($attendee instanceof EE_Attendee) {
773
+			$attendee_name = $attendee->full_name($apply_html_entities);
774
+		} else {
775
+			$attendee_name = esc_html__('Unknown', 'event_espresso');
776
+		}
777
+		return $attendee_name;
778
+	}
779
+
780
+
781
+	/**
782
+	 *        get Event ID
783
+	 */
784
+	public function event_ID()
785
+	{
786
+		return $this->get('EVT_ID');
787
+	}
788
+
789
+
790
+	/**
791
+	 *        get Event ID
792
+	 */
793
+	public function event_name()
794
+	{
795
+		$event = $this->event_obj();
796
+		if ($event) {
797
+			return $event->name();
798
+		} else {
799
+			return null;
800
+		}
801
+	}
802
+
803
+
804
+	/**
805
+	 * Fetches the event this registration is for
806
+	 *
807
+	 * @return EE_Event
808
+	 * @throws EE_Error
809
+	 */
810
+	public function event_obj()
811
+	{
812
+		return $this->get_first_related('Event');
813
+	}
814
+
815
+
816
+	/**
817
+	 *        get Attendee ID
818
+	 */
819
+	public function attendee_ID()
820
+	{
821
+		return $this->get('ATT_ID');
822
+	}
823
+
824
+
825
+	/**
826
+	 *        get PHP Session ID
827
+	 */
828
+	public function session_ID()
829
+	{
830
+		return $this->get('REG_session');
831
+	}
832
+
833
+
834
+	/**
835
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
836
+	 *
837
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
838
+	 * @return string
839
+	 */
840
+	public function receipt_url($messenger = 'html')
841
+	{
842
+
843
+		/**
844
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template
845
+		 * already in use on old system.  If there is then we just return the standard url for it.
846
+		 *
847
+		 * @since 4.5.0
848
+		 */
849
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
850
+		$has_custom = EEH_Template::locate_template(
851
+			$template_relative_path,
852
+			array(),
853
+			true,
854
+			true,
855
+			true
856
+		);
857
+
858
+		if ($has_custom) {
859
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
860
+		}
861
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
862
+	}
863
+
864
+
865
+	/**
866
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
867
+	 *
868
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
869
+	 * @return string
870
+	 * @throws EE_Error
871
+	 */
872
+	public function invoice_url($messenger = 'html')
873
+	{
874
+		/**
875
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template
876
+		 * already in use on old system.  If there is then we just return the standard url for it.
877
+		 *
878
+		 * @since 4.5.0
879
+		 */
880
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
881
+		$has_custom = EEH_Template::locate_template(
882
+			$template_relative_path,
883
+			array(),
884
+			true,
885
+			true,
886
+			true
887
+		);
888
+
889
+		if ($has_custom) {
890
+			if ($messenger == 'html') {
891
+				return $this->invoice_url('launch');
892
+			}
893
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
894
+
895
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
896
+			if ($messenger == 'html') {
897
+				$query_args['html'] = true;
898
+			}
899
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
900
+		}
901
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
902
+	}
903
+
904
+
905
+	/**
906
+	 * get Registration URL Link
907
+	 *
908
+	 * @access public
909
+	 * @return string
910
+	 * @throws EE_Error
911
+	 */
912
+	public function reg_url_link()
913
+	{
914
+		return (string) $this->get('REG_url_link');
915
+	}
916
+
917
+
918
+	/**
919
+	 * Echoes out invoice_url()
920
+	 *
921
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
922
+	 * @return void
923
+	 * @throws EE_Error
924
+	 */
925
+	public function e_invoice_url($type = 'launch')
926
+	{
927
+		echo esc_url_raw($this->invoice_url($type));
928
+	}
929
+
930
+
931
+	/**
932
+	 * Echoes out payment_overview_url
933
+	 */
934
+	public function e_payment_overview_url()
935
+	{
936
+		echo esc_url_raw($this->payment_overview_url());
937
+	}
938
+
939
+
940
+	/**
941
+	 * Gets the URL for the checkout payment options reg step
942
+	 * with this registration's REG_url_link added as a query parameter
943
+	 *
944
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
945
+	 *                            payment overview url.
946
+	 * @return string
947
+	 * @throws InvalidInterfaceException
948
+	 * @throws InvalidDataTypeException
949
+	 * @throws EE_Error
950
+	 * @throws InvalidArgumentException
951
+	 */
952
+	public function payment_overview_url($clear_session = false)
953
+	{
954
+		return add_query_arg(
955
+			(array) apply_filters(
956
+				'FHEE__EE_Registration__payment_overview_url__query_args',
957
+				array(
958
+					'e_reg_url_link' => $this->reg_url_link(),
959
+					'step'           => 'payment_options',
960
+					'revisit'        => true,
961
+					'clear_session'  => (bool) $clear_session,
962
+				),
963
+				$this
964
+			),
965
+			EE_Registry::instance()->CFG->core->reg_page_url()
966
+		);
967
+	}
968
+
969
+
970
+	/**
971
+	 * Gets the URL for the checkout attendee information reg step
972
+	 * with this registration's REG_url_link added as a query parameter
973
+	 *
974
+	 * @return string
975
+	 * @throws InvalidInterfaceException
976
+	 * @throws InvalidDataTypeException
977
+	 * @throws EE_Error
978
+	 * @throws InvalidArgumentException
979
+	 */
980
+	public function edit_attendee_information_url()
981
+	{
982
+		return add_query_arg(
983
+			(array) apply_filters(
984
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
985
+				array(
986
+					'e_reg_url_link' => $this->reg_url_link(),
987
+					'step'           => 'attendee_information',
988
+					'revisit'        => true,
989
+				),
990
+				$this
991
+			),
992
+			EE_Registry::instance()->CFG->core->reg_page_url()
993
+		);
994
+	}
995
+
996
+
997
+	/**
998
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
999
+	 *
1000
+	 * @return string
1001
+	 * @throws EE_Error
1002
+	 */
1003
+	public function get_admin_edit_url()
1004
+	{
1005
+		return EEH_URL::add_query_args_and_nonce(
1006
+			array(
1007
+				'page'    => 'espresso_registrations',
1008
+				'action'  => 'view_registration',
1009
+				'_REG_ID' => $this->ID(),
1010
+			),
1011
+			admin_url('admin.php')
1012
+		);
1013
+	}
1014
+
1015
+
1016
+	/**
1017
+	 *    is_primary_registrant?
1018
+	 */
1019
+	public function is_primary_registrant()
1020
+	{
1021
+		return $this->get('REG_count') === 1 ? true : false;
1022
+	}
1023
+
1024
+
1025
+	/**
1026
+	 * This returns the primary registration object for this registration group (which may be this object).
1027
+	 *
1028
+	 * @return EE_Registration
1029
+	 * @throws EE_Error
1030
+	 */
1031
+	public function get_primary_registration()
1032
+	{
1033
+		if ($this->is_primary_registrant()) {
1034
+			return $this;
1035
+		}
1036
+
1037
+		// k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1038
+		/** @var EE_Registration $primary_registrant */
1039
+		$primary_registrant = EEM_Registration::instance()->get_one(
1040
+			array(
1041
+				array(
1042
+					'TXN_ID'    => $this->transaction_ID(),
1043
+					'REG_count' => 1,
1044
+				),
1045
+			)
1046
+		);
1047
+		return $primary_registrant;
1048
+	}
1049
+
1050
+
1051
+	/**
1052
+	 *        get  Attendee Number
1053
+	 *
1054
+	 * @access        public
1055
+	 */
1056
+	public function count()
1057
+	{
1058
+		return $this->get('REG_count');
1059
+	}
1060
+
1061
+
1062
+	/**
1063
+	 *        get Group Size
1064
+	 */
1065
+	public function group_size()
1066
+	{
1067
+		return $this->get('REG_group_size');
1068
+	}
1069
+
1070
+
1071
+	/**
1072
+	 *        get Registration Date
1073
+	 */
1074
+	public function date()
1075
+	{
1076
+		return $this->get('REG_date');
1077
+	}
1078
+
1079
+
1080
+	/**
1081
+	 * gets a pretty date
1082
+	 *
1083
+	 * @param string $date_format
1084
+	 * @param string $time_format
1085
+	 * @return string
1086
+	 * @throws EE_Error
1087
+	 */
1088
+	public function pretty_date($date_format = null, $time_format = null)
1089
+	{
1090
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 * final_price
1096
+	 * the registration's share of the transaction total, so that the
1097
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1098
+	 *
1099
+	 * @return float
1100
+	 * @throws EE_Error
1101
+	 */
1102
+	public function final_price()
1103
+	{
1104
+		return $this->get('REG_final_price');
1105
+	}
1106
+
1107
+
1108
+	/**
1109
+	 * pretty_final_price
1110
+	 *  final price as formatted string, with correct decimal places and currency symbol
1111
+	 *
1112
+	 * @return string
1113
+	 * @throws EE_Error
1114
+	 */
1115
+	public function pretty_final_price()
1116
+	{
1117
+		return $this->get_pretty('REG_final_price');
1118
+	}
1119
+
1120
+
1121
+	/**
1122
+	 * get paid (yeah)
1123
+	 *
1124
+	 * @return float
1125
+	 * @throws EE_Error
1126
+	 */
1127
+	public function paid()
1128
+	{
1129
+		return $this->get('REG_paid');
1130
+	}
1131
+
1132
+
1133
+	/**
1134
+	 * pretty_paid
1135
+	 *
1136
+	 * @return float
1137
+	 * @throws EE_Error
1138
+	 */
1139
+	public function pretty_paid()
1140
+	{
1141
+		return $this->get_pretty('REG_paid');
1142
+	}
1143
+
1144
+
1145
+	/**
1146
+	 * owes_monies_and_can_pay
1147
+	 * whether or not this registration has monies owing and it's' status allows payment
1148
+	 *
1149
+	 * @param array $requires_payment
1150
+	 * @return bool
1151
+	 * @throws EE_Error
1152
+	 */
1153
+	public function owes_monies_and_can_pay($requires_payment = array())
1154
+	{
1155
+		// these reg statuses require payment (if event is not free)
1156
+		$requires_payment = ! empty($requires_payment)
1157
+			? $requires_payment
1158
+			: EEM_Registration::reg_statuses_that_allow_payment();
1159
+		if (
1160
+			in_array($this->status_ID(), $requires_payment) &&
1161
+			$this->final_price() != 0 &&
1162
+			$this->final_price() != $this->paid()
1163
+		) {
1164
+			return true;
1165
+		} else {
1166
+			return false;
1167
+		}
1168
+	}
1169
+
1170
+
1171
+	/**
1172
+	 * Prints out the return value of $this->pretty_status()
1173
+	 *
1174
+	 * @param bool $show_icons
1175
+	 * @return void
1176
+	 * @throws EE_Error
1177
+	 */
1178
+	public function e_pretty_status($show_icons = false)
1179
+	{
1180
+		echo $this->pretty_status($show_icons); // already escaped
1181
+	}
1182
+
1183
+
1184
+	/**
1185
+	 * Returns a nice version of the status for displaying to customers
1186
+	 *
1187
+	 * @param bool $show_icons
1188
+	 * @return string
1189
+	 * @throws EE_Error
1190
+	 */
1191
+	public function pretty_status($show_icons = false)
1192
+	{
1193
+		$status = EEM_Status::instance()->localized_status(
1194
+			array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1195
+			false,
1196
+			'sentence'
1197
+		);
1198
+		$icon = '';
1199
+		switch ($this->status_ID()) {
1200
+			case EEM_Registration::status_id_approved:
1201
+				$icon = $show_icons
1202
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1203
+					: '';
1204
+				break;
1205
+			case EEM_Registration::status_id_pending_payment:
1206
+				$icon = $show_icons
1207
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1208
+					: '';
1209
+				break;
1210
+			case EEM_Registration::status_id_not_approved:
1211
+				$icon = $show_icons
1212
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1213
+					: '';
1214
+				break;
1215
+			case EEM_Registration::status_id_cancelled:
1216
+				$icon = $show_icons
1217
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1218
+					: '';
1219
+				break;
1220
+			case EEM_Registration::status_id_incomplete:
1221
+				$icon = $show_icons
1222
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1223
+					: '';
1224
+				break;
1225
+			case EEM_Registration::status_id_declined:
1226
+				$icon = $show_icons
1227
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1228
+					: '';
1229
+				break;
1230
+			case EEM_Registration::status_id_wait_list:
1231
+				$icon = $show_icons
1232
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1233
+					: '';
1234
+				break;
1235
+		}
1236
+		return $icon . $status[ $this->status_ID() ];
1237
+	}
1238
+
1239
+
1240
+	/**
1241
+	 *        get Attendee Is Going
1242
+	 */
1243
+	public function att_is_going()
1244
+	{
1245
+		return $this->get('REG_att_is_going');
1246
+	}
1247
+
1248
+
1249
+	/**
1250
+	 * Gets related answers
1251
+	 *
1252
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1253
+	 * @return EE_Answer[]
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	public function answers($query_params = null)
1257
+	{
1258
+		return $this->get_many_related('Answer', $query_params);
1259
+	}
1260
+
1261
+
1262
+	/**
1263
+	 * Gets the registration's answer value to the specified question
1264
+	 * (either the question's ID or a question object)
1265
+	 *
1266
+	 * @param EE_Question|int $question
1267
+	 * @param bool            $pretty_value
1268
+	 * @return array|string if pretty_value= true, the result will always be a string
1269
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1270
+	 * will convert it into some kind of string)
1271
+	 * @throws EE_Error
1272
+	 */
1273
+	public function answer_value_to_question($question, $pretty_value = true)
1274
+	{
1275
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1276
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1277
+	}
1278
+
1279
+
1280
+	/**
1281
+	 * question_groups
1282
+	 * returns an array of EE_Question_Group objects for this registration
1283
+	 *
1284
+	 * @return EE_Question_Group[]
1285
+	 * @throws EE_Error
1286
+	 * @throws InvalidArgumentException
1287
+	 * @throws InvalidDataTypeException
1288
+	 * @throws InvalidInterfaceException
1289
+	 * @throws ReflectionException
1290
+	 */
1291
+	public function question_groups()
1292
+	{
1293
+		return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1294
+	}
1295
+
1296
+
1297
+	/**
1298
+	 * count_question_groups
1299
+	 * returns a count of the number of EE_Question_Group objects for this registration
1300
+	 *
1301
+	 * @return int
1302
+	 * @throws EE_Error
1303
+	 * @throws EntityNotFoundException
1304
+	 * @throws InvalidArgumentException
1305
+	 * @throws InvalidDataTypeException
1306
+	 * @throws InvalidInterfaceException
1307
+	 * @throws ReflectionException
1308
+	 */
1309
+	public function count_question_groups()
1310
+	{
1311
+		return EEM_Event::instance()->count_related(
1312
+			$this->event_ID(),
1313
+			'Question_Group',
1314
+			[
1315
+				[
1316
+					'Event_Question_Group.'
1317
+					. EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1318
+				]
1319
+			]
1320
+		);
1321
+	}
1322
+
1323
+
1324
+	/**
1325
+	 * Returns the registration date in the 'standard' string format
1326
+	 * (function may be improved in the future to allow for different formats and timezones)
1327
+	 *
1328
+	 * @return string
1329
+	 * @throws EE_Error
1330
+	 */
1331
+	public function reg_date()
1332
+	{
1333
+		return $this->get_datetime('REG_date');
1334
+	}
1335
+
1336
+
1337
+	/**
1338
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1339
+	 * the ticket this registration purchased, or the datetime they have registered
1340
+	 * to attend)
1341
+	 *
1342
+	 * @return EE_Datetime_Ticket
1343
+	 * @throws EE_Error
1344
+	 */
1345
+	public function datetime_ticket()
1346
+	{
1347
+		return $this->get_first_related('Datetime_Ticket');
1348
+	}
1349
+
1350
+
1351
+	/**
1352
+	 * Sets the registration's datetime_ticket.
1353
+	 *
1354
+	 * @param EE_Datetime_Ticket $datetime_ticket
1355
+	 * @return EE_Datetime_Ticket
1356
+	 * @throws EE_Error
1357
+	 */
1358
+	public function set_datetime_ticket($datetime_ticket)
1359
+	{
1360
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1361
+	}
1362
+
1363
+	/**
1364
+	 * Gets deleted
1365
+	 *
1366
+	 * @return bool
1367
+	 * @throws EE_Error
1368
+	 */
1369
+	public function deleted()
1370
+	{
1371
+		return $this->get('REG_deleted');
1372
+	}
1373
+
1374
+	/**
1375
+	 * Sets deleted
1376
+	 *
1377
+	 * @param boolean $deleted
1378
+	 * @return bool
1379
+	 * @throws EE_Error
1380
+	 * @throws RuntimeException
1381
+	 */
1382
+	public function set_deleted($deleted)
1383
+	{
1384
+		if ($deleted) {
1385
+			$this->delete();
1386
+		} else {
1387
+			$this->restore();
1388
+		}
1389
+	}
1390
+
1391
+
1392
+	/**
1393
+	 * Get the status object of this object
1394
+	 *
1395
+	 * @return EE_Status
1396
+	 * @throws EE_Error
1397
+	 */
1398
+	public function status_obj()
1399
+	{
1400
+		return $this->get_first_related('Status');
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * Returns the number of times this registration has checked into any of the datetimes
1406
+	 * its available for
1407
+	 *
1408
+	 * @return int
1409
+	 * @throws EE_Error
1410
+	 */
1411
+	public function count_checkins()
1412
+	{
1413
+		return $this->get_model()->count_related($this, 'Checkin');
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1419
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1420
+	 *
1421
+	 * @return int
1422
+	 * @throws EE_Error
1423
+	 */
1424
+	public function count_checkins_not_checkedout()
1425
+	{
1426
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1427
+	}
1428
+
1429
+
1430
+	/**
1431
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1432
+	 *
1433
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1434
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1435
+	 *                                          consider registration status as well as datetime access.
1436
+	 * @return bool
1437
+	 * @throws EE_Error
1438
+	 */
1439
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1440
+	{
1441
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1442
+
1443
+		// first check registration status
1444
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1445
+			return false;
1446
+		}
1447
+		// is there a datetime ticket that matches this dtt_ID?
1448
+		if (
1449
+			! (EEM_Datetime_Ticket::instance()->exists(
1450
+				array(
1451
+				array(
1452
+					'TKT_ID' => $this->get('TKT_ID'),
1453
+					'DTT_ID' => $DTT_ID,
1454
+				),
1455
+				)
1456
+			))
1457
+		) {
1458
+			return false;
1459
+		}
1460
+
1461
+		// final check is against TKT_uses
1462
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1463
+	}
1464
+
1465
+
1466
+	/**
1467
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1468
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1469
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1470
+	 * then return false.  Otherwise return true.
1471
+	 *
1472
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1473
+	 * @return bool true means can checkin.  false means cannot checkin.
1474
+	 * @throws EE_Error
1475
+	 */
1476
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1477
+	{
1478
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1479
+
1480
+		if (! $DTT_ID) {
1481
+			return false;
1482
+		}
1483
+
1484
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1485
+
1486
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1487
+		// check-in or not.
1488
+		if (! $max_uses || $max_uses === EE_INF) {
1489
+			return true;
1490
+		}
1491
+
1492
+		// does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1493
+		// go ahead and toggle.
1494
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1495
+			return true;
1496
+		}
1497
+
1498
+		// made it here so the last check is whether the number of checkins per unique datetime on this registration
1499
+		// disallows further check-ins.
1500
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1501
+			array(
1502
+				array(
1503
+					'REG_ID' => $this->ID(),
1504
+					'CHK_in' => true,
1505
+				),
1506
+			),
1507
+			'DTT_ID',
1508
+			true
1509
+		);
1510
+		// checkins have already reached their max number of uses
1511
+		// so registrant can NOT checkin
1512
+		if ($count_unique_dtt_checkins >= $max_uses) {
1513
+			EE_Error::add_error(
1514
+				esc_html__(
1515
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1516
+					'event_espresso'
1517
+				),
1518
+				__FILE__,
1519
+				__FUNCTION__,
1520
+				__LINE__
1521
+			);
1522
+			return false;
1523
+		}
1524
+		return true;
1525
+	}
1526
+
1527
+
1528
+	/**
1529
+	 * toggle Check-in status for this registration
1530
+	 * Check-ins are toggled in the following order:
1531
+	 * never checked in -> checked in
1532
+	 * checked in -> checked out
1533
+	 * checked out -> checked in
1534
+	 *
1535
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1536
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1537
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1538
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1539
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1540
+	 * @throws EE_Error
1541
+	 */
1542
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1543
+	{
1544
+		if (empty($DTT_ID)) {
1545
+			$datetime = $this->get_latest_related_datetime();
1546
+			$DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1547
+			// verify the registration can checkin for the given DTT_ID
1548
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1549
+			EE_Error::add_error(
1550
+				sprintf(
1551
+					esc_html__(
1552
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1553
+						'event_espresso'
1554
+					),
1555
+					$this->ID(),
1556
+					$DTT_ID
1557
+				),
1558
+				__FILE__,
1559
+				__FUNCTION__,
1560
+				__LINE__
1561
+			);
1562
+			return false;
1563
+		}
1564
+		$status_paths = array(
1565
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1566
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1567
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1568
+		);
1569
+		// start by getting the current status so we know what status we'll be changing to.
1570
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1571
+		$status_to = $status_paths[ $cur_status ];
1572
+		// database only records true for checked IN or false for checked OUT
1573
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1574
+		$new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1575
+		// add relation - note Check-ins are always creating new rows
1576
+		// because we are keeping track of Check-ins over time.
1577
+		// Eventually we'll probably want to show a list table
1578
+		// for the individual Check-ins so that they can be managed.
1579
+		$checkin = EE_Checkin::new_instance(
1580
+			array(
1581
+				'REG_ID' => $this->ID(),
1582
+				'DTT_ID' => $DTT_ID,
1583
+				'CHK_in' => $new_status,
1584
+			)
1585
+		);
1586
+		// if the record could not be saved then return false
1587
+		if ($checkin->save() === 0) {
1588
+			if (WP_DEBUG) {
1589
+				global $wpdb;
1590
+				$error = sprintf(
1591
+					esc_html__(
1592
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1593
+						'event_espresso'
1594
+					),
1595
+					'<br />',
1596
+					$wpdb->last_error
1597
+				);
1598
+			} else {
1599
+				$error = esc_html__(
1600
+					'Registration check in update failed because of an unknown database error',
1601
+					'event_espresso'
1602
+				);
1603
+			}
1604
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1605
+			return false;
1606
+		}
1607
+		// Fire a checked_in and checkout_out action.
1608
+		$checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1609
+		do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1610
+		return $status_to;
1611
+	}
1612
+
1613
+
1614
+	/**
1615
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1616
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1617
+	 *
1618
+	 * @return EE_Datetime|null
1619
+	 * @throws EE_Error
1620
+	 */
1621
+	public function get_latest_related_datetime()
1622
+	{
1623
+		return EEM_Datetime::instance()->get_one(
1624
+			array(
1625
+				array(
1626
+					'Ticket.Registration.REG_ID' => $this->ID(),
1627
+				),
1628
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1629
+			)
1630
+		);
1631
+	}
1632
+
1633
+
1634
+	/**
1635
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1636
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1637
+	 *
1638
+	 * @throws EE_Error
1639
+	 */
1640
+	public function get_earliest_related_datetime()
1641
+	{
1642
+		return EEM_Datetime::instance()->get_one(
1643
+			array(
1644
+				array(
1645
+					'Ticket.Registration.REG_ID' => $this->ID(),
1646
+				),
1647
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1648
+			)
1649
+		);
1650
+	}
1651
+
1652
+
1653
+	/**
1654
+	 * This method simply returns the check-in status for this registration and the given datetime.
1655
+	 * If neither the datetime nor the checkin values are provided as arguments,
1656
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1657
+	 *
1658
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1659
+	 *                            (if empty we'll get the primary datetime for
1660
+	 *                            this registration (via event) and use it's ID);
1661
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1662
+	 *
1663
+	 * @return int                Integer representing Check-in status.
1664
+	 * @throws EE_Error
1665
+	 */
1666
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1667
+	{
1668
+		$checkin_query_params = array(
1669
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1670
+		);
1671
+
1672
+		if ($DTT_ID > 0) {
1673
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1674
+		}
1675
+
1676
+		// get checkin object (if exists)
1677
+		$checkin = $checkin instanceof EE_Checkin
1678
+			? $checkin
1679
+			: $this->get_first_related('Checkin', $checkin_query_params);
1680
+		if ($checkin instanceof EE_Checkin) {
1681
+			if ($checkin->get('CHK_in')) {
1682
+				return EE_Checkin::status_checked_in; // checked in
1683
+			}
1684
+			return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1685
+		}
1686
+		return EE_Checkin::status_checked_never; // never been checked in
1687
+	}
1688
+
1689
+
1690
+	/**
1691
+	 * This method returns a localized message for the toggled Check-in message.
1692
+	 *
1693
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1694
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1695
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1696
+	 *                     message can be customized with the attendee name.
1697
+	 * @return string internationalized message
1698
+	 * @throws EE_Error
1699
+	 */
1700
+	public function get_checkin_msg($DTT_ID, $error = false)
1701
+	{
1702
+		// let's get the attendee first so we can include the name of the attendee
1703
+		$attendee = $this->get_first_related('Attendee');
1704
+		if ($attendee instanceof EE_Attendee) {
1705
+			if ($error) {
1706
+				return sprintf(esc_html__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1707
+			}
1708
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1709
+			// what is the status message going to be?
1710
+			switch ($cur_status) {
1711
+				case EE_Checkin::status_checked_never:
1712
+					return sprintf(
1713
+						esc_html__("%s has been removed from Check-in records", "event_espresso"),
1714
+						$attendee->full_name()
1715
+					);
1716
+					break;
1717
+				case EE_Checkin::status_checked_in:
1718
+					return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1719
+					break;
1720
+				case EE_Checkin::status_checked_out:
1721
+					return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1722
+					break;
1723
+			}
1724
+		}
1725
+		return esc_html__("The check-in status could not be determined.", "event_espresso");
1726
+	}
1727
+
1728
+
1729
+	/**
1730
+	 * Returns the related EE_Transaction to this registration
1731
+	 *
1732
+	 * @return EE_Transaction
1733
+	 * @throws EE_Error
1734
+	 * @throws EntityNotFoundException
1735
+	 */
1736
+	public function transaction()
1737
+	{
1738
+		$transaction = $this->get_first_related('Transaction');
1739
+		if (! $transaction instanceof \EE_Transaction) {
1740
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1741
+		}
1742
+		return $transaction;
1743
+	}
1744
+
1745
+
1746
+	/**
1747
+	 *        get Registration Code
1748
+	 */
1749
+	public function reg_code()
1750
+	{
1751
+		return $this->get('REG_code');
1752
+	}
1753
+
1754
+
1755
+	/**
1756
+	 *        get Transaction ID
1757
+	 */
1758
+	public function transaction_ID()
1759
+	{
1760
+		return $this->get('TXN_ID');
1761
+	}
1762
+
1763
+
1764
+	/**
1765
+	 * @return int
1766
+	 * @throws EE_Error
1767
+	 */
1768
+	public function ticket_ID()
1769
+	{
1770
+		return $this->get('TKT_ID');
1771
+	}
1772
+
1773
+
1774
+	/**
1775
+	 *        Set Registration Code
1776
+	 *
1777
+	 * @access    public
1778
+	 * @param    string  $REG_code Registration Code
1779
+	 * @param    boolean $use_default
1780
+	 * @throws EE_Error
1781
+	 */
1782
+	public function set_reg_code($REG_code, $use_default = false)
1783
+	{
1784
+		if (empty($REG_code)) {
1785
+			EE_Error::add_error(
1786
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
1787
+				__FILE__,
1788
+				__FUNCTION__,
1789
+				__LINE__
1790
+			);
1791
+			return;
1792
+		}
1793
+		if (! $this->reg_code()) {
1794
+			parent::set('REG_code', $REG_code, $use_default);
1795
+		} else {
1796
+			EE_Error::doing_it_wrong(
1797
+				__CLASS__ . '::' . __FUNCTION__,
1798
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1799
+				'4.6.0'
1800
+			);
1801
+		}
1802
+	}
1803
+
1804
+
1805
+	/**
1806
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1807
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1808
+	 *    $registration->transaction()->registrations();
1809
+	 *
1810
+	 * @since 4.5.0
1811
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
1812
+	 * @throws EE_Error
1813
+	 */
1814
+	public function get_all_other_registrations_in_group()
1815
+	{
1816
+		if ($this->group_size() < 2) {
1817
+			return array();
1818
+		}
1819
+
1820
+		$query[0] = array(
1821
+			'TXN_ID' => $this->transaction_ID(),
1822
+			'REG_ID' => array('!=', $this->ID()),
1823
+			'TKT_ID' => $this->ticket_ID(),
1824
+		);
1825
+		/** @var EE_Registration[] $registrations */
1826
+		$registrations = $this->get_model()->get_all($query);
1827
+		return $registrations;
1828
+	}
1829
+
1830
+	/**
1831
+	 * Return the link to the admin details for the object.
1832
+	 *
1833
+	 * @return string
1834
+	 * @throws EE_Error
1835
+	 */
1836
+	public function get_admin_details_link()
1837
+	{
1838
+		EE_Registry::instance()->load_helper('URL');
1839
+		return EEH_URL::add_query_args_and_nonce(
1840
+			array(
1841
+				'page'    => 'espresso_registrations',
1842
+				'action'  => 'view_registration',
1843
+				'_REG_ID' => $this->ID(),
1844
+			),
1845
+			admin_url('admin.php')
1846
+		);
1847
+	}
1848
+
1849
+	/**
1850
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1851
+	 *
1852
+	 * @return string
1853
+	 * @throws EE_Error
1854
+	 */
1855
+	public function get_admin_edit_link()
1856
+	{
1857
+		return $this->get_admin_details_link();
1858
+	}
1859
+
1860
+	/**
1861
+	 * Returns the link to a settings page for the object.
1862
+	 *
1863
+	 * @return string
1864
+	 * @throws EE_Error
1865
+	 */
1866
+	public function get_admin_settings_link()
1867
+	{
1868
+		return $this->get_admin_details_link();
1869
+	}
1870
+
1871
+	/**
1872
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1873
+	 *
1874
+	 * @return string
1875
+	 */
1876
+	public function get_admin_overview_link()
1877
+	{
1878
+		EE_Registry::instance()->load_helper('URL');
1879
+		return EEH_URL::add_query_args_and_nonce(
1880
+			array(
1881
+				'page' => 'espresso_registrations',
1882
+			),
1883
+			admin_url('admin.php')
1884
+		);
1885
+	}
1886
+
1887
+
1888
+	/**
1889
+	 * @param array $query_params
1890
+	 *
1891
+	 * @return \EE_Registration[]
1892
+	 * @throws EE_Error
1893
+	 */
1894
+	public function payments($query_params = array())
1895
+	{
1896
+		return $this->get_many_related('Payment', $query_params);
1897
+	}
1898
+
1899
+
1900
+	/**
1901
+	 * @param array $query_params
1902
+	 *
1903
+	 * @return \EE_Registration_Payment[]
1904
+	 * @throws EE_Error
1905
+	 */
1906
+	public function registration_payments($query_params = array())
1907
+	{
1908
+		return $this->get_many_related('Registration_Payment', $query_params);
1909
+	}
1910
+
1911
+
1912
+	/**
1913
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1914
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1915
+	 *
1916
+	 * @return EE_Payment_Method|null
1917
+	 */
1918
+	public function payment_method()
1919
+	{
1920
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1921
+	}
1922
+
1923
+
1924
+	/**
1925
+	 * @return \EE_Line_Item
1926
+	 * @throws EntityNotFoundException
1927
+	 * @throws EE_Error
1928
+	 */
1929
+	public function ticket_line_item()
1930
+	{
1931
+		$ticket = $this->ticket();
1932
+		$transaction = $this->transaction();
1933
+		$line_item = null;
1934
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1935
+			$transaction->total_line_item(),
1936
+			'Ticket',
1937
+			array($ticket->ID())
1938
+		);
1939
+		foreach ($ticket_line_items as $ticket_line_item) {
1940
+			if (
1941
+				$ticket_line_item instanceof \EE_Line_Item
1942
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1943
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1944
+			) {
1945
+				$line_item = $ticket_line_item;
1946
+				break;
1947
+			}
1948
+		}
1949
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1950
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1951
+		}
1952
+		return $line_item;
1953
+	}
1954
+
1955
+
1956
+	/**
1957
+	 * Soft Deletes this model object.
1958
+	 *
1959
+	 * @return boolean | int
1960
+	 * @throws RuntimeException
1961
+	 * @throws EE_Error
1962
+	 */
1963
+	public function delete()
1964
+	{
1965
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1966
+			$this->set_status(EEM_Registration::status_id_cancelled);
1967
+		}
1968
+		return parent::delete();
1969
+	}
1970
+
1971
+
1972
+	/**
1973
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1974
+	 *
1975
+	 * @throws EE_Error
1976
+	 * @throws RuntimeException
1977
+	 */
1978
+	public function restore()
1979
+	{
1980
+		$previous_status = $this->get_extra_meta(
1981
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1982
+			true,
1983
+			EEM_Registration::status_id_cancelled
1984
+		);
1985
+		if ($previous_status) {
1986
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1987
+			$this->set_status($previous_status);
1988
+		}
1989
+		return parent::restore();
1990
+	}
1991
+
1992
+
1993
+	/**
1994
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1995
+	 *
1996
+	 * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1997
+	 *                                           depending on whether the reg status changes to or from "Approved"
1998
+	 * @return boolean whether the Registration status was updated
1999
+	 * @throws EE_Error
2000
+	 * @throws RuntimeException
2001
+	 */
2002
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2003
+	{
2004
+		$paid = $this->paid();
2005
+		$price = $this->final_price();
2006
+		switch (true) {
2007
+			// overpaid or paid
2008
+			case EEH_Money::compare_floats($paid, $price, '>'):
2009
+			case EEH_Money::compare_floats($paid, $price):
2010
+				$new_status = EEM_Registration::status_id_approved;
2011
+				break;
2012
+			//  underpaid
2013
+			case EEH_Money::compare_floats($paid, $price, '<'):
2014
+				$new_status = EEM_Registration::status_id_pending_payment;
2015
+				break;
2016
+			// uhhh Houston...
2017
+			default:
2018
+				throw new RuntimeException(
2019
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2020
+				);
2021
+		}
2022
+		if ($new_status !== $this->status_ID()) {
2023
+			if ($trigger_set_status_logic) {
2024
+				return $this->set_status($new_status);
2025
+			}
2026
+			parent::set('STS_ID', $new_status);
2027
+			return true;
2028
+		}
2029
+		return false;
2030
+	}
2031
+
2032
+
2033
+	/*************************** DEPRECATED ***************************/
2034
+
2035
+
2036
+	/**
2037
+	 * @deprecated
2038
+	 * @since     4.7.0
2039
+	 * @access    public
2040
+	 */
2041
+	public function price_paid()
2042
+	{
2043
+		EE_Error::doing_it_wrong(
2044
+			'EE_Registration::price_paid()',
2045
+			esc_html__(
2046
+				'This method is deprecated, please use EE_Registration::final_price() instead.',
2047
+				'event_espresso'
2048
+			),
2049
+			'4.7.0'
2050
+		);
2051
+		return $this->final_price();
2052
+	}
2053
+
2054
+
2055
+	/**
2056
+	 * @deprecated
2057
+	 * @since     4.7.0
2058
+	 * @access    public
2059
+	 * @param    float $REG_final_price
2060
+	 * @throws EE_Error
2061
+	 * @throws RuntimeException
2062
+	 */
2063
+	public function set_price_paid($REG_final_price = 0.00)
2064
+	{
2065
+		EE_Error::doing_it_wrong(
2066
+			'EE_Registration::set_price_paid()',
2067
+			esc_html__(
2068
+				'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2069
+				'event_espresso'
2070
+			),
2071
+			'4.7.0'
2072
+		);
2073
+		$this->set_final_price($REG_final_price);
2074
+	}
2075
+
2076
+
2077
+	/**
2078
+	 * @deprecated
2079
+	 * @since 4.7.0
2080
+	 * @return string
2081
+	 * @throws EE_Error
2082
+	 */
2083
+	public function pretty_price_paid()
2084
+	{
2085
+		EE_Error::doing_it_wrong(
2086
+			'EE_Registration::pretty_price_paid()',
2087
+			esc_html__(
2088
+				'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2089
+				'event_espresso'
2090
+			),
2091
+			'4.7.0'
2092
+		);
2093
+		return $this->pretty_final_price();
2094
+	}
2095
+
2096
+
2097
+	/**
2098
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2099
+	 *
2100
+	 * @deprecated 4.9.17
2101
+	 * @return EE_Datetime
2102
+	 * @throws EE_Error
2103
+	 * @throws EntityNotFoundException
2104
+	 */
2105
+	public function get_related_primary_datetime()
2106
+	{
2107
+		EE_Error::doing_it_wrong(
2108
+			__METHOD__,
2109
+			esc_html__(
2110
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2111
+				'event_espresso'
2112
+			),
2113
+			'4.9.17',
2114
+			'5.0.0'
2115
+		);
2116
+		return $this->event()->primary_datetime();
2117
+	}
2118
+
2119
+	/**
2120
+	 * Returns the contact's name (or "Unknown" if there is no contact.)
2121
+	 * @since 4.10.12.p
2122
+	 * @return string
2123
+	 * @throws EE_Error
2124
+	 * @throws InvalidArgumentException
2125
+	 * @throws InvalidDataTypeException
2126
+	 * @throws InvalidInterfaceException
2127
+	 * @throws ReflectionException
2128
+	 */
2129
+	public function name()
2130
+	{
2131
+		return $this->attendeeName();
2132
+	}
2133 2133
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Spacing   +119 added lines, -119 removed lines patch added patch discarded remove patch
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
         $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147 147
         // verify client code has not passed any invalid field names
148 148
         foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
149
+            if ( ! isset($model_fields[$field_name])) {
150 150
                 throw new EE_Error(
151 151
                     sprintf(
152 152
                         esc_html__(
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
             }
162 162
         }
163 163
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
164
+        if ( ! empty($date_formats) && is_array($date_formats)) {
165 165
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
166 166
         } else {
167 167
             // set default formats for date and time
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
             foreach ($model_fields as $fieldName => $field) {
175 175
                 $this->set_from_db(
176 176
                     $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
177
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null
178 178
                 );
179 179
             }
180 180
         } else {
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
             foreach ($model_fields as $fieldName => $field) {
184 184
                 $this->set(
185 185
                     $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
186
+                    isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null,
187 187
                     true
188 188
                 );
189 189
             }
@@ -191,15 +191,15 @@  discard block
 block discarded – undo
191 191
         // remember what values were passed to this constructor
192 192
         $this->_props_n_values_provided_in_constructor = $fieldValues;
193 193
         // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
194
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
195 195
             $model->add_to_entity_map($this);
196 196
         }
197 197
         // setup all the relations
198 198
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199 199
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
200
+                $this->_model_relations[$relation_name] = null;
201 201
             } else {
202
-                $this->_model_relations[ $relation_name ] = array();
202
+                $this->_model_relations[$relation_name] = array();
203 203
             }
204 204
         }
205 205
         /**
@@ -251,10 +251,10 @@  discard block
 block discarded – undo
251 251
     public function get_original($field_name)
252 252
     {
253 253
         if (
254
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
254
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
255 255
             && $field_settings = $this->get_model()->field_settings_for($field_name)
256 256
         ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
257
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
258 258
         }
259 259
         return null;
260 260
     }
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         // then don't do anything
292 292
         if (
293 293
             ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
294
+            && $this->_fields[$field_name] === $field_value
295 295
             && $this->ID()
296 296
         ) {
297 297
             return;
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
             $holder_of_value = $field_obj->prepare_for_set($field_value);
310 310
             // should the value be null?
311 311
             if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
312
+                $this->_fields[$field_name] = $field_obj->get_default_value();
313 313
                 /**
314 314
                  * To save having to refactor all the models, if a default value is used for a
315 315
                  * EE_Datetime_Field, and that value is not null nor is it a DateTime
@@ -320,15 +320,15 @@  discard block
 block discarded – undo
320 320
                  */
321 321
                 if (
322 322
                     $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
323
+                    && $this->_fields[$field_name] !== null
324
+                    && ! $this->_fields[$field_name] instanceof DateTime
325 325
                 ) {
326
-                    empty($this->_fields[ $field_name ])
326
+                    empty($this->_fields[$field_name])
327 327
                         ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
328
+                        : $this->set($field_name, $this->_fields[$field_name]);
329 329
                 }
330 330
             } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
331
+                $this->_fields[$field_name] = $holder_of_value;
332 332
             }
333 333
             // if we're not in the constructor...
334 334
             // now check if what we set was a primary key
@@ -391,8 +391,8 @@  discard block
 block discarded – undo
391 391
      */
392 392
     public function getCustomSelect($alias)
393 393
     {
394
-        return isset($this->custom_selection_results[ $alias ])
395
-            ? $this->custom_selection_results[ $alias ]
394
+        return isset($this->custom_selection_results[$alias])
395
+            ? $this->custom_selection_results[$alias]
396 396
             : null;
397 397
     }
398 398
 
@@ -479,8 +479,8 @@  discard block
 block discarded – undo
479 479
         foreach ($model_fields as $field_name => $field_obj) {
480 480
             if ($field_obj instanceof EE_Datetime_Field) {
481 481
                 $field_obj->set_timezone($this->_timezone);
482
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
482
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
483
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
484 484
                 }
485 485
             }
486 486
         }
@@ -538,7 +538,7 @@  discard block
 block discarded – undo
538 538
      */
539 539
     public function get_format($full = true)
540 540
     {
541
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
541
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542 542
     }
543 543
 
544 544
 
@@ -564,11 +564,11 @@  discard block
 block discarded – undo
564 564
     public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565 565
     {
566 566
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
-        if (! $object_to_cache instanceof EE_Base_Class) {
567
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
568 568
             return false;
569 569
         }
570 570
         // also get "how" the object is related, or throw an error
571
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
571
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572 572
             throw new EE_Error(
573 573
                 sprintf(
574 574
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -582,38 +582,38 @@  discard block
 block discarded – undo
582 582
             // if it's a "belongs to" relationship, then there's only one related model object
583 583
             // eg, if this is a registration, there's only 1 attendee for it
584 584
             // so for these model objects just set it to be cached
585
-            $this->_model_relations[ $relationName ] = $object_to_cache;
585
+            $this->_model_relations[$relationName] = $object_to_cache;
586 586
             $return = true;
587 587
         } else {
588 588
             // otherwise, this is the "many" side of a one to many relationship,
589 589
             // so we'll add the object to the array of related objects for that type.
590 590
             // eg: if this is an event, there are many registrations for that event,
591 591
             // so we cache the registrations in an array
592
-            if (! is_array($this->_model_relations[ $relationName ])) {
592
+            if ( ! is_array($this->_model_relations[$relationName])) {
593 593
                 // if for some reason, the cached item is a model object,
594 594
                 // then stick that in the array, otherwise start with an empty array
595
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
595
+                $this->_model_relations[$relationName] = $this->_model_relations[$relationName]
596 596
                                                            instanceof
597 597
                                                            EE_Base_Class
598
-                    ? array($this->_model_relations[ $relationName ]) : array();
598
+                    ? array($this->_model_relations[$relationName]) : array();
599 599
             }
600 600
             // first check for a cache_id which is normally empty
601
-            if (! empty($cache_id)) {
601
+            if ( ! empty($cache_id)) {
602 602
                 // if the cache_id exists, then it means we are purposely trying to cache this
603 603
                 // with a known key that can then be used to retrieve the object later on
604
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
604
+                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
605 605
                 $return = $cache_id;
606 606
             } elseif ($object_to_cache->ID()) {
607 607
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
608
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
608
+                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
609 609
                 $return = $object_to_cache->ID();
610 610
             } else {
611 611
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
612
+                $this->_model_relations[$relationName][] = $object_to_cache;
613 613
                 // move the internal pointer to the end of the array
614
-                end($this->_model_relations[ $relationName ]);
614
+                end($this->_model_relations[$relationName]);
615 615
                 // and grab the key so that we can return it
616
-                $return = key($this->_model_relations[ $relationName ]);
616
+                $return = key($this->_model_relations[$relationName]);
617 617
             }
618 618
         }
619 619
         return $return;
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
         // first make sure this property exists
640 640
         $this->get_model()->field_settings_for($fieldname);
641 641
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
642
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
643 643
     }
644 644
 
645 645
 
@@ -668,9 +668,9 @@  discard block
 block discarded – undo
668 668
         $model = $this->get_model();
669 669
         $model->field_settings_for($fieldname);
670 670
         $cache_type = $pretty ? 'pretty' : 'standard';
671
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
671
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
672
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
673
+            return $this->_cached_properties[$fieldname][$cache_type];
674 674
         }
675 675
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676 676
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -698,12 +698,12 @@  discard block
 block discarded – undo
698 698
         if ($field_obj instanceof EE_Datetime_Field) {
699 699
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700 700
         }
701
-        if (! isset($this->_fields[ $fieldname ])) {
702
-            $this->_fields[ $fieldname ] = null;
701
+        if ( ! isset($this->_fields[$fieldname])) {
702
+            $this->_fields[$fieldname] = null;
703 703
         }
704 704
         $value = $pretty
705
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
705
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
706
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
707 707
         return $value;
708 708
     }
709 709
 
@@ -761,8 +761,8 @@  discard block
 block discarded – undo
761 761
      */
762 762
     protected function _clear_cached_property($property_name)
763 763
     {
764
-        if (isset($this->_cached_properties[ $property_name ])) {
765
-            unset($this->_cached_properties[ $property_name ]);
764
+        if (isset($this->_cached_properties[$property_name])) {
765
+            unset($this->_cached_properties[$property_name]);
766 766
         }
767 767
     }
768 768
 
@@ -814,7 +814,7 @@  discard block
 block discarded – undo
814 814
     {
815 815
         $relationship_to_model = $this->get_model()->related_settings_for($relationName);
816 816
         $index_in_cache = '';
817
-        if (! $relationship_to_model) {
817
+        if ( ! $relationship_to_model) {
818 818
             throw new EE_Error(
819 819
                 sprintf(
820 820
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -825,10 +825,10 @@  discard block
 block discarded – undo
825 825
         }
826 826
         if ($clear_all) {
827 827
             $obj_removed = true;
828
-            $this->_model_relations[ $relationName ] = null;
828
+            $this->_model_relations[$relationName] = null;
829 829
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
830
-            $obj_removed = $this->_model_relations[ $relationName ];
831
-            $this->_model_relations[ $relationName ] = null;
830
+            $obj_removed = $this->_model_relations[$relationName];
831
+            $this->_model_relations[$relationName] = null;
832 832
         } else {
833 833
             if (
834 834
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -836,12 +836,12 @@  discard block
 block discarded – undo
836 836
             ) {
837 837
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
838 838
                 if (
839
-                    is_array($this->_model_relations[ $relationName ])
840
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
839
+                    is_array($this->_model_relations[$relationName])
840
+                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
841 841
                 ) {
842 842
                     $index_found_at = null;
843 843
                     // find this object in the array even though it has a different key
844
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
844
+                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
845 845
                         /** @noinspection TypeUnsafeComparisonInspection */
846 846
                         if (
847 847
                             $obj instanceof EE_Base_Class
@@ -875,9 +875,9 @@  discard block
 block discarded – undo
875 875
             }
876 876
             // supposedly we've found it. But it could just be that the client code
877 877
             // provided a bad index/object
878
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
879
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
880
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
878
+            if (isset($this->_model_relations[$relationName][$index_in_cache])) {
879
+                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
880
+                unset($this->_model_relations[$relationName][$index_in_cache]);
881 881
             } else {
882 882
                 // that thing was never cached anyways.
883 883
                 $obj_removed = null;
@@ -908,7 +908,7 @@  discard block
 block discarded – undo
908 908
         $current_cache_id = ''
909 909
     ) {
910 910
         // verify that incoming object is of the correct type
911
-        $obj_class = 'EE_' . $relationName;
911
+        $obj_class = 'EE_'.$relationName;
912 912
         if ($newly_saved_object instanceof $obj_class) {
913 913
             /* @type EE_Base_Class $newly_saved_object */
914 914
             // now get the type of relation
@@ -916,18 +916,18 @@  discard block
 block discarded – undo
916 916
             // if this is a 1:1 relationship
917 917
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
918 918
                 // then just replace the cached object with the newly saved object
919
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
919
+                $this->_model_relations[$relationName] = $newly_saved_object;
920 920
                 return true;
921 921
                 // or if it's some kind of sordid feral polyamorous relationship...
922 922
             }
923 923
             if (
924
-                is_array($this->_model_relations[ $relationName ])
925
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
924
+                is_array($this->_model_relations[$relationName])
925
+                && isset($this->_model_relations[$relationName][$current_cache_id])
926 926
             ) {
927 927
                 // then remove the current cached item
928
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
928
+                unset($this->_model_relations[$relationName][$current_cache_id]);
929 929
                 // and cache the newly saved object using it's new ID
930
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
930
+                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
931 931
                 return true;
932 932
             }
933 933
         }
@@ -944,8 +944,8 @@  discard block
 block discarded – undo
944 944
      */
945 945
     public function get_one_from_cache($relationName)
946 946
     {
947
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
948
-            ? $this->_model_relations[ $relationName ]
947
+        $cached_array_or_object = isset($this->_model_relations[$relationName])
948
+            ? $this->_model_relations[$relationName]
949 949
             : null;
950 950
         if (is_array($cached_array_or_object)) {
951 951
             return array_shift($cached_array_or_object);
@@ -968,7 +968,7 @@  discard block
 block discarded – undo
968 968
      */
969 969
     public function get_all_from_cache($relationName)
970 970
     {
971
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
971
+        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
972 972
         // if the result is not an array, but exists, make it an array
973 973
         $objects = is_array($objects) ? $objects : array($objects);
974 974
         // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
@@ -1152,7 +1152,7 @@  discard block
 block discarded – undo
1152 1152
             } else {
1153 1153
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1154 1154
             }
1155
-            $this->_fields[ $field_name ] = $field_value;
1155
+            $this->_fields[$field_name] = $field_value;
1156 1156
             $this->_clear_cached_property($field_name);
1157 1157
         }
1158 1158
     }
@@ -1192,9 +1192,9 @@  discard block
 block discarded – undo
1192 1192
     public function get_raw($field_name)
1193 1193
     {
1194 1194
         $field_settings = $this->get_model()->field_settings_for($field_name);
1195
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
-            ? $this->_fields[ $field_name ]->format('U')
1197
-            : $this->_fields[ $field_name ];
1195
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1196
+            ? $this->_fields[$field_name]->format('U')
1197
+            : $this->_fields[$field_name];
1198 1198
     }
1199 1199
 
1200 1200
 
@@ -1216,7 +1216,7 @@  discard block
 block discarded – undo
1216 1216
     public function get_DateTime_object($field_name)
1217 1217
     {
1218 1218
         $field_settings = $this->get_model()->field_settings_for($field_name);
1219
-        if (! $field_settings instanceof EE_Datetime_Field) {
1219
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1220 1220
             EE_Error::add_error(
1221 1221
                 sprintf(
1222 1222
                     esc_html__(
@@ -1231,8 +1231,8 @@  discard block
 block discarded – undo
1231 1231
             );
1232 1232
             return false;
1233 1233
         }
1234
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
-            ? clone $this->_fields[ $field_name ]
1234
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1235
+            ? clone $this->_fields[$field_name]
1236 1236
             : null;
1237 1237
     }
1238 1238
 
@@ -1474,7 +1474,7 @@  discard block
 block discarded – undo
1474 1474
      */
1475 1475
     public function get_i18n_datetime($field_name, $format = '')
1476 1476
     {
1477
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1477
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1478 1478
         return date_i18n(
1479 1479
             $format,
1480 1480
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1586,21 +1586,21 @@  discard block
 block discarded – undo
1586 1586
         $field->set_time_format($this->_tm_frmt);
1587 1587
         switch ($what) {
1588 1588
             case 'T':
1589
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_time(
1589
+                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1590 1590
                     $datetime_value,
1591
-                    $this->_fields[ $fieldname ]
1591
+                    $this->_fields[$fieldname]
1592 1592
                 );
1593 1593
                 $this->_has_changes = true;
1594 1594
                 break;
1595 1595
             case 'D':
1596
-                $this->_fields[ $fieldname ] = $field->prepare_for_set_with_new_date(
1596
+                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1597 1597
                     $datetime_value,
1598
-                    $this->_fields[ $fieldname ]
1598
+                    $this->_fields[$fieldname]
1599 1599
                 );
1600 1600
                 $this->_has_changes = true;
1601 1601
                 break;
1602 1602
             case 'B':
1603
-                $this->_fields[ $fieldname ] = $field->prepare_for_set($datetime_value);
1603
+                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1604 1604
                 $this->_has_changes = true;
1605 1605
                 break;
1606 1606
         }
@@ -1643,7 +1643,7 @@  discard block
 block discarded – undo
1643 1643
         $this->set_timezone($timezone);
1644 1644
         $fn = (array) $field_name;
1645 1645
         $args = array_merge($fn, (array) $args);
1646
-        if (! method_exists($this, $callback)) {
1646
+        if ( ! method_exists($this, $callback)) {
1647 1647
             throw new EE_Error(
1648 1648
                 sprintf(
1649 1649
                     esc_html__(
@@ -1655,7 +1655,7 @@  discard block
 block discarded – undo
1655 1655
             );
1656 1656
         }
1657 1657
         $args = (array) $args;
1658
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1658
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1659 1659
         $this->set_timezone($original_timezone);
1660 1660
         return $return;
1661 1661
     }
@@ -1770,8 +1770,8 @@  discard block
 block discarded – undo
1770 1770
     {
1771 1771
         $model = $this->get_model();
1772 1772
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
-            if (! empty($this->_model_relations[ $relation_name ])) {
1774
-                $related_objects = $this->_model_relations[ $relation_name ];
1773
+            if ( ! empty($this->_model_relations[$relation_name])) {
1774
+                $related_objects = $this->_model_relations[$relation_name];
1775 1775
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776 1776
                     // this relation only stores a single model object, not an array
1777 1777
                     // but let's make it consistent
@@ -1828,7 +1828,7 @@  discard block
 block discarded – undo
1828 1828
             $this->set($column, $value);
1829 1829
         }
1830 1830
         // no changes ? then don't do anything
1831
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1831
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1832 1832
             return 0;
1833 1833
         }
1834 1834
         /**
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
          * @param EE_Base_Class $model_object the model object about to be saved.
1839 1839
          */
1840 1840
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1841
-        if (! $this->allow_persist()) {
1841
+        if ( ! $this->allow_persist()) {
1842 1842
             return 0;
1843 1843
         }
1844 1844
         // now get current attribute values
@@ -1853,10 +1853,10 @@  discard block
 block discarded – undo
1853 1853
         if ($model->has_primary_key_field()) {
1854 1854
             if ($model->get_primary_key_field()->is_auto_increment()) {
1855 1855
                 // ok check if it's set, if so: update; if not, insert
1856
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1856
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1857 1857
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1858 1858
                 } else {
1859
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1859
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1860 1860
                     $results = $model->insert($save_cols_n_values);
1861 1861
                     if ($results) {
1862 1862
                         // if successful, set the primary key
@@ -1866,7 +1866,7 @@  discard block
 block discarded – undo
1866 1866
                         // will get added to the mapper before we can add this one!
1867 1867
                         // but if we just avoid using the SET method, all that headache can be avoided
1868 1868
                         $pk_field_name = $model->primary_key_name();
1869
-                        $this->_fields[ $pk_field_name ] = $results;
1869
+                        $this->_fields[$pk_field_name] = $results;
1870 1870
                         $this->_clear_cached_property($pk_field_name);
1871 1871
                         $model->add_to_entity_map($this);
1872 1872
                         $this->_update_cached_related_model_objs_fks();
@@ -1883,8 +1883,8 @@  discard block
 block discarded – undo
1883 1883
                                     'event_espresso'
1884 1884
                                 ),
1885 1885
                                 get_class($this),
1886
-                                get_class($model) . '::instance()->add_to_entity_map()',
1887
-                                get_class($model) . '::instance()->get_one_by_ID()',
1886
+                                get_class($model).'::instance()->add_to_entity_map()',
1887
+                                get_class($model).'::instance()->get_one_by_ID()',
1888 1888
                                 '<br />'
1889 1889
                             )
1890 1890
                         );
@@ -1986,27 +1986,27 @@  discard block
 block discarded – undo
1986 1986
     public function save_new_cached_related_model_objs()
1987 1987
     {
1988 1988
         // make sure this has been saved
1989
-        if (! $this->ID()) {
1989
+        if ( ! $this->ID()) {
1990 1990
             $id = $this->save();
1991 1991
         } else {
1992 1992
             $id = $this->ID();
1993 1993
         }
1994 1994
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1995 1995
         foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1996
-            if ($this->_model_relations[ $relationName ]) {
1996
+            if ($this->_model_relations[$relationName]) {
1997 1997
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1998 1998
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1999 1999
                 /* @var $related_model_obj EE_Base_Class */
2000 2000
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
2001 2001
                     // add a relation to that relation type (which saves the appropriate thing in the process)
2002 2002
                     // but ONLY if it DOES NOT exist in the DB
2003
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2003
+                    $related_model_obj = $this->_model_relations[$relationName];
2004 2004
                     // if( ! $related_model_obj->ID()){
2005 2005
                     $this->_add_relation_to($related_model_obj, $relationName);
2006 2006
                     $related_model_obj->save_new_cached_related_model_objs();
2007 2007
                     // }
2008 2008
                 } else {
2009
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2009
+                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
2010 2010
                         // add a relation to that relation type (which saves the appropriate thing in the process)
2011 2011
                         // but ONLY if it DOES NOT exist in the DB
2012 2012
                         // if( ! $related_model_obj->ID()){
@@ -2033,7 +2033,7 @@  discard block
 block discarded – undo
2033 2033
      */
2034 2034
     public function get_model()
2035 2035
     {
2036
-        if (! $this->_model) {
2036
+        if ( ! $this->_model) {
2037 2037
             $modelName = self::_get_model_classname(get_class($this));
2038 2038
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2039 2039
         } else {
@@ -2059,9 +2059,9 @@  discard block
 block discarded – undo
2059 2059
         $primary_id_ref = self::_get_primary_key_name($classname);
2060 2060
         if (
2061 2061
             array_key_exists($primary_id_ref, $props_n_values)
2062
-            && ! empty($props_n_values[ $primary_id_ref ])
2062
+            && ! empty($props_n_values[$primary_id_ref])
2063 2063
         ) {
2064
-            $id = $props_n_values[ $primary_id_ref ];
2064
+            $id = $props_n_values[$primary_id_ref];
2065 2065
             return self::_get_model($classname)->get_from_entity_map($id);
2066 2066
         }
2067 2067
         return false;
@@ -2096,10 +2096,10 @@  discard block
 block discarded – undo
2096 2096
             $primary_id_ref = self::_get_primary_key_name($classname);
2097 2097
             if (
2098 2098
                 array_key_exists($primary_id_ref, $props_n_values)
2099
-                && ! empty($props_n_values[ $primary_id_ref ])
2099
+                && ! empty($props_n_values[$primary_id_ref])
2100 2100
             ) {
2101 2101
                 $existing = $model->get_one_by_ID(
2102
-                    $props_n_values[ $primary_id_ref ]
2102
+                    $props_n_values[$primary_id_ref]
2103 2103
                 );
2104 2104
             }
2105 2105
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2111,7 +2111,7 @@  discard block
 block discarded – undo
2111 2111
         }
2112 2112
         if ($existing) {
2113 2113
             // set date formats if present before setting values
2114
-            if (! empty($date_formats) && is_array($date_formats)) {
2114
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2115 2115
                 $existing->set_date_format($date_formats[0]);
2116 2116
                 $existing->set_time_format($date_formats[1]);
2117 2117
             } else {
@@ -2144,7 +2144,7 @@  discard block
 block discarded – undo
2144 2144
     protected static function _get_model($classname, $timezone = null)
2145 2145
     {
2146 2146
         // find model for this class
2147
-        if (! $classname) {
2147
+        if ( ! $classname) {
2148 2148
             throw new EE_Error(
2149 2149
                 sprintf(
2150 2150
                     esc_html__(
@@ -2193,7 +2193,7 @@  discard block
 block discarded – undo
2193 2193
         if (strpos($model_name, 'EE_') === 0) {
2194 2194
             $model_classname = str_replace('EE_', 'EEM_', $model_name);
2195 2195
         } else {
2196
-            $model_classname = 'EEM_' . $model_name;
2196
+            $model_classname = 'EEM_'.$model_name;
2197 2197
         }
2198 2198
         return $model_classname;
2199 2199
     }
@@ -2212,7 +2212,7 @@  discard block
 block discarded – undo
2212 2212
      */
2213 2213
     protected static function _get_primary_key_name($classname = null)
2214 2214
     {
2215
-        if (! $classname) {
2215
+        if ( ! $classname) {
2216 2216
             throw new EE_Error(
2217 2217
                 sprintf(
2218 2218
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2242,7 +2242,7 @@  discard block
 block discarded – undo
2242 2242
         $model = $this->get_model();
2243 2243
         // now that we know the name of the variable, use a variable variable to get its value and return its
2244 2244
         if ($model->has_primary_key_field()) {
2245
-            return $this->_fields[ $model->primary_key_name() ];
2245
+            return $this->_fields[$model->primary_key_name()];
2246 2246
         }
2247 2247
         return $model->get_index_primary_key_string($this->_fields);
2248 2248
     }
@@ -2295,7 +2295,7 @@  discard block
 block discarded – undo
2295 2295
             }
2296 2296
         } else {
2297 2297
             // this thing doesn't exist in the DB,  so just cache it
2298
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2298
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2299 2299
                 throw new EE_Error(
2300 2300
                     sprintf(
2301 2301
                         esc_html__(
@@ -2460,7 +2460,7 @@  discard block
 block discarded – undo
2460 2460
             } else {
2461 2461
                 // did we already cache the result of this query?
2462 2462
                 $cached_results = $this->get_all_from_cache($relationName);
2463
-                if (! $cached_results) {
2463
+                if ( ! $cached_results) {
2464 2464
                     $related_model_objects = $this->get_model()->get_all_related(
2465 2465
                         $this,
2466 2466
                         $relationName,
@@ -2571,7 +2571,7 @@  discard block
 block discarded – undo
2571 2571
             } else {
2572 2572
                 // first, check if we've already cached the result of this query
2573 2573
                 $cached_result = $this->get_one_from_cache($relationName);
2574
-                if (! $cached_result) {
2574
+                if ( ! $cached_result) {
2575 2575
                     $related_model_object = $model->get_first_related(
2576 2576
                         $this,
2577 2577
                         $relationName,
@@ -2595,7 +2595,7 @@  discard block
 block discarded – undo
2595 2595
             }
2596 2596
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2597 2597
             // just get what's cached on this object
2598
-            if (! $related_model_object) {
2598
+            if ( ! $related_model_object) {
2599 2599
                 $related_model_object = $this->get_one_from_cache($relationName);
2600 2600
             }
2601 2601
         }
@@ -2677,7 +2677,7 @@  discard block
 block discarded – undo
2677 2677
      */
2678 2678
     public function is_set($field_name)
2679 2679
     {
2680
-        return isset($this->_fields[ $field_name ]);
2680
+        return isset($this->_fields[$field_name]);
2681 2681
     }
2682 2682
 
2683 2683
 
@@ -2693,7 +2693,7 @@  discard block
 block discarded – undo
2693 2693
     {
2694 2694
         foreach ((array) $properties as $property_name) {
2695 2695
             // first make sure this property exists
2696
-            if (! $this->_fields[ $property_name ]) {
2696
+            if ( ! $this->_fields[$property_name]) {
2697 2697
                 throw new EE_Error(
2698 2698
                     sprintf(
2699 2699
                         esc_html__(
@@ -2725,7 +2725,7 @@  discard block
 block discarded – undo
2725 2725
         $properties = array();
2726 2726
         // remove prepended underscore
2727 2727
         foreach ($fields as $field_name => $settings) {
2728
-            $properties[ $field_name ] = $this->get($field_name);
2728
+            $properties[$field_name] = $this->get($field_name);
2729 2729
         }
2730 2730
         return $properties;
2731 2731
     }
@@ -2762,7 +2762,7 @@  discard block
 block discarded – undo
2762 2762
     {
2763 2763
         $className = get_class($this);
2764 2764
         $tagName = "FHEE__{$className}__{$methodName}";
2765
-        if (! has_filter($tagName)) {
2765
+        if ( ! has_filter($tagName)) {
2766 2766
             throw new EE_Error(
2767 2767
                 sprintf(
2768 2768
                     esc_html__(
@@ -2807,7 +2807,7 @@  discard block
 block discarded – undo
2807 2807
             $query_params[0]['EXM_value'] = $meta_value;
2808 2808
         }
2809 2809
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2810
-        if (! $existing_rows_like_that) {
2810
+        if ( ! $existing_rows_like_that) {
2811 2811
             return $this->add_extra_meta($meta_key, $meta_value);
2812 2812
         }
2813 2813
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2925,7 +2925,7 @@  discard block
 block discarded – undo
2925 2925
                 $values = array();
2926 2926
                 foreach ($results as $result) {
2927 2927
                     if ($result instanceof EE_Extra_Meta) {
2928
-                        $values[ $result->ID() ] = $result->value();
2928
+                        $values[$result->ID()] = $result->value();
2929 2929
                     }
2930 2930
                 }
2931 2931
                 return $values;
@@ -2970,17 +2970,17 @@  discard block
 block discarded – undo
2970 2970
             );
2971 2971
             foreach ($extra_meta_objs as $extra_meta_obj) {
2972 2972
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2973
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2973
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2974 2974
                 }
2975 2975
             }
2976 2976
         } else {
2977 2977
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2978 2978
             foreach ($extra_meta_objs as $extra_meta_obj) {
2979 2979
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2980
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2981
-                        $return_array[ $extra_meta_obj->key() ] = array();
2980
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2981
+                        $return_array[$extra_meta_obj->key()] = array();
2982 2982
                     }
2983
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2983
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2984 2984
                 }
2985 2985
             }
2986 2986
         }
@@ -3061,8 +3061,8 @@  discard block
 block discarded – undo
3061 3061
                             'event_espresso'
3062 3062
                         ),
3063 3063
                         $this->ID(),
3064
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3065
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3064
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3065
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3066 3066
                     )
3067 3067
                 );
3068 3068
             }
@@ -3095,7 +3095,7 @@  discard block
 block discarded – undo
3095 3095
     {
3096 3096
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3097 3097
         // if it wasn't even there to start off.
3098
-        if (! $this->ID()) {
3098
+        if ( ! $this->ID()) {
3099 3099
             $this->save();
3100 3100
         }
3101 3101
         global $wpdb;
@@ -3325,7 +3325,7 @@  discard block
 block discarded – undo
3325 3325
         $model = $this->get_model();
3326 3326
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3327 3327
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3328
-                $classname = 'EE_' . $model->get_this_model_name();
3328
+                $classname = 'EE_'.$model->get_this_model_name();
3329 3329
                 if (
3330 3330
                     $this->get_one_from_cache($relation_name) instanceof $classname
3331 3331
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3366,7 +3366,7 @@  discard block
 block discarded – undo
3366 3366
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3367 3367
         foreach ($this->_fields as $field => $value) {
3368 3368
             if ($value instanceof DateTime) {
3369
-                $this->_fields[ $field ] = clone $value;
3369
+                $this->_fields[$field] = clone $value;
3370 3370
             }
3371 3371
         }
3372 3372
     }
Please login to merge, or discard this 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); // sanitized
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
1801
-     *                                  (often client code will change the fields' values before calling save)
1802
-     * @return false|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); // sanitized
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
1801
+	 *                                  (often client code will change the fields' values before calling save)
1802
+	 * @return false|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.