Completed
Branch master (16095c)
by
unknown
09:17 queued 04:49
created
core/services/request/CurrentPage.php 1 patch
Indentation   +316 added lines, -316 removed lines patch added patch discarded remove patch
@@ -23,320 +23,320 @@
 block discarded – undo
23 23
  */
24 24
 class CurrentPage
25 25
 {
26
-    /**
27
-     * @var EE_CPT_Strategy
28
-     */
29
-    private $cpt_strategy;
30
-
31
-    /**
32
-     * @var bool
33
-     */
34
-    private $initialized;
35
-
36
-    /**
37
-     * @var bool
38
-     */
39
-    private $is_espresso_page;
40
-
41
-    /**
42
-     * @var int
43
-     */
44
-    private $post_id = 0;
45
-
46
-    /**
47
-     * @var string|null
48
-     */
49
-    private $post_name = '';
50
-
51
-    /**
52
-     * @var array
53
-     */
54
-    private $post_type = [];
55
-
56
-    /**
57
-     * @var RequestInterface $request
58
-     */
59
-    private $request;
60
-
61
-
62
-    /**
63
-     * CurrentPage constructor.
64
-     *
65
-     * @param EE_CPT_Strategy  $cpt_strategy
66
-     * @param RequestInterface $request
67
-     */
68
-    public function __construct(EE_CPT_Strategy $cpt_strategy, RequestInterface $request)
69
-    {
70
-        $this->cpt_strategy = $cpt_strategy;
71
-        $this->request      = $request;
72
-        $this->initialized  = is_admin();
73
-        // analyse the incoming WP request
74
-        add_action('parse_request', [$this, 'parseQueryVars'], 2, 1);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param WP|null $WP
80
-     * @return void
81
-     */
82
-    public function parseQueryVars(WP $WP = null)
83
-    {
84
-        if ($this->initialized) {
85
-            return;
86
-        }
87
-        // if somebody forgot to provide us with WP, that's ok because its global
88
-        if (! $WP instanceof WP) {
89
-            global $WP;
90
-        }
91
-        $this->post_id   = $this->getPostId($WP);
92
-        $this->post_name = $this->getPostName($WP);
93
-        $this->post_type = $this->getPostType($WP);
94
-        // true or false ? is this page being used by EE ?
95
-        $this->setEspressoPage();
96
-        remove_action('parse_request', [$this, 'parseRequest'], 2);
97
-        $this->initialized = true;
98
-    }
99
-
100
-
101
-    /**
102
-     * Just a helper method for getting the url for the displayed page.
103
-     *
104
-     * @param WP|null $WP
105
-     * @return string
106
-     */
107
-    public function getPermalink(WP $WP = null): string
108
-    {
109
-        $post_id = $this->post_id ?: $this->getPostId($WP);
110
-        if ($post_id) {
111
-            return get_permalink($post_id);
112
-        }
113
-        if (! $WP instanceof WP) {
114
-            global $WP;
115
-        }
116
-        if ($WP instanceof WP && $WP->request) {
117
-            return site_url($WP->request);
118
-        }
119
-        return esc_url_raw(site_url($_SERVER['REQUEST_URI']));
120
-    }
121
-
122
-
123
-    /**
124
-     * @return array
125
-     */
126
-    public function espressoPostType(): array
127
-    {
128
-        return array_filter(
129
-            $this->post_type,
130
-            function ($post_type) {
131
-                return strpos($post_type, 'espresso_') === 0;
132
-            }
133
-        );
134
-    }
135
-
136
-
137
-    /**
138
-     * pokes and prods the WP object query_vars in an attempt to shake out a page/post ID
139
-     *
140
-     * @param WP|null $WP $WP
141
-     * @return int
142
-     */
143
-    private function getPostId(WP $WP = null): ?int
144
-    {
145
-        $post_id = 0;
146
-        if ($WP instanceof WP) {
147
-            // look for the post ID in the aptly named 'p' query var
148
-            if (isset($WP->query_vars['p'])) {
149
-                $post_id = $WP->query_vars['p'];
150
-            }
151
-            // not a post? what about a page?
152
-            if (! $post_id && isset($WP->query_vars['page_id'])) {
153
-                $post_id = $WP->query_vars['page_id'];
154
-            }
155
-            // ok... maybe pretty permalinks are off and the ID is set in the raw request...
156
-            // but hasn't been processed yet ie: this method is being called too early :\
157
-            if (! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
158
-                $post_id = basename($WP->request);
159
-            }
160
-        }
161
-        // none of the above? ok what about an explicit "post_id" URL parameter?
162
-        if (! $post_id && $this->request->requestParamIsSet('post_id')) {
163
-            $post_id = $this->request->getRequestParam('post_id', 0, DataType::INT);
164
-        }
165
-        return (int) $post_id;
166
-    }
167
-
168
-
169
-    /**
170
-     * similar to getPostId() above but attempts to obtain the "name" for the current page/post
171
-     *
172
-     * @param WP|null $WP $WP
173
-     * @return string|null
174
-     */
175
-    private function getPostName(WP $WP = null): ?string
176
-    {
177
-        global $wpdb;
178
-        $post_name = '';
179
-        if ($WP instanceof WP) {
180
-            // if this is a post, then is the post name set?
181
-            if (isset($WP->query_vars['name']) && ! empty($WP->query_vars['name'])) {
182
-                $post_name = is_array($WP->query_vars['name']) ? $WP->query_vars['name'][0] : $WP->query_vars['name'];
183
-            }
184
-            // what about the page name?
185
-            if (! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
186
-                $post_name = is_array($WP->query_vars['pagename']) ? $WP->query_vars['pagename'][0]
187
-                    : $WP->query_vars['pagename'];
188
-            }
189
-            // this stinks but let's run a query to try and get the post name from the URL
190
-            // (assuming pretty permalinks are on)
191
-            if (! $post_name && ! empty($WP->request)) {
192
-                $possible_post_name = basename($WP->request);
193
-                if (! is_numeric($possible_post_name)) {
194
-                    $SQL                = "SELECT ID from {$wpdb->posts}";
195
-                    $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
196
-                    $SQL                .= ' AND post_name=%s';
197
-                    $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
198
-                    if ($possible_post_name) {
199
-                        $post_name = $possible_post_name;
200
-                    }
201
-                }
202
-            }
203
-        }
204
-        // ug... ok... nothing yet... but do we have a post ID?
205
-        // if so then... sigh... run a query to get the post name :\
206
-        if (! $post_name && $this->post_id) {
207
-            $SQL                = "SELECT post_name from {$wpdb->posts}";
208
-            $SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
209
-            $SQL                .= ' AND ID=%d';
210
-            $possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->post_id));
211
-            if ($possible_post_name) {
212
-                $post_name = $possible_post_name;
213
-            }
214
-        }
215
-        // still nothing? ok what about an explicit 'post_name' URL parameter?
216
-        if (! $post_name && $this->request->requestParamIsSet('post_name')) {
217
-            $post_name = $this->request->getRequestParam('post_name');
218
-        }
219
-        return $post_name;
220
-    }
221
-
222
-
223
-    /**
224
-     * also similar to getPostId() and getPostName() above but not as insane
225
-     *
226
-     * @param WP|null $WP $WP
227
-     * @return array
228
-     */
229
-    private function getPostType(WP $WP = null): array
230
-    {
231
-        $post_types = [];
232
-        if ($WP instanceof WP) {
233
-            $post_types = isset($WP->query_vars['post_type'])
234
-                ? (array) $WP->query_vars['post_type']
235
-                : [];
236
-        }
237
-        if (empty($post_types) && $this->request->requestParamIsSet('post_type')) {
238
-            $post_types = $this->request->getRequestParam('post_type', [], DataType::STRING, true);
239
-        }
240
-        return (array) $post_types;
241
-    }
242
-
243
-
244
-    /**
245
-     * if TRUE, then the current page is somehow utilizing EE logic
246
-     *
247
-     * @return bool
248
-     */
249
-    public function isEspressoPage(): bool
250
-    {
251
-        if ($this->is_espresso_page === null) {
252
-            $this->setEspressoPage();
253
-        }
254
-        return $this->is_espresso_page;
255
-    }
256
-
257
-
258
-    /**
259
-     * @return int
260
-     */
261
-    public function postId(): int
262
-    {
263
-        return $this->post_id;
264
-    }
265
-
266
-
267
-    /**
268
-     * @return string|null
269
-     */
270
-    public function postName(): ?string
271
-    {
272
-        return $this->post_name;
273
-    }
274
-
275
-
276
-    /**
277
-     * @return array
278
-     */
279
-    public function postType(): array
280
-    {
281
-        return $this->post_type;
282
-    }
283
-
284
-
285
-    /**
286
-     * for manually indicating the current page will utilize EE logic
287
-     *
288
-     * @param bool|int|string|null $value
289
-     * @return void
290
-     */
291
-    public function setEspressoPage($value = null)
292
-    {
293
-        $this->is_espresso_page = $value !== null
294
-            ? filter_var($value, FILTER_VALIDATE_BOOLEAN)
295
-            : $this->testForEspressoPage();
296
-    }
297
-
298
-
299
-    /**
300
-     * attempts to determine if the current page/post is an EE related page/post
301
-     * because it utilizes one of our CPT taxonomies, endpoints, or post types
302
-     *
303
-     * @return bool
304
-     */
305
-    private function testForEspressoPage(): bool
306
-    {
307
-        // in case it has already been set
308
-        if ($this->is_espresso_page) {
309
-            return true;
310
-        }
311
-        global $WP;
312
-        $espresso_CPT_taxonomies = $this->cpt_strategy->get_CPT_taxonomies();
313
-        if (is_array($espresso_CPT_taxonomies)) {
314
-            foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
315
-                if (isset($WP->query_vars, $WP->query_vars[ $espresso_CPT_taxonomy ])) {
316
-                    return true;
317
-                }
318
-            }
319
-        }
320
-        // load espresso CPT endpoints
321
-        $espresso_CPT_endpoints  = $this->cpt_strategy->get_CPT_endpoints();
322
-        $post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
323
-        foreach ($this->post_type as $post_type) {
324
-            // was a post name passed ?
325
-            if (isset($post_type_CPT_endpoints[ $post_type ])) {
326
-                // kk we know this is an espresso page, but is it a specific post ?
327
-                if (! $this->post_name) {
328
-                    $espresso_post_type = $this->request->getRequestParam('post_type');
329
-                    // there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
330
-                    // this essentially sets the post_name to "events" (or whatever EE CPT)
331
-                    $post_name = $post_type_CPT_endpoints[ $espresso_post_type ] ?? '';
332
-                    // if the post type matches one of ours then set the post name to the endpoint
333
-                    if ($post_name) {
334
-                        $this->post_name = $post_name;
335
-                    }
336
-                }
337
-                return true;
338
-            }
339
-        }
340
-        return false;
341
-    }
26
+	/**
27
+	 * @var EE_CPT_Strategy
28
+	 */
29
+	private $cpt_strategy;
30
+
31
+	/**
32
+	 * @var bool
33
+	 */
34
+	private $initialized;
35
+
36
+	/**
37
+	 * @var bool
38
+	 */
39
+	private $is_espresso_page;
40
+
41
+	/**
42
+	 * @var int
43
+	 */
44
+	private $post_id = 0;
45
+
46
+	/**
47
+	 * @var string|null
48
+	 */
49
+	private $post_name = '';
50
+
51
+	/**
52
+	 * @var array
53
+	 */
54
+	private $post_type = [];
55
+
56
+	/**
57
+	 * @var RequestInterface $request
58
+	 */
59
+	private $request;
60
+
61
+
62
+	/**
63
+	 * CurrentPage constructor.
64
+	 *
65
+	 * @param EE_CPT_Strategy  $cpt_strategy
66
+	 * @param RequestInterface $request
67
+	 */
68
+	public function __construct(EE_CPT_Strategy $cpt_strategy, RequestInterface $request)
69
+	{
70
+		$this->cpt_strategy = $cpt_strategy;
71
+		$this->request      = $request;
72
+		$this->initialized  = is_admin();
73
+		// analyse the incoming WP request
74
+		add_action('parse_request', [$this, 'parseQueryVars'], 2, 1);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param WP|null $WP
80
+	 * @return void
81
+	 */
82
+	public function parseQueryVars(WP $WP = null)
83
+	{
84
+		if ($this->initialized) {
85
+			return;
86
+		}
87
+		// if somebody forgot to provide us with WP, that's ok because its global
88
+		if (! $WP instanceof WP) {
89
+			global $WP;
90
+		}
91
+		$this->post_id   = $this->getPostId($WP);
92
+		$this->post_name = $this->getPostName($WP);
93
+		$this->post_type = $this->getPostType($WP);
94
+		// true or false ? is this page being used by EE ?
95
+		$this->setEspressoPage();
96
+		remove_action('parse_request', [$this, 'parseRequest'], 2);
97
+		$this->initialized = true;
98
+	}
99
+
100
+
101
+	/**
102
+	 * Just a helper method for getting the url for the displayed page.
103
+	 *
104
+	 * @param WP|null $WP
105
+	 * @return string
106
+	 */
107
+	public function getPermalink(WP $WP = null): string
108
+	{
109
+		$post_id = $this->post_id ?: $this->getPostId($WP);
110
+		if ($post_id) {
111
+			return get_permalink($post_id);
112
+		}
113
+		if (! $WP instanceof WP) {
114
+			global $WP;
115
+		}
116
+		if ($WP instanceof WP && $WP->request) {
117
+			return site_url($WP->request);
118
+		}
119
+		return esc_url_raw(site_url($_SERVER['REQUEST_URI']));
120
+	}
121
+
122
+
123
+	/**
124
+	 * @return array
125
+	 */
126
+	public function espressoPostType(): array
127
+	{
128
+		return array_filter(
129
+			$this->post_type,
130
+			function ($post_type) {
131
+				return strpos($post_type, 'espresso_') === 0;
132
+			}
133
+		);
134
+	}
135
+
136
+
137
+	/**
138
+	 * pokes and prods the WP object query_vars in an attempt to shake out a page/post ID
139
+	 *
140
+	 * @param WP|null $WP $WP
141
+	 * @return int
142
+	 */
143
+	private function getPostId(WP $WP = null): ?int
144
+	{
145
+		$post_id = 0;
146
+		if ($WP instanceof WP) {
147
+			// look for the post ID in the aptly named 'p' query var
148
+			if (isset($WP->query_vars['p'])) {
149
+				$post_id = $WP->query_vars['p'];
150
+			}
151
+			// not a post? what about a page?
152
+			if (! $post_id && isset($WP->query_vars['page_id'])) {
153
+				$post_id = $WP->query_vars['page_id'];
154
+			}
155
+			// ok... maybe pretty permalinks are off and the ID is set in the raw request...
156
+			// but hasn't been processed yet ie: this method is being called too early :\
157
+			if (! $post_id && $WP->request !== null && is_numeric(basename($WP->request))) {
158
+				$post_id = basename($WP->request);
159
+			}
160
+		}
161
+		// none of the above? ok what about an explicit "post_id" URL parameter?
162
+		if (! $post_id && $this->request->requestParamIsSet('post_id')) {
163
+			$post_id = $this->request->getRequestParam('post_id', 0, DataType::INT);
164
+		}
165
+		return (int) $post_id;
166
+	}
167
+
168
+
169
+	/**
170
+	 * similar to getPostId() above but attempts to obtain the "name" for the current page/post
171
+	 *
172
+	 * @param WP|null $WP $WP
173
+	 * @return string|null
174
+	 */
175
+	private function getPostName(WP $WP = null): ?string
176
+	{
177
+		global $wpdb;
178
+		$post_name = '';
179
+		if ($WP instanceof WP) {
180
+			// if this is a post, then is the post name set?
181
+			if (isset($WP->query_vars['name']) && ! empty($WP->query_vars['name'])) {
182
+				$post_name = is_array($WP->query_vars['name']) ? $WP->query_vars['name'][0] : $WP->query_vars['name'];
183
+			}
184
+			// what about the page name?
185
+			if (! $post_name && isset($WP->query_vars['pagename']) && ! empty($WP->query_vars['pagename'])) {
186
+				$post_name = is_array($WP->query_vars['pagename']) ? $WP->query_vars['pagename'][0]
187
+					: $WP->query_vars['pagename'];
188
+			}
189
+			// this stinks but let's run a query to try and get the post name from the URL
190
+			// (assuming pretty permalinks are on)
191
+			if (! $post_name && ! empty($WP->request)) {
192
+				$possible_post_name = basename($WP->request);
193
+				if (! is_numeric($possible_post_name)) {
194
+					$SQL                = "SELECT ID from {$wpdb->posts}";
195
+					$SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
196
+					$SQL                .= ' AND post_name=%s';
197
+					$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $possible_post_name));
198
+					if ($possible_post_name) {
199
+						$post_name = $possible_post_name;
200
+					}
201
+				}
202
+			}
203
+		}
204
+		// ug... ok... nothing yet... but do we have a post ID?
205
+		// if so then... sigh... run a query to get the post name :\
206
+		if (! $post_name && $this->post_id) {
207
+			$SQL                = "SELECT post_name from {$wpdb->posts}";
208
+			$SQL                .= " WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash')";
209
+			$SQL                .= ' AND ID=%d';
210
+			$possible_post_name = $wpdb->get_var($wpdb->prepare($SQL, $this->post_id));
211
+			if ($possible_post_name) {
212
+				$post_name = $possible_post_name;
213
+			}
214
+		}
215
+		// still nothing? ok what about an explicit 'post_name' URL parameter?
216
+		if (! $post_name && $this->request->requestParamIsSet('post_name')) {
217
+			$post_name = $this->request->getRequestParam('post_name');
218
+		}
219
+		return $post_name;
220
+	}
221
+
222
+
223
+	/**
224
+	 * also similar to getPostId() and getPostName() above but not as insane
225
+	 *
226
+	 * @param WP|null $WP $WP
227
+	 * @return array
228
+	 */
229
+	private function getPostType(WP $WP = null): array
230
+	{
231
+		$post_types = [];
232
+		if ($WP instanceof WP) {
233
+			$post_types = isset($WP->query_vars['post_type'])
234
+				? (array) $WP->query_vars['post_type']
235
+				: [];
236
+		}
237
+		if (empty($post_types) && $this->request->requestParamIsSet('post_type')) {
238
+			$post_types = $this->request->getRequestParam('post_type', [], DataType::STRING, true);
239
+		}
240
+		return (array) $post_types;
241
+	}
242
+
243
+
244
+	/**
245
+	 * if TRUE, then the current page is somehow utilizing EE logic
246
+	 *
247
+	 * @return bool
248
+	 */
249
+	public function isEspressoPage(): bool
250
+	{
251
+		if ($this->is_espresso_page === null) {
252
+			$this->setEspressoPage();
253
+		}
254
+		return $this->is_espresso_page;
255
+	}
256
+
257
+
258
+	/**
259
+	 * @return int
260
+	 */
261
+	public function postId(): int
262
+	{
263
+		return $this->post_id;
264
+	}
265
+
266
+
267
+	/**
268
+	 * @return string|null
269
+	 */
270
+	public function postName(): ?string
271
+	{
272
+		return $this->post_name;
273
+	}
274
+
275
+
276
+	/**
277
+	 * @return array
278
+	 */
279
+	public function postType(): array
280
+	{
281
+		return $this->post_type;
282
+	}
283
+
284
+
285
+	/**
286
+	 * for manually indicating the current page will utilize EE logic
287
+	 *
288
+	 * @param bool|int|string|null $value
289
+	 * @return void
290
+	 */
291
+	public function setEspressoPage($value = null)
292
+	{
293
+		$this->is_espresso_page = $value !== null
294
+			? filter_var($value, FILTER_VALIDATE_BOOLEAN)
295
+			: $this->testForEspressoPage();
296
+	}
297
+
298
+
299
+	/**
300
+	 * attempts to determine if the current page/post is an EE related page/post
301
+	 * because it utilizes one of our CPT taxonomies, endpoints, or post types
302
+	 *
303
+	 * @return bool
304
+	 */
305
+	private function testForEspressoPage(): bool
306
+	{
307
+		// in case it has already been set
308
+		if ($this->is_espresso_page) {
309
+			return true;
310
+		}
311
+		global $WP;
312
+		$espresso_CPT_taxonomies = $this->cpt_strategy->get_CPT_taxonomies();
313
+		if (is_array($espresso_CPT_taxonomies)) {
314
+			foreach ($espresso_CPT_taxonomies as $espresso_CPT_taxonomy => $details) {
315
+				if (isset($WP->query_vars, $WP->query_vars[ $espresso_CPT_taxonomy ])) {
316
+					return true;
317
+				}
318
+			}
319
+		}
320
+		// load espresso CPT endpoints
321
+		$espresso_CPT_endpoints  = $this->cpt_strategy->get_CPT_endpoints();
322
+		$post_type_CPT_endpoints = array_flip($espresso_CPT_endpoints);
323
+		foreach ($this->post_type as $post_type) {
324
+			// was a post name passed ?
325
+			if (isset($post_type_CPT_endpoints[ $post_type ])) {
326
+				// kk we know this is an espresso page, but is it a specific post ?
327
+				if (! $this->post_name) {
328
+					$espresso_post_type = $this->request->getRequestParam('post_type');
329
+					// there's no specific post name set, so maybe it's one of our endpoints like www.domain.com/events
330
+					// this essentially sets the post_name to "events" (or whatever EE CPT)
331
+					$post_name = $post_type_CPT_endpoints[ $espresso_post_type ] ?? '';
332
+					// if the post type matches one of ours then set the post name to the endpoint
333
+					if ($post_name) {
334
+						$this->post_name = $post_name;
335
+					}
336
+				}
337
+				return true;
338
+			}
339
+		}
340
+		return false;
341
+	}
342 342
 }
Please login to merge, or discard this patch.
core/services/converters/date_time_formats/PhpToUnicode.php 2 patches
Indentation   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -4,99 +4,99 @@
 block discarded – undo
4 4
 
5 5
 class PhpToUnicode
6 6
 {
7
-    /**
8
-     * array where keys are PHP date format parameters
9
-     * and values are Unicode Date Format substitutions
10
-     */
11
-    public static array $date_formats = [
12
-        // YEAR
13
-        'y'  => 'yy',    // 00, 01, ..., 99
14
-        'Y'  => 'yyyy',  // 2000, 2001, ..., 2099
15
-        'o'  => 'GGGG',  // ISO "week-numbering year" 2000, 2001, ..., 2099
16
-        // MONTH
17
-        'M'  => 'MMM',   // Jan, Feb, ..., Dec
18
-        'n'  => 'M',     // 1, 2, ..., 12
19
-        'm'  => 'MM',    // 01, 02, ..., 12
20
-        'F'  => 'MMMM',  // January, February, ..., December
21
-        // DAY
22
-        'd'  => 'dd',    // 01, 02, ..., 31
23
-        'D'  => 'eee',   // Sun, Mon, ..., Sat
24
-        'jS' => 'do',   // 1st, 2nd, ..., 31st
25
-        'j'  => 'd',     // 1, 2, ..., 31
26
-        'l'  => 'eeee',  // Sunday, Monday, ..., Saturday
27
-        'N'  => 'e',     // Day of week 0, 1, ..., 6
28
-        'w'  => 'i',     // ISO Day of week 1, 2, ..., 7
29
-        'z'  => 'D',   // day of the year 0 - 365 to 1 - 366
30
-        // WEEK
31
-        'W'  => 'w',
32
-        // CHARACTERS
33
-        '|'  => '',
34
-    ];
7
+	/**
8
+	 * array where keys are PHP date format parameters
9
+	 * and values are Unicode Date Format substitutions
10
+	 */
11
+	public static array $date_formats = [
12
+		// YEAR
13
+		'y'  => 'yy',    // 00, 01, ..., 99
14
+		'Y'  => 'yyyy',  // 2000, 2001, ..., 2099
15
+		'o'  => 'GGGG',  // ISO "week-numbering year" 2000, 2001, ..., 2099
16
+		// MONTH
17
+		'M'  => 'MMM',   // Jan, Feb, ..., Dec
18
+		'n'  => 'M',     // 1, 2, ..., 12
19
+		'm'  => 'MM',    // 01, 02, ..., 12
20
+		'F'  => 'MMMM',  // January, February, ..., December
21
+		// DAY
22
+		'd'  => 'dd',    // 01, 02, ..., 31
23
+		'D'  => 'eee',   // Sun, Mon, ..., Sat
24
+		'jS' => 'do',   // 1st, 2nd, ..., 31st
25
+		'j'  => 'd',     // 1, 2, ..., 31
26
+		'l'  => 'eeee',  // Sunday, Monday, ..., Saturday
27
+		'N'  => 'e',     // Day of week 0, 1, ..., 6
28
+		'w'  => 'i',     // ISO Day of week 1, 2, ..., 7
29
+		'z'  => 'D',   // day of the year 0 - 365 to 1 - 366
30
+		// WEEK
31
+		'W'  => 'w',
32
+		// CHARACTERS
33
+		'|'  => '',
34
+	];
35 35
 
36 36
 
37
-    /**
38
-     * array where keys are PHP time format parameters
39
-     * and values are Unicode Time Format substitutions
40
-     */
41
-    public static array $time_formats = [
42
-        // 'a' => 'a', // am, pm, no specific JS alternative
43
-        'A' => 'a', // AM, PM
44
-        // HOUR
45
-        // convert "g" to an intermediary format
46
-        // to avoid its result getting replaced by "h"
47
-        'g' => '@',     // 1, 2, ..., 12
48
-        'h' => 'hh',    // 01, 02, ..., 12
49
-        '@' => 'h',     // 1, 2, ..., 12
50
-        'G' => '#',     // 0, 1, ... 23
51
-        'H' => 'HH',    // 00, 01, ... 23
52
-        '#' => 'H',     // 0, 1, ... 23
53
-        // MINUTES & SECONDS
54
-        'i' => 'mm',    // minutes 00, 01, ..., 59
55
-        's' => 'ss',    // seconds 00, 01, ..., 59
56
-        'v' => 'SSS',   // milliseconds 000, 001, ..., 999
57
-        'u' => 'SSS',   // microseconds (not in unicode) 000, 001, ..., 999
58
-    ];
37
+	/**
38
+	 * array where keys are PHP time format parameters
39
+	 * and values are Unicode Time Format substitutions
40
+	 */
41
+	public static array $time_formats = [
42
+		// 'a' => 'a', // am, pm, no specific JS alternative
43
+		'A' => 'a', // AM, PM
44
+		// HOUR
45
+		// convert "g" to an intermediary format
46
+		// to avoid its result getting replaced by "h"
47
+		'g' => '@',     // 1, 2, ..., 12
48
+		'h' => 'hh',    // 01, 02, ..., 12
49
+		'@' => 'h',     // 1, 2, ..., 12
50
+		'G' => '#',     // 0, 1, ... 23
51
+		'H' => 'HH',    // 00, 01, ... 23
52
+		'#' => 'H',     // 0, 1, ... 23
53
+		// MINUTES & SECONDS
54
+		'i' => 'mm',    // minutes 00, 01, ..., 59
55
+		's' => 'ss',    // seconds 00, 01, ..., 59
56
+		'v' => 'SSS',   // milliseconds 000, 001, ..., 999
57
+		'u' => 'SSS',   // microseconds (not in unicode) 000, 001, ..., 999
58
+	];
59 59
 
60 60
 
61
-    /**
62
-     * array where keys are PHP timezone format parameters
63
-     * and values are Unicode Timezone Format substitutions
64
-     */
65
-    public static array $timezone_formats = [
66
-        'Z' => 'xx',    // -0100, +0000, ..., +1200
67
-        'e' => 'xxx',     // Timezone identifier UTC, GMT, Atlantic/Azores to -01:00, +00:00, ... +12:00
68
-        'T' => 'xxx',     // Timezone abbreviation EST, MDT to -01:00, +00:00, ... +12:00
69
-        'P' => 'xxx',     // -01:00, +00:00, ... +12:00
70
-        'O' => 'xx',    // -0100, +0000, ..., +1200
71
-    ];
61
+	/**
62
+	 * array where keys are PHP timezone format parameters
63
+	 * and values are Unicode Timezone Format substitutions
64
+	 */
65
+	public static array $timezone_formats = [
66
+		'Z' => 'xx',    // -0100, +0000, ..., +1200
67
+		'e' => 'xxx',     // Timezone identifier UTC, GMT, Atlantic/Azores to -01:00, +00:00, ... +12:00
68
+		'T' => 'xxx',     // Timezone abbreviation EST, MDT to -01:00, +00:00, ... +12:00
69
+		'P' => 'xxx',     // -01:00, +00:00, ... +12:00
70
+		'O' => 'xx',    // -0100, +0000, ..., +1200
71
+	];
72 72
 
73 73
 
74
-    /**
75
-     * @param string $date_format
76
-     * @return string
77
-     */
78
-    public function convertDateFormat(string $date_format): string
79
-    {
80
-        foreach (PhpToUnicode::$date_formats as $find => $replace) {
81
-            $date_format = (string) str_replace($find, $replace, $date_format);
82
-        }
83
-        return trim($date_format);
84
-    }
74
+	/**
75
+	 * @param string $date_format
76
+	 * @return string
77
+	 */
78
+	public function convertDateFormat(string $date_format): string
79
+	{
80
+		foreach (PhpToUnicode::$date_formats as $find => $replace) {
81
+			$date_format = (string) str_replace($find, $replace, $date_format);
82
+		}
83
+		return trim($date_format);
84
+	}
85 85
 
86 86
 
87
-    /**
88
-     * @param string $time_format
89
-     * @return string
90
-     */
91
-    public function convertTimeFormat(string $time_format): string
92
-    {
93
-        foreach (PhpToUnicode::$time_formats as $find => $replace) {
94
-            $time_format = (string) str_replace($find, $replace, $time_format);
95
-        }
96
-        // and just in case the timezone has been added
97
-        foreach (PhpToUnicode::$timezone_formats as $find => $replace) {
98
-            $time_format = (string) str_replace($find, $replace, $time_format);
99
-        }
100
-        return trim($time_format);
101
-    }
87
+	/**
88
+	 * @param string $time_format
89
+	 * @return string
90
+	 */
91
+	public function convertTimeFormat(string $time_format): string
92
+	{
93
+		foreach (PhpToUnicode::$time_formats as $find => $replace) {
94
+			$time_format = (string) str_replace($find, $replace, $time_format);
95
+		}
96
+		// and just in case the timezone has been added
97
+		foreach (PhpToUnicode::$timezone_formats as $find => $replace) {
98
+			$time_format = (string) str_replace($find, $replace, $time_format);
99
+		}
100
+		return trim($time_format);
101
+	}
102 102
 }
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -10,23 +10,23 @@  discard block
 block discarded – undo
10 10
      */
11 11
     public static array $date_formats = [
12 12
         // YEAR
13
-        'y'  => 'yy',    // 00, 01, ..., 99
14
-        'Y'  => 'yyyy',  // 2000, 2001, ..., 2099
15
-        'o'  => 'GGGG',  // ISO "week-numbering year" 2000, 2001, ..., 2099
13
+        'y'  => 'yy', // 00, 01, ..., 99
14
+        'Y'  => 'yyyy', // 2000, 2001, ..., 2099
15
+        'o'  => 'GGGG', // ISO "week-numbering year" 2000, 2001, ..., 2099
16 16
         // MONTH
17
-        'M'  => 'MMM',   // Jan, Feb, ..., Dec
18
-        'n'  => 'M',     // 1, 2, ..., 12
19
-        'm'  => 'MM',    // 01, 02, ..., 12
20
-        'F'  => 'MMMM',  // January, February, ..., December
17
+        'M'  => 'MMM', // Jan, Feb, ..., Dec
18
+        'n'  => 'M', // 1, 2, ..., 12
19
+        'm'  => 'MM', // 01, 02, ..., 12
20
+        'F'  => 'MMMM', // January, February, ..., December
21 21
         // DAY
22
-        'd'  => 'dd',    // 01, 02, ..., 31
23
-        'D'  => 'eee',   // Sun, Mon, ..., Sat
24
-        'jS' => 'do',   // 1st, 2nd, ..., 31st
25
-        'j'  => 'd',     // 1, 2, ..., 31
26
-        'l'  => 'eeee',  // Sunday, Monday, ..., Saturday
27
-        'N'  => 'e',     // Day of week 0, 1, ..., 6
28
-        'w'  => 'i',     // ISO Day of week 1, 2, ..., 7
29
-        'z'  => 'D',   // day of the year 0 - 365 to 1 - 366
22
+        'd'  => 'dd', // 01, 02, ..., 31
23
+        'D'  => 'eee', // Sun, Mon, ..., Sat
24
+        'jS' => 'do', // 1st, 2nd, ..., 31st
25
+        'j'  => 'd', // 1, 2, ..., 31
26
+        'l'  => 'eeee', // Sunday, Monday, ..., Saturday
27
+        'N'  => 'e', // Day of week 0, 1, ..., 6
28
+        'w'  => 'i', // ISO Day of week 1, 2, ..., 7
29
+        'z'  => 'D', // day of the year 0 - 365 to 1 - 366
30 30
         // WEEK
31 31
         'W'  => 'w',
32 32
         // CHARACTERS
@@ -44,17 +44,17 @@  discard block
 block discarded – undo
44 44
         // HOUR
45 45
         // convert "g" to an intermediary format
46 46
         // to avoid its result getting replaced by "h"
47
-        'g' => '@',     // 1, 2, ..., 12
48
-        'h' => 'hh',    // 01, 02, ..., 12
49
-        '@' => 'h',     // 1, 2, ..., 12
50
-        'G' => '#',     // 0, 1, ... 23
51
-        'H' => 'HH',    // 00, 01, ... 23
52
-        '#' => 'H',     // 0, 1, ... 23
47
+        'g' => '@', // 1, 2, ..., 12
48
+        'h' => 'hh', // 01, 02, ..., 12
49
+        '@' => 'h', // 1, 2, ..., 12
50
+        'G' => '#', // 0, 1, ... 23
51
+        'H' => 'HH', // 00, 01, ... 23
52
+        '#' => 'H', // 0, 1, ... 23
53 53
         // MINUTES & SECONDS
54
-        'i' => 'mm',    // minutes 00, 01, ..., 59
55
-        's' => 'ss',    // seconds 00, 01, ..., 59
56
-        'v' => 'SSS',   // milliseconds 000, 001, ..., 999
57
-        'u' => 'SSS',   // microseconds (not in unicode) 000, 001, ..., 999
54
+        'i' => 'mm', // minutes 00, 01, ..., 59
55
+        's' => 'ss', // seconds 00, 01, ..., 59
56
+        'v' => 'SSS', // milliseconds 000, 001, ..., 999
57
+        'u' => 'SSS', // microseconds (not in unicode) 000, 001, ..., 999
58 58
     ];
59 59
 
60 60
 
@@ -63,11 +63,11 @@  discard block
 block discarded – undo
63 63
      * and values are Unicode Timezone Format substitutions
64 64
      */
65 65
     public static array $timezone_formats = [
66
-        'Z' => 'xx',    // -0100, +0000, ..., +1200
67
-        'e' => 'xxx',     // Timezone identifier UTC, GMT, Atlantic/Azores to -01:00, +00:00, ... +12:00
68
-        'T' => 'xxx',     // Timezone abbreviation EST, MDT to -01:00, +00:00, ... +12:00
69
-        'P' => 'xxx',     // -01:00, +00:00, ... +12:00
70
-        'O' => 'xx',    // -0100, +0000, ..., +1200
66
+        'Z' => 'xx', // -0100, +0000, ..., +1200
67
+        'e' => 'xxx', // Timezone identifier UTC, GMT, Atlantic/Azores to -01:00, +00:00, ... +12:00
68
+        'T' => 'xxx', // Timezone abbreviation EST, MDT to -01:00, +00:00, ... +12:00
69
+        'P' => 'xxx', // -01:00, +00:00, ... +12:00
70
+        'O' => 'xx', // -0100, +0000, ..., +1200
71 71
     ];
72 72
 
73 73
 
Please login to merge, or discard this patch.
core/services/admin/AdminListTableFilters.php 2 patches
Indentation   +105 added lines, -105 removed lines patch added patch discarded remove patch
@@ -12,74 +12,74 @@  discard block
 block discarded – undo
12 12
  */
13 13
 class AdminListTableFilters
14 14
 {
15
-    /**
16
-     * @var RequestInterface
17
-     */
18
-    protected RequestInterface $request;
19
-
20
-    protected string           $search_term;
21
-
22
-    protected ?string          $orderby;
23
-
24
-    protected ?string          $order;
25
-
26
-    protected ?string          $detached;
27
-
28
-    protected ?string          $post_mime_type;
29
-
30
-
31
-    public function __construct(RequestInterface $request)
32
-    {
33
-        $this->request = $request;
34
-        // add_action('admin_enqueue_scripts', [$this, 'loadScriptsStyles']);
35
-    }
36
-
37
-
38
-    public function loadScriptsStyles()
39
-    {
40
-        wp_enqueue_script(EspressoLegacyAdminAssetManager::JS_HANDLE_EE_ADMIN);
41
-    }
42
-
43
-
44
-    /**
45
-     * Sets the parameters from request
46
-     *
47
-     * @return void
48
-     */
49
-    private function setRequestParams(): void
50
-    {
51
-        $this->search_term    = $this->request->getRequestParam('s', '');
52
-        $this->orderby        = $this->request->getRequestParam('orderby');
53
-        $this->order          = $this->request->getRequestParam('order');
54
-        $this->post_mime_type = $this->request->getRequestParam('post_mime_type');
55
-        $this->detached       = $this->request->getRequestParam('detached');
56
-    }
57
-
58
-
59
-    /**
60
-     * Displays the search box with reset button
61
-     *
62
-     * @param string $text     The 'submit' button label.
63
-     * @param string $input_id ID attribute value for the search input field.
64
-     * @param string $url      Reset URL
65
-     * @return void
66
-     */
67
-    public function searchBox(string $text, string $input_id, string $url): void
68
-    {
69
-        $this->setRequestParams();
70
-        if (! empty($this->orderby)) {
71
-            echo '<input type="hidden" name="orderby" value="' . esc_attr($this->orderby) . '" />';
72
-        }
73
-        if (! empty($this->order)) {
74
-            echo '<input type="hidden" name="order" value="' . esc_attr($this->order) . '" />';
75
-        }
76
-        if (! empty($this->post_mime_type)) {
77
-            echo '<input type="hidden" name="post_mime_type" value="' . esc_attr($this->post_mime_type) . '" />';
78
-        }
79
-        if (! empty($this->detached)) {
80
-            echo '<input type="hidden" name="detached" value="' . esc_attr($this->detached) . '" />';
81
-        }
82
-        ?>
15
+	/**
16
+	 * @var RequestInterface
17
+	 */
18
+	protected RequestInterface $request;
19
+
20
+	protected string           $search_term;
21
+
22
+	protected ?string          $orderby;
23
+
24
+	protected ?string          $order;
25
+
26
+	protected ?string          $detached;
27
+
28
+	protected ?string          $post_mime_type;
29
+
30
+
31
+	public function __construct(RequestInterface $request)
32
+	{
33
+		$this->request = $request;
34
+		// add_action('admin_enqueue_scripts', [$this, 'loadScriptsStyles']);
35
+	}
36
+
37
+
38
+	public function loadScriptsStyles()
39
+	{
40
+		wp_enqueue_script(EspressoLegacyAdminAssetManager::JS_HANDLE_EE_ADMIN);
41
+	}
42
+
43
+
44
+	/**
45
+	 * Sets the parameters from request
46
+	 *
47
+	 * @return void
48
+	 */
49
+	private function setRequestParams(): void
50
+	{
51
+		$this->search_term    = $this->request->getRequestParam('s', '');
52
+		$this->orderby        = $this->request->getRequestParam('orderby');
53
+		$this->order          = $this->request->getRequestParam('order');
54
+		$this->post_mime_type = $this->request->getRequestParam('post_mime_type');
55
+		$this->detached       = $this->request->getRequestParam('detached');
56
+	}
57
+
58
+
59
+	/**
60
+	 * Displays the search box with reset button
61
+	 *
62
+	 * @param string $text     The 'submit' button label.
63
+	 * @param string $input_id ID attribute value for the search input field.
64
+	 * @param string $url      Reset URL
65
+	 * @return void
66
+	 */
67
+	public function searchBox(string $text, string $input_id, string $url): void
68
+	{
69
+		$this->setRequestParams();
70
+		if (! empty($this->orderby)) {
71
+			echo '<input type="hidden" name="orderby" value="' . esc_attr($this->orderby) . '" />';
72
+		}
73
+		if (! empty($this->order)) {
74
+			echo '<input type="hidden" name="order" value="' . esc_attr($this->order) . '" />';
75
+		}
76
+		if (! empty($this->post_mime_type)) {
77
+			echo '<input type="hidden" name="post_mime_type" value="' . esc_attr($this->post_mime_type) . '" />';
78
+		}
79
+		if (! empty($this->detached)) {
80
+			echo '<input type="hidden" name="detached" value="' . esc_attr($this->detached) . '" />';
81
+		}
82
+		?>
83 83
         <p class="search-box">
84 84
             <label class="screen-reader-text" for="<?php echo esc_attr($input_id); ?>"><?php echo $text; ?>:</label>
85 85
             <input type="search"
@@ -94,36 +94,36 @@  discard block
 block discarded – undo
94 94
             </button>
95 95
             <?php //submit_button($text, '', '', false, ['id' => 'search-submit']); ?>
96 96
             <?php
97
-            if (! empty($this->search_term)) {
98
-                echo wp_kses($this->generateResetButton($url), AllowedTags::getAllowedTags());
99
-            }
100
-            ?>
97
+			if (! empty($this->search_term)) {
98
+				echo wp_kses($this->generateResetButton($url), AllowedTags::getAllowedTags());
99
+			}
100
+			?>
101 101
         </p>
102 102
         <?php
103
-    }
104
-
105
-
106
-    /**
107
-     * filters
108
-     * This receives the filters array from children _get_table_filters() and assembles the string including the filter
109
-     * button.
110
-     *
111
-     * @param string[] $filters
112
-     * @param string   $url Reset URL
113
-     * @return void  echos html showing filters
114
-     */
115
-    public function filters(array $filters, string $url): void
116
-    {
117
-        $use_filters = $this->request->getRequestParam('use_filters', false, DataType::BOOL);
118
-        $use_filters = $use_filters ? 'yes' : 'no';
119
-
120
-        $filters_html = '';
121
-        foreach ($filters as $filter) {
122
-            $filters_html .= wp_kses($filter, AllowedTags::getWithFormTags());
123
-        }
124
-        $filter_submit_btn_text = esc_html__('Filter', 'event_espresso');
125
-
126
-        echo "
103
+	}
104
+
105
+
106
+	/**
107
+	 * filters
108
+	 * This receives the filters array from children _get_table_filters() and assembles the string including the filter
109
+	 * button.
110
+	 *
111
+	 * @param string[] $filters
112
+	 * @param string   $url Reset URL
113
+	 * @return void  echos html showing filters
114
+	 */
115
+	public function filters(array $filters, string $url): void
116
+	{
117
+		$use_filters = $this->request->getRequestParam('use_filters', false, DataType::BOOL);
118
+		$use_filters = $use_filters ? 'yes' : 'no';
119
+
120
+		$filters_html = '';
121
+		foreach ($filters as $filter) {
122
+			$filters_html .= wp_kses($filter, AllowedTags::getWithFormTags());
123
+		}
124
+		$filter_submit_btn_text = esc_html__('Filter', 'event_espresso');
125
+
126
+		echo "
127 127
         <div id='ee-list-table-filters-dv' class='ee-list-table-filters actions alignleft'>
128 128
            $filters_html
129 129
             <span class='ee-list-table-filters__submit-buttons'>
@@ -146,20 +146,20 @@  discard block
 block discarded – undo
146 146
             <span class='ee-list-table-filters-toggle-text'>" . esc_html__('show filters', 'event_espresso') . "</span>
147 147
         </button>
148 148
         ";
149
-    }
149
+	}
150 150
 
151 151
 
152
-    /**
153
-     * @param string $url Reset URL
154
-     * @return string
155
-     */
156
-    private function generateResetButton(string $url): string
157
-    {
158
-        return '<a class="ee-aria-tooltip button button--icon-only"
152
+	/**
153
+	 * @param string $url Reset URL
154
+	 * @return string
155
+	 */
156
+	private function generateResetButton(string $url): string
157
+	{
158
+		return '<a class="ee-aria-tooltip button button--icon-only"
159 159
             href="' . esc_url_raw($url) . '"
160 160
             aria-label="' . esc_attr__('Reset Filters', 'event_espresso') . '"
161 161
         >
162 162
             <span class="dashicons dashicons-update"></span>
163 163
         </a>';
164
-    }
164
+	}
165 165
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -67,17 +67,17 @@  discard block
 block discarded – undo
67 67
     public function searchBox(string $text, string $input_id, string $url): void
68 68
     {
69 69
         $this->setRequestParams();
70
-        if (! empty($this->orderby)) {
71
-            echo '<input type="hidden" name="orderby" value="' . esc_attr($this->orderby) . '" />';
70
+        if ( ! empty($this->orderby)) {
71
+            echo '<input type="hidden" name="orderby" value="'.esc_attr($this->orderby).'" />';
72 72
         }
73
-        if (! empty($this->order)) {
74
-            echo '<input type="hidden" name="order" value="' . esc_attr($this->order) . '" />';
73
+        if ( ! empty($this->order)) {
74
+            echo '<input type="hidden" name="order" value="'.esc_attr($this->order).'" />';
75 75
         }
76
-        if (! empty($this->post_mime_type)) {
77
-            echo '<input type="hidden" name="post_mime_type" value="' . esc_attr($this->post_mime_type) . '" />';
76
+        if ( ! empty($this->post_mime_type)) {
77
+            echo '<input type="hidden" name="post_mime_type" value="'.esc_attr($this->post_mime_type).'" />';
78 78
         }
79
-        if (! empty($this->detached)) {
80
-            echo '<input type="hidden" name="detached" value="' . esc_attr($this->detached) . '" />';
79
+        if ( ! empty($this->detached)) {
80
+            echo '<input type="hidden" name="detached" value="'.esc_attr($this->detached).'" />';
81 81
         }
82 82
         ?>
83 83
         <p class="search-box">
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
             </button>
95 95
             <?php //submit_button($text, '', '', false, ['id' => 'search-submit']); ?>
96 96
             <?php
97
-            if (! empty($this->search_term)) {
97
+            if ( ! empty($this->search_term)) {
98 98
                 echo wp_kses($this->generateResetButton($url), AllowedTags::getAllowedTags());
99 99
             }
100 100
             ?>
@@ -133,17 +133,17 @@  discard block
 block discarded – undo
133 133
                        value='$filter_submit_btn_text'
134 134
                 />
135 135
                 <input type='hidden' id='ee-list-table-use-filters' name='use_filters' value='$use_filters' />
136
-                " . wp_kses($this->generateResetButton($url), AllowedTags::getAllowedTags()) . "
136
+                ".wp_kses($this->generateResetButton($url), AllowedTags::getAllowedTags())."
137 137
             </span>
138 138
         </div>
139 139
         <button id='ee-list-table-filters-toggle'
140 140
             class='button button--secondary button--small'
141 141
             data-target='ee-list-table-filters'
142
-            data-hide-text='" . esc_html__('hide filters', 'event_espresso') . "'
143
-            data-show-text='" . esc_html__('show filters', 'event_espresso') . "'
142
+            data-hide-text='" . esc_html__('hide filters', 'event_espresso')."'
143
+            data-show-text='" . esc_html__('show filters', 'event_espresso')."'
144 144
         >
145 145
             <span class='dashicons dashicons-filter'></span>
146
-            <span class='ee-list-table-filters-toggle-text'>" . esc_html__('show filters', 'event_espresso') . "</span>
146
+            <span class='ee-list-table-filters-toggle-text'>" . esc_html__('show filters', 'event_espresso')."</span>
147 147
         </button>
148 148
         ";
149 149
     }
@@ -156,8 +156,8 @@  discard block
 block discarded – undo
156 156
     private function generateResetButton(string $url): string
157 157
     {
158 158
         return '<a class="ee-aria-tooltip button button--icon-only"
159
-            href="' . esc_url_raw($url) . '"
160
-            aria-label="' . esc_attr__('Reset Filters', 'event_espresso') . '"
159
+            href="' . esc_url_raw($url).'"
160
+            aria-label="' . esc_attr__('Reset Filters', 'event_espresso').'"
161 161
         >
162 162
             <span class="dashicons dashicons-update"></span>
163 163
         </a>';
Please login to merge, or discard this patch.
core/services/routing/Router.php 2 patches
Indentation   +225 added lines, -225 removed lines patch added patch discarded remove patch
@@ -14,229 +14,229 @@
 block discarded – undo
14 14
  */
15 15
 class Router
16 16
 {
17
-    protected EE_Dependency_Map $dependency_map;
18
-
19
-    protected LoaderInterface   $loader;
20
-
21
-    protected RouteHandler      $route_handler;
22
-
23
-    protected string            $route_request_type;
24
-
25
-    protected array             $routes_loaded;
26
-
27
-
28
-    /**
29
-     * RoutingSwitch constructor.
30
-     *
31
-     * @param EE_Dependency_Map $dependency_map
32
-     * @param LoaderInterface   $loader
33
-     * @param RouteHandler      $router
34
-     */
35
-    public function __construct(EE_Dependency_Map $dependency_map, LoaderInterface $loader, RouteHandler $router)
36
-    {
37
-        $this->dependency_map = $dependency_map;
38
-        $this->loader         = $loader;
39
-        $this->route_handler  = $router;
40
-    }
41
-
42
-
43
-    /**
44
-     * @throws Exception
45
-     */
46
-    public function loadPrimaryRoutes()
47
-    {
48
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
49
-            return;
50
-        }
51
-        $this->dependency_map->registerDependencies(
52
-            'EventEspresso\core\domain\entities\routing\handlers\admin\ActivationRequests',
53
-            Route::getFullDependencies()
54
-        );
55
-        $this->dependency_map->registerDependencies(
56
-            'EventEspresso\core\domain\entities\routing\handlers\shared\RegularRequests',
57
-            Route::getFullDependencies()
58
-        );
59
-        // now load and prep all primary Routes
60
-        $this->route_handler->addRoute('EventEspresso\core\domain\entities\routing\handlers\admin\ActivationRequests');
61
-        $this->route_handler->addRoute('EventEspresso\core\domain\entities\routing\handlers\shared\RegularRequests');
62
-        $this->route_request_type = $this->route_handler->getRouteRequestType();
63
-        do_action(
64
-            'AHEE__EventEspresso_core_services_routing_Router__loadPrimaryRoutes',
65
-            $this->route_handler,
66
-            $this->route_request_type,
67
-            $this->dependency_map
68
-        );
69
-        $this->routes_loaded[ __FUNCTION__ ] = true;
70
-    }
71
-
72
-
73
-    /**
74
-     * @throws Exception
75
-     */
76
-    public function registerShortcodesModulesAndWidgets()
77
-    {
78
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
79
-            return;
80
-        }
81
-        do_action(
82
-            'AHEE__EventEspresso_core_services_routing_Router__registerShortcodesModulesAndWidgets',
83
-            $this->route_handler,
84
-            $this->route_request_type,
85
-            $this->dependency_map
86
-        );
87
-        switch ($this->route_request_type) {
88
-            case PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION:
89
-                break;
90
-            case PrimaryRoute::ROUTE_REQUEST_TYPE_REGULAR:
91
-                $this->route_handler->addRoute(
92
-                    'EventEspresso\core\domain\entities\routing\handlers\frontend\ShortcodeRequests'
93
-                );
94
-                break;
95
-        }
96
-        $this->routes_loaded[ __FUNCTION__ ] = true;
97
-    }
98
-
99
-
100
-    /**
101
-     * @throws Exception
102
-     */
103
-    public function brewEspresso()
104
-    {
105
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
106
-            return;
107
-        }
108
-        do_action(
109
-            'AHEE__EventEspresso_core_services_routing_Router__brewEspresso',
110
-            $this->route_handler,
111
-            $this->route_request_type,
112
-            $this->dependency_map
113
-        );
114
-        switch ($this->route_request_type) {
115
-            case PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION:
116
-                break;
117
-            case PrimaryRoute::ROUTE_REQUEST_TYPE_REGULAR:
118
-                $this->route_handler->addRoute(
119
-                    'EventEspresso\core\domain\entities\routing\handlers\shared\GQLRequests'
120
-                );
121
-                $this->route_handler->addRoute(
122
-                    'EventEspresso\core\domain\entities\routing\handlers\shared\RestApiRequests'
123
-                );
124
-                break;
125
-        }
126
-        $this->routes_loaded[ __FUNCTION__ ] = true;
127
-    }
128
-
129
-
130
-    /**
131
-     * @throws Exception
132
-     */
133
-    public function loadControllers()
134
-    {
135
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
136
-            return;
137
-        }
138
-        do_action(
139
-            'AHEE__EventEspresso_core_services_routing_Router__loadControllers',
140
-            $this->route_handler,
141
-            $this->route_request_type,
142
-            $this->dependency_map
143
-        );
144
-        $this->route_handler->addRoute(
145
-            'EventEspresso\core\domain\entities\routing\handlers\admin\AdminRoute'
146
-        );
147
-        switch ($this->route_request_type) {
148
-            case PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION:
149
-                $this->route_handler->addRoute(
150
-                    'EventEspresso\core\domain\entities\routing\handlers\admin\WordPressPluginsPage'
151
-                );
152
-                break;
153
-            case PrimaryRoute::ROUTE_REQUEST_TYPE_REGULAR:
154
-                $this->route_handler->addRoute(
155
-                    'EventEspresso\core\domain\entities\routing\handlers\frontend\FrontendRequests'
156
-                );
157
-                $this->route_handler->addRoute(
158
-                    'EventEspresso\core\domain\entities\routing\handlers\admin\EspressoLegacyAdmin'
159
-                );
160
-                $this->route_handler->addRoute(
161
-                    'EventEspresso\core\domain\entities\routing\handlers\admin\EspressoEventsAdmin'
162
-                );
163
-                $this->route_handler->addRoute(
164
-                    'EventEspresso\core\domain\entities\routing\handlers\admin\EspressoEventEditor'
165
-                );
166
-                $this->route_handler->addRoute(
167
-                    'EventEspresso\core\domain\entities\routing\handlers\admin\GutenbergEditor'
168
-                );
169
-                $this->route_handler->addRoute(
170
-                    'EventEspresso\core\domain\entities\routing\handlers\admin\NonEspressoAdminAjax'
171
-                );
172
-                $this->route_handler->addRoute(
173
-                    'EventEspresso\core\domain\entities\routing\handlers\admin\WordPressPluginsPage'
174
-                );
175
-                $this->route_handler->addRoute(
176
-                    'EventEspresso\core\domain\entities\routing\handlers\admin\WordPressProfilePage'
177
-                );
178
-                $this->route_handler->addRoute(
179
-                    'EventEspresso\core\domain\entities\routing\handlers\shared\WordPressHeartbeat'
180
-                );
181
-                break;
182
-        }
183
-        $this->routes_loaded[ __FUNCTION__ ] = true;
184
-    }
185
-
186
-
187
-    /**
188
-     * @throws Exception
189
-     */
190
-    public function coreLoadedAndReady()
191
-    {
192
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
193
-            return;
194
-        }
195
-        do_action(
196
-            'AHEE__EventEspresso_core_services_routing_Router__coreLoadedAndReady',
197
-            $this->route_handler,
198
-            $this->route_request_type,
199
-            $this->dependency_map
200
-        );
201
-        switch ($this->route_request_type) {
202
-            case PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION:
203
-                break;
204
-            case PrimaryRoute::ROUTE_REQUEST_TYPE_REGULAR:
205
-                $this->route_handler->addRoute(
206
-                    'EventEspresso\core\domain\entities\routing\handlers\shared\AssetRequests'
207
-                );
208
-                $this->route_handler->addRoute(
209
-                    'EventEspresso\core\domain\entities\routing\handlers\shared\SessionRequests'
210
-                );
211
-                break;
212
-        }
213
-        $this->routes_loaded[ __FUNCTION__ ] = true;
214
-    }
215
-
216
-
217
-    /**
218
-     * @throws Exception
219
-     */
220
-    public function initializeLast()
221
-    {
222
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
223
-            return;
224
-        }
225
-        do_action(
226
-            'AHEE__EventEspresso_core_services_routing_Router__initializeLast',
227
-            $this->route_handler,
228
-            $this->route_request_type,
229
-            $this->dependency_map
230
-        );
231
-        switch ($this->route_request_type) {
232
-            case PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION:
233
-                break;
234
-            case PrimaryRoute::ROUTE_REQUEST_TYPE_REGULAR:
235
-                $this->route_handler->addRoute(
236
-                    'EventEspresso\core\domain\entities\routing\handlers\admin\PersonalDataRequests'
237
-                );
238
-                break;
239
-        }
240
-        $this->routes_loaded[ __FUNCTION__ ] = true;
241
-    }
17
+	protected EE_Dependency_Map $dependency_map;
18
+
19
+	protected LoaderInterface   $loader;
20
+
21
+	protected RouteHandler      $route_handler;
22
+
23
+	protected string            $route_request_type;
24
+
25
+	protected array             $routes_loaded;
26
+
27
+
28
+	/**
29
+	 * RoutingSwitch constructor.
30
+	 *
31
+	 * @param EE_Dependency_Map $dependency_map
32
+	 * @param LoaderInterface   $loader
33
+	 * @param RouteHandler      $router
34
+	 */
35
+	public function __construct(EE_Dependency_Map $dependency_map, LoaderInterface $loader, RouteHandler $router)
36
+	{
37
+		$this->dependency_map = $dependency_map;
38
+		$this->loader         = $loader;
39
+		$this->route_handler  = $router;
40
+	}
41
+
42
+
43
+	/**
44
+	 * @throws Exception
45
+	 */
46
+	public function loadPrimaryRoutes()
47
+	{
48
+		if (isset($this->routes_loaded[ __FUNCTION__ ])) {
49
+			return;
50
+		}
51
+		$this->dependency_map->registerDependencies(
52
+			'EventEspresso\core\domain\entities\routing\handlers\admin\ActivationRequests',
53
+			Route::getFullDependencies()
54
+		);
55
+		$this->dependency_map->registerDependencies(
56
+			'EventEspresso\core\domain\entities\routing\handlers\shared\RegularRequests',
57
+			Route::getFullDependencies()
58
+		);
59
+		// now load and prep all primary Routes
60
+		$this->route_handler->addRoute('EventEspresso\core\domain\entities\routing\handlers\admin\ActivationRequests');
61
+		$this->route_handler->addRoute('EventEspresso\core\domain\entities\routing\handlers\shared\RegularRequests');
62
+		$this->route_request_type = $this->route_handler->getRouteRequestType();
63
+		do_action(
64
+			'AHEE__EventEspresso_core_services_routing_Router__loadPrimaryRoutes',
65
+			$this->route_handler,
66
+			$this->route_request_type,
67
+			$this->dependency_map
68
+		);
69
+		$this->routes_loaded[ __FUNCTION__ ] = true;
70
+	}
71
+
72
+
73
+	/**
74
+	 * @throws Exception
75
+	 */
76
+	public function registerShortcodesModulesAndWidgets()
77
+	{
78
+		if (isset($this->routes_loaded[ __FUNCTION__ ])) {
79
+			return;
80
+		}
81
+		do_action(
82
+			'AHEE__EventEspresso_core_services_routing_Router__registerShortcodesModulesAndWidgets',
83
+			$this->route_handler,
84
+			$this->route_request_type,
85
+			$this->dependency_map
86
+		);
87
+		switch ($this->route_request_type) {
88
+			case PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION:
89
+				break;
90
+			case PrimaryRoute::ROUTE_REQUEST_TYPE_REGULAR:
91
+				$this->route_handler->addRoute(
92
+					'EventEspresso\core\domain\entities\routing\handlers\frontend\ShortcodeRequests'
93
+				);
94
+				break;
95
+		}
96
+		$this->routes_loaded[ __FUNCTION__ ] = true;
97
+	}
98
+
99
+
100
+	/**
101
+	 * @throws Exception
102
+	 */
103
+	public function brewEspresso()
104
+	{
105
+		if (isset($this->routes_loaded[ __FUNCTION__ ])) {
106
+			return;
107
+		}
108
+		do_action(
109
+			'AHEE__EventEspresso_core_services_routing_Router__brewEspresso',
110
+			$this->route_handler,
111
+			$this->route_request_type,
112
+			$this->dependency_map
113
+		);
114
+		switch ($this->route_request_type) {
115
+			case PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION:
116
+				break;
117
+			case PrimaryRoute::ROUTE_REQUEST_TYPE_REGULAR:
118
+				$this->route_handler->addRoute(
119
+					'EventEspresso\core\domain\entities\routing\handlers\shared\GQLRequests'
120
+				);
121
+				$this->route_handler->addRoute(
122
+					'EventEspresso\core\domain\entities\routing\handlers\shared\RestApiRequests'
123
+				);
124
+				break;
125
+		}
126
+		$this->routes_loaded[ __FUNCTION__ ] = true;
127
+	}
128
+
129
+
130
+	/**
131
+	 * @throws Exception
132
+	 */
133
+	public function loadControllers()
134
+	{
135
+		if (isset($this->routes_loaded[ __FUNCTION__ ])) {
136
+			return;
137
+		}
138
+		do_action(
139
+			'AHEE__EventEspresso_core_services_routing_Router__loadControllers',
140
+			$this->route_handler,
141
+			$this->route_request_type,
142
+			$this->dependency_map
143
+		);
144
+		$this->route_handler->addRoute(
145
+			'EventEspresso\core\domain\entities\routing\handlers\admin\AdminRoute'
146
+		);
147
+		switch ($this->route_request_type) {
148
+			case PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION:
149
+				$this->route_handler->addRoute(
150
+					'EventEspresso\core\domain\entities\routing\handlers\admin\WordPressPluginsPage'
151
+				);
152
+				break;
153
+			case PrimaryRoute::ROUTE_REQUEST_TYPE_REGULAR:
154
+				$this->route_handler->addRoute(
155
+					'EventEspresso\core\domain\entities\routing\handlers\frontend\FrontendRequests'
156
+				);
157
+				$this->route_handler->addRoute(
158
+					'EventEspresso\core\domain\entities\routing\handlers\admin\EspressoLegacyAdmin'
159
+				);
160
+				$this->route_handler->addRoute(
161
+					'EventEspresso\core\domain\entities\routing\handlers\admin\EspressoEventsAdmin'
162
+				);
163
+				$this->route_handler->addRoute(
164
+					'EventEspresso\core\domain\entities\routing\handlers\admin\EspressoEventEditor'
165
+				);
166
+				$this->route_handler->addRoute(
167
+					'EventEspresso\core\domain\entities\routing\handlers\admin\GutenbergEditor'
168
+				);
169
+				$this->route_handler->addRoute(
170
+					'EventEspresso\core\domain\entities\routing\handlers\admin\NonEspressoAdminAjax'
171
+				);
172
+				$this->route_handler->addRoute(
173
+					'EventEspresso\core\domain\entities\routing\handlers\admin\WordPressPluginsPage'
174
+				);
175
+				$this->route_handler->addRoute(
176
+					'EventEspresso\core\domain\entities\routing\handlers\admin\WordPressProfilePage'
177
+				);
178
+				$this->route_handler->addRoute(
179
+					'EventEspresso\core\domain\entities\routing\handlers\shared\WordPressHeartbeat'
180
+				);
181
+				break;
182
+		}
183
+		$this->routes_loaded[ __FUNCTION__ ] = true;
184
+	}
185
+
186
+
187
+	/**
188
+	 * @throws Exception
189
+	 */
190
+	public function coreLoadedAndReady()
191
+	{
192
+		if (isset($this->routes_loaded[ __FUNCTION__ ])) {
193
+			return;
194
+		}
195
+		do_action(
196
+			'AHEE__EventEspresso_core_services_routing_Router__coreLoadedAndReady',
197
+			$this->route_handler,
198
+			$this->route_request_type,
199
+			$this->dependency_map
200
+		);
201
+		switch ($this->route_request_type) {
202
+			case PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION:
203
+				break;
204
+			case PrimaryRoute::ROUTE_REQUEST_TYPE_REGULAR:
205
+				$this->route_handler->addRoute(
206
+					'EventEspresso\core\domain\entities\routing\handlers\shared\AssetRequests'
207
+				);
208
+				$this->route_handler->addRoute(
209
+					'EventEspresso\core\domain\entities\routing\handlers\shared\SessionRequests'
210
+				);
211
+				break;
212
+		}
213
+		$this->routes_loaded[ __FUNCTION__ ] = true;
214
+	}
215
+
216
+
217
+	/**
218
+	 * @throws Exception
219
+	 */
220
+	public function initializeLast()
221
+	{
222
+		if (isset($this->routes_loaded[ __FUNCTION__ ])) {
223
+			return;
224
+		}
225
+		do_action(
226
+			'AHEE__EventEspresso_core_services_routing_Router__initializeLast',
227
+			$this->route_handler,
228
+			$this->route_request_type,
229
+			$this->dependency_map
230
+		);
231
+		switch ($this->route_request_type) {
232
+			case PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION:
233
+				break;
234
+			case PrimaryRoute::ROUTE_REQUEST_TYPE_REGULAR:
235
+				$this->route_handler->addRoute(
236
+					'EventEspresso\core\domain\entities\routing\handlers\admin\PersonalDataRequests'
237
+				);
238
+				break;
239
+		}
240
+		$this->routes_loaded[ __FUNCTION__ ] = true;
241
+	}
242 242
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
      */
46 46
     public function loadPrimaryRoutes()
47 47
     {
48
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
48
+        if (isset($this->routes_loaded[__FUNCTION__])) {
49 49
             return;
50 50
         }
51 51
         $this->dependency_map->registerDependencies(
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
             $this->route_request_type,
67 67
             $this->dependency_map
68 68
         );
69
-        $this->routes_loaded[ __FUNCTION__ ] = true;
69
+        $this->routes_loaded[__FUNCTION__] = true;
70 70
     }
71 71
 
72 72
 
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
      */
76 76
     public function registerShortcodesModulesAndWidgets()
77 77
     {
78
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
78
+        if (isset($this->routes_loaded[__FUNCTION__])) {
79 79
             return;
80 80
         }
81 81
         do_action(
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
                 );
94 94
                 break;
95 95
         }
96
-        $this->routes_loaded[ __FUNCTION__ ] = true;
96
+        $this->routes_loaded[__FUNCTION__] = true;
97 97
     }
98 98
 
99 99
 
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
      */
103 103
     public function brewEspresso()
104 104
     {
105
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
105
+        if (isset($this->routes_loaded[__FUNCTION__])) {
106 106
             return;
107 107
         }
108 108
         do_action(
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
                 );
124 124
                 break;
125 125
         }
126
-        $this->routes_loaded[ __FUNCTION__ ] = true;
126
+        $this->routes_loaded[__FUNCTION__] = true;
127 127
     }
128 128
 
129 129
 
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
      */
133 133
     public function loadControllers()
134 134
     {
135
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
135
+        if (isset($this->routes_loaded[__FUNCTION__])) {
136 136
             return;
137 137
         }
138 138
         do_action(
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
                 );
181 181
                 break;
182 182
         }
183
-        $this->routes_loaded[ __FUNCTION__ ] = true;
183
+        $this->routes_loaded[__FUNCTION__] = true;
184 184
     }
185 185
 
186 186
 
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
      */
190 190
     public function coreLoadedAndReady()
191 191
     {
192
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
192
+        if (isset($this->routes_loaded[__FUNCTION__])) {
193 193
             return;
194 194
         }
195 195
         do_action(
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
                 );
211 211
                 break;
212 212
         }
213
-        $this->routes_loaded[ __FUNCTION__ ] = true;
213
+        $this->routes_loaded[__FUNCTION__] = true;
214 214
     }
215 215
 
216 216
 
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
      */
220 220
     public function initializeLast()
221 221
     {
222
-        if (isset($this->routes_loaded[ __FUNCTION__ ])) {
222
+        if (isset($this->routes_loaded[__FUNCTION__])) {
223 223
             return;
224 224
         }
225 225
         do_action(
@@ -237,6 +237,6 @@  discard block
 block discarded – undo
237 237
                 );
238 238
                 break;
239 239
         }
240
-        $this->routes_loaded[ __FUNCTION__ ] = true;
240
+        $this->routes_loaded[__FUNCTION__] = true;
241 241
     }
242 242
 }
Please login to merge, or discard this patch.
core/services/shortcodes/LegacyShortcodesManager.php 1 patch
Indentation   +454 added lines, -454 removed lines patch added patch discarded remove patch
@@ -26,458 +26,458 @@
 block discarded – undo
26 26
  */
27 27
 class LegacyShortcodesManager
28 28
 {
29
-    /**
30
-     * @var string
31
-     */
32
-    public const SHORTCODE_PREFIX = 'EES_';
33
-
34
-    protected CurrentPage $current_page;
35
-
36
-    private EE_Registry $registry;
37
-
38
-
39
-    /**
40
-     * LegacyShortcodesManager constructor.
41
-     *
42
-     * @param EE_Registry $registry
43
-     * @param CurrentPage $current_page
44
-     */
45
-    public function __construct(EE_Registry $registry, CurrentPage $current_page)
46
-    {
47
-        $this->registry     = $registry;
48
-        $this->current_page = $current_page;
49
-    }
50
-
51
-
52
-    /**
53
-     * @return EE_Registry
54
-     */
55
-    public function registry(): EE_Registry
56
-    {
57
-        return $this->registry;
58
-    }
59
-
60
-
61
-    /**
62
-     * registerShortcodes
63
-     *
64
-     * @return void
65
-     */
66
-    public function registerShortcodes()
67
-    {
68
-        $this->registry->shortcodes = $this->getShortcodes();
69
-    }
70
-
71
-
72
-    /**
73
-     * getShortcodes
74
-     *
75
-     * @return array|RegistryContainer
76
-     */
77
-    public function getShortcodes()
78
-    {
79
-        // previously this method would glob the shortcodes directory
80
-        // then filter that list of shortcodes to register,
81
-        // but now we are going to just supply an empty array.
82
-        // this allows any shortcodes that have not yet been converted to the new system
83
-        // to still get loaded and processed, albeit using the same legacy logic as before
84
-        $shortcodes_to_register = apply_filters(
85
-            'FHEE__EE_Config__register_shortcodes__shortcodes_to_register',
86
-            []
87
-        );
88
-        if (! empty($shortcodes_to_register)) {
89
-            // cycle thru shortcode folders
90
-            foreach ($shortcodes_to_register as $shortcode_path) {
91
-                // add to list of installed shortcode modules
92
-                $this->registerShortcode($shortcode_path);
93
-            }
94
-        }
95
-        // filter list of installed modules
96
-        return apply_filters(
97
-            'FHEE__EE_Config___register_shortcodes__installed_shortcodes',
98
-            ! empty($this->registry->shortcodes)
99
-                ? $this->registry->shortcodes
100
-                : []
101
-        );
102
-    }
103
-
104
-
105
-    /**
106
-     * register_shortcode - makes core aware of this shortcode
107
-     *
108
-     * @param string|null $shortcode_path - full path up to and including shortcode folder
109
-     * @return    bool
110
-     */
111
-    public function registerShortcode(string $shortcode_path = ''): bool
112
-    {
113
-        do_action('AHEE__EE_Config__register_shortcode__begin', $shortcode_path);
114
-        $shortcode_ext = '.shortcode.php';
115
-        // make all separators match
116
-        $shortcode_path = str_replace(['\\', '/'], '/', $shortcode_path);
117
-        // does the file path INCLUDE the actual file name as part of the path ?
118
-        if (strpos($shortcode_path, $shortcode_ext) !== false) {
119
-            // grab shortcode file name from directory name and break apart at dots
120
-            $shortcode_file = explode('.', basename($shortcode_path));
121
-            // take first segment from file name pieces and remove class prefix if it exists
122
-            $shortcode = LegacyShortcodesManager::stripShortcodeClassPrefix($shortcode_file[0]);
123
-            // sanitize shortcode directory name
124
-            $shortcode = sanitize_key($shortcode);
125
-            // now we need to rebuild the shortcode path
126
-            $shortcode_path = explode('/', $shortcode_path);
127
-            // remove last segment
128
-            array_pop($shortcode_path);
129
-            // glue it back together
130
-            $shortcode_path = implode('/', $shortcode_path) . '/';
131
-        } else {
132
-            // we need to generate the filename based off of the folder name
133
-            // grab and sanitize shortcode directory name
134
-            $shortcode      = sanitize_key(basename($shortcode_path));
135
-            $shortcode_path = rtrim($shortcode_path, '/') . '/';
136
-        }
137
-        // create classname from shortcode directory or file name
138
-        $shortcode = str_replace(' ', '_', ucwords(str_replace('_', ' ', $shortcode)));
139
-        // add class prefix
140
-        $shortcode_class = LegacyShortcodesManager::addShortcodeClassPrefix($shortcode);
141
-        // does the shortcode exist ?
142
-        if (! is_readable($shortcode_path . '/' . $shortcode_class . $shortcode_ext)) {
143
-            $msg = sprintf(
144
-                esc_html__(
145
-                    'The requested %1$s shortcode file could not be found or is not readable due to file permissions. It should be in %2$s',
146
-                    'event_espresso'
147
-                ),
148
-                $shortcode_class,
149
-                $shortcode_path . '/' . $shortcode_class . $shortcode_ext
150
-            );
151
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
152
-            return false;
153
-        }
154
-        // load the shortcode class file
155
-        require_once($shortcode_path . $shortcode_class . $shortcode_ext);
156
-        // verify that class exists
157
-        if (! class_exists($shortcode_class)) {
158
-            $msg = sprintf(
159
-                esc_html__('The requested %s shortcode class does not exist.', 'event_espresso'),
160
-                $shortcode_class
161
-            );
162
-            EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
163
-            return false;
164
-        }
165
-        $shortcode = strtoupper($shortcode);
166
-        // add to array of registered shortcodes
167
-        $this->registry->shortcodes->{$shortcode} = $shortcode_path . $shortcode_class . $shortcode_ext;
168
-        return true;
169
-    }
170
-
171
-
172
-    /**
173
-     *    _initialize_shortcodes
174
-     *    allow shortcodes to set hooks for the rest of the system
175
-     *
176
-     * @return void
177
-     */
178
-    public function addShortcodes()
179
-    {
180
-        // cycle thru shortcode folders
181
-        foreach ($this->registry->shortcodes as $shortcode => $shortcode_path) {
182
-            // add class prefix
183
-            $shortcode_class = LegacyShortcodesManager::addShortcodeClassPrefix($shortcode);
184
-            // fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
185
-            // which set hooks ?
186
-            if (is_admin()) {
187
-                // fire immediately
188
-                call_user_func([$shortcode_class, 'set_hooks_admin']);
189
-            } else {
190
-                // delay until other systems are online
191
-                add_action(
192
-                    'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons',
193
-                    [$shortcode_class, 'set_hooks']
194
-                );
195
-                // convert classname to UPPERCASE and create WP shortcode.
196
-                $shortcode_tag = strtoupper($shortcode);
197
-                // but first check if the shortcode has already
198
-                // been added before assigning 'fallback_shortcode_processor'
199
-                if (! shortcode_exists($shortcode_tag)) {
200
-                    // NOTE: this shortcode declaration will get overridden if the shortcode
201
-                    // is successfully detected in the post content in initializeShortcode()
202
-                    add_shortcode($shortcode_tag, [$shortcode_class, 'fallback_shortcode_processor']);
203
-                }
204
-            }
205
-        }
206
-    }
207
-
208
-
209
-    /**
210
-     * callback for the WP "get_header" hook point
211
-     * checks posts for EE shortcodes, and initializes them,
212
-     * then toggles filter switch that loads core default assets
213
-     *
214
-     * @param WP_Query $wp_query
215
-     * @return void
216
-     * @throws ReflectionException
217
-     */
218
-    public function initializeShortcodes(WP_Query $wp_query)
219
-    {
220
-        if (
221
-            empty($this->registry->shortcodes)
222
-            || defined('EE_TESTS_DIR')
223
-            || ! $wp_query->is_main_query()
224
-            || is_admin()
225
-        ) {
226
-            return;
227
-        }
228
-        // in case shortcode is loaded unexpectedly and deps haven't been set up correctly
229
-        EE_Dependency_Map::register_dependencies(
230
-            'EE_Front_Controller',
231
-            [
232
-                'EE_Registry'                                     => EE_Dependency_Map::load_from_cache,
233
-                'EventEspresso\core\services\request\CurrentPage' => EE_Dependency_Map::load_from_cache,
234
-                'EE_Module_Request_Router'                        => EE_Dependency_Map::load_from_cache,
235
-            ]
236
-        );
237
-        global $wp;
238
-        /** @var EE_Front_controller $Front_Controller */
239
-        $Front_Controller = LoaderFactory::getLoader()->getShared('EE_Front_Controller');
240
-        do_action('AHEE__EE_Front_Controller__initialize_shortcodes__begin', $wp, $Front_Controller);
241
-        $this->current_page->parseQueryVars();
242
-        // grab post_name from request
243
-        $current_post  = apply_filters(
244
-            'FHEE__EE_Front_Controller__initialize_shortcodes__current_post_name',
245
-            $this->current_page->postName()
246
-        );
247
-        $show_on_front = get_option('show_on_front');
248
-        // if it's not set, then check if frontpage is blog
249
-        if (empty($current_post)) {
250
-            // yup.. this is the posts page, prepare to load all shortcode modules
251
-            $current_post = 'posts';
252
-            // unless..
253
-            if ($show_on_front === 'page') {
254
-                // some other page is set as the homepage
255
-                $page_on_front = get_option('page_on_front');
256
-                if ($page_on_front) {
257
-                    // k now we need to find the post_name for this page
258
-                    global $wpdb;
259
-                    $page_on_front = $wpdb->get_var(
260
-                        $wpdb->prepare(
261
-                            "SELECT post_name from $wpdb->posts WHERE post_type='page' AND post_status NOT IN ('auto-draft', 'inherit', 'trash') AND ID=%d",
262
-                            $page_on_front
263
-                        )
264
-                    );
265
-                    // set the current post slug to what it actually is
266
-                    $current_post = $page_on_front ?: $current_post;
267
-                }
268
-            }
269
-        }
270
-        // in case $current_post is hierarchical like: /parent-page/current-page
271
-        $current_post = basename($current_post);
272
-        if (
273
-            // is current page/post the "blog" page ?
274
-            $current_post === EE_Config::get_page_for_posts()
275
-            // or are we on a category page?
276
-            || (
277
-                is_array(term_exists($current_post, 'category'))
278
-                || array_key_exists('category_name', $wp->query_vars)
279
-            )
280
-        ) {
281
-            // initialize all legacy shortcodes
282
-            $load_assets = $this->parseContentForShortcodes('', true);
283
-        } else {
284
-            global $post;
285
-            if ($post instanceof WP_Post) {
286
-                $post_content = $post->post_content;
287
-            } else {
288
-                global $wpdb;
289
-                $post_content = $wpdb->get_var(
290
-                    $wpdb->prepare(
291
-                        "SELECT post_content from $wpdb->posts WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND post_name=%s",
292
-                        $current_post
293
-                    )
294
-                );
295
-            }
296
-            $load_assets = $this->parseContentForShortcodes($post_content);
297
-        }
298
-        if ($load_assets) {
299
-            $this->current_page->setEspressoPage(true);
300
-            add_filter('FHEE_load_css', '__return_true');
301
-            add_filter('FHEE_load_js', '__return_true');
302
-        }
303
-        do_action('AHEE__EE_Front_Controller__initialize_shortcodes__end', $Front_Controller);
304
-    }
305
-
306
-
307
-    /**
308
-     * checks supplied content against list of legacy shortcodes,
309
-     * then initializes any found shortcodes, and returns true.
310
-     * returns false if no shortcodes found.
311
-     *
312
-     * @param string|null $content
313
-     * @param bool $load_all if true, then ALL active legacy shortcodes will be initialized
314
-     * @return bool
315
-     * @throws ReflectionException
316
-     */
317
-    public function parseContentForShortcodes(?string $content = '', bool $load_all = false): bool
318
-    {
319
-        $content = $content ?? '';
320
-        $has_shortcode = false;
321
-        foreach ($this->registry->shortcodes as $shortcode_class => $shortcode) {
322
-            if ($load_all || has_shortcode($content, $shortcode_class)) {
323
-                // load up the shortcode
324
-                $this->initializeShortcode($shortcode_class);
325
-                $has_shortcode = true;
326
-            }
327
-        }
328
-        // one last test for an [espresso_*] shortcode
329
-        if (! $has_shortcode) {
330
-            $has_shortcode = strpos($content, '[espresso_') !== false;
331
-        }
332
-        return $has_shortcode;
333
-    }
334
-
335
-
336
-    /**
337
-     * given a shortcode name, will instantiate the shortcode and call it's run() method
338
-     *
339
-     * @param string  $shortcode_class
340
-     * @param WP|null $wp
341
-     * @throws ReflectionException
342
-     */
343
-    public function initializeShortcode(string $shortcode_class = '', WP $wp = null): void
344
-    {
345
-        // don't do anything if shortcode is already initialized
346
-        if (
347
-            empty($this->registry->shortcodes->{$shortcode_class})
348
-            || ! is_string($this->registry->shortcodes->{$shortcode_class})
349
-        ) {
350
-            return;
351
-        }
352
-        // let's pause to reflect on this...
353
-        $sc_reflector = new ReflectionClass(LegacyShortcodesManager::addShortcodeClassPrefix($shortcode_class));
354
-        // ensure that class is actually a shortcode
355
-        if (
356
-            defined('WP_DEBUG')
357
-            && WP_DEBUG === true
358
-            && ! $sc_reflector->isSubclassOf('EES_Shortcode')
359
-        ) {
360
-            EE_Error::add_error(
361
-                sprintf(
362
-                    esc_html__(
363
-                        'The requested %s shortcode is not of the class "EES_Shortcode". Please check your files.',
364
-                        'event_espresso'
365
-                    ),
366
-                    $shortcode_class
367
-                ),
368
-                __FILE__,
369
-                __FUNCTION__,
370
-                __LINE__
371
-            );
372
-            add_filter('FHEE_run_EE_the_content', '__return_true');
373
-            return;
374
-        }
375
-        global $wp;
376
-        // and pass the request object to the run method
377
-        $this->registry->shortcodes->{$shortcode_class} = $sc_reflector->newInstance();
378
-        // fire the shortcode class's run method, so that it can activate resources
379
-        $this->registry->shortcodes->{$shortcode_class}->run($wp);
380
-    }
381
-
382
-
383
-    /**
384
-     * get classname, remove EES_prefix, and convert to UPPERCASE
385
-     *
386
-     * @param string $class_name
387
-     * @return string
388
-     */
389
-    public static function generateShortcodeTagFromClassName(string $class_name): string
390
-    {
391
-        return strtoupper(LegacyShortcodesManager::stripShortcodeClassPrefix(strtoupper($class_name)));
392
-    }
393
-
394
-
395
-    /**
396
-     * add EES_prefix and Capitalize words
397
-     *
398
-     * @param string $tag
399
-     * @return string
400
-     */
401
-    public static function generateShortcodeClassNameFromTag(string $tag): string
402
-    {
403
-        // order of operation runs from inside to out
404
-        // 5) maybe add prefix
405
-        return LegacyShortcodesManager::addShortcodeClassPrefix(
406
-        // 4) find spaces, replace with underscores
407
-            str_replace(
408
-                ' ',
409
-                '_',
410
-                // 3) capitalize first letter of each word
411
-                ucwords(
412
-                // 2) also change to lowercase so ucwords() will work
413
-                    strtolower(
414
-                    // 1) find underscores, replace with spaces so ucwords() will work
415
-                        str_replace(
416
-                            '_',
417
-                            ' ',
418
-                            $tag
419
-                        )
420
-                    )
421
-                )
422
-            )
423
-        );
424
-    }
425
-
426
-
427
-    /**
428
-     * maybe add EES_ prefix
429
-     *
430
-     * @param string $class_name
431
-     * @return string
432
-     */
433
-    public static function addShortcodeClassPrefix(string $class_name): string
434
-    {
435
-        return strpos($class_name, LegacyShortcodesManager::SHORTCODE_PREFIX) === 0
436
-            ? $class_name
437
-            : LegacyShortcodesManager::SHORTCODE_PREFIX . $class_name;
438
-    }
439
-
440
-
441
-    /**
442
-     * maybe remove EES_ prefix
443
-     *
444
-     * @param string $class_name
445
-     * @return string
446
-     */
447
-    public static function stripShortcodeClassPrefix(string $class_name): string
448
-    {
449
-        return strpos($class_name, LegacyShortcodesManager::SHORTCODE_PREFIX) === 0
450
-            ? substr($class_name, 4)
451
-            : $class_name;
452
-    }
453
-
454
-
455
-    /**
456
-     * @return array
457
-     */
458
-    public function getEspressoShortcodeTags(): array
459
-    {
460
-        static $shortcode_tags = [];
461
-        if (empty($shortcode_tags)) {
462
-            $shortcode_tags = array_keys((array) $this->registry->shortcodes);
463
-        }
464
-        return $shortcode_tags;
465
-    }
466
-
467
-
468
-    /**
469
-     * @param string $content
470
-     * @return string
471
-     * @throws ReflectionException
472
-     */
473
-    public function doShortcode(string $content): string
474
-    {
475
-        foreach ($this->getEspressoShortcodeTags() as $shortcode_tag) {
476
-            if (strpos($content, $shortcode_tag) !== false) {
477
-                $shortcode_class = LegacyShortcodesManager::generateShortcodeClassNameFromTag($shortcode_tag);
478
-                $this->initializeShortcode($shortcode_class);
479
-            }
480
-        }
481
-        return do_shortcode($content);
482
-    }
29
+	/**
30
+	 * @var string
31
+	 */
32
+	public const SHORTCODE_PREFIX = 'EES_';
33
+
34
+	protected CurrentPage $current_page;
35
+
36
+	private EE_Registry $registry;
37
+
38
+
39
+	/**
40
+	 * LegacyShortcodesManager constructor.
41
+	 *
42
+	 * @param EE_Registry $registry
43
+	 * @param CurrentPage $current_page
44
+	 */
45
+	public function __construct(EE_Registry $registry, CurrentPage $current_page)
46
+	{
47
+		$this->registry     = $registry;
48
+		$this->current_page = $current_page;
49
+	}
50
+
51
+
52
+	/**
53
+	 * @return EE_Registry
54
+	 */
55
+	public function registry(): EE_Registry
56
+	{
57
+		return $this->registry;
58
+	}
59
+
60
+
61
+	/**
62
+	 * registerShortcodes
63
+	 *
64
+	 * @return void
65
+	 */
66
+	public function registerShortcodes()
67
+	{
68
+		$this->registry->shortcodes = $this->getShortcodes();
69
+	}
70
+
71
+
72
+	/**
73
+	 * getShortcodes
74
+	 *
75
+	 * @return array|RegistryContainer
76
+	 */
77
+	public function getShortcodes()
78
+	{
79
+		// previously this method would glob the shortcodes directory
80
+		// then filter that list of shortcodes to register,
81
+		// but now we are going to just supply an empty array.
82
+		// this allows any shortcodes that have not yet been converted to the new system
83
+		// to still get loaded and processed, albeit using the same legacy logic as before
84
+		$shortcodes_to_register = apply_filters(
85
+			'FHEE__EE_Config__register_shortcodes__shortcodes_to_register',
86
+			[]
87
+		);
88
+		if (! empty($shortcodes_to_register)) {
89
+			// cycle thru shortcode folders
90
+			foreach ($shortcodes_to_register as $shortcode_path) {
91
+				// add to list of installed shortcode modules
92
+				$this->registerShortcode($shortcode_path);
93
+			}
94
+		}
95
+		// filter list of installed modules
96
+		return apply_filters(
97
+			'FHEE__EE_Config___register_shortcodes__installed_shortcodes',
98
+			! empty($this->registry->shortcodes)
99
+				? $this->registry->shortcodes
100
+				: []
101
+		);
102
+	}
103
+
104
+
105
+	/**
106
+	 * register_shortcode - makes core aware of this shortcode
107
+	 *
108
+	 * @param string|null $shortcode_path - full path up to and including shortcode folder
109
+	 * @return    bool
110
+	 */
111
+	public function registerShortcode(string $shortcode_path = ''): bool
112
+	{
113
+		do_action('AHEE__EE_Config__register_shortcode__begin', $shortcode_path);
114
+		$shortcode_ext = '.shortcode.php';
115
+		// make all separators match
116
+		$shortcode_path = str_replace(['\\', '/'], '/', $shortcode_path);
117
+		// does the file path INCLUDE the actual file name as part of the path ?
118
+		if (strpos($shortcode_path, $shortcode_ext) !== false) {
119
+			// grab shortcode file name from directory name and break apart at dots
120
+			$shortcode_file = explode('.', basename($shortcode_path));
121
+			// take first segment from file name pieces and remove class prefix if it exists
122
+			$shortcode = LegacyShortcodesManager::stripShortcodeClassPrefix($shortcode_file[0]);
123
+			// sanitize shortcode directory name
124
+			$shortcode = sanitize_key($shortcode);
125
+			// now we need to rebuild the shortcode path
126
+			$shortcode_path = explode('/', $shortcode_path);
127
+			// remove last segment
128
+			array_pop($shortcode_path);
129
+			// glue it back together
130
+			$shortcode_path = implode('/', $shortcode_path) . '/';
131
+		} else {
132
+			// we need to generate the filename based off of the folder name
133
+			// grab and sanitize shortcode directory name
134
+			$shortcode      = sanitize_key(basename($shortcode_path));
135
+			$shortcode_path = rtrim($shortcode_path, '/') . '/';
136
+		}
137
+		// create classname from shortcode directory or file name
138
+		$shortcode = str_replace(' ', '_', ucwords(str_replace('_', ' ', $shortcode)));
139
+		// add class prefix
140
+		$shortcode_class = LegacyShortcodesManager::addShortcodeClassPrefix($shortcode);
141
+		// does the shortcode exist ?
142
+		if (! is_readable($shortcode_path . '/' . $shortcode_class . $shortcode_ext)) {
143
+			$msg = sprintf(
144
+				esc_html__(
145
+					'The requested %1$s shortcode file could not be found or is not readable due to file permissions. It should be in %2$s',
146
+					'event_espresso'
147
+				),
148
+				$shortcode_class,
149
+				$shortcode_path . '/' . $shortcode_class . $shortcode_ext
150
+			);
151
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
152
+			return false;
153
+		}
154
+		// load the shortcode class file
155
+		require_once($shortcode_path . $shortcode_class . $shortcode_ext);
156
+		// verify that class exists
157
+		if (! class_exists($shortcode_class)) {
158
+			$msg = sprintf(
159
+				esc_html__('The requested %s shortcode class does not exist.', 'event_espresso'),
160
+				$shortcode_class
161
+			);
162
+			EE_Error::add_error($msg . '||' . $msg, __FILE__, __FUNCTION__, __LINE__);
163
+			return false;
164
+		}
165
+		$shortcode = strtoupper($shortcode);
166
+		// add to array of registered shortcodes
167
+		$this->registry->shortcodes->{$shortcode} = $shortcode_path . $shortcode_class . $shortcode_ext;
168
+		return true;
169
+	}
170
+
171
+
172
+	/**
173
+	 *    _initialize_shortcodes
174
+	 *    allow shortcodes to set hooks for the rest of the system
175
+	 *
176
+	 * @return void
177
+	 */
178
+	public function addShortcodes()
179
+	{
180
+		// cycle thru shortcode folders
181
+		foreach ($this->registry->shortcodes as $shortcode => $shortcode_path) {
182
+			// add class prefix
183
+			$shortcode_class = LegacyShortcodesManager::addShortcodeClassPrefix($shortcode);
184
+			// fire the shortcode class's set_hooks methods in case it needs to hook into other parts of the system
185
+			// which set hooks ?
186
+			if (is_admin()) {
187
+				// fire immediately
188
+				call_user_func([$shortcode_class, 'set_hooks_admin']);
189
+			} else {
190
+				// delay until other systems are online
191
+				add_action(
192
+					'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons',
193
+					[$shortcode_class, 'set_hooks']
194
+				);
195
+				// convert classname to UPPERCASE and create WP shortcode.
196
+				$shortcode_tag = strtoupper($shortcode);
197
+				// but first check if the shortcode has already
198
+				// been added before assigning 'fallback_shortcode_processor'
199
+				if (! shortcode_exists($shortcode_tag)) {
200
+					// NOTE: this shortcode declaration will get overridden if the shortcode
201
+					// is successfully detected in the post content in initializeShortcode()
202
+					add_shortcode($shortcode_tag, [$shortcode_class, 'fallback_shortcode_processor']);
203
+				}
204
+			}
205
+		}
206
+	}
207
+
208
+
209
+	/**
210
+	 * callback for the WP "get_header" hook point
211
+	 * checks posts for EE shortcodes, and initializes them,
212
+	 * then toggles filter switch that loads core default assets
213
+	 *
214
+	 * @param WP_Query $wp_query
215
+	 * @return void
216
+	 * @throws ReflectionException
217
+	 */
218
+	public function initializeShortcodes(WP_Query $wp_query)
219
+	{
220
+		if (
221
+			empty($this->registry->shortcodes)
222
+			|| defined('EE_TESTS_DIR')
223
+			|| ! $wp_query->is_main_query()
224
+			|| is_admin()
225
+		) {
226
+			return;
227
+		}
228
+		// in case shortcode is loaded unexpectedly and deps haven't been set up correctly
229
+		EE_Dependency_Map::register_dependencies(
230
+			'EE_Front_Controller',
231
+			[
232
+				'EE_Registry'                                     => EE_Dependency_Map::load_from_cache,
233
+				'EventEspresso\core\services\request\CurrentPage' => EE_Dependency_Map::load_from_cache,
234
+				'EE_Module_Request_Router'                        => EE_Dependency_Map::load_from_cache,
235
+			]
236
+		);
237
+		global $wp;
238
+		/** @var EE_Front_controller $Front_Controller */
239
+		$Front_Controller = LoaderFactory::getLoader()->getShared('EE_Front_Controller');
240
+		do_action('AHEE__EE_Front_Controller__initialize_shortcodes__begin', $wp, $Front_Controller);
241
+		$this->current_page->parseQueryVars();
242
+		// grab post_name from request
243
+		$current_post  = apply_filters(
244
+			'FHEE__EE_Front_Controller__initialize_shortcodes__current_post_name',
245
+			$this->current_page->postName()
246
+		);
247
+		$show_on_front = get_option('show_on_front');
248
+		// if it's not set, then check if frontpage is blog
249
+		if (empty($current_post)) {
250
+			// yup.. this is the posts page, prepare to load all shortcode modules
251
+			$current_post = 'posts';
252
+			// unless..
253
+			if ($show_on_front === 'page') {
254
+				// some other page is set as the homepage
255
+				$page_on_front = get_option('page_on_front');
256
+				if ($page_on_front) {
257
+					// k now we need to find the post_name for this page
258
+					global $wpdb;
259
+					$page_on_front = $wpdb->get_var(
260
+						$wpdb->prepare(
261
+							"SELECT post_name from $wpdb->posts WHERE post_type='page' AND post_status NOT IN ('auto-draft', 'inherit', 'trash') AND ID=%d",
262
+							$page_on_front
263
+						)
264
+					);
265
+					// set the current post slug to what it actually is
266
+					$current_post = $page_on_front ?: $current_post;
267
+				}
268
+			}
269
+		}
270
+		// in case $current_post is hierarchical like: /parent-page/current-page
271
+		$current_post = basename($current_post);
272
+		if (
273
+			// is current page/post the "blog" page ?
274
+			$current_post === EE_Config::get_page_for_posts()
275
+			// or are we on a category page?
276
+			|| (
277
+				is_array(term_exists($current_post, 'category'))
278
+				|| array_key_exists('category_name', $wp->query_vars)
279
+			)
280
+		) {
281
+			// initialize all legacy shortcodes
282
+			$load_assets = $this->parseContentForShortcodes('', true);
283
+		} else {
284
+			global $post;
285
+			if ($post instanceof WP_Post) {
286
+				$post_content = $post->post_content;
287
+			} else {
288
+				global $wpdb;
289
+				$post_content = $wpdb->get_var(
290
+					$wpdb->prepare(
291
+						"SELECT post_content from $wpdb->posts WHERE post_status NOT IN ('auto-draft', 'inherit', 'trash') AND post_name=%s",
292
+						$current_post
293
+					)
294
+				);
295
+			}
296
+			$load_assets = $this->parseContentForShortcodes($post_content);
297
+		}
298
+		if ($load_assets) {
299
+			$this->current_page->setEspressoPage(true);
300
+			add_filter('FHEE_load_css', '__return_true');
301
+			add_filter('FHEE_load_js', '__return_true');
302
+		}
303
+		do_action('AHEE__EE_Front_Controller__initialize_shortcodes__end', $Front_Controller);
304
+	}
305
+
306
+
307
+	/**
308
+	 * checks supplied content against list of legacy shortcodes,
309
+	 * then initializes any found shortcodes, and returns true.
310
+	 * returns false if no shortcodes found.
311
+	 *
312
+	 * @param string|null $content
313
+	 * @param bool $load_all if true, then ALL active legacy shortcodes will be initialized
314
+	 * @return bool
315
+	 * @throws ReflectionException
316
+	 */
317
+	public function parseContentForShortcodes(?string $content = '', bool $load_all = false): bool
318
+	{
319
+		$content = $content ?? '';
320
+		$has_shortcode = false;
321
+		foreach ($this->registry->shortcodes as $shortcode_class => $shortcode) {
322
+			if ($load_all || has_shortcode($content, $shortcode_class)) {
323
+				// load up the shortcode
324
+				$this->initializeShortcode($shortcode_class);
325
+				$has_shortcode = true;
326
+			}
327
+		}
328
+		// one last test for an [espresso_*] shortcode
329
+		if (! $has_shortcode) {
330
+			$has_shortcode = strpos($content, '[espresso_') !== false;
331
+		}
332
+		return $has_shortcode;
333
+	}
334
+
335
+
336
+	/**
337
+	 * given a shortcode name, will instantiate the shortcode and call it's run() method
338
+	 *
339
+	 * @param string  $shortcode_class
340
+	 * @param WP|null $wp
341
+	 * @throws ReflectionException
342
+	 */
343
+	public function initializeShortcode(string $shortcode_class = '', WP $wp = null): void
344
+	{
345
+		// don't do anything if shortcode is already initialized
346
+		if (
347
+			empty($this->registry->shortcodes->{$shortcode_class})
348
+			|| ! is_string($this->registry->shortcodes->{$shortcode_class})
349
+		) {
350
+			return;
351
+		}
352
+		// let's pause to reflect on this...
353
+		$sc_reflector = new ReflectionClass(LegacyShortcodesManager::addShortcodeClassPrefix($shortcode_class));
354
+		// ensure that class is actually a shortcode
355
+		if (
356
+			defined('WP_DEBUG')
357
+			&& WP_DEBUG === true
358
+			&& ! $sc_reflector->isSubclassOf('EES_Shortcode')
359
+		) {
360
+			EE_Error::add_error(
361
+				sprintf(
362
+					esc_html__(
363
+						'The requested %s shortcode is not of the class "EES_Shortcode". Please check your files.',
364
+						'event_espresso'
365
+					),
366
+					$shortcode_class
367
+				),
368
+				__FILE__,
369
+				__FUNCTION__,
370
+				__LINE__
371
+			);
372
+			add_filter('FHEE_run_EE_the_content', '__return_true');
373
+			return;
374
+		}
375
+		global $wp;
376
+		// and pass the request object to the run method
377
+		$this->registry->shortcodes->{$shortcode_class} = $sc_reflector->newInstance();
378
+		// fire the shortcode class's run method, so that it can activate resources
379
+		$this->registry->shortcodes->{$shortcode_class}->run($wp);
380
+	}
381
+
382
+
383
+	/**
384
+	 * get classname, remove EES_prefix, and convert to UPPERCASE
385
+	 *
386
+	 * @param string $class_name
387
+	 * @return string
388
+	 */
389
+	public static function generateShortcodeTagFromClassName(string $class_name): string
390
+	{
391
+		return strtoupper(LegacyShortcodesManager::stripShortcodeClassPrefix(strtoupper($class_name)));
392
+	}
393
+
394
+
395
+	/**
396
+	 * add EES_prefix and Capitalize words
397
+	 *
398
+	 * @param string $tag
399
+	 * @return string
400
+	 */
401
+	public static function generateShortcodeClassNameFromTag(string $tag): string
402
+	{
403
+		// order of operation runs from inside to out
404
+		// 5) maybe add prefix
405
+		return LegacyShortcodesManager::addShortcodeClassPrefix(
406
+		// 4) find spaces, replace with underscores
407
+			str_replace(
408
+				' ',
409
+				'_',
410
+				// 3) capitalize first letter of each word
411
+				ucwords(
412
+				// 2) also change to lowercase so ucwords() will work
413
+					strtolower(
414
+					// 1) find underscores, replace with spaces so ucwords() will work
415
+						str_replace(
416
+							'_',
417
+							' ',
418
+							$tag
419
+						)
420
+					)
421
+				)
422
+			)
423
+		);
424
+	}
425
+
426
+
427
+	/**
428
+	 * maybe add EES_ prefix
429
+	 *
430
+	 * @param string $class_name
431
+	 * @return string
432
+	 */
433
+	public static function addShortcodeClassPrefix(string $class_name): string
434
+	{
435
+		return strpos($class_name, LegacyShortcodesManager::SHORTCODE_PREFIX) === 0
436
+			? $class_name
437
+			: LegacyShortcodesManager::SHORTCODE_PREFIX . $class_name;
438
+	}
439
+
440
+
441
+	/**
442
+	 * maybe remove EES_ prefix
443
+	 *
444
+	 * @param string $class_name
445
+	 * @return string
446
+	 */
447
+	public static function stripShortcodeClassPrefix(string $class_name): string
448
+	{
449
+		return strpos($class_name, LegacyShortcodesManager::SHORTCODE_PREFIX) === 0
450
+			? substr($class_name, 4)
451
+			: $class_name;
452
+	}
453
+
454
+
455
+	/**
456
+	 * @return array
457
+	 */
458
+	public function getEspressoShortcodeTags(): array
459
+	{
460
+		static $shortcode_tags = [];
461
+		if (empty($shortcode_tags)) {
462
+			$shortcode_tags = array_keys((array) $this->registry->shortcodes);
463
+		}
464
+		return $shortcode_tags;
465
+	}
466
+
467
+
468
+	/**
469
+	 * @param string $content
470
+	 * @return string
471
+	 * @throws ReflectionException
472
+	 */
473
+	public function doShortcode(string $content): string
474
+	{
475
+		foreach ($this->getEspressoShortcodeTags() as $shortcode_tag) {
476
+			if (strpos($content, $shortcode_tag) !== false) {
477
+				$shortcode_class = LegacyShortcodesManager::generateShortcodeClassNameFromTag($shortcode_tag);
478
+				$this->initializeShortcode($shortcode_class);
479
+			}
480
+		}
481
+		return do_shortcode($content);
482
+	}
483 483
 }
Please login to merge, or discard this patch.
core/services/graphql/types/TypeBase.php 2 patches
Indentation   +252 added lines, -252 removed lines patch added patch discarded remove patch
@@ -36,256 +36,256 @@
 block discarded – undo
36 36
  */
37 37
 abstract class TypeBase implements TypeInterface
38 38
 {
39
-    /**
40
-     * The graphql namespace/prefix.
41
-     */
42
-    protected string    $namespace   = 'Espresso';
43
-
44
-    protected ?EEM_Base $model       = null;
45
-
46
-    protected string    $name        = '';
47
-
48
-    protected string    $description = '';
49
-
50
-    /**
51
-     * @var GraphQLFieldInterface[] $fields
52
-     */
53
-    protected array         $fields              = [];
54
-
55
-    protected FieldResolver $field_resolver;
56
-
57
-    protected bool          $is_custom_post_type = false;
58
-
59
-
60
-    /**
61
-     * TypeBase constructor.
62
-     *
63
-     * @param EEM_Base|null $model
64
-     */
65
-    public function __construct(EEM_Base $model = null)
66
-    {
67
-        $this->model = $model;
68
-        $this->setFields($this->getFields());
69
-        $this->field_resolver = new FieldResolver(
70
-            $this->model,
71
-            $this->getFieldsForResolver()
72
-        );
73
-    }
74
-
75
-
76
-    /**
77
-     * @return GraphQLFieldInterface[]
78
-     * @since 5.0.0.p
79
-     */
80
-    abstract protected function getFields(): array;
81
-
82
-
83
-    /**
84
-     * @return string
85
-     */
86
-    public function name(): string
87
-    {
88
-        return $this->name;
89
-    }
90
-
91
-
92
-    /**
93
-     * @param string $name
94
-     */
95
-    protected function setName(string $name)
96
-    {
97
-        $this->name = $name;
98
-    }
99
-
100
-
101
-    /**
102
-     * @return string
103
-     */
104
-    public function description(): string
105
-    {
106
-        return $this->description;
107
-    }
108
-
109
-
110
-    /**
111
-     * @param string $description
112
-     */
113
-    protected function setDescription(string $description)
114
-    {
115
-        $this->description = $description;
116
-    }
117
-
118
-
119
-    /**
120
-     * @return GraphQLFieldInterface[]
121
-     * @since 5.0.0.p
122
-     */
123
-    public function fields(): array
124
-    {
125
-        return $this->fields;
126
-    }
127
-
128
-
129
-    /**
130
-     * @param GraphQLFieldInterface[] $fields
131
-     */
132
-    protected function setFields(array $fields)
133
-    {
134
-        foreach ($fields as $field) {
135
-            if ($field instanceof GraphQLField) {
136
-                $this->fields[] = $field;
137
-            }
138
-        }
139
-    }
140
-
141
-
142
-    /**
143
-     * Creates a key map for internal resolver.
144
-     *
145
-     * @return array
146
-     * @since 5.0.0.p
147
-     */
148
-    public function getFieldsForResolver(): array
149
-    {
150
-        $fields = [];
151
-        foreach ($this->fields() as $field) {
152
-            if ($field->useForOutput()) {
153
-                $fields[ $field->name() ] = $field;
154
-            }
155
-        }
156
-        return $fields;
157
-    }
158
-
159
-
160
-    /**
161
-     * @return bool
162
-     */
163
-    public function isCustomPostType(): bool
164
-    {
165
-        return $this->is_custom_post_type;
166
-    }
167
-
168
-
169
-    /**
170
-     * @param bool $is_custom_post_type
171
-     */
172
-    protected function setIsCustomPostType(bool $is_custom_post_type)
173
-    {
174
-        $this->is_custom_post_type = filter_var($is_custom_post_type, FILTER_VALIDATE_BOOLEAN);
175
-    }
176
-
177
-
178
-    /**
179
-     * @param int|float $value
180
-     * @return int
181
-     * @since 5.0.0.p
182
-     */
183
-    public function parseInfiniteValue($value): int
184
-    {
185
-        $value = trim((string) $value);
186
-        return $value === ''
187
-               || $value === '&infin;'
188
-               || $value === 'INF'
189
-               || $value === INF
190
-               || $value === EE_INF
191
-               || is_infinite((float) $value)
192
-            ? -1
193
-            : $value;
194
-    }
195
-
196
-
197
-    /**
198
-     * @param mixed $source
199
-     * @return EE_Base_Class|null
200
-     * @throws EE_Error
201
-     * @throws ReflectionException
202
-     */
203
-    private function getModel($source): ?EE_Base_Class
204
-    {
205
-        // If it comes from a custom connection
206
-        // where the $source is already instantiated.
207
-        if ($source instanceof EE_Base_Class) {
208
-            return $source;
209
-        }
210
-        return $source instanceof Post
211
-            ? $this->model->get_one_by_ID($source->ID)
212
-            : null;
213
-    }
214
-
215
-
216
-    /**
217
-     * @param mixed       $source  The source that's passed down the GraphQL queries
218
-     * @param array       $args    The inputArgs on the field
219
-     * @param AppContext  $context The AppContext passed down the GraphQL tree
220
-     * @param ResolveInfo $info    The ResolveInfo passed down the GraphQL tree
221
-     * @return EE_Base_Class|Deferred|string|null
222
-     * @throws EE_Error
223
-     * @throws InvalidDataTypeException
224
-     * @throws InvalidInterfaceException
225
-     * @throws UnexpectedEntityException
226
-     * @throws UserError
227
-     * @throws InvalidArgumentException
228
-     * @throws ReflectionException
229
-     * @since 5.0.0.p
230
-     */
231
-    public function resolveField($source, array $args, AppContext $context, ResolveInfo $info)
232
-    {
233
-        $source = $source instanceof RootQuery
234
-            ? $source
235
-            : $this->getModel($source);
236
-
237
-        return $this->field_resolver->resolve($source, $args, $context, $info);
238
-    }
239
-
240
-
241
-    /**
242
-     * @param mixed      $payload The payload returned after mutation
243
-     * @param array      $args    The inputArgs on the field
244
-     * @param AppContext $context The AppContext passed down the GraphQL tree
245
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|null
246
-     * @throws EE_Error
247
-     * @throws ReflectionException
248
-     */
249
-    public function resolveFromPayload($payload, array $args, AppContext $context)
250
-    {
251
-        if (empty($payload['id'])) {
252
-            return null;
253
-        }
254
-        return $this->model->get_one_by_ID($payload['id']);
255
-    }
256
-
257
-
258
-    /**
259
-     * Prepares a datetime value in ISO8601/RFC3339 format.
260
-     * It is assumed that the value of $datetime is in the format
261
-     * returned by EE_Base_Class::get_format().
262
-     *
263
-     * @param string        $datetime The datetime value.
264
-     * @param EE_Base_Class $source   The source object.
265
-     * @return string ISO8601/RFC3339 formatted datetime.
266
-     * @throws Exception
267
-     */
268
-    public function formatDatetime(string $datetime, EE_Base_Class $source): string
269
-    {
270
-        $format = $source->get_format();
271
-        // create date object based on local timezone
272
-        $datetime = DateTime::createFromFormat($format, $datetime, new DateTimeZone($source->get_timezone()));
273
-        // change the timezone to UTC
274
-        $datetime->setTimezone(new DateTimeZone('UTC'));
275
-
276
-        return $datetime->format(DateTimeInterface::RFC3339);
277
-    }
278
-
279
-
280
-    /**
281
-     * Converts an object to JSON. The object must have a "toJson" method.
282
-     *
283
-     * @param JsonableInterface $object The object/value.
284
-     * @param EE_Base_Class     $source The source object.
285
-     * @return string JSON representation of the object.
286
-     */
287
-    public function toJson(JsonableInterface $object, EE_Base_Class $source): string
288
-    {
289
-        return $object->toJson();
290
-    }
39
+	/**
40
+	 * The graphql namespace/prefix.
41
+	 */
42
+	protected string    $namespace   = 'Espresso';
43
+
44
+	protected ?EEM_Base $model       = null;
45
+
46
+	protected string    $name        = '';
47
+
48
+	protected string    $description = '';
49
+
50
+	/**
51
+	 * @var GraphQLFieldInterface[] $fields
52
+	 */
53
+	protected array         $fields              = [];
54
+
55
+	protected FieldResolver $field_resolver;
56
+
57
+	protected bool          $is_custom_post_type = false;
58
+
59
+
60
+	/**
61
+	 * TypeBase constructor.
62
+	 *
63
+	 * @param EEM_Base|null $model
64
+	 */
65
+	public function __construct(EEM_Base $model = null)
66
+	{
67
+		$this->model = $model;
68
+		$this->setFields($this->getFields());
69
+		$this->field_resolver = new FieldResolver(
70
+			$this->model,
71
+			$this->getFieldsForResolver()
72
+		);
73
+	}
74
+
75
+
76
+	/**
77
+	 * @return GraphQLFieldInterface[]
78
+	 * @since 5.0.0.p
79
+	 */
80
+	abstract protected function getFields(): array;
81
+
82
+
83
+	/**
84
+	 * @return string
85
+	 */
86
+	public function name(): string
87
+	{
88
+		return $this->name;
89
+	}
90
+
91
+
92
+	/**
93
+	 * @param string $name
94
+	 */
95
+	protected function setName(string $name)
96
+	{
97
+		$this->name = $name;
98
+	}
99
+
100
+
101
+	/**
102
+	 * @return string
103
+	 */
104
+	public function description(): string
105
+	{
106
+		return $this->description;
107
+	}
108
+
109
+
110
+	/**
111
+	 * @param string $description
112
+	 */
113
+	protected function setDescription(string $description)
114
+	{
115
+		$this->description = $description;
116
+	}
117
+
118
+
119
+	/**
120
+	 * @return GraphQLFieldInterface[]
121
+	 * @since 5.0.0.p
122
+	 */
123
+	public function fields(): array
124
+	{
125
+		return $this->fields;
126
+	}
127
+
128
+
129
+	/**
130
+	 * @param GraphQLFieldInterface[] $fields
131
+	 */
132
+	protected function setFields(array $fields)
133
+	{
134
+		foreach ($fields as $field) {
135
+			if ($field instanceof GraphQLField) {
136
+				$this->fields[] = $field;
137
+			}
138
+		}
139
+	}
140
+
141
+
142
+	/**
143
+	 * Creates a key map for internal resolver.
144
+	 *
145
+	 * @return array
146
+	 * @since 5.0.0.p
147
+	 */
148
+	public function getFieldsForResolver(): array
149
+	{
150
+		$fields = [];
151
+		foreach ($this->fields() as $field) {
152
+			if ($field->useForOutput()) {
153
+				$fields[ $field->name() ] = $field;
154
+			}
155
+		}
156
+		return $fields;
157
+	}
158
+
159
+
160
+	/**
161
+	 * @return bool
162
+	 */
163
+	public function isCustomPostType(): bool
164
+	{
165
+		return $this->is_custom_post_type;
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param bool $is_custom_post_type
171
+	 */
172
+	protected function setIsCustomPostType(bool $is_custom_post_type)
173
+	{
174
+		$this->is_custom_post_type = filter_var($is_custom_post_type, FILTER_VALIDATE_BOOLEAN);
175
+	}
176
+
177
+
178
+	/**
179
+	 * @param int|float $value
180
+	 * @return int
181
+	 * @since 5.0.0.p
182
+	 */
183
+	public function parseInfiniteValue($value): int
184
+	{
185
+		$value = trim((string) $value);
186
+		return $value === ''
187
+			   || $value === '&infin;'
188
+			   || $value === 'INF'
189
+			   || $value === INF
190
+			   || $value === EE_INF
191
+			   || is_infinite((float) $value)
192
+			? -1
193
+			: $value;
194
+	}
195
+
196
+
197
+	/**
198
+	 * @param mixed $source
199
+	 * @return EE_Base_Class|null
200
+	 * @throws EE_Error
201
+	 * @throws ReflectionException
202
+	 */
203
+	private function getModel($source): ?EE_Base_Class
204
+	{
205
+		// If it comes from a custom connection
206
+		// where the $source is already instantiated.
207
+		if ($source instanceof EE_Base_Class) {
208
+			return $source;
209
+		}
210
+		return $source instanceof Post
211
+			? $this->model->get_one_by_ID($source->ID)
212
+			: null;
213
+	}
214
+
215
+
216
+	/**
217
+	 * @param mixed       $source  The source that's passed down the GraphQL queries
218
+	 * @param array       $args    The inputArgs on the field
219
+	 * @param AppContext  $context The AppContext passed down the GraphQL tree
220
+	 * @param ResolveInfo $info    The ResolveInfo passed down the GraphQL tree
221
+	 * @return EE_Base_Class|Deferred|string|null
222
+	 * @throws EE_Error
223
+	 * @throws InvalidDataTypeException
224
+	 * @throws InvalidInterfaceException
225
+	 * @throws UnexpectedEntityException
226
+	 * @throws UserError
227
+	 * @throws InvalidArgumentException
228
+	 * @throws ReflectionException
229
+	 * @since 5.0.0.p
230
+	 */
231
+	public function resolveField($source, array $args, AppContext $context, ResolveInfo $info)
232
+	{
233
+		$source = $source instanceof RootQuery
234
+			? $source
235
+			: $this->getModel($source);
236
+
237
+		return $this->field_resolver->resolve($source, $args, $context, $info);
238
+	}
239
+
240
+
241
+	/**
242
+	 * @param mixed      $payload The payload returned after mutation
243
+	 * @param array      $args    The inputArgs on the field
244
+	 * @param AppContext $context The AppContext passed down the GraphQL tree
245
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|null
246
+	 * @throws EE_Error
247
+	 * @throws ReflectionException
248
+	 */
249
+	public function resolveFromPayload($payload, array $args, AppContext $context)
250
+	{
251
+		if (empty($payload['id'])) {
252
+			return null;
253
+		}
254
+		return $this->model->get_one_by_ID($payload['id']);
255
+	}
256
+
257
+
258
+	/**
259
+	 * Prepares a datetime value in ISO8601/RFC3339 format.
260
+	 * It is assumed that the value of $datetime is in the format
261
+	 * returned by EE_Base_Class::get_format().
262
+	 *
263
+	 * @param string        $datetime The datetime value.
264
+	 * @param EE_Base_Class $source   The source object.
265
+	 * @return string ISO8601/RFC3339 formatted datetime.
266
+	 * @throws Exception
267
+	 */
268
+	public function formatDatetime(string $datetime, EE_Base_Class $source): string
269
+	{
270
+		$format = $source->get_format();
271
+		// create date object based on local timezone
272
+		$datetime = DateTime::createFromFormat($format, $datetime, new DateTimeZone($source->get_timezone()));
273
+		// change the timezone to UTC
274
+		$datetime->setTimezone(new DateTimeZone('UTC'));
275
+
276
+		return $datetime->format(DateTimeInterface::RFC3339);
277
+	}
278
+
279
+
280
+	/**
281
+	 * Converts an object to JSON. The object must have a "toJson" method.
282
+	 *
283
+	 * @param JsonableInterface $object The object/value.
284
+	 * @param EE_Base_Class     $source The source object.
285
+	 * @return string JSON representation of the object.
286
+	 */
287
+	public function toJson(JsonableInterface $object, EE_Base_Class $source): string
288
+	{
289
+		return $object->toJson();
290
+	}
291 291
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
     /**
51 51
      * @var GraphQLFieldInterface[] $fields
52 52
      */
53
-    protected array         $fields              = [];
53
+    protected array         $fields = [];
54 54
 
55 55
     protected FieldResolver $field_resolver;
56 56
 
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
         $fields = [];
151 151
         foreach ($this->fields() as $field) {
152 152
             if ($field->useForOutput()) {
153
-                $fields[ $field->name() ] = $field;
153
+                $fields[$field->name()] = $field;
154 154
             }
155 155
         }
156 156
         return $fields;
Please login to merge, or discard this patch.
core/db_classes/EE_Attendee.class.php 1 patch
Indentation   +737 added lines, -737 removed lines patch added patch discarded remove patch
@@ -15,741 +15,741 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Attendee extends EE_CPT_Base implements EEI_Contact, AddressInterface, EEI_Admin_Links, EEI_Attendee
17 17
 {
18
-    /**
19
-     * Sets some dynamic defaults
20
-     *
21
-     * @param array  $fieldValues
22
-     * @param bool   $bydb
23
-     * @param string $timezone
24
-     * @param array  $date_formats
25
-     * @throws EE_Error
26
-     * @throws ReflectionException
27
-     */
28
-    protected function __construct($fieldValues = null, $bydb = false, $timezone = null, $date_formats = [])
29
-    {
30
-        if (! isset($fieldValues['ATT_full_name'])) {
31
-            $fname                        = $fieldValues['ATT_fname'] ?? '';
32
-            $lname                        = $fieldValues['ATT_lname'] ?? '';
33
-            $fieldValues['ATT_full_name'] = "$fname $lname";
34
-        }
35
-        if (! isset($fieldValues['ATT_slug'])) {
36
-            // $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
37
-            $fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
38
-        }
39
-        if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
40
-            $fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
41
-        }
42
-        parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
43
-    }
44
-
45
-
46
-    /**
47
-     * @param array       $props_n_values     incoming values
48
-     * @param string|null $timezone           incoming timezone (if not set the timezone set for the website
49
-     *                                        will be
50
-     *                                        used.)
51
-     * @param array       $date_formats       incoming date_formats in an array where the first value is the
52
-     *                                        date_format and the second value is the time format
53
-     * @return EE_Attendee
54
-     * @throws EE_Error
55
-     * @throws ReflectionException
56
-     */
57
-    public static function new_instance(
58
-        array $props_n_values = [],
59
-        ?string $timezone = '',
60
-        array $date_formats = []
61
-    ): EE_Attendee {
62
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
63
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
64
-    }
65
-
66
-
67
-    /**
68
-     * @param array       $props_n_values incoming values from the database
69
-     * @param string|null $timezone       incoming timezone as set by the model.
70
-     *                                    If not set, the timezone for the website will be used.
71
-     * @return EE_Attendee
72
-     * @throws EE_Error
73
-     * @throws ReflectionException
74
-     */
75
-    public static function new_instance_from_db(array $props_n_values = [], ?string $timezone = ''): EE_Attendee
76
-    {
77
-        return new self($props_n_values, true, $timezone);
78
-    }
79
-
80
-
81
-    /**
82
-     * @param string|null $fname
83
-     * @throws EE_Error
84
-     * @throws ReflectionException
85
-     */
86
-    public function set_fname(?string $fname = '')
87
-    {
88
-        $this->set('ATT_fname', (string) $fname);
89
-    }
90
-
91
-
92
-    /**
93
-     * @param string|null $lname
94
-     * @throws EE_Error
95
-     * @throws ReflectionException
96
-     */
97
-    public function set_lname(?string $lname = '')
98
-    {
99
-        $this->set('ATT_lname', (string) $lname);
100
-    }
101
-
102
-
103
-    /**
104
-     * @param string|null $address
105
-     * @throws EE_Error
106
-     * @throws ReflectionException
107
-     */
108
-    public function set_address(?string $address = '')
109
-    {
110
-        $this->set('ATT_address', (string) $address);
111
-    }
112
-
113
-
114
-    /**
115
-     * @param string|null $address2
116
-     * @throws EE_Error
117
-     * @throws ReflectionException
118
-     */
119
-    public function set_address2(?string $address2 = '')
120
-    {
121
-        $this->set('ATT_address2', (string) $address2);
122
-    }
123
-
124
-
125
-    /**
126
-     * @param string|null $city
127
-     * @throws EE_Error
128
-     * @throws ReflectionException
129
-     */
130
-    public function set_city(?string $city = '')
131
-    {
132
-        $this->set('ATT_city', $city);
133
-    }
134
-
135
-
136
-    /**
137
-     * @param int|null $STA_ID
138
-     * @throws EE_Error
139
-     * @throws ReflectionException
140
-     */
141
-    public function set_state(?int $STA_ID = 0)
142
-    {
143
-        $this->set('STA_ID', $STA_ID);
144
-    }
145
-
146
-
147
-    /**
148
-     * @param string|null $CNT_ISO
149
-     * @throws EE_Error
150
-     * @throws ReflectionException
151
-     */
152
-    public function set_country(?string $CNT_ISO = '')
153
-    {
154
-        $this->set('CNT_ISO', $CNT_ISO);
155
-    }
156
-
157
-
158
-    /**
159
-     * @param string|null $zip
160
-     * @throws EE_Error
161
-     * @throws ReflectionException
162
-     */
163
-    public function set_zip(?string $zip = '')
164
-    {
165
-        $this->set('ATT_zip', $zip);
166
-    }
167
-
168
-
169
-    /**
170
-     * @param string|null $email
171
-     * @throws EE_Error
172
-     * @throws ReflectionException
173
-     */
174
-    public function set_email(?string $email = '')
175
-    {
176
-        $this->set('ATT_email', $email);
177
-    }
178
-
179
-
180
-    /**
181
-     * @param string|null $phone
182
-     * @throws EE_Error
183
-     * @throws ReflectionException
184
-     */
185
-    public function set_phone(?string $phone = '')
186
-    {
187
-        $this->set('ATT_phone', $phone);
188
-    }
189
-
190
-
191
-    /**
192
-     * @param bool|int|string|null $ATT_deleted
193
-     * @throws EE_Error
194
-     * @throws ReflectionException
195
-     */
196
-    public function set_deleted($ATT_deleted = false)
197
-    {
198
-        $this->set('ATT_deleted', $ATT_deleted);
199
-    }
200
-
201
-
202
-    /**
203
-     * Returns the value for the post_author id saved with the cpt
204
-     *
205
-     * @return int
206
-     * @throws EE_Error
207
-     * @throws ReflectionException
208
-     * @since 4.5.0
209
-     */
210
-    public function wp_user(): int
211
-    {
212
-        return (int) $this->get('ATT_author');
213
-    }
214
-
215
-
216
-    /**
217
-     * @return string
218
-     * @throws EE_Error
219
-     * @throws ReflectionException
220
-     */
221
-    public function fname(): string
222
-    {
223
-        return (string) $this->get('ATT_fname');
224
-    }
225
-
226
-
227
-    /**
228
-     * echoes out the attendee's first name
229
-     *
230
-     * @return void
231
-     * @throws EE_Error
232
-     * @throws ReflectionException
233
-     */
234
-    public function e_full_name()
235
-    {
236
-        echo esc_html($this->full_name());
237
-    }
238
-
239
-
240
-    /**
241
-     * Returns the first and last name concatenated together with a space.
242
-     *
243
-     * @param bool $apply_html_entities
244
-     * @return string
245
-     * @throws EE_Error
246
-     * @throws ReflectionException
247
-     */
248
-    public function full_name(bool $apply_html_entities = false): string
249
-    {
250
-        $full_name = [$this->fname(), $this->lname()];
251
-        $full_name = array_filter($full_name);
252
-        $full_name = implode(' ', $full_name);
253
-        return $apply_html_entities
254
-            ? htmlentities($full_name, ENT_QUOTES, 'UTF-8')
255
-            : $full_name;
256
-    }
257
-
258
-
259
-    /**
260
-     * This returns the value of the `ATT_full_name` field which is usually equivalent to calling `full_name()` unless
261
-     * the post_title field has been directly modified in the db for the post (espresso_attendees post type) for this
262
-     * attendee.
263
-     *
264
-     * @param bool $apply_html_entities
265
-     * @return string
266
-     * @throws EE_Error
267
-     * @throws ReflectionException
268
-     */
269
-    public function ATT_full_name(bool $apply_html_entities = false): string
270
-    {
271
-        return $apply_html_entities
272
-            ? htmlentities((string) $this->get('ATT_full_name'), ENT_QUOTES, 'UTF-8')
273
-            : (string) $this->get('ATT_full_name');
274
-    }
275
-
276
-
277
-    /**
278
-     * @return string
279
-     * @throws EE_Error
280
-     * @throws ReflectionException
281
-     */
282
-    public function lname(): string
283
-    {
284
-        return (string) $this->get('ATT_lname');
285
-    }
286
-
287
-
288
-    /**
289
-     * @return string
290
-     * @throws EE_Error
291
-     * @throws ReflectionException
292
-     */
293
-    public function bio(): string
294
-    {
295
-        return (string) $this->get('ATT_bio');
296
-    }
297
-
298
-
299
-    /**
300
-     * @return string
301
-     * @throws EE_Error
302
-     * @throws ReflectionException
303
-     */
304
-    public function short_bio(): string
305
-    {
306
-        return (string) $this->get('ATT_short_bio');
307
-    }
308
-
309
-
310
-    /**
311
-     * Gets the attendee's full address as an array so client code can decide hwo to display it
312
-     *
313
-     * @return array numerically indexed, with each part of the address that is known.
314
-     * Eg, if the user only responded to state and country,
315
-     * it would be array(0=>'Alabama',1=>'USA')
316
-     * @return array
317
-     * @throws EE_Error
318
-     * @throws ReflectionException
319
-     */
320
-    public function full_address_as_array(): array
321
-    {
322
-        $full_address_array     = [];
323
-        $initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
324
-        foreach ($initial_address_fields as $address_field_name) {
325
-            $address_fields_value = $this->get($address_field_name);
326
-            if (! empty($address_fields_value)) {
327
-                $full_address_array[] = $address_fields_value;
328
-            }
329
-        }
330
-        // now handle state and country
331
-        $state_obj = $this->state_obj();
332
-        if ($state_obj instanceof EE_State) {
333
-            $full_address_array[] = $state_obj->name();
334
-        }
335
-        $country_obj = $this->country_obj();
336
-        if ($country_obj instanceof EE_Country) {
337
-            $full_address_array[] = $country_obj->name();
338
-        }
339
-        // lastly get the xip
340
-        $zip_value = $this->zip();
341
-        if (! empty($zip_value)) {
342
-            $full_address_array[] = $zip_value;
343
-        }
344
-        return $full_address_array;
345
-    }
346
-
347
-
348
-    /**
349
-     * @return string
350
-     * @throws EE_Error
351
-     * @throws ReflectionException
352
-     */
353
-    public function address(): string
354
-    {
355
-        return (string) $this->get('ATT_address');
356
-    }
357
-
358
-
359
-    /**
360
-     * @return string
361
-     * @throws EE_Error
362
-     * @throws ReflectionException
363
-     */
364
-    public function address2(): string
365
-    {
366
-        return (string) $this->get('ATT_address2');
367
-    }
368
-
369
-
370
-    /**
371
-     * @return string
372
-     * @throws EE_Error
373
-     * @throws ReflectionException
374
-     */
375
-    public function city(): string
376
-    {
377
-        return (string) $this->get('ATT_city');
378
-    }
379
-
380
-
381
-    /**
382
-     * @return int
383
-     * @throws EE_Error
384
-     * @throws ReflectionException
385
-     */
386
-    public function state_ID(): int
387
-    {
388
-        return (int) $this->get('STA_ID');
389
-    }
390
-
391
-
392
-    /**
393
-     * @return string
394
-     * @throws EE_Error
395
-     * @throws ReflectionException
396
-     */
397
-    public function state_abbrev(): string
398
-    {
399
-        return $this->state_obj() instanceof EE_State
400
-            ? $this->state_obj()->abbrev()
401
-            : '';
402
-    }
403
-
404
-
405
-    /**
406
-     * @return EE_State|null
407
-     * @throws EE_Error
408
-     * @throws ReflectionException
409
-     */
410
-    public function state_obj(): ?EE_State
411
-    {
412
-        return $this->get_first_related('State');
413
-    }
414
-
415
-
416
-    /**
417
-     * @return string
418
-     * @throws EE_Error
419
-     * @throws ReflectionException
420
-     */
421
-    public function state_name(): string
422
-    {
423
-        return $this->state_obj() instanceof EE_State
424
-            ? $this->state_obj()->name()
425
-            : '';
426
-    }
427
-
428
-
429
-    /**
430
-     * either displays the state abbreviation or the state name, as determined
431
-     * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
432
-     * defaults to abbreviation
433
-     *
434
-     * @return string
435
-     * @throws EE_Error
436
-     * @throws ReflectionException
437
-     */
438
-    public function state(): string
439
-    {
440
-        return apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())
441
-            ? $this->state_abbrev()
442
-            : $this->state_name();
443
-    }
444
-
445
-
446
-    /**
447
-     * @return string
448
-     * @throws EE_Error
449
-     * @throws ReflectionException
450
-     */
451
-    public function country_ID(): string
452
-    {
453
-        return (string) $this->get('CNT_ISO');
454
-    }
455
-
456
-
457
-    /**
458
-     * @return EE_Country|null
459
-     * @throws EE_Error
460
-     * @throws ReflectionException
461
-     */
462
-    public function country_obj(): ?EE_Country
463
-    {
464
-        return $this->get_first_related('Country');
465
-    }
466
-
467
-
468
-    /**
469
-     * @return string
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     */
473
-    public function country_name(): string
474
-    {
475
-        return $this->country_obj() instanceof EE_Country
476
-            ? $this->country_obj()->name()
477
-            : '';
478
-    }
479
-
480
-
481
-    /**
482
-     * either displays the country ISO2 code or the country name, as determined
483
-     * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
484
-     * defaults to abbreviation
485
-     *
486
-     * @return string
487
-     * @throws EE_Error
488
-     * @throws ReflectionException
489
-     */
490
-    public function country(): string
491
-    {
492
-        return apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())
493
-            ? $this->country_ID()
494
-            : $this->country_name();
495
-    }
496
-
497
-
498
-    /**
499
-     * @return string
500
-     * @throws EE_Error
501
-     * @throws ReflectionException
502
-     */
503
-    public function zip(): string
504
-    {
505
-        return (string) $this->get('ATT_zip');
506
-    }
507
-
508
-
509
-    /**
510
-     * @return string
511
-     * @throws EE_Error
512
-     * @throws ReflectionException
513
-     */
514
-    public function email(): string
515
-    {
516
-        return (string) $this->get('ATT_email');
517
-    }
518
-
519
-
520
-    /**
521
-     * @return string
522
-     * @throws EE_Error
523
-     * @throws ReflectionException
524
-     */
525
-    public function phone(): string
526
-    {
527
-        return (string) $this->get('ATT_phone');
528
-    }
529
-
530
-
531
-    /**
532
-     * @return bool
533
-     * @throws EE_Error
534
-     * @throws ReflectionException
535
-     */
536
-    public function deleted(): bool
537
-    {
538
-        return (bool) $this->get('ATT_deleted');
539
-    }
540
-
541
-
542
-    /**
543
-     * @param array $query_params
544
-     * @return EE_Registration[]
545
-     * @throws EE_Error
546
-     * @throws ReflectionException
547
-     */
548
-    public function get_registrations(array $query_params = []): array
549
-    {
550
-        return $this->get_many_related('Registration', $query_params);
551
-    }
552
-
553
-
554
-    /**
555
-     * Gets the most recent registration of this attendee
556
-     *
557
-     * @return EE_Registration|null
558
-     * @throws EE_Error
559
-     * @throws ReflectionException
560
-     */
561
-    public function get_most_recent_registration(): ?EE_Registration
562
-    {
563
-        return $this->get_first_related('Registration', ['order_by' => ['REG_date' => 'DESC']]);
564
-    }
565
-
566
-
567
-    /**
568
-     * Gets the most recent registration for this attend at this event
569
-     *
570
-     * @param int $event_id
571
-     * @return EE_Registration|null
572
-     * @throws EE_Error
573
-     * @throws ReflectionException
574
-     */
575
-    public function get_most_recent_registration_for_event(int $event_id): ?EE_Registration
576
-    {
577
-        return $this->get_first_related(
578
-            'Registration',
579
-            [['EVT_ID' => $event_id], 'order_by' => ['REG_date' => 'DESC']]
580
-        );
581
-    }
582
-
583
-
584
-    /**
585
-     * returns any events attached to this attendee ($_Event property);
586
-     *
587
-     * @return EE_Event[]
588
-     * @throws EE_Error
589
-     * @throws ReflectionException
590
-     */
591
-    public function events(): array
592
-    {
593
-        return $this->get_many_related('Event');
594
-    }
595
-
596
-
597
-    /**
598
-     * Gets the billing info array where keys match espresso_reg_page_billing_inputs(),
599
-     * and keys are their cleaned values. @param EE_Payment_Method $payment_method the _gateway_name property on the
600
-     * gateway class
601
-     *
602
-     * @return EE_Form_Section_Proper|null
603
-     * @throws EE_Error
604
-     * @throws ReflectionException
605
-     * @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was used to save the billing info
606
-     */
607
-    public function billing_info_for_payment_method(EE_Payment_Method $payment_method): ?EE_Form_Section_Proper
608
-    {
609
-        $pm_type = $payment_method->type_obj();
610
-        if (! $pm_type instanceof EE_PMT_Base) {
611
-            return null;
612
-        }
613
-        $billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
614
-        if (! $billing_info) {
615
-            return null;
616
-        }
617
-        $billing_form = $pm_type->billing_form();
618
-        // double-check the form isn't totally hidden, in which case pretend there is no form
619
-        $form_totally_hidden = true;
620
-        foreach ($billing_form->inputs_in_subsections() as $input) {
621
-            if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
622
-                $form_totally_hidden = false;
623
-                break;
624
-            }
625
-        }
626
-        if ($form_totally_hidden) {
627
-            return null;
628
-        }
629
-        if ($billing_form instanceof EE_Form_Section_Proper) {
630
-            $billing_form->receive_form_submission([$billing_form->name() => $billing_info], false);
631
-        }
632
-
633
-        return $billing_form;
634
-    }
635
-
636
-
637
-    /**
638
-     * Gets the postmeta key that holds this attendee's billing info for the
639
-     * specified payment method
640
-     *
641
-     * @param EE_Payment_Method $payment_method
642
-     * @return string
643
-     * @throws EE_Error
644
-     */
645
-    public function get_billing_info_postmeta_name(EE_Payment_Method $payment_method): string
646
-    {
647
-        return $payment_method->type_obj() instanceof EE_PMT_Base
648
-            ? 'billing_info_' . $payment_method->type_obj()->system_name()
649
-            : '';
650
-    }
651
-
652
-
653
-    /**
654
-     * Saves the billing info to the attendee.
655
-     *
656
-     * @param EE_Billing_Attendee_Info_Form|null $billing_form
657
-     * @param EE_Payment_Method                  $payment_method
658
-     * @return boolean
659
-     * @throws EE_Error
660
-     * @throws ReflectionException
661
-     * @see EE_Attendee::billing_info_for_payment_method() which is used to retrieve it
662
-     */
663
-    public function save_and_clean_billing_info_for_payment_method(
664
-        ?EE_Billing_Attendee_Info_Form $billing_form,
665
-        EE_Payment_Method $payment_method
666
-    ): bool {
667
-        if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
668
-            EE_Error::add_error(
669
-                esc_html__('Cannot save billing info because there is none.', 'event_espresso'),
670
-                __FILE__,
671
-                __FUNCTION__,
672
-                __LINE__
673
-            );
674
-            return false;
675
-        }
676
-        $billing_form->clean_sensitive_data();
677
-        return update_post_meta(
678
-            $this->ID(),
679
-            $this->get_billing_info_postmeta_name($payment_method),
680
-            $billing_form->input_values(true)
681
-        );
682
-    }
683
-
684
-
685
-    /**
686
-     * Return the link to the admin details for the object.
687
-     *
688
-     * @return string
689
-     * @throws EE_Error
690
-     * @throws InvalidArgumentException
691
-     * @throws InvalidDataTypeException
692
-     * @throws InvalidInterfaceException
693
-     * @throws ReflectionException
694
-     */
695
-    public function get_admin_details_link(): string
696
-    {
697
-        return $this->get_admin_edit_link();
698
-    }
699
-
700
-
701
-    /**
702
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
703
-     *
704
-     * @return string
705
-     * @throws EE_Error
706
-     * @throws InvalidArgumentException
707
-     * @throws ReflectionException
708
-     * @throws InvalidDataTypeException
709
-     * @throws InvalidInterfaceException
710
-     */
711
-    public function get_admin_edit_link(): string
712
-    {
713
-        return EEH_URL::add_query_args_and_nonce(
714
-            [
715
-                'page'   => 'espresso_registrations',
716
-                'action' => 'edit_attendee',
717
-                'post'   => $this->ID(),
718
-            ],
719
-            admin_url('admin.php')
720
-        );
721
-    }
722
-
723
-
724
-    /**
725
-     * Returns the link to a settings page for the object.
726
-     *
727
-     * @return string
728
-     * @throws EE_Error
729
-     * @throws InvalidArgumentException
730
-     * @throws InvalidDataTypeException
731
-     * @throws InvalidInterfaceException
732
-     * @throws ReflectionException
733
-     */
734
-    public function get_admin_settings_link(): string
735
-    {
736
-        return $this->get_admin_edit_link();
737
-    }
738
-
739
-
740
-    /**
741
-     * Returns the link to the "overview" for the object (typically the "list table" view).
742
-     *
743
-     * @return string
744
-     */
745
-    public function get_admin_overview_link(): string
746
-    {
747
-        return EEH_URL::add_query_args_and_nonce(
748
-            [
749
-                'page'   => 'espresso_registrations',
750
-                'action' => 'contact_list',
751
-            ],
752
-            admin_url('admin.php')
753
-        );
754
-    }
18
+	/**
19
+	 * Sets some dynamic defaults
20
+	 *
21
+	 * @param array  $fieldValues
22
+	 * @param bool   $bydb
23
+	 * @param string $timezone
24
+	 * @param array  $date_formats
25
+	 * @throws EE_Error
26
+	 * @throws ReflectionException
27
+	 */
28
+	protected function __construct($fieldValues = null, $bydb = false, $timezone = null, $date_formats = [])
29
+	{
30
+		if (! isset($fieldValues['ATT_full_name'])) {
31
+			$fname                        = $fieldValues['ATT_fname'] ?? '';
32
+			$lname                        = $fieldValues['ATT_lname'] ?? '';
33
+			$fieldValues['ATT_full_name'] = "$fname $lname";
34
+		}
35
+		if (! isset($fieldValues['ATT_slug'])) {
36
+			// $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
37
+			$fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
38
+		}
39
+		if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
40
+			$fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
41
+		}
42
+		parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
43
+	}
44
+
45
+
46
+	/**
47
+	 * @param array       $props_n_values     incoming values
48
+	 * @param string|null $timezone           incoming timezone (if not set the timezone set for the website
49
+	 *                                        will be
50
+	 *                                        used.)
51
+	 * @param array       $date_formats       incoming date_formats in an array where the first value is the
52
+	 *                                        date_format and the second value is the time format
53
+	 * @return EE_Attendee
54
+	 * @throws EE_Error
55
+	 * @throws ReflectionException
56
+	 */
57
+	public static function new_instance(
58
+		array $props_n_values = [],
59
+		?string $timezone = '',
60
+		array $date_formats = []
61
+	): EE_Attendee {
62
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
63
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
64
+	}
65
+
66
+
67
+	/**
68
+	 * @param array       $props_n_values incoming values from the database
69
+	 * @param string|null $timezone       incoming timezone as set by the model.
70
+	 *                                    If not set, the timezone for the website will be used.
71
+	 * @return EE_Attendee
72
+	 * @throws EE_Error
73
+	 * @throws ReflectionException
74
+	 */
75
+	public static function new_instance_from_db(array $props_n_values = [], ?string $timezone = ''): EE_Attendee
76
+	{
77
+		return new self($props_n_values, true, $timezone);
78
+	}
79
+
80
+
81
+	/**
82
+	 * @param string|null $fname
83
+	 * @throws EE_Error
84
+	 * @throws ReflectionException
85
+	 */
86
+	public function set_fname(?string $fname = '')
87
+	{
88
+		$this->set('ATT_fname', (string) $fname);
89
+	}
90
+
91
+
92
+	/**
93
+	 * @param string|null $lname
94
+	 * @throws EE_Error
95
+	 * @throws ReflectionException
96
+	 */
97
+	public function set_lname(?string $lname = '')
98
+	{
99
+		$this->set('ATT_lname', (string) $lname);
100
+	}
101
+
102
+
103
+	/**
104
+	 * @param string|null $address
105
+	 * @throws EE_Error
106
+	 * @throws ReflectionException
107
+	 */
108
+	public function set_address(?string $address = '')
109
+	{
110
+		$this->set('ATT_address', (string) $address);
111
+	}
112
+
113
+
114
+	/**
115
+	 * @param string|null $address2
116
+	 * @throws EE_Error
117
+	 * @throws ReflectionException
118
+	 */
119
+	public function set_address2(?string $address2 = '')
120
+	{
121
+		$this->set('ATT_address2', (string) $address2);
122
+	}
123
+
124
+
125
+	/**
126
+	 * @param string|null $city
127
+	 * @throws EE_Error
128
+	 * @throws ReflectionException
129
+	 */
130
+	public function set_city(?string $city = '')
131
+	{
132
+		$this->set('ATT_city', $city);
133
+	}
134
+
135
+
136
+	/**
137
+	 * @param int|null $STA_ID
138
+	 * @throws EE_Error
139
+	 * @throws ReflectionException
140
+	 */
141
+	public function set_state(?int $STA_ID = 0)
142
+	{
143
+		$this->set('STA_ID', $STA_ID);
144
+	}
145
+
146
+
147
+	/**
148
+	 * @param string|null $CNT_ISO
149
+	 * @throws EE_Error
150
+	 * @throws ReflectionException
151
+	 */
152
+	public function set_country(?string $CNT_ISO = '')
153
+	{
154
+		$this->set('CNT_ISO', $CNT_ISO);
155
+	}
156
+
157
+
158
+	/**
159
+	 * @param string|null $zip
160
+	 * @throws EE_Error
161
+	 * @throws ReflectionException
162
+	 */
163
+	public function set_zip(?string $zip = '')
164
+	{
165
+		$this->set('ATT_zip', $zip);
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param string|null $email
171
+	 * @throws EE_Error
172
+	 * @throws ReflectionException
173
+	 */
174
+	public function set_email(?string $email = '')
175
+	{
176
+		$this->set('ATT_email', $email);
177
+	}
178
+
179
+
180
+	/**
181
+	 * @param string|null $phone
182
+	 * @throws EE_Error
183
+	 * @throws ReflectionException
184
+	 */
185
+	public function set_phone(?string $phone = '')
186
+	{
187
+		$this->set('ATT_phone', $phone);
188
+	}
189
+
190
+
191
+	/**
192
+	 * @param bool|int|string|null $ATT_deleted
193
+	 * @throws EE_Error
194
+	 * @throws ReflectionException
195
+	 */
196
+	public function set_deleted($ATT_deleted = false)
197
+	{
198
+		$this->set('ATT_deleted', $ATT_deleted);
199
+	}
200
+
201
+
202
+	/**
203
+	 * Returns the value for the post_author id saved with the cpt
204
+	 *
205
+	 * @return int
206
+	 * @throws EE_Error
207
+	 * @throws ReflectionException
208
+	 * @since 4.5.0
209
+	 */
210
+	public function wp_user(): int
211
+	{
212
+		return (int) $this->get('ATT_author');
213
+	}
214
+
215
+
216
+	/**
217
+	 * @return string
218
+	 * @throws EE_Error
219
+	 * @throws ReflectionException
220
+	 */
221
+	public function fname(): string
222
+	{
223
+		return (string) $this->get('ATT_fname');
224
+	}
225
+
226
+
227
+	/**
228
+	 * echoes out the attendee's first name
229
+	 *
230
+	 * @return void
231
+	 * @throws EE_Error
232
+	 * @throws ReflectionException
233
+	 */
234
+	public function e_full_name()
235
+	{
236
+		echo esc_html($this->full_name());
237
+	}
238
+
239
+
240
+	/**
241
+	 * Returns the first and last name concatenated together with a space.
242
+	 *
243
+	 * @param bool $apply_html_entities
244
+	 * @return string
245
+	 * @throws EE_Error
246
+	 * @throws ReflectionException
247
+	 */
248
+	public function full_name(bool $apply_html_entities = false): string
249
+	{
250
+		$full_name = [$this->fname(), $this->lname()];
251
+		$full_name = array_filter($full_name);
252
+		$full_name = implode(' ', $full_name);
253
+		return $apply_html_entities
254
+			? htmlentities($full_name, ENT_QUOTES, 'UTF-8')
255
+			: $full_name;
256
+	}
257
+
258
+
259
+	/**
260
+	 * This returns the value of the `ATT_full_name` field which is usually equivalent to calling `full_name()` unless
261
+	 * the post_title field has been directly modified in the db for the post (espresso_attendees post type) for this
262
+	 * attendee.
263
+	 *
264
+	 * @param bool $apply_html_entities
265
+	 * @return string
266
+	 * @throws EE_Error
267
+	 * @throws ReflectionException
268
+	 */
269
+	public function ATT_full_name(bool $apply_html_entities = false): string
270
+	{
271
+		return $apply_html_entities
272
+			? htmlentities((string) $this->get('ATT_full_name'), ENT_QUOTES, 'UTF-8')
273
+			: (string) $this->get('ATT_full_name');
274
+	}
275
+
276
+
277
+	/**
278
+	 * @return string
279
+	 * @throws EE_Error
280
+	 * @throws ReflectionException
281
+	 */
282
+	public function lname(): string
283
+	{
284
+		return (string) $this->get('ATT_lname');
285
+	}
286
+
287
+
288
+	/**
289
+	 * @return string
290
+	 * @throws EE_Error
291
+	 * @throws ReflectionException
292
+	 */
293
+	public function bio(): string
294
+	{
295
+		return (string) $this->get('ATT_bio');
296
+	}
297
+
298
+
299
+	/**
300
+	 * @return string
301
+	 * @throws EE_Error
302
+	 * @throws ReflectionException
303
+	 */
304
+	public function short_bio(): string
305
+	{
306
+		return (string) $this->get('ATT_short_bio');
307
+	}
308
+
309
+
310
+	/**
311
+	 * Gets the attendee's full address as an array so client code can decide hwo to display it
312
+	 *
313
+	 * @return array numerically indexed, with each part of the address that is known.
314
+	 * Eg, if the user only responded to state and country,
315
+	 * it would be array(0=>'Alabama',1=>'USA')
316
+	 * @return array
317
+	 * @throws EE_Error
318
+	 * @throws ReflectionException
319
+	 */
320
+	public function full_address_as_array(): array
321
+	{
322
+		$full_address_array     = [];
323
+		$initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
324
+		foreach ($initial_address_fields as $address_field_name) {
325
+			$address_fields_value = $this->get($address_field_name);
326
+			if (! empty($address_fields_value)) {
327
+				$full_address_array[] = $address_fields_value;
328
+			}
329
+		}
330
+		// now handle state and country
331
+		$state_obj = $this->state_obj();
332
+		if ($state_obj instanceof EE_State) {
333
+			$full_address_array[] = $state_obj->name();
334
+		}
335
+		$country_obj = $this->country_obj();
336
+		if ($country_obj instanceof EE_Country) {
337
+			$full_address_array[] = $country_obj->name();
338
+		}
339
+		// lastly get the xip
340
+		$zip_value = $this->zip();
341
+		if (! empty($zip_value)) {
342
+			$full_address_array[] = $zip_value;
343
+		}
344
+		return $full_address_array;
345
+	}
346
+
347
+
348
+	/**
349
+	 * @return string
350
+	 * @throws EE_Error
351
+	 * @throws ReflectionException
352
+	 */
353
+	public function address(): string
354
+	{
355
+		return (string) $this->get('ATT_address');
356
+	}
357
+
358
+
359
+	/**
360
+	 * @return string
361
+	 * @throws EE_Error
362
+	 * @throws ReflectionException
363
+	 */
364
+	public function address2(): string
365
+	{
366
+		return (string) $this->get('ATT_address2');
367
+	}
368
+
369
+
370
+	/**
371
+	 * @return string
372
+	 * @throws EE_Error
373
+	 * @throws ReflectionException
374
+	 */
375
+	public function city(): string
376
+	{
377
+		return (string) $this->get('ATT_city');
378
+	}
379
+
380
+
381
+	/**
382
+	 * @return int
383
+	 * @throws EE_Error
384
+	 * @throws ReflectionException
385
+	 */
386
+	public function state_ID(): int
387
+	{
388
+		return (int) $this->get('STA_ID');
389
+	}
390
+
391
+
392
+	/**
393
+	 * @return string
394
+	 * @throws EE_Error
395
+	 * @throws ReflectionException
396
+	 */
397
+	public function state_abbrev(): string
398
+	{
399
+		return $this->state_obj() instanceof EE_State
400
+			? $this->state_obj()->abbrev()
401
+			: '';
402
+	}
403
+
404
+
405
+	/**
406
+	 * @return EE_State|null
407
+	 * @throws EE_Error
408
+	 * @throws ReflectionException
409
+	 */
410
+	public function state_obj(): ?EE_State
411
+	{
412
+		return $this->get_first_related('State');
413
+	}
414
+
415
+
416
+	/**
417
+	 * @return string
418
+	 * @throws EE_Error
419
+	 * @throws ReflectionException
420
+	 */
421
+	public function state_name(): string
422
+	{
423
+		return $this->state_obj() instanceof EE_State
424
+			? $this->state_obj()->name()
425
+			: '';
426
+	}
427
+
428
+
429
+	/**
430
+	 * either displays the state abbreviation or the state name, as determined
431
+	 * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
432
+	 * defaults to abbreviation
433
+	 *
434
+	 * @return string
435
+	 * @throws EE_Error
436
+	 * @throws ReflectionException
437
+	 */
438
+	public function state(): string
439
+	{
440
+		return apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())
441
+			? $this->state_abbrev()
442
+			: $this->state_name();
443
+	}
444
+
445
+
446
+	/**
447
+	 * @return string
448
+	 * @throws EE_Error
449
+	 * @throws ReflectionException
450
+	 */
451
+	public function country_ID(): string
452
+	{
453
+		return (string) $this->get('CNT_ISO');
454
+	}
455
+
456
+
457
+	/**
458
+	 * @return EE_Country|null
459
+	 * @throws EE_Error
460
+	 * @throws ReflectionException
461
+	 */
462
+	public function country_obj(): ?EE_Country
463
+	{
464
+		return $this->get_first_related('Country');
465
+	}
466
+
467
+
468
+	/**
469
+	 * @return string
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 */
473
+	public function country_name(): string
474
+	{
475
+		return $this->country_obj() instanceof EE_Country
476
+			? $this->country_obj()->name()
477
+			: '';
478
+	}
479
+
480
+
481
+	/**
482
+	 * either displays the country ISO2 code or the country name, as determined
483
+	 * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
484
+	 * defaults to abbreviation
485
+	 *
486
+	 * @return string
487
+	 * @throws EE_Error
488
+	 * @throws ReflectionException
489
+	 */
490
+	public function country(): string
491
+	{
492
+		return apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())
493
+			? $this->country_ID()
494
+			: $this->country_name();
495
+	}
496
+
497
+
498
+	/**
499
+	 * @return string
500
+	 * @throws EE_Error
501
+	 * @throws ReflectionException
502
+	 */
503
+	public function zip(): string
504
+	{
505
+		return (string) $this->get('ATT_zip');
506
+	}
507
+
508
+
509
+	/**
510
+	 * @return string
511
+	 * @throws EE_Error
512
+	 * @throws ReflectionException
513
+	 */
514
+	public function email(): string
515
+	{
516
+		return (string) $this->get('ATT_email');
517
+	}
518
+
519
+
520
+	/**
521
+	 * @return string
522
+	 * @throws EE_Error
523
+	 * @throws ReflectionException
524
+	 */
525
+	public function phone(): string
526
+	{
527
+		return (string) $this->get('ATT_phone');
528
+	}
529
+
530
+
531
+	/**
532
+	 * @return bool
533
+	 * @throws EE_Error
534
+	 * @throws ReflectionException
535
+	 */
536
+	public function deleted(): bool
537
+	{
538
+		return (bool) $this->get('ATT_deleted');
539
+	}
540
+
541
+
542
+	/**
543
+	 * @param array $query_params
544
+	 * @return EE_Registration[]
545
+	 * @throws EE_Error
546
+	 * @throws ReflectionException
547
+	 */
548
+	public function get_registrations(array $query_params = []): array
549
+	{
550
+		return $this->get_many_related('Registration', $query_params);
551
+	}
552
+
553
+
554
+	/**
555
+	 * Gets the most recent registration of this attendee
556
+	 *
557
+	 * @return EE_Registration|null
558
+	 * @throws EE_Error
559
+	 * @throws ReflectionException
560
+	 */
561
+	public function get_most_recent_registration(): ?EE_Registration
562
+	{
563
+		return $this->get_first_related('Registration', ['order_by' => ['REG_date' => 'DESC']]);
564
+	}
565
+
566
+
567
+	/**
568
+	 * Gets the most recent registration for this attend at this event
569
+	 *
570
+	 * @param int $event_id
571
+	 * @return EE_Registration|null
572
+	 * @throws EE_Error
573
+	 * @throws ReflectionException
574
+	 */
575
+	public function get_most_recent_registration_for_event(int $event_id): ?EE_Registration
576
+	{
577
+		return $this->get_first_related(
578
+			'Registration',
579
+			[['EVT_ID' => $event_id], 'order_by' => ['REG_date' => 'DESC']]
580
+		);
581
+	}
582
+
583
+
584
+	/**
585
+	 * returns any events attached to this attendee ($_Event property);
586
+	 *
587
+	 * @return EE_Event[]
588
+	 * @throws EE_Error
589
+	 * @throws ReflectionException
590
+	 */
591
+	public function events(): array
592
+	{
593
+		return $this->get_many_related('Event');
594
+	}
595
+
596
+
597
+	/**
598
+	 * Gets the billing info array where keys match espresso_reg_page_billing_inputs(),
599
+	 * and keys are their cleaned values. @param EE_Payment_Method $payment_method the _gateway_name property on the
600
+	 * gateway class
601
+	 *
602
+	 * @return EE_Form_Section_Proper|null
603
+	 * @throws EE_Error
604
+	 * @throws ReflectionException
605
+	 * @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was used to save the billing info
606
+	 */
607
+	public function billing_info_for_payment_method(EE_Payment_Method $payment_method): ?EE_Form_Section_Proper
608
+	{
609
+		$pm_type = $payment_method->type_obj();
610
+		if (! $pm_type instanceof EE_PMT_Base) {
611
+			return null;
612
+		}
613
+		$billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
614
+		if (! $billing_info) {
615
+			return null;
616
+		}
617
+		$billing_form = $pm_type->billing_form();
618
+		// double-check the form isn't totally hidden, in which case pretend there is no form
619
+		$form_totally_hidden = true;
620
+		foreach ($billing_form->inputs_in_subsections() as $input) {
621
+			if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
622
+				$form_totally_hidden = false;
623
+				break;
624
+			}
625
+		}
626
+		if ($form_totally_hidden) {
627
+			return null;
628
+		}
629
+		if ($billing_form instanceof EE_Form_Section_Proper) {
630
+			$billing_form->receive_form_submission([$billing_form->name() => $billing_info], false);
631
+		}
632
+
633
+		return $billing_form;
634
+	}
635
+
636
+
637
+	/**
638
+	 * Gets the postmeta key that holds this attendee's billing info for the
639
+	 * specified payment method
640
+	 *
641
+	 * @param EE_Payment_Method $payment_method
642
+	 * @return string
643
+	 * @throws EE_Error
644
+	 */
645
+	public function get_billing_info_postmeta_name(EE_Payment_Method $payment_method): string
646
+	{
647
+		return $payment_method->type_obj() instanceof EE_PMT_Base
648
+			? 'billing_info_' . $payment_method->type_obj()->system_name()
649
+			: '';
650
+	}
651
+
652
+
653
+	/**
654
+	 * Saves the billing info to the attendee.
655
+	 *
656
+	 * @param EE_Billing_Attendee_Info_Form|null $billing_form
657
+	 * @param EE_Payment_Method                  $payment_method
658
+	 * @return boolean
659
+	 * @throws EE_Error
660
+	 * @throws ReflectionException
661
+	 * @see EE_Attendee::billing_info_for_payment_method() which is used to retrieve it
662
+	 */
663
+	public function save_and_clean_billing_info_for_payment_method(
664
+		?EE_Billing_Attendee_Info_Form $billing_form,
665
+		EE_Payment_Method $payment_method
666
+	): bool {
667
+		if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
668
+			EE_Error::add_error(
669
+				esc_html__('Cannot save billing info because there is none.', 'event_espresso'),
670
+				__FILE__,
671
+				__FUNCTION__,
672
+				__LINE__
673
+			);
674
+			return false;
675
+		}
676
+		$billing_form->clean_sensitive_data();
677
+		return update_post_meta(
678
+			$this->ID(),
679
+			$this->get_billing_info_postmeta_name($payment_method),
680
+			$billing_form->input_values(true)
681
+		);
682
+	}
683
+
684
+
685
+	/**
686
+	 * Return the link to the admin details for the object.
687
+	 *
688
+	 * @return string
689
+	 * @throws EE_Error
690
+	 * @throws InvalidArgumentException
691
+	 * @throws InvalidDataTypeException
692
+	 * @throws InvalidInterfaceException
693
+	 * @throws ReflectionException
694
+	 */
695
+	public function get_admin_details_link(): string
696
+	{
697
+		return $this->get_admin_edit_link();
698
+	}
699
+
700
+
701
+	/**
702
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
703
+	 *
704
+	 * @return string
705
+	 * @throws EE_Error
706
+	 * @throws InvalidArgumentException
707
+	 * @throws ReflectionException
708
+	 * @throws InvalidDataTypeException
709
+	 * @throws InvalidInterfaceException
710
+	 */
711
+	public function get_admin_edit_link(): string
712
+	{
713
+		return EEH_URL::add_query_args_and_nonce(
714
+			[
715
+				'page'   => 'espresso_registrations',
716
+				'action' => 'edit_attendee',
717
+				'post'   => $this->ID(),
718
+			],
719
+			admin_url('admin.php')
720
+		);
721
+	}
722
+
723
+
724
+	/**
725
+	 * Returns the link to a settings page for the object.
726
+	 *
727
+	 * @return string
728
+	 * @throws EE_Error
729
+	 * @throws InvalidArgumentException
730
+	 * @throws InvalidDataTypeException
731
+	 * @throws InvalidInterfaceException
732
+	 * @throws ReflectionException
733
+	 */
734
+	public function get_admin_settings_link(): string
735
+	{
736
+		return $this->get_admin_edit_link();
737
+	}
738
+
739
+
740
+	/**
741
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
742
+	 *
743
+	 * @return string
744
+	 */
745
+	public function get_admin_overview_link(): string
746
+	{
747
+		return EEH_URL::add_query_args_and_nonce(
748
+			[
749
+				'page'   => 'espresso_registrations',
750
+				'action' => 'contact_list',
751
+			],
752
+			admin_url('admin.php')
753
+		);
754
+	}
755 755
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +3358 added lines, -3358 removed lines patch added patch discarded remove patch
@@ -15,3374 +15,3374 @@
 block discarded – undo
15 15
  */
16 16
 abstract class EE_Base_Class
17 17
 {
18
-    /**
19
-     * @var EEM_Base|null
20
-     */
21
-    protected $_model = null;
22
-
23
-    /**
24
-     * This is an array of the original properties and values provided during construction
25
-     * of this model object. (keys are model field names, values are their values).
26
-     * This list is important to remember so that when we are merging data from the db, we know
27
-     * which values to override and which to not override.
28
-     *
29
-     * @var array
30
-     */
31
-    protected array $_props_n_values_provided_in_constructor;
32
-
33
-    /**
34
-     * Timezone
35
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
36
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
37
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
38
-     * access to it.
39
-     *
40
-     * @var string
41
-     */
42
-    protected string $_timezone = '';
43
-
44
-    /**
45
-     * date format
46
-     * pattern or format for displaying dates
47
-     *
48
-     * @var string $_dt_frmt
49
-     */
50
-    protected string $_dt_frmt = '';
51
-
52
-    /**
53
-     * time format
54
-     * pattern or format for displaying time
55
-     *
56
-     * @var string $_tm_frmt
57
-     */
58
-    protected string $_tm_frmt = '';
59
-
60
-    /**
61
-     * This property is for holding a cached array of object properties indexed by property name as the key.
62
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
63
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
64
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
65
-     *
66
-     * @var array
67
-     */
68
-    protected array $_cached_properties = [];
69
-
70
-    /**
71
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
72
-     * single
73
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
74
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
75
-     * all others have an array)
76
-     *
77
-     * @var array
78
-     */
79
-    protected array $_model_relations = [];
80
-
81
-    /**
82
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
83
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
84
-     *
85
-     * @var array
86
-     */
87
-    protected array $_fields = [];
88
-
89
-    /**
90
-     * @var bool indicating whether or not this model object is intended to ever be saved
91
-     * For example, we might create model objects intended to only be used for the duration
92
-     * of this request and to be thrown away, and if they were accidentally saved
93
-     * it would be a bug.
94
-     */
95
-    protected bool $_allow_persist = true;
96
-
97
-    /**
98
-     * @var bool indicating whether or not this model object's properties have changed since construction
99
-     */
100
-    protected bool $_has_changes = false;
101
-
102
-    /**
103
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
104
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
105
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
106
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
107
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
108
-     * array as:
109
-     * array(
110
-     *  'Registration_Count' => 24
111
-     * );
112
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
113
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
114
-     * info)
115
-     *
116
-     * @var array
117
-     */
118
-    protected array $custom_selection_results = [];
119
-
120
-
121
-    /**
122
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
123
-     * play nice
124
-     *
125
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
126
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
127
-     *                                                         TXN_amount, QST_name, etc) and values are their values
128
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
129
-     *                                                         corresponding db model or not.
130
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
131
-     *                                                         be in when instantiating a EE_Base_Class object.
132
-     * @param array   $date_formats                            An array of date formats to set on construct where first
133
-     *                                                         value is the date_format and second value is the time
134
-     *                                                         format.
135
-     * @throws InvalidArgumentException
136
-     * @throws InvalidInterfaceException
137
-     * @throws InvalidDataTypeException
138
-     * @throws EE_Error
139
-     * @throws ReflectionException
140
-     */
141
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
142
-    {
143
-        $className = get_class($this);
144
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
145
-        $model = $this->get_model();
146
-        $model_fields = $model->field_settings(false);
147
-        // ensure $fieldValues is an array
148
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
149
-        // remember what values were passed to this constructor
150
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
151
-        // verify client code has not passed any invalid field names
152
-        foreach ($fieldValues as $field_name => $field_value) {
153
-            if (! isset($model_fields[ $field_name ])) {
154
-                throw new EE_Error(
155
-                    sprintf(
156
-                        esc_html__(
157
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
158
-                            'event_espresso'
159
-                        ),
160
-                        $field_name,
161
-                        get_class($this),
162
-                        implode(', ', array_keys($model_fields))
163
-                    )
164
-                );
165
-            }
166
-        }
167
-
168
-        $date_format = null;
169
-        $time_format = null;
170
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
171
-        if (! empty($date_formats) && is_array($date_formats)) {
172
-            [$date_format, $time_format] = $date_formats;
173
-        }
174
-        $this->set_date_format($date_format);
175
-        $this->set_time_format($time_format);
176
-        // if db model is instantiating
177
-        foreach ($model_fields as $fieldName => $field) {
178
-            if ($bydb) {
179
-                // client code has indicated these field values are from the database
180
-                    $this->set_from_db(
181
-                        $fieldName,
182
-                        $fieldValues[ $fieldName ] ?? null
183
-                    );
184
-            } else {
185
-                // we're constructing a brand new instance of the model object.
186
-                // Generally, this means we'll need to do more field validation
187
-                    $this->set(
188
-                    $fieldName,
189
-                    $fieldValues[ $fieldName ] ?? null,
190
-                    true
191
-                );
192
-            }
193
-        }
194
-        // remember in entity mapper
195
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
-            $model->add_to_entity_map($this);
197
-        }
198
-        // setup all the relations
199
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
202
-            } else {
203
-                $this->_model_relations[ $relation_name ] = array();
204
-            }
205
-        }
206
-        /**
207
-         * Action done at the end of each model object construction
208
-         *
209
-         * @param EE_Base_Class $this the model object just created
210
-         */
211
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
-    }
213
-
214
-
215
-    /**
216
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
217
-     *
218
-     * @return boolean
219
-     */
220
-    public function allow_persist()
221
-    {
222
-        return $this->_allow_persist;
223
-    }
224
-
225
-
226
-    /**
227
-     * Sets whether or not this model object should be allowed to be saved to the DB.
228
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
-     * you got new information that somehow made you change your mind.
230
-     *
231
-     * @param boolean $allow_persist
232
-     * @return boolean
233
-     */
234
-    public function set_allow_persist($allow_persist)
235
-    {
236
-        return $this->_allow_persist = $allow_persist;
237
-    }
238
-
239
-
240
-    /**
241
-     * Gets the field's original value when this object was constructed during this request.
242
-     * This can be helpful when determining if a model object has changed or not
243
-     *
244
-     * @param string $field_name
245
-     * @return mixed|null
246
-     * @throws ReflectionException
247
-     * @throws InvalidArgumentException
248
-     * @throws InvalidInterfaceException
249
-     * @throws InvalidDataTypeException
250
-     * @throws EE_Error
251
-     */
252
-    public function get_original($field_name)
253
-    {
254
-        if (
255
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
256
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
257
-        ) {
258
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
259
-        }
260
-        return null;
261
-    }
262
-
263
-
264
-    /**
265
-     * @param EE_Base_Class $obj
266
-     * @return string
267
-     */
268
-    public function get_class($obj)
269
-    {
270
-        return get_class($obj);
271
-    }
272
-
273
-
274
-    /**
275
-     * Overrides parent because parent expects old models.
276
-     * This also doesn't do any validation, and won't work for serialized arrays
277
-     *
278
-     * @param string $field_name
279
-     * @param mixed  $field_value
280
-     * @param bool   $use_default
281
-     * @throws InvalidArgumentException
282
-     * @throws InvalidInterfaceException
283
-     * @throws InvalidDataTypeException
284
-     * @throws EE_Error
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     * @throws ReflectionException
288
-     */
289
-    public function set(string $field_name, $field_value, bool $use_default = false)
290
-    {
291
-        // if not using default and nothing has changed, and object has already been setup (has ID),
292
-        // then don't do anything
293
-        if (
294
-            ! $use_default
295
-            && $this->_fields[ $field_name ] === $field_value
296
-            && $this->ID()
297
-        ) {
298
-            return;
299
-        }
300
-        $model = $this->get_model();
301
-        $this->_has_changes = true;
302
-        $field_obj = $model->field_settings_for($field_name);
303
-        if (! $field_obj instanceof EE_Model_Field_Base) {
304
-            throw new EE_Error(
305
-                sprintf(
306
-                    esc_html__(
307
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
308
-                        'event_espresso'
309
-                    ),
310
-                    $field_name
311
-                )
312
-            );
313
-        }
314
-        // if ( method_exists( $field_obj, 'set_timezone' )) {
315
-        if ($field_obj instanceof EE_Datetime_Field) {
316
-            $field_obj->set_timezone($this->_timezone);
317
-            $field_obj->set_date_format($this->_dt_frmt);
318
-            $field_obj->set_time_format($this->_tm_frmt);
319
-        }
320
-        $holder_of_value = $field_obj->prepare_for_set($field_value);
321
-        // should the value be null?
322
-        if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
323
-            $this->_fields[ $field_name ] = $field_obj->get_default_value();
324
-            /**
325
-             * To save having to refactor all the models, if a default value is used for a
326
-             * EE_Datetime_Field, and that value is not null nor is it a DateTime
327
-             * object.  Then let's do a set again to ensure that it becomes a DateTime
328
-             * object.
329
-             *
330
-             * @since 4.6.10+
331
-             */
332
-            if (
333
-                $field_obj instanceof EE_Datetime_Field
334
-                && $this->_fields[ $field_name ] !== null
335
-                && ! $this->_fields[ $field_name ] instanceof DateTime
336
-            ) {
337
-                empty($this->_fields[ $field_name ])
338
-                    ? $this->set($field_name, time())
339
-                    : $this->set($field_name, $this->_fields[ $field_name ]);
340
-            }
341
-        } else {
342
-            $this->_fields[ $field_name ] = $holder_of_value;
343
-        }
344
-        // if we're not in the constructor...
345
-        // now check if what we set was a primary key
346
-        if (
18
+	/**
19
+	 * @var EEM_Base|null
20
+	 */
21
+	protected $_model = null;
22
+
23
+	/**
24
+	 * This is an array of the original properties and values provided during construction
25
+	 * of this model object. (keys are model field names, values are their values).
26
+	 * This list is important to remember so that when we are merging data from the db, we know
27
+	 * which values to override and which to not override.
28
+	 *
29
+	 * @var array
30
+	 */
31
+	protected array $_props_n_values_provided_in_constructor;
32
+
33
+	/**
34
+	 * Timezone
35
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
36
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
37
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
38
+	 * access to it.
39
+	 *
40
+	 * @var string
41
+	 */
42
+	protected string $_timezone = '';
43
+
44
+	/**
45
+	 * date format
46
+	 * pattern or format for displaying dates
47
+	 *
48
+	 * @var string $_dt_frmt
49
+	 */
50
+	protected string $_dt_frmt = '';
51
+
52
+	/**
53
+	 * time format
54
+	 * pattern or format for displaying time
55
+	 *
56
+	 * @var string $_tm_frmt
57
+	 */
58
+	protected string $_tm_frmt = '';
59
+
60
+	/**
61
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
62
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
63
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
64
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
65
+	 *
66
+	 * @var array
67
+	 */
68
+	protected array $_cached_properties = [];
69
+
70
+	/**
71
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
72
+	 * single
73
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
74
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
75
+	 * all others have an array)
76
+	 *
77
+	 * @var array
78
+	 */
79
+	protected array $_model_relations = [];
80
+
81
+	/**
82
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
83
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
84
+	 *
85
+	 * @var array
86
+	 */
87
+	protected array $_fields = [];
88
+
89
+	/**
90
+	 * @var bool indicating whether or not this model object is intended to ever be saved
91
+	 * For example, we might create model objects intended to only be used for the duration
92
+	 * of this request and to be thrown away, and if they were accidentally saved
93
+	 * it would be a bug.
94
+	 */
95
+	protected bool $_allow_persist = true;
96
+
97
+	/**
98
+	 * @var bool indicating whether or not this model object's properties have changed since construction
99
+	 */
100
+	protected bool $_has_changes = false;
101
+
102
+	/**
103
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
104
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
105
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
106
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
107
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
108
+	 * array as:
109
+	 * array(
110
+	 *  'Registration_Count' => 24
111
+	 * );
112
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
113
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
114
+	 * info)
115
+	 *
116
+	 * @var array
117
+	 */
118
+	protected array $custom_selection_results = [];
119
+
120
+
121
+	/**
122
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
123
+	 * play nice
124
+	 *
125
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
126
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
127
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
128
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
129
+	 *                                                         corresponding db model or not.
130
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
131
+	 *                                                         be in when instantiating a EE_Base_Class object.
132
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
133
+	 *                                                         value is the date_format and second value is the time
134
+	 *                                                         format.
135
+	 * @throws InvalidArgumentException
136
+	 * @throws InvalidInterfaceException
137
+	 * @throws InvalidDataTypeException
138
+	 * @throws EE_Error
139
+	 * @throws ReflectionException
140
+	 */
141
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
142
+	{
143
+		$className = get_class($this);
144
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
145
+		$model = $this->get_model();
146
+		$model_fields = $model->field_settings(false);
147
+		// ensure $fieldValues is an array
148
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
149
+		// remember what values were passed to this constructor
150
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
151
+		// verify client code has not passed any invalid field names
152
+		foreach ($fieldValues as $field_name => $field_value) {
153
+			if (! isset($model_fields[ $field_name ])) {
154
+				throw new EE_Error(
155
+					sprintf(
156
+						esc_html__(
157
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
158
+							'event_espresso'
159
+						),
160
+						$field_name,
161
+						get_class($this),
162
+						implode(', ', array_keys($model_fields))
163
+					)
164
+				);
165
+			}
166
+		}
167
+
168
+		$date_format = null;
169
+		$time_format = null;
170
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
171
+		if (! empty($date_formats) && is_array($date_formats)) {
172
+			[$date_format, $time_format] = $date_formats;
173
+		}
174
+		$this->set_date_format($date_format);
175
+		$this->set_time_format($time_format);
176
+		// if db model is instantiating
177
+		foreach ($model_fields as $fieldName => $field) {
178
+			if ($bydb) {
179
+				// client code has indicated these field values are from the database
180
+					$this->set_from_db(
181
+						$fieldName,
182
+						$fieldValues[ $fieldName ] ?? null
183
+					);
184
+			} else {
185
+				// we're constructing a brand new instance of the model object.
186
+				// Generally, this means we'll need to do more field validation
187
+					$this->set(
188
+					$fieldName,
189
+					$fieldValues[ $fieldName ] ?? null,
190
+					true
191
+				);
192
+			}
193
+		}
194
+		// remember in entity mapper
195
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
+			$model->add_to_entity_map($this);
197
+		}
198
+		// setup all the relations
199
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
+				$this->_model_relations[ $relation_name ] = null;
202
+			} else {
203
+				$this->_model_relations[ $relation_name ] = array();
204
+			}
205
+		}
206
+		/**
207
+		 * Action done at the end of each model object construction
208
+		 *
209
+		 * @param EE_Base_Class $this the model object just created
210
+		 */
211
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
+	}
213
+
214
+
215
+	/**
216
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
217
+	 *
218
+	 * @return boolean
219
+	 */
220
+	public function allow_persist()
221
+	{
222
+		return $this->_allow_persist;
223
+	}
224
+
225
+
226
+	/**
227
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
228
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
+	 * you got new information that somehow made you change your mind.
230
+	 *
231
+	 * @param boolean $allow_persist
232
+	 * @return boolean
233
+	 */
234
+	public function set_allow_persist($allow_persist)
235
+	{
236
+		return $this->_allow_persist = $allow_persist;
237
+	}
238
+
239
+
240
+	/**
241
+	 * Gets the field's original value when this object was constructed during this request.
242
+	 * This can be helpful when determining if a model object has changed or not
243
+	 *
244
+	 * @param string $field_name
245
+	 * @return mixed|null
246
+	 * @throws ReflectionException
247
+	 * @throws InvalidArgumentException
248
+	 * @throws InvalidInterfaceException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws EE_Error
251
+	 */
252
+	public function get_original($field_name)
253
+	{
254
+		if (
255
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
256
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
257
+		) {
258
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
259
+		}
260
+		return null;
261
+	}
262
+
263
+
264
+	/**
265
+	 * @param EE_Base_Class $obj
266
+	 * @return string
267
+	 */
268
+	public function get_class($obj)
269
+	{
270
+		return get_class($obj);
271
+	}
272
+
273
+
274
+	/**
275
+	 * Overrides parent because parent expects old models.
276
+	 * This also doesn't do any validation, and won't work for serialized arrays
277
+	 *
278
+	 * @param string $field_name
279
+	 * @param mixed  $field_value
280
+	 * @param bool   $use_default
281
+	 * @throws InvalidArgumentException
282
+	 * @throws InvalidInterfaceException
283
+	 * @throws InvalidDataTypeException
284
+	 * @throws EE_Error
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 * @throws ReflectionException
288
+	 */
289
+	public function set(string $field_name, $field_value, bool $use_default = false)
290
+	{
291
+		// if not using default and nothing has changed, and object has already been setup (has ID),
292
+		// then don't do anything
293
+		if (
294
+			! $use_default
295
+			&& $this->_fields[ $field_name ] === $field_value
296
+			&& $this->ID()
297
+		) {
298
+			return;
299
+		}
300
+		$model = $this->get_model();
301
+		$this->_has_changes = true;
302
+		$field_obj = $model->field_settings_for($field_name);
303
+		if (! $field_obj instanceof EE_Model_Field_Base) {
304
+			throw new EE_Error(
305
+				sprintf(
306
+					esc_html__(
307
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
308
+						'event_espresso'
309
+					),
310
+					$field_name
311
+				)
312
+			);
313
+		}
314
+		// if ( method_exists( $field_obj, 'set_timezone' )) {
315
+		if ($field_obj instanceof EE_Datetime_Field) {
316
+			$field_obj->set_timezone($this->_timezone);
317
+			$field_obj->set_date_format($this->_dt_frmt);
318
+			$field_obj->set_time_format($this->_tm_frmt);
319
+		}
320
+		$holder_of_value = $field_obj->prepare_for_set($field_value);
321
+		// should the value be null?
322
+		if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
323
+			$this->_fields[ $field_name ] = $field_obj->get_default_value();
324
+			/**
325
+			 * To save having to refactor all the models, if a default value is used for a
326
+			 * EE_Datetime_Field, and that value is not null nor is it a DateTime
327
+			 * object.  Then let's do a set again to ensure that it becomes a DateTime
328
+			 * object.
329
+			 *
330
+			 * @since 4.6.10+
331
+			 */
332
+			if (
333
+				$field_obj instanceof EE_Datetime_Field
334
+				&& $this->_fields[ $field_name ] !== null
335
+				&& ! $this->_fields[ $field_name ] instanceof DateTime
336
+			) {
337
+				empty($this->_fields[ $field_name ])
338
+					? $this->set($field_name, time())
339
+					: $this->set($field_name, $this->_fields[ $field_name ]);
340
+			}
341
+		} else {
342
+			$this->_fields[ $field_name ] = $holder_of_value;
343
+		}
344
+		// if we're not in the constructor...
345
+		// now check if what we set was a primary key
346
+		if (
347 347
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
348
-            $this->_props_n_values_provided_in_constructor
349
-            && $field_value
350
-            && $field_name === $model->primary_key_name()
351
-        ) {
352
-            // if so, we want all this object's fields to be filled either with
353
-            // what we've explicitly set on this model
354
-            // or what we have in the db
355
-            // echo "setting primary key!";
356
-            $fields_on_model = self::_get_model(get_class($this))->field_settings();
357
-            $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
358
-            foreach ($fields_on_model as $field_obj) {
359
-                if (
360
-                    ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
361
-                    && $field_obj->get_name() !== $field_name
362
-                ) {
363
-                    $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
364
-                }
365
-            }
366
-            // oh this model object has an ID? well make sure its in the entity mapper
367
-            $model->add_to_entity_map($this);
368
-        }
369
-        // let's unset any cache for this field_name from the $_cached_properties property.
370
-        $this->_clear_cached_property($field_name);
371
-    }
372
-
373
-
374
-    /**
375
-     * Overrides parent because parent expects old models.
376
-     * This also doesn't do any validation, and won't work for serialized arrays
377
-     *
378
-     * @param string $field_name
379
-     * @param mixed  $field_value_from_db
380
-     * @throws ReflectionException
381
-     * @throws InvalidArgumentException
382
-     * @throws InvalidInterfaceException
383
-     * @throws InvalidDataTypeException
384
-     * @throws EE_Error
385
-     */
386
-    public function set_from_db(string $field_name, $field_value_from_db)
387
-    {
388
-        $field_obj = $this->get_model()->field_settings_for($field_name);
389
-        if ($field_obj instanceof EE_Model_Field_Base) {
390
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
391
-            // eg, a CPT model object could have an entry in the posts table, but no
392
-            // entry in the meta table. Meaning that all its columns in the meta table
393
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
394
-            if ($field_value_from_db === null) {
395
-                if ($field_obj->is_nullable()) {
396
-                    // if the field allows nulls, then let it be null
397
-                    $field_value = null;
398
-                } else {
399
-                    $field_value = $field_obj->get_default_value();
400
-                }
401
-            } else {
402
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
403
-            }
404
-            $this->_fields[ $field_name ] = $field_value;
405
-            $this->_clear_cached_property($field_name);
406
-        }
407
-    }
408
-
409
-
410
-    /**
411
-     * Set custom select values for model.
412
-     *
413
-     * @param array $custom_select_values
414
-     */
415
-    public function setCustomSelectsValues(array $custom_select_values)
416
-    {
417
-        $this->custom_selection_results = $custom_select_values;
418
-    }
419
-
420
-
421
-    /**
422
-     * Returns the custom select value for the provided alias if its set.
423
-     * If not set, returns null.
424
-     *
425
-     * @param string $alias
426
-     * @return string|int|float|null
427
-     */
428
-    public function getCustomSelect($alias)
429
-    {
430
-        return isset($this->custom_selection_results[ $alias ])
431
-            ? $this->custom_selection_results[ $alias ]
432
-            : null;
433
-    }
434
-
435
-
436
-    /**
437
-     * This sets the field value on the db column if it exists for the given $column_name or
438
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
439
-     *
440
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
441
-     * @param string $field_name  Must be the exact column name.
442
-     * @param mixed  $field_value The value to set.
443
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
444
-     * @throws InvalidArgumentException
445
-     * @throws InvalidInterfaceException
446
-     * @throws InvalidDataTypeException
447
-     * @throws EE_Error
448
-     * @throws ReflectionException
449
-     */
450
-    public function set_field_or_extra_meta($field_name, $field_value)
451
-    {
452
-        if ($this->get_model()->has_field($field_name)) {
453
-            $this->set($field_name, $field_value);
454
-            return true;
455
-        }
456
-        // ensure this object is saved first so that extra meta can be properly related.
457
-        $this->save();
458
-        return $this->update_extra_meta($field_name, $field_value);
459
-    }
460
-
461
-
462
-    /**
463
-     * This retrieves the value of the db column set on this class or if that's not present
464
-     * it will attempt to retrieve from extra_meta if found.
465
-     * Example Usage:
466
-     * Via EE_Message child class:
467
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
468
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
469
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
470
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
471
-     * value for those extra fields dynamically via the EE_message object.
472
-     *
473
-     * @param  string $field_name expecting the fully qualified field name.
474
-     * @return mixed|null  value for the field if found.  null if not found.
475
-     * @throws ReflectionException
476
-     * @throws InvalidArgumentException
477
-     * @throws InvalidInterfaceException
478
-     * @throws InvalidDataTypeException
479
-     * @throws EE_Error
480
-     */
481
-    public function get_field_or_extra_meta($field_name)
482
-    {
483
-        if ($this->get_model()->has_field($field_name)) {
484
-            $column_value = $this->get($field_name);
485
-        } else {
486
-            // This isn't a column in the main table, let's see if it is in the extra meta.
487
-            $column_value = $this->get_extra_meta($field_name, true, null);
488
-        }
489
-        return $column_value;
490
-    }
491
-
492
-
493
-    /**
494
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
495
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
496
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
497
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
498
-     *
499
-     * @access public
500
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
501
-     * @return void
502
-     * @throws InvalidArgumentException
503
-     * @throws InvalidInterfaceException
504
-     * @throws InvalidDataTypeException
505
-     * @throws EE_Error
506
-     * @throws ReflectionException
507
-     */
508
-    public function set_timezone($timezone = '')
509
-    {
510
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
511
-        // make sure we clear all cached properties because they won't be relevant now
512
-        $this->_clear_cached_properties();
513
-        // make sure we update field settings and the date for all EE_Datetime_Fields
514
-        $model_fields = $this->get_model()->field_settings(false);
515
-        foreach ($model_fields as $field_name => $field_obj) {
516
-            if ($field_obj instanceof EE_Datetime_Field) {
517
-                $field_obj->set_timezone($this->_timezone);
518
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
519
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
520
-                }
521
-            }
522
-        }
523
-    }
524
-
525
-
526
-    /**
527
-     * This just returns whatever is set for the current timezone.
528
-     *
529
-     * @access public
530
-     * @return string timezone string
531
-     */
532
-    public function get_timezone()
533
-    {
534
-        return $this->_timezone;
535
-    }
536
-
537
-
538
-    /**
539
-     * This sets the internal date format to what is sent in to be used as the new default for the class
540
-     * internally instead of wp set date format options
541
-     *
542
-     * @param string|null $format should be a format recognizable by PHP date() functions.
543
-     * @since 4.6
544
-     */
545
-    public function set_date_format(?string $format = 'Y-m-d')
546
-    {
547
-        $format = $format ?: 'Y-m-d';
548
-        $this->_dt_frmt = new DateFormat($format);
549
-        // clear cached_properties because they won't be relevant now.
550
-        $this->_clear_cached_properties();
551
-    }
552
-
553
-
554
-    /**
555
-     * This sets the internal time format string to what is sent in to be used as the new default for the
556
-     * class internally instead of wp set time format options.
557
-     *
558
-     * @param string|null $format should be a format recognizable by PHP date() functions.
559
-     * @since 4.6
560
-     */
561
-    public function set_time_format(?string $format = 'H:i:s')
562
-    {
563
-        $format = $format ?: 'H:i:s';
564
-        $this->_tm_frmt = new TimeFormat($format);
565
-        // clear cached_properties because they won't be relevant now.
566
-        $this->_clear_cached_properties();
567
-    }
568
-
569
-
570
-    /**
571
-     * This returns the current internal set format for the date and time formats.
572
-     *
573
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
574
-     *                             where the first value is the date format and the second value is the time format.
575
-     * @return mixed string|array
576
-     */
577
-    public function get_format($full = true)
578
-    {
579
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
580
-    }
581
-
582
-
583
-    /**
584
-     * cache
585
-     * stores the passed model object on the current model object.
586
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
587
-     *
588
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
589
-     *                                       'Registration' associated with this model object
590
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
591
-     *                                       that could be a payment or a registration)
592
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
593
-     *                                       items which will be stored in an array on this object
594
-     * @throws ReflectionException
595
-     * @throws InvalidArgumentException
596
-     * @throws InvalidInterfaceException
597
-     * @throws InvalidDataTypeException
598
-     * @throws EE_Error
599
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
600
-     *                                       related thing, no array)
601
-     */
602
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
603
-    {
604
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
605
-        if (! $object_to_cache instanceof EE_Base_Class) {
606
-            return false;
607
-        }
608
-        // also get "how" the object is related, or throw an error
609
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
610
-            throw new EE_Error(
611
-                sprintf(
612
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
613
-                    $relationName,
614
-                    get_class($this)
615
-                )
616
-            );
617
-        }
618
-        // how many things are related ?
619
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
620
-            // if it's a "belongs to" relationship, then there's only one related model object
621
-            // eg, if this is a registration, there's only 1 attendee for it
622
-            // so for these model objects just set it to be cached
623
-            $this->_model_relations[ $relationName ] = $object_to_cache;
624
-            $return = true;
625
-        } else {
626
-            // otherwise, this is the "many" side of a one to many relationship,
627
-            // so we'll add the object to the array of related objects for that type.
628
-            // eg: if this is an event, there are many registrations for that event,
629
-            // so we cache the registrations in an array
630
-            if (! is_array($this->_model_relations[ $relationName ])) {
631
-                // if for some reason, the cached item is a model object,
632
-                // then stick that in the array, otherwise start with an empty array
633
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
634
-                                                           instanceof
635
-                                                           EE_Base_Class
636
-                    ? array($this->_model_relations[ $relationName ]) : array();
637
-            }
638
-            // first check for a cache_id which is normally empty
639
-            if (! empty($cache_id)) {
640
-                // if the cache_id exists, then it means we are purposely trying to cache this
641
-                // with a known key that can then be used to retrieve the object later on
642
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
643
-                $return = $cache_id;
644
-            } elseif ($object_to_cache->ID()) {
645
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
646
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
647
-                $return = $object_to_cache->ID();
648
-            } else {
649
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
650
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
651
-                // move the internal pointer to the end of the array
652
-                end($this->_model_relations[ $relationName ]);
653
-                // and grab the key so that we can return it
654
-                $return = key($this->_model_relations[ $relationName ]);
655
-            }
656
-        }
657
-        return $return;
658
-    }
659
-
660
-
661
-    /**
662
-     * For adding an item to the cached_properties property.
663
-     *
664
-     * @access protected
665
-     * @param string      $fieldname the property item the corresponding value is for.
666
-     * @param mixed       $value     The value we are caching.
667
-     * @param string|null $cache_type
668
-     * @return void
669
-     * @throws ReflectionException
670
-     * @throws InvalidArgumentException
671
-     * @throws InvalidInterfaceException
672
-     * @throws InvalidDataTypeException
673
-     * @throws EE_Error
674
-     */
675
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
676
-    {
677
-        // first make sure this property exists
678
-        $this->get_model()->field_settings_for($fieldname);
679
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
680
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
681
-    }
682
-
683
-
684
-    /**
685
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
686
-     * This also SETS the cache if we return the actual property!
687
-     *
688
-     * @param string $fieldname        the name of the property we're trying to retrieve
689
-     * @param bool   $pretty
690
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
691
-     *                                 (in cases where the same property may be used for different outputs
692
-     *                                 - i.e. datetime, money etc.)
693
-     *                                 It can also accept certain pre-defined "schema" strings
694
-     *                                 to define how to output the property.
695
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
696
-     * @return mixed                   whatever the value for the property is we're retrieving
697
-     * @throws ReflectionException
698
-     * @throws InvalidArgumentException
699
-     * @throws InvalidInterfaceException
700
-     * @throws InvalidDataTypeException
701
-     * @throws EE_Error
702
-     */
703
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
704
-    {
705
-        // verify the field exists
706
-        $model = $this->get_model();
707
-        $model->field_settings_for($fieldname);
708
-        $cache_type = $pretty ? 'pretty' : 'standard';
709
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
710
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
711
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
712
-        }
713
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
714
-        $this->_set_cached_property($fieldname, $value, $cache_type);
715
-        return $value;
716
-    }
717
-
718
-
719
-    /**
720
-     * If the cache didn't fetch the needed item, this fetches it.
721
-     *
722
-     * @param string $fieldname
723
-     * @param bool   $pretty
724
-     * @param string $extra_cache_ref
725
-     * @return mixed
726
-     * @throws InvalidArgumentException
727
-     * @throws InvalidInterfaceException
728
-     * @throws InvalidDataTypeException
729
-     * @throws EE_Error
730
-     * @throws ReflectionException
731
-     */
732
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
733
-    {
734
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
735
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
736
-        if ($field_obj instanceof EE_Datetime_Field) {
737
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
738
-        }
739
-        if (! isset($this->_fields[ $fieldname ])) {
740
-            $this->_fields[ $fieldname ] = null;
741
-        }
742
-        return $pretty
743
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
744
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
745
-    }
746
-
747
-
748
-    /**
749
-     * set timezone, formats, and output for EE_Datetime_Field objects
750
-     *
751
-     * @param EE_Datetime_Field $datetime_field
752
-     * @param bool              $pretty
753
-     * @param null              $date_or_time
754
-     * @return void
755
-     * @throws InvalidArgumentException
756
-     * @throws InvalidInterfaceException
757
-     * @throws InvalidDataTypeException
758
-     */
759
-    protected function _prepare_datetime_field(
760
-        EE_Datetime_Field $datetime_field,
761
-        $pretty = false,
762
-        $date_or_time = null
763
-    ) {
764
-        $datetime_field->set_timezone($this->_timezone);
765
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
766
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
767
-        // set the output returned
768
-        switch ($date_or_time) {
769
-            case 'D':
770
-                $datetime_field->set_date_time_output('date');
771
-                break;
772
-            case 'T':
773
-                $datetime_field->set_date_time_output('time');
774
-                break;
775
-            default:
776
-                $datetime_field->set_date_time_output();
777
-        }
778
-    }
779
-
780
-
781
-    /**
782
-     * This just takes care of clearing out the cached_properties
783
-     *
784
-     * @return void
785
-     */
786
-    protected function _clear_cached_properties()
787
-    {
788
-        $this->_cached_properties = array();
789
-    }
790
-
791
-
792
-    /**
793
-     * This just clears out ONE property if it exists in the cache
794
-     *
795
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
796
-     * @return void
797
-     */
798
-    protected function _clear_cached_property($property_name)
799
-    {
800
-        if (isset($this->_cached_properties[ $property_name ])) {
801
-            unset($this->_cached_properties[ $property_name ]);
802
-        }
803
-    }
804
-
805
-
806
-    /**
807
-     * Ensures that this related thing is a model object.
808
-     *
809
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
810
-     * @param string $model_name   name of the related thing, eg 'Attendee',
811
-     * @return EE_Base_Class
812
-     * @throws ReflectionException
813
-     * @throws InvalidArgumentException
814
-     * @throws InvalidInterfaceException
815
-     * @throws InvalidDataTypeException
816
-     * @throws EE_Error
817
-     */
818
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
819
-    {
820
-        $other_model_instance = self::_get_model_instance_with_name(
821
-            self::_get_model_classname($model_name),
822
-            $this->_timezone
823
-        );
824
-        return $other_model_instance->ensure_is_obj($object_or_id);
825
-    }
826
-
827
-
828
-    /**
829
-     * Forgets the cached model of the given relation Name. So the next time we request it,
830
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
831
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
832
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
833
-     *
834
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
835
-     *                                                     Eg 'Registration'
836
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
837
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
838
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
839
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
840
-     *                                                     this is HasMany or HABTM.
841
-     * @throws ReflectionException
842
-     * @throws InvalidArgumentException
843
-     * @throws InvalidInterfaceException
844
-     * @throws InvalidDataTypeException
845
-     * @throws EE_Error
846
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
847
-     *                                                     relation from all
848
-     */
849
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
850
-    {
851
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
852
-        $index_in_cache = '';
853
-        if (! $relationship_to_model) {
854
-            throw new EE_Error(
855
-                sprintf(
856
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
857
-                    $relationName,
858
-                    get_class($this)
859
-                )
860
-            );
861
-        }
862
-        if ($clear_all) {
863
-            $obj_removed = true;
864
-            $this->_model_relations[ $relationName ] = null;
865
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
866
-            $obj_removed = $this->_model_relations[ $relationName ];
867
-            $this->_model_relations[ $relationName ] = null;
868
-        } else {
869
-            if (
870
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
871
-                && $object_to_remove_or_index_into_array->ID()
872
-            ) {
873
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
874
-                if (
875
-                    is_array($this->_model_relations[ $relationName ])
876
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
877
-                ) {
878
-                    $index_found_at = null;
879
-                    // find this object in the array even though it has a different key
880
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
881
-                        /** @noinspection TypeUnsafeComparisonInspection */
882
-                        if (
883
-                            $obj instanceof EE_Base_Class
884
-                            && (
885
-                                $obj == $object_to_remove_or_index_into_array
886
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
887
-                            )
888
-                        ) {
889
-                            $index_found_at = $index;
890
-                            break;
891
-                        }
892
-                    }
893
-                    if ($index_found_at) {
894
-                        $index_in_cache = $index_found_at;
895
-                    } else {
896
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
897
-                        // if it wasn't in it to begin with. So we're done
898
-                        return $object_to_remove_or_index_into_array;
899
-                    }
900
-                }
901
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
902
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
903
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
904
-                    /** @noinspection TypeUnsafeComparisonInspection */
905
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
906
-                        $index_in_cache = $index;
907
-                    }
908
-                }
909
-            } else {
910
-                $index_in_cache = $object_to_remove_or_index_into_array;
911
-            }
912
-            // supposedly we've found it. But it could just be that the client code
913
-            // provided a bad index/object
914
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
915
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
916
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
917
-            } else {
918
-                // that thing was never cached anyways.
919
-                $obj_removed = null;
920
-            }
921
-        }
922
-        return $obj_removed;
923
-    }
924
-
925
-
926
-    /**
927
-     * update_cache_after_object_save
928
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
929
-     * obtained after being saved to the db
930
-     *
931
-     * @param string        $relationName       - the type of object that is cached
932
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
933
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
934
-     * @return boolean TRUE on success, FALSE on fail
935
-     * @throws ReflectionException
936
-     * @throws InvalidArgumentException
937
-     * @throws InvalidInterfaceException
938
-     * @throws InvalidDataTypeException
939
-     * @throws EE_Error
940
-     */
941
-    public function update_cache_after_object_save(
942
-        $relationName,
943
-        EE_Base_Class $newly_saved_object,
944
-        $current_cache_id = ''
945
-    ) {
946
-        // verify that incoming object is of the correct type
947
-        $obj_class = 'EE_' . $relationName;
948
-        if ($newly_saved_object instanceof $obj_class) {
949
-            /* @type EE_Base_Class $newly_saved_object */
950
-            // now get the type of relation
951
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
952
-            // if this is a 1:1 relationship
953
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
954
-                // then just replace the cached object with the newly saved object
955
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
956
-                return true;
957
-                // or if it's some kind of sordid feral polyamorous relationship...
958
-            }
959
-            if (
960
-                is_array($this->_model_relations[ $relationName ])
961
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
962
-            ) {
963
-                // then remove the current cached item
964
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
965
-                // and cache the newly saved object using it's new ID
966
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
967
-                return true;
968
-            }
969
-        }
970
-        return false;
971
-    }
972
-
973
-
974
-    /**
975
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
976
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
977
-     *
978
-     * @param string $relationName
979
-     * @return EE_Base_Class
980
-     */
981
-    public function get_one_from_cache($relationName)
982
-    {
983
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
984
-            ? $this->_model_relations[ $relationName ]
985
-            : null;
986
-        if (is_array($cached_array_or_object)) {
987
-            return array_shift($cached_array_or_object);
988
-        }
989
-        return $cached_array_or_object;
990
-    }
991
-
992
-
993
-    /**
994
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
995
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
996
-     *
997
-     * @param string $relationName
998
-     * @throws ReflectionException
999
-     * @throws InvalidArgumentException
1000
-     * @throws InvalidInterfaceException
1001
-     * @throws InvalidDataTypeException
1002
-     * @throws EE_Error
1003
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
1004
-     */
1005
-    public function get_all_from_cache($relationName)
1006
-    {
1007
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
1008
-        // if the result is not an array, but exists, make it an array
1009
-        $objects = is_array($objects) ? $objects : array($objects);
1010
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
1011
-        // basically, if this model object was stored in the session, and these cached model objects
1012
-        // already have IDs, let's make sure they're in their model's entity mapper
1013
-        // otherwise we will have duplicates next time we call
1014
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
1015
-        $model = EE_Registry::instance()->load_model($relationName);
1016
-        foreach ($objects as $model_object) {
1017
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
1018
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
1019
-                if ($model_object->ID()) {
1020
-                    $model->add_to_entity_map($model_object);
1021
-                }
1022
-            } else {
1023
-                throw new EE_Error(
1024
-                    sprintf(
1025
-                        esc_html__(
1026
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
1027
-                            'event_espresso'
1028
-                        ),
1029
-                        $relationName,
1030
-                        gettype($model_object)
1031
-                    )
1032
-                );
1033
-            }
1034
-        }
1035
-        return $objects;
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1041
-     * matching the given query conditions.
1042
-     *
1043
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1044
-     * @param int   $limit              How many objects to return.
1045
-     * @param array $query_params       Any additional conditions on the query.
1046
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1047
-     *                                  you can indicate just the columns you want returned
1048
-     * @return array|EE_Base_Class[]
1049
-     * @throws ReflectionException
1050
-     * @throws InvalidArgumentException
1051
-     * @throws InvalidInterfaceException
1052
-     * @throws InvalidDataTypeException
1053
-     * @throws EE_Error
1054
-     */
1055
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1056
-    {
1057
-        $model = $this->get_model();
1058
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1059
-            ? $model->get_primary_key_field()->get_name()
1060
-            : $field_to_order_by;
1061
-        $current_value = ! empty($field) ? $this->get($field) : null;
1062
-        if (empty($field) || empty($current_value)) {
1063
-            return array();
1064
-        }
1065
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1066
-    }
1067
-
1068
-
1069
-    /**
1070
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1071
-     * matching the given query conditions.
1072
-     *
1073
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1074
-     * @param int   $limit              How many objects to return.
1075
-     * @param array $query_params       Any additional conditions on the query.
1076
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1077
-     *                                  you can indicate just the columns you want returned
1078
-     * @return array|EE_Base_Class[]
1079
-     * @throws ReflectionException
1080
-     * @throws InvalidArgumentException
1081
-     * @throws InvalidInterfaceException
1082
-     * @throws InvalidDataTypeException
1083
-     * @throws EE_Error
1084
-     */
1085
-    public function previous_x(
1086
-        $field_to_order_by = null,
1087
-        $limit = 1,
1088
-        $query_params = array(),
1089
-        $columns_to_select = null
1090
-    ) {
1091
-        $model = $this->get_model();
1092
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1093
-            ? $model->get_primary_key_field()->get_name()
1094
-            : $field_to_order_by;
1095
-        $current_value = ! empty($field) ? $this->get($field) : null;
1096
-        if (empty($field) || empty($current_value)) {
1097
-            return array();
1098
-        }
1099
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1100
-    }
1101
-
1102
-
1103
-    /**
1104
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1105
-     * matching the given query conditions.
1106
-     *
1107
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1108
-     * @param array $query_params       Any additional conditions on the query.
1109
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1110
-     *                                  you can indicate just the columns you want returned
1111
-     * @return array|EE_Base_Class
1112
-     * @throws ReflectionException
1113
-     * @throws InvalidArgumentException
1114
-     * @throws InvalidInterfaceException
1115
-     * @throws InvalidDataTypeException
1116
-     * @throws EE_Error
1117
-     */
1118
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1119
-    {
1120
-        $model = $this->get_model();
1121
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1122
-            ? $model->get_primary_key_field()->get_name()
1123
-            : $field_to_order_by;
1124
-        $current_value = ! empty($field) ? $this->get($field) : null;
1125
-        if (empty($field) || empty($current_value)) {
1126
-            return array();
1127
-        }
1128
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1129
-    }
1130
-
1131
-
1132
-    /**
1133
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1134
-     * matching the given query conditions.
1135
-     *
1136
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1137
-     * @param array $query_params       Any additional conditions on the query.
1138
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1139
-     *                                  you can indicate just the column you want returned
1140
-     * @return array|EE_Base_Class
1141
-     * @throws ReflectionException
1142
-     * @throws InvalidArgumentException
1143
-     * @throws InvalidInterfaceException
1144
-     * @throws InvalidDataTypeException
1145
-     * @throws EE_Error
1146
-     */
1147
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1148
-    {
1149
-        $model = $this->get_model();
1150
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1151
-            ? $model->get_primary_key_field()->get_name()
1152
-            : $field_to_order_by;
1153
-        $current_value = ! empty($field) ? $this->get($field) : null;
1154
-        if (empty($field) || empty($current_value)) {
1155
-            return array();
1156
-        }
1157
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     * verifies that the specified field is of the correct type
1163
-     *
1164
-     * @param string $field_name
1165
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1166
-     *                                (in cases where the same property may be used for different outputs
1167
-     *                                - i.e. datetime, money etc.)
1168
-     * @return mixed
1169
-     * @throws ReflectionException
1170
-     * @throws InvalidArgumentException
1171
-     * @throws InvalidInterfaceException
1172
-     * @throws InvalidDataTypeException
1173
-     * @throws EE_Error
1174
-     */
1175
-    public function get($field_name, $extra_cache_ref = null)
1176
-    {
1177
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * This method simply returns the RAW unprocessed value for the given property in this class
1183
-     *
1184
-     * @param  string $field_name A valid fieldname
1185
-     * @return mixed              Whatever the raw value stored on the property is.
1186
-     * @throws ReflectionException
1187
-     * @throws InvalidArgumentException
1188
-     * @throws InvalidInterfaceException
1189
-     * @throws InvalidDataTypeException
1190
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1191
-     */
1192
-    public function get_raw($field_name)
1193
-    {
1194
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1195
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
-            ? $this->_fields[ $field_name ]->format('U')
1197
-            : $this->_fields[ $field_name ];
1198
-    }
1199
-
1200
-
1201
-    /**
1202
-     * This is used to return the internal DateTime object used for a field that is a
1203
-     * EE_Datetime_Field.
1204
-     *
1205
-     * @param string $field_name               The field name retrieving the DateTime object.
1206
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1207
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1208
-     *                                         EE_Datetime_Field and but the field value is null, then
1209
-     *                                         just null is returned (because that indicates that likely
1210
-     *                                         this field is nullable).
1211
-     * @throws InvalidArgumentException
1212
-     * @throws InvalidDataTypeException
1213
-     * @throws InvalidInterfaceException
1214
-     * @throws ReflectionException
1215
-     */
1216
-    public function get_DateTime_object($field_name)
1217
-    {
1218
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1219
-        if (! $field_settings instanceof EE_Datetime_Field) {
1220
-            EE_Error::add_error(
1221
-                sprintf(
1222
-                    esc_html__(
1223
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1224
-                        'event_espresso'
1225
-                    ),
1226
-                    $field_name
1227
-                ),
1228
-                __FILE__,
1229
-                __FUNCTION__,
1230
-                __LINE__
1231
-            );
1232
-            return false;
1233
-        }
1234
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
-            ? clone $this->_fields[ $field_name ]
1236
-            : null;
1237
-    }
1238
-
1239
-
1240
-    /**
1241
-     * To be used in template to immediately echo out the value, and format it for output.
1242
-     * Eg, should call stripslashes and whatnot before echoing
1243
-     *
1244
-     * @param string $field_name      the name of the field as it appears in the DB
1245
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1246
-     *                                (in cases where the same property may be used for different outputs
1247
-     *                                - i.e. datetime, money etc.)
1248
-     * @return void
1249
-     * @throws ReflectionException
1250
-     * @throws InvalidArgumentException
1251
-     * @throws InvalidInterfaceException
1252
-     * @throws InvalidDataTypeException
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function e($field_name, $extra_cache_ref = null)
1256
-    {
1257
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1258
-    }
1259
-
1260
-
1261
-    /**
1262
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1263
-     * can be easily used as the value of form input.
1264
-     *
1265
-     * @param string $field_name
1266
-     * @return void
1267
-     * @throws ReflectionException
1268
-     * @throws InvalidArgumentException
1269
-     * @throws InvalidInterfaceException
1270
-     * @throws InvalidDataTypeException
1271
-     * @throws EE_Error
1272
-     */
1273
-    public function f($field_name)
1274
-    {
1275
-        $this->e($field_name, 'form_input');
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * Same as `f()` but just returns the value instead of echoing it
1281
-     *
1282
-     * @param string $field_name
1283
-     * @return string
1284
-     * @throws ReflectionException
1285
-     * @throws InvalidArgumentException
1286
-     * @throws InvalidInterfaceException
1287
-     * @throws InvalidDataTypeException
1288
-     * @throws EE_Error
1289
-     */
1290
-    public function get_f($field_name)
1291
-    {
1292
-        return (string) $this->get_pretty($field_name, 'form_input');
1293
-    }
1294
-
1295
-
1296
-    /**
1297
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1298
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1299
-     * to see what options are available.
1300
-     *
1301
-     * @param string $field_name
1302
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1303
-     *                                (in cases where the same property may be used for different outputs
1304
-     *                                - i.e. datetime, money etc.)
1305
-     * @return mixed
1306
-     * @throws ReflectionException
1307
-     * @throws InvalidArgumentException
1308
-     * @throws InvalidInterfaceException
1309
-     * @throws InvalidDataTypeException
1310
-     * @throws EE_Error
1311
-     */
1312
-    public function get_pretty($field_name, $extra_cache_ref = null)
1313
-    {
1314
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1315
-    }
1316
-
1317
-
1318
-    /**
1319
-     * This simply returns the datetime for the given field name
1320
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1321
-     * (and the equivalent e_date, e_time, e_datetime).
1322
-     *
1323
-     * @access   protected
1324
-     * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1325
-     * @param string|null $date_format  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|null $time_format  Same as above except this is for time format
1329
-     * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1330
-     * @param bool|null   $echo         Whether the datetime is 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 EE_Error
1334
-     * @throws ReflectionException
1335
-     */
1336
-    protected function _get_datetime(
1337
-        string $field_name,
1338
-        ?string $date_format = '',
1339
-        ?string $time_format = '',
1340
-        ?string $date_or_time = '',
1341
-        ?bool $echo = false
1342
-    ) {
1343
-        // clear cached property
1344
-        $this->_clear_cached_property($field_name);
1345
-        // reset format properties because they are used in get()
1346
-        $this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1347
-        $this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1348
-        if ($echo) {
1349
-            $this->e($field_name, $date_or_time);
1350
-            return '';
1351
-        }
1352
-        return $this->get($field_name, $date_or_time);
1353
-    }
1354
-
1355
-
1356
-    /**
1357
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1358
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1359
-     * other echoes the pretty value for dtt)
1360
-     *
1361
-     * @param  string $field_name name of model object datetime field holding the value
1362
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1363
-     * @return string            datetime value formatted
1364
-     * @throws ReflectionException
1365
-     * @throws InvalidArgumentException
1366
-     * @throws InvalidInterfaceException
1367
-     * @throws InvalidDataTypeException
1368
-     * @throws EE_Error
1369
-     */
1370
-    public function get_date($field_name, $format = '')
1371
-    {
1372
-        return $this->_get_datetime($field_name, $format, null, 'D');
1373
-    }
1374
-
1375
-
1376
-    /**
1377
-     * @param        $field_name
1378
-     * @param string $format
1379
-     * @throws ReflectionException
1380
-     * @throws InvalidArgumentException
1381
-     * @throws InvalidInterfaceException
1382
-     * @throws InvalidDataTypeException
1383
-     * @throws EE_Error
1384
-     */
1385
-    public function e_date($field_name, $format = '')
1386
-    {
1387
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1388
-    }
1389
-
1390
-
1391
-    /**
1392
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1393
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1394
-     * other echoes the pretty value for dtt)
1395
-     *
1396
-     * @param  string $field_name name of model object datetime field holding the value
1397
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1398
-     * @return string             datetime value formatted
1399
-     * @throws ReflectionException
1400
-     * @throws InvalidArgumentException
1401
-     * @throws InvalidInterfaceException
1402
-     * @throws InvalidDataTypeException
1403
-     * @throws EE_Error
1404
-     */
1405
-    public function get_time($field_name, $format = '')
1406
-    {
1407
-        return $this->_get_datetime($field_name, null, $format, 'T');
1408
-    }
1409
-
1410
-
1411
-    /**
1412
-     * @param        $field_name
1413
-     * @param string $format
1414
-     * @throws ReflectionException
1415
-     * @throws InvalidArgumentException
1416
-     * @throws InvalidInterfaceException
1417
-     * @throws InvalidDataTypeException
1418
-     * @throws EE_Error
1419
-     */
1420
-    public function e_time($field_name, $format = '')
1421
-    {
1422
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1423
-    }
1424
-
1425
-
1426
-    /**
1427
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1428
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1429
-     * other echoes the pretty value for dtt)
1430
-     *
1431
-     * @param  string $field_name name of model object datetime field holding the value
1432
-     * @param  string $date_format    format for the date returned (if NULL we use default in dt_frmt property)
1433
-     * @param  string $time_format    format for the time returned (if NULL we use default in tm_frmt property)
1434
-     * @return string             datetime value formatted
1435
-     * @throws ReflectionException
1436
-     * @throws InvalidArgumentException
1437
-     * @throws InvalidInterfaceException
1438
-     * @throws InvalidDataTypeException
1439
-     * @throws EE_Error
1440
-     */
1441
-    public function get_datetime($field_name, $date_format = '', $time_format = '')
1442
-    {
1443
-        return $this->_get_datetime($field_name, $date_format, $time_format);
1444
-    }
1445
-
1446
-
1447
-    /**
1448
-     * @param string $field_name
1449
-     * @param string $date_format
1450
-     * @param string $time_format
1451
-     * @throws ReflectionException
1452
-     * @throws InvalidArgumentException
1453
-     * @throws InvalidInterfaceException
1454
-     * @throws InvalidDataTypeException
1455
-     * @throws EE_Error
1456
-     */
1457
-    public function e_datetime($field_name, $date_format = '', $time_format = '')
1458
-    {
1459
-        $this->_get_datetime($field_name, $date_format, $time_format, null, true);
1460
-    }
1461
-
1462
-
1463
-    /**
1464
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1465
-     *
1466
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1467
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1468
-     *                           on the object will be used.
1469
-     * @return string Date and time string in set locale or false if no field exists for the given
1470
-     * @throws ReflectionException
1471
-     * @throws InvalidArgumentException
1472
-     * @throws InvalidInterfaceException
1473
-     * @throws InvalidDataTypeException
1474
-     * @throws EE_Error
1475
-     *                           field name.
1476
-     */
1477
-    public function get_i18n_datetime($field_name, $format = '')
1478
-    {
1479
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1480
-        return date_i18n(
1481
-            $format,
1482
-            EEH_DTT_Helper::get_timestamp_with_offset(
1483
-                $this->get_raw($field_name),
1484
-                $this->_timezone
1485
-            )
1486
-        );
1487
-    }
1488
-
1489
-
1490
-    /**
1491
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1492
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1493
-     * thrown.
1494
-     *
1495
-     * @param  string $field_name The field name being checked
1496
-     * @throws ReflectionException
1497
-     * @throws InvalidArgumentException
1498
-     * @throws InvalidInterfaceException
1499
-     * @throws InvalidDataTypeException
1500
-     * @throws EE_Error
1501
-     * @return EE_Datetime_Field
1502
-     */
1503
-    protected function _get_dtt_field_settings($field_name)
1504
-    {
1505
-        $field = $this->get_model()->field_settings_for($field_name);
1506
-        // check if field is dtt
1507
-        if ($field instanceof EE_Datetime_Field) {
1508
-            return $field;
1509
-        }
1510
-        throw new EE_Error(
1511
-            sprintf(
1512
-                esc_html__(
1513
-                    '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',
1514
-                    'event_espresso'
1515
-                ),
1516
-                $field_name,
1517
-                self::_get_model_classname(get_class($this))
1518
-            )
1519
-        );
1520
-    }
1521
-
1522
-
1523
-
1524
-
1525
-    /**
1526
-     * NOTE ABOUT BELOW:
1527
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1528
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1529
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1530
-     * method and make sure you send the entire datetime value for setting.
1531
-     */
1532
-    /**
1533
-     * sets the time on a datetime property
1534
-     *
1535
-     * @access protected
1536
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1537
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1538
-     * @throws ReflectionException
1539
-     * @throws InvalidArgumentException
1540
-     * @throws InvalidInterfaceException
1541
-     * @throws InvalidDataTypeException
1542
-     * @throws EE_Error
1543
-     */
1544
-    protected function _set_time_for($time, $fieldname)
1545
-    {
1546
-        $this->_set_date_time('T', $time, $fieldname);
1547
-    }
1548
-
1549
-
1550
-    /**
1551
-     * sets the date on a datetime property
1552
-     *
1553
-     * @access protected
1554
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1555
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1556
-     * @throws ReflectionException
1557
-     * @throws InvalidArgumentException
1558
-     * @throws InvalidInterfaceException
1559
-     * @throws InvalidDataTypeException
1560
-     * @throws EE_Error
1561
-     */
1562
-    protected function _set_date_for($date, $fieldname)
1563
-    {
1564
-        $this->_set_date_time('D', $date, $fieldname);
1565
-    }
1566
-
1567
-
1568
-    /**
1569
-     * This takes care of setting a date or time independently on a given model object property. This method also
1570
-     * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1571
-     *
1572
-     * @access protected
1573
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1574
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1575
-     * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1576
-     *                                        EE_Datetime_Field property)
1577
-     * @throws ReflectionException
1578
-     * @throws InvalidArgumentException
1579
-     * @throws InvalidInterfaceException
1580
-     * @throws InvalidDataTypeException
1581
-     * @throws EE_Error
1582
-     */
1583
-    protected function _set_date_time(string $what, $datetime_value, string $field_name)
1584
-    {
1585
-        $field = $this->_get_dtt_field_settings($field_name);
1586
-        $field->set_timezone($this->_timezone);
1587
-        $field->set_date_format($this->_dt_frmt);
1588
-        $field->set_time_format($this->_tm_frmt);
1589
-        switch ($what) {
1590
-            case 'T':
1591
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1592
-                    $datetime_value,
1593
-                    $this->_fields[ $field_name ]
1594
-                );
1595
-                $this->_has_changes = true;
1596
-                break;
1597
-            case 'D':
1598
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1599
-                    $datetime_value,
1600
-                    $this->_fields[ $field_name ]
1601
-                );
1602
-                $this->_has_changes = true;
1603
-                break;
1604
-            case 'B':
1605
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1606
-                $this->_has_changes = true;
1607
-                break;
1608
-        }
1609
-        $this->_clear_cached_property($field_name);
1610
-    }
1611
-
1612
-
1613
-    /**
1614
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1615
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1616
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1617
-     * that could lead to some unexpected results!
1618
-     *
1619
-     * @access public
1620
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1621
-     *                                         value being returned.
1622
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1623
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1624
-     * @param string $prepend                  You can include something to prepend on the timestamp
1625
-     * @param string $append                   You can include something to append on the timestamp
1626
-     * @throws ReflectionException
1627
-     * @throws InvalidArgumentException
1628
-     * @throws InvalidInterfaceException
1629
-     * @throws InvalidDataTypeException
1630
-     * @throws EE_Error
1631
-     * @return string timestamp
1632
-     */
1633
-    public function display_in_my_timezone(
1634
-        $field_name,
1635
-        $callback = 'get_datetime',
1636
-        $args = null,
1637
-        $prepend = '',
1638
-        $append = ''
1639
-    ) {
1640
-        $timezone = EEH_DTT_Helper::get_timezone();
1641
-        if ($timezone === $this->_timezone) {
1642
-            return '';
1643
-        }
1644
-        $original_timezone = $this->_timezone;
1645
-        $this->set_timezone($timezone);
1646
-        $fn = (array) $field_name;
1647
-        $args = array_merge($fn, (array) $args);
1648
-        if (! method_exists($this, $callback)) {
1649
-            throw new EE_Error(
1650
-                sprintf(
1651
-                    esc_html__(
1652
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1653
-                        'event_espresso'
1654
-                    ),
1655
-                    $callback
1656
-                )
1657
-            );
1658
-        }
1659
-        $args = (array) $args;
1660
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1661
-        $this->set_timezone($original_timezone);
1662
-        return $return;
1663
-    }
1664
-
1665
-
1666
-    /**
1667
-     * Deletes this model object.
1668
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1669
-     * override
1670
-     * `EE_Base_Class::_delete` NOT this class.
1671
-     *
1672
-     * @return boolean | int
1673
-     * @throws ReflectionException
1674
-     * @throws InvalidArgumentException
1675
-     * @throws InvalidInterfaceException
1676
-     * @throws InvalidDataTypeException
1677
-     * @throws EE_Error
1678
-     */
1679
-    public function delete()
1680
-    {
1681
-        /**
1682
-         * Called just before the `EE_Base_Class::_delete` method call.
1683
-         * Note:
1684
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1685
-         * should be aware that `_delete` may not always result in a permanent delete.
1686
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1687
-         * soft deletes (trash) the object and does not permanently delete it.
1688
-         *
1689
-         * @param EE_Base_Class $model_object about to be 'deleted'
1690
-         */
1691
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1692
-        $result = $this->_delete();
1693
-        /**
1694
-         * Called just after the `EE_Base_Class::_delete` method call.
1695
-         * Note:
1696
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1697
-         * should be aware that `_delete` may not always result in a permanent delete.
1698
-         * For example `EE_Soft_Base_Class::_delete`
1699
-         * soft deletes (trash) the object and does not permanently delete it.
1700
-         *
1701
-         * @param EE_Base_Class $model_object that was just 'deleted'
1702
-         * @param boolean       $result
1703
-         */
1704
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1705
-        return $result;
1706
-    }
1707
-
1708
-
1709
-    /**
1710
-     * Calls the specific delete method for the instantiated class.
1711
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1712
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1713
-     * `EE_Base_Class::delete`
1714
-     *
1715
-     * @return bool|int
1716
-     * @throws ReflectionException
1717
-     * @throws InvalidArgumentException
1718
-     * @throws InvalidInterfaceException
1719
-     * @throws InvalidDataTypeException
1720
-     * @throws EE_Error
1721
-     */
1722
-    protected function _delete()
1723
-    {
1724
-        return $this->delete_permanently();
1725
-    }
1726
-
1727
-
1728
-    /**
1729
-     * Deletes this model object permanently from db
1730
-     * (but keep in mind related models may block the delete and return an error)
1731
-     *
1732
-     * @return bool | int
1733
-     * @throws ReflectionException
1734
-     * @throws InvalidArgumentException
1735
-     * @throws InvalidInterfaceException
1736
-     * @throws InvalidDataTypeException
1737
-     * @throws EE_Error
1738
-     */
1739
-    public function delete_permanently()
1740
-    {
1741
-        /**
1742
-         * Called just before HARD deleting a model object
1743
-         *
1744
-         * @param EE_Base_Class $model_object about to be 'deleted'
1745
-         */
1746
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1747
-        $model = $this->get_model();
1748
-        $result = $model->delete_permanently_by_ID($this->ID());
1749
-        $this->refresh_cache_of_related_objects();
1750
-        /**
1751
-         * Called just after HARD deleting a model object
1752
-         *
1753
-         * @param EE_Base_Class $model_object that was just 'deleted'
1754
-         * @param boolean       $result
1755
-         */
1756
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1757
-        return $result;
1758
-    }
1759
-
1760
-
1761
-    /**
1762
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1763
-     * related model objects
1764
-     *
1765
-     * @throws ReflectionException
1766
-     * @throws InvalidArgumentException
1767
-     * @throws InvalidInterfaceException
1768
-     * @throws InvalidDataTypeException
1769
-     * @throws EE_Error
1770
-     */
1771
-    public function refresh_cache_of_related_objects()
1772
-    {
1773
-        $model = $this->get_model();
1774
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1775
-            if (! empty($this->_model_relations[ $relation_name ])) {
1776
-                $related_objects = $this->_model_relations[ $relation_name ];
1777
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1778
-                    // this relation only stores a single model object, not an array
1779
-                    // but let's make it consistent
1780
-                    $related_objects = array($related_objects);
1781
-                }
1782
-                foreach ($related_objects as $related_object) {
1783
-                    // only refresh their cache if they're in memory
1784
-                    if ($related_object instanceof EE_Base_Class) {
1785
-                        $related_object->clear_cache(
1786
-                            $model->get_this_model_name(),
1787
-                            $this
1788
-                        );
1789
-                    }
1790
-                }
1791
-            }
1792
-        }
1793
-    }
1794
-
1795
-
1796
-    /**
1797
-     *        Saves this object to the database. An array may be supplied to set some values on this
1798
-     * object just before saving.
1799
-     *
1800
-     * @access public
1801
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1802
-     *                                 if provided during the save() method (often client code will change the fields'
1803
-     *                                 values before calling save)
1804
-     * @return bool|int|string         1 on a successful update
1805
-     *                                 the ID of the new entry on insert
1806
-     *                                 0 on failure or if the model object isn't allowed to persist
1807
-     *                                 (as determined by EE_Base_Class::allow_persist())
1808
-     * @throws InvalidInterfaceException
1809
-     * @throws InvalidDataTypeException
1810
-     * @throws EE_Error
1811
-     * @throws InvalidArgumentException
1812
-     * @throws ReflectionException
1813
-     * @throws ReflectionException
1814
-     * @throws ReflectionException
1815
-     */
1816
-    public function save($set_cols_n_values = array())
1817
-    {
1818
-        $model = $this->get_model();
1819
-        /**
1820
-         * Filters the fields we're about to save on the model object
1821
-         *
1822
-         * @param array         $set_cols_n_values
1823
-         * @param EE_Base_Class $model_object
1824
-         */
1825
-        $set_cols_n_values = (array) apply_filters(
1826
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1827
-            $set_cols_n_values,
1828
-            $this
1829
-        );
1830
-        // set attributes as provided in $set_cols_n_values
1831
-        foreach ($set_cols_n_values as $column => $value) {
1832
-            $this->set($column, $value);
1833
-        }
1834
-        // no changes ? then don't do anything
1835
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1836
-            return 0;
1837
-        }
1838
-        /**
1839
-         * Saving a model object.
1840
-         * Before we perform a save, this action is fired.
1841
-         *
1842
-         * @param EE_Base_Class $model_object the model object about to be saved.
1843
-         */
1844
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1845
-        if (! $this->allow_persist()) {
1846
-            return 0;
1847
-        }
1848
-        // now get current attribute values
1849
-        $save_cols_n_values = $this->_fields;
1850
-        // if the object already has an ID, update it. Otherwise, insert it
1851
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1852
-        // They have been
1853
-        $old_assumption_concerning_value_preparation = $model
1854
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1855
-        $model->assume_values_already_prepared_by_model_object(true);
1856
-        // does this model have an autoincrement PK?
1857
-        if ($model->has_primary_key_field()) {
1858
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1859
-                // ok check if it's set, if so: update; if not, insert
1860
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1861
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1862
-                } else {
1863
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1864
-                    $results = $model->insert($save_cols_n_values);
1865
-                    if ($results) {
1866
-                        // if successful, set the primary key
1867
-                        // but don't use the normal SET method, because it will check if
1868
-                        // an item with the same ID exists in the mapper & db, then
1869
-                        // will find it in the db (because we just added it) and THAT object
1870
-                        // will get added to the mapper before we can add this one!
1871
-                        // but if we just avoid using the SET method, all that headache can be avoided
1872
-                        $pk_field_name = $model->primary_key_name();
1873
-                        $this->_fields[ $pk_field_name ] = $results;
1874
-                        $this->_clear_cached_property($pk_field_name);
1875
-                        $model->add_to_entity_map($this);
1876
-                        $this->_update_cached_related_model_objs_fks();
1877
-                    }
1878
-                }
1879
-            } else {// PK is NOT auto-increment
1880
-                // so check if one like it already exists in the db
1881
-                if ($model->exists_by_ID($this->ID())) {
1882
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1883
-                        throw new EE_Error(
1884
-                            sprintf(
1885
-                                esc_html__(
1886
-                                    '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',
1887
-                                    'event_espresso'
1888
-                                ),
1889
-                                get_class($this),
1890
-                                get_class($model) . '::instance()->add_to_entity_map()',
1891
-                                get_class($model) . '::instance()->get_one_by_ID()',
1892
-                                '<br />'
1893
-                            )
1894
-                        );
1895
-                    }
1896
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1897
-                } else {
1898
-                    $results = $model->insert($save_cols_n_values);
1899
-                    $this->_update_cached_related_model_objs_fks();
1900
-                }
1901
-            }
1902
-        } else {// there is NO primary key
1903
-            $already_in_db = false;
1904
-            foreach ($model->unique_indexes() as $index) {
1905
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1906
-                if ($model->exists(array($uniqueness_where_params))) {
1907
-                    $already_in_db = true;
1908
-                }
1909
-            }
1910
-            if ($already_in_db) {
1911
-                $combined_pk_fields_n_values = array_intersect_key(
1912
-                    $save_cols_n_values,
1913
-                    $model->get_combined_primary_key_fields()
1914
-                );
1915
-                $results = $model->update(
1916
-                    $save_cols_n_values,
1917
-                    $combined_pk_fields_n_values
1918
-                );
1919
-            } else {
1920
-                $results = $model->insert($save_cols_n_values);
1921
-            }
1922
-        }
1923
-        // restore the old assumption about values being prepared by the model object
1924
-        $model->assume_values_already_prepared_by_model_object(
1925
-            $old_assumption_concerning_value_preparation
1926
-        );
1927
-        /**
1928
-         * After saving the model object this action is called
1929
-         *
1930
-         * @param EE_Base_Class $model_object which was just saved
1931
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1932
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1933
-         */
1934
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1935
-        $this->_has_changes = false;
1936
-        return $results;
1937
-    }
1938
-
1939
-
1940
-    /**
1941
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1942
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1943
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1944
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1945
-     * 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
1946
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1947
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1948
-     *
1949
-     * @return void
1950
-     * @throws ReflectionException
1951
-     * @throws InvalidArgumentException
1952
-     * @throws InvalidInterfaceException
1953
-     * @throws InvalidDataTypeException
1954
-     * @throws EE_Error
1955
-     */
1956
-    protected function _update_cached_related_model_objs_fks()
1957
-    {
1958
-        $model = $this->get_model();
1959
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1960
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1961
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1962
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1963
-                        $model->get_this_model_name()
1964
-                    );
1965
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1966
-                    if ($related_model_obj_in_cache->ID()) {
1967
-                        $related_model_obj_in_cache->save();
1968
-                    }
1969
-                }
1970
-            }
1971
-        }
1972
-    }
1973
-
1974
-
1975
-    /**
1976
-     * Saves this model object and its NEW cached relations to the database.
1977
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1978
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1979
-     * because otherwise, there's a potential for infinite looping of saving
1980
-     * Saves the cached related model objects, and ensures the relation between them
1981
-     * and this object and properly setup
1982
-     *
1983
-     * @return int ID of new model object on save; 0 on failure+
1984
-     * @throws ReflectionException
1985
-     * @throws InvalidArgumentException
1986
-     * @throws InvalidInterfaceException
1987
-     * @throws InvalidDataTypeException
1988
-     * @throws EE_Error
1989
-     */
1990
-    public function save_new_cached_related_model_objs()
1991
-    {
1992
-        // make sure this has been saved
1993
-        if (! $this->ID()) {
1994
-            $id = $this->save();
1995
-        } else {
1996
-            $id = $this->ID();
1997
-        }
1998
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1999
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
2000
-            if ($this->_model_relations[ $relationName ]) {
2001
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2002
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2003
-                /* @var $related_model_obj EE_Base_Class */
2004
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2005
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2006
-                    // but ONLY if it DOES NOT exist in the DB
2007
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2008
-                    // if( ! $related_model_obj->ID()){
2009
-                    $this->_add_relation_to($related_model_obj, $relationName);
2010
-                    $related_model_obj->save_new_cached_related_model_objs();
2011
-                    // }
2012
-                } else {
2013
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2014
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2015
-                        // but ONLY if it DOES NOT exist in the DB
2016
-                        // if( ! $related_model_obj->ID()){
2017
-                        $this->_add_relation_to($related_model_obj, $relationName);
2018
-                        $related_model_obj->save_new_cached_related_model_objs();
2019
-                        // }
2020
-                    }
2021
-                }
2022
-            }
2023
-        }
2024
-        return $id;
2025
-    }
2026
-
2027
-
2028
-    /**
2029
-     * for getting a model while instantiated.
2030
-     *
2031
-     * @return EEM_Base | EEM_CPT_Base
2032
-     * @throws ReflectionException
2033
-     * @throws InvalidArgumentException
2034
-     * @throws InvalidInterfaceException
2035
-     * @throws InvalidDataTypeException
2036
-     * @throws EE_Error
2037
-     */
2038
-    public function get_model()
2039
-    {
2040
-        if (! $this->_model) {
2041
-            $modelName = self::_get_model_classname(get_class($this));
2042
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2043
-        } else {
2044
-            $this->_model->set_timezone($this->_timezone);
2045
-        }
2046
-        return $this->_model;
2047
-    }
2048
-
2049
-
2050
-    /**
2051
-     * @param $props_n_values
2052
-     * @param $classname
2053
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2054
-     * @throws ReflectionException
2055
-     * @throws InvalidArgumentException
2056
-     * @throws InvalidInterfaceException
2057
-     * @throws InvalidDataTypeException
2058
-     * @throws EE_Error
2059
-     */
2060
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2061
-    {
2062
-        // TODO: will not work for Term_Relationships because they have no PK!
2063
-        $primary_id_ref = self::_get_primary_key_name($classname);
2064
-        if (
2065
-            array_key_exists($primary_id_ref, $props_n_values)
2066
-            && ! empty($props_n_values[ $primary_id_ref ])
2067
-        ) {
2068
-            $id = $props_n_values[ $primary_id_ref ];
2069
-            return self::_get_model($classname)->get_from_entity_map($id);
2070
-        }
2071
-        return false;
2072
-    }
2073
-
2074
-
2075
-    /**
2076
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2077
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2078
-     * 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
2079
-     * we return false.
2080
-     *
2081
-     * @param  array  $props_n_values   incoming array of properties and their values
2082
-     * @param  string $classname        the classname of the child class
2083
-     * @param null    $timezone
2084
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2085
-     *                                  date_format and the second value is the time format
2086
-     * @return mixed (EE_Base_Class|bool)
2087
-     * @throws InvalidArgumentException
2088
-     * @throws InvalidInterfaceException
2089
-     * @throws InvalidDataTypeException
2090
-     * @throws EE_Error
2091
-     * @throws ReflectionException
2092
-     * @throws ReflectionException
2093
-     * @throws ReflectionException
2094
-     */
2095
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2096
-    {
2097
-        $existing = null;
2098
-        $model = self::_get_model($classname, $timezone);
2099
-        if ($model->has_primary_key_field()) {
2100
-            $primary_id_ref = self::_get_primary_key_name($classname);
2101
-            if (
2102
-                array_key_exists($primary_id_ref, $props_n_values)
2103
-                && ! empty($props_n_values[ $primary_id_ref ])
2104
-            ) {
2105
-                $existing = $model->get_one_by_ID(
2106
-                    $props_n_values[ $primary_id_ref ]
2107
-                );
2108
-            }
2109
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2110
-            // no primary key on this model, but there's still a matching item in the DB
2111
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2112
-                self::_get_model($classname, $timezone)
2113
-                    ->get_index_primary_key_string($props_n_values)
2114
-            );
2115
-        }
2116
-        if ($existing) {
2117
-            // set date formats if present before setting values
2118
-            if (! empty($date_formats) && is_array($date_formats)) {
2119
-                $existing->set_date_format($date_formats[0]);
2120
-                $existing->set_time_format($date_formats[1]);
2121
-            } else {
2122
-                // set default formats for date and time
2123
-                $existing->set_date_format(get_option('date_format'));
2124
-                $existing->set_time_format(get_option('time_format'));
2125
-            }
2126
-            foreach ($props_n_values as $property => $field_value) {
2127
-                $existing->set($property, $field_value);
2128
-            }
2129
-            return $existing;
2130
-        }
2131
-        return false;
2132
-    }
2133
-
2134
-
2135
-    /**
2136
-     * Gets the EEM_*_Model for this class
2137
-     *
2138
-     * @access public now, as this is more convenient
2139
-     * @param      $classname
2140
-     * @param null $timezone
2141
-     * @throws ReflectionException
2142
-     * @throws InvalidArgumentException
2143
-     * @throws InvalidInterfaceException
2144
-     * @throws InvalidDataTypeException
2145
-     * @throws EE_Error
2146
-     * @return EEM_Base
2147
-     */
2148
-    protected static function _get_model($classname, $timezone = null)
2149
-    {
2150
-        // find model for this class
2151
-        if (! $classname) {
2152
-            throw new EE_Error(
2153
-                sprintf(
2154
-                    esc_html__(
2155
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2156
-                        'event_espresso'
2157
-                    ),
2158
-                    $classname
2159
-                )
2160
-            );
2161
-        }
2162
-        $modelName = self::_get_model_classname($classname);
2163
-        return self::_get_model_instance_with_name($modelName, $timezone);
2164
-    }
2165
-
2166
-
2167
-    /**
2168
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2169
-     *
2170
-     * @param string $model_classname
2171
-     * @param null   $timezone
2172
-     * @return EEM_Base
2173
-     * @throws ReflectionException
2174
-     * @throws InvalidArgumentException
2175
-     * @throws InvalidInterfaceException
2176
-     * @throws InvalidDataTypeException
2177
-     * @throws EE_Error
2178
-     */
2179
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2180
-    {
2181
-        $model_classname = str_replace('EEM_', '', $model_classname);
2182
-        $model = EE_Registry::instance()->load_model($model_classname);
2183
-        $model->set_timezone($timezone);
2184
-        return $model;
2185
-    }
2186
-
2187
-
2188
-    /**
2189
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2190
-     * Also works if a model class's classname is provided (eg EE_Registration).
2191
-     *
2192
-     * @param string|null $model_name
2193
-     * @return string like EEM_Attendee
2194
-     */
2195
-    private static function _get_model_classname($model_name = '')
2196
-    {
2197
-        return strpos((string) $model_name, 'EE_') === 0
2198
-            ? str_replace('EE_', 'EEM_', $model_name)
2199
-            : 'EEM_' . $model_name;
2200
-    }
2201
-
2202
-
2203
-    /**
2204
-     * returns the name of the primary key attribute
2205
-     *
2206
-     * @param null $classname
2207
-     * @throws ReflectionException
2208
-     * @throws InvalidArgumentException
2209
-     * @throws InvalidInterfaceException
2210
-     * @throws InvalidDataTypeException
2211
-     * @throws EE_Error
2212
-     * @return string
2213
-     */
2214
-    protected static function _get_primary_key_name($classname = null)
2215
-    {
2216
-        if (! $classname) {
2217
-            throw new EE_Error(
2218
-                sprintf(
2219
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2220
-                    $classname
2221
-                )
2222
-            );
2223
-        }
2224
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2225
-    }
2226
-
2227
-
2228
-    /**
2229
-     * Gets the value of the primary key.
2230
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2231
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2232
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2233
-     *
2234
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2235
-     * @throws ReflectionException
2236
-     * @throws InvalidArgumentException
2237
-     * @throws InvalidInterfaceException
2238
-     * @throws InvalidDataTypeException
2239
-     * @throws EE_Error
2240
-     */
2241
-    public function ID()
2242
-    {
2243
-        $model = $this->get_model();
2244
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2245
-        if ($model->has_primary_key_field()) {
2246
-            return $this->_fields[ $model->primary_key_name() ];
2247
-        }
2248
-        return $model->get_index_primary_key_string($this->_fields);
2249
-    }
2250
-
2251
-
2252
-    /**
2253
-     * @param EE_Base_Class|int|string $otherModelObjectOrID
2254
-     * @param string                   $relationName
2255
-     * @return bool
2256
-     * @throws EE_Error
2257
-     * @throws ReflectionException
2258
-     * @since   5.0.0.p
2259
-     */
2260
-    public function hasRelation($otherModelObjectOrID, string $relationName): bool
2261
-    {
2262
-        $other_model = self::_get_model_instance_with_name(
2263
-            self::_get_model_classname($relationName),
2264
-            $this->_timezone
2265
-        );
2266
-        $primary_key = $other_model->primary_key_name();
2267
-        /** @var EE_Base_Class $otherModelObject */
2268
-        $otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2269
-        return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2270
-    }
2271
-
2272
-
2273
-    /**
2274
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2275
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2276
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2277
-     *
2278
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2279
-     * @param string $relationName                     eg 'Events','Question',etc.
2280
-     *                                                 an attendee to a group, you also want to specify which role they
2281
-     *                                                 will have in that group. So you would use this parameter to
2282
-     *                                                 specify array('role-column-name'=>'role-id')
2283
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2284
-     *                                                 allow you to further constrict the relation to being added.
2285
-     *                                                 However, keep in mind that the columns (keys) given must match a
2286
-     *                                                 column on the JOIN table and currently only the HABTM models
2287
-     *                                                 accept these additional conditions.  Also remember that if an
2288
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2289
-     *                                                 NEW row is created in the join table.
2290
-     * @param null   $cache_id
2291
-     * @throws ReflectionException
2292
-     * @throws InvalidArgumentException
2293
-     * @throws InvalidInterfaceException
2294
-     * @throws InvalidDataTypeException
2295
-     * @throws EE_Error
2296
-     * @return EE_Base_Class the object the relation was added to
2297
-     */
2298
-    public function _add_relation_to(
2299
-        $otherObjectModelObjectOrID,
2300
-        $relationName,
2301
-        $extra_join_model_fields_n_values = array(),
2302
-        $cache_id = null
2303
-    ) {
2304
-        $model = $this->get_model();
2305
-        // if this thing exists in the DB, save the relation to the DB
2306
-        if ($this->ID()) {
2307
-            $otherObject = $model->add_relationship_to(
2308
-                $this,
2309
-                $otherObjectModelObjectOrID,
2310
-                $relationName,
2311
-                $extra_join_model_fields_n_values
2312
-            );
2313
-            // clear cache so future get_many_related and get_first_related() return new results.
2314
-            $this->clear_cache($relationName, $otherObject, true);
2315
-            if ($otherObject instanceof EE_Base_Class) {
2316
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2317
-            }
2318
-        } else {
2319
-            // this thing doesn't exist in the DB,  so just cache it
2320
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2321
-                throw new EE_Error(
2322
-                    sprintf(
2323
-                        esc_html__(
2324
-                            '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',
2325
-                            'event_espresso'
2326
-                        ),
2327
-                        $otherObjectModelObjectOrID,
2328
-                        get_class($this)
2329
-                    )
2330
-                );
2331
-            }
2332
-            $otherObject = $otherObjectModelObjectOrID;
2333
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2334
-        }
2335
-        if ($otherObject instanceof EE_Base_Class) {
2336
-            // fix the reciprocal relation too
2337
-            if ($otherObject->ID()) {
2338
-                // its saved so assumed relations exist in the DB, so we can just
2339
-                // clear the cache so future queries use the updated info in the DB
2340
-                $otherObject->clear_cache(
2341
-                    $model->get_this_model_name(),
2342
-                    null,
2343
-                    true
2344
-                );
2345
-            } else {
2346
-                // it's not saved, so it caches relations like this
2347
-                $otherObject->cache($model->get_this_model_name(), $this);
2348
-            }
2349
-        }
2350
-        return $otherObject;
2351
-    }
2352
-
2353
-
2354
-    /**
2355
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2356
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2357
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2358
-     * from the cache
2359
-     *
2360
-     * @param mixed  $otherObjectModelObjectOrID
2361
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2362
-     *                to the DB yet
2363
-     * @param string $relationName
2364
-     * @param array  $where_query
2365
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2366
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2367
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2368
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2369
-     *                deleted.
2370
-     * @return EE_Base_Class the relation was removed from
2371
-     * @throws ReflectionException
2372
-     * @throws InvalidArgumentException
2373
-     * @throws InvalidInterfaceException
2374
-     * @throws InvalidDataTypeException
2375
-     * @throws EE_Error
2376
-     */
2377
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2378
-    {
2379
-        if ($this->ID()) {
2380
-            // if this exists in the DB, save the relation change to the DB too
2381
-            $otherObject = $this->get_model()->remove_relationship_to(
2382
-                $this,
2383
-                $otherObjectModelObjectOrID,
2384
-                $relationName,
2385
-                $where_query
2386
-            );
2387
-            $this->clear_cache(
2388
-                $relationName,
2389
-                $otherObject
2390
-            );
2391
-        } else {
2392
-            // this doesn't exist in the DB, just remove it from the cache
2393
-            $otherObject = $this->clear_cache(
2394
-                $relationName,
2395
-                $otherObjectModelObjectOrID
2396
-            );
2397
-        }
2398
-        if ($otherObject instanceof EE_Base_Class) {
2399
-            $otherObject->clear_cache(
2400
-                $this->get_model()->get_this_model_name(),
2401
-                $this
2402
-            );
2403
-        }
2404
-        return $otherObject;
2405
-    }
2406
-
2407
-
2408
-    /**
2409
-     * Removes ALL the related things for the $relationName.
2410
-     *
2411
-     * @param string $relationName
2412
-     * @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
2413
-     * @return EE_Base_Class
2414
-     * @throws ReflectionException
2415
-     * @throws InvalidArgumentException
2416
-     * @throws InvalidInterfaceException
2417
-     * @throws InvalidDataTypeException
2418
-     * @throws EE_Error
2419
-     */
2420
-    public function _remove_relations($relationName, $where_query_params = array())
2421
-    {
2422
-        if ($this->ID()) {
2423
-            // if this exists in the DB, save the relation change to the DB too
2424
-            $otherObjects = $this->get_model()->remove_relations(
2425
-                $this,
2426
-                $relationName,
2427
-                $where_query_params
2428
-            );
2429
-            $this->clear_cache(
2430
-                $relationName,
2431
-                null,
2432
-                true
2433
-            );
2434
-        } else {
2435
-            // this doesn't exist in the DB, just remove it from the cache
2436
-            $otherObjects = $this->clear_cache(
2437
-                $relationName,
2438
-                null,
2439
-                true
2440
-            );
2441
-        }
2442
-        if (is_array($otherObjects)) {
2443
-            foreach ($otherObjects as $otherObject) {
2444
-                $otherObject->clear_cache(
2445
-                    $this->get_model()->get_this_model_name(),
2446
-                    $this
2447
-                );
2448
-            }
2449
-        }
2450
-        return $otherObjects;
2451
-    }
2452
-
2453
-
2454
-    /**
2455
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2456
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2457
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2458
-     * because we want to get even deleted items etc.
2459
-     *
2460
-     * @param string $relationName key in the model's _model_relations array
2461
-     * @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
2462
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2463
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2464
-     *                             results if you want IDs
2465
-     * @throws ReflectionException
2466
-     * @throws InvalidArgumentException
2467
-     * @throws InvalidInterfaceException
2468
-     * @throws InvalidDataTypeException
2469
-     * @throws EE_Error
2470
-     */
2471
-    public function get_many_related($relationName, $query_params = array())
2472
-    {
2473
-        if ($this->ID()) {
2474
-            // this exists in the DB, so get the related things from either the cache or the DB
2475
-            // if there are query parameters, forget about caching the related model objects.
2476
-            if ($query_params) {
2477
-                $related_model_objects = $this->get_model()->get_all_related(
2478
-                    $this,
2479
-                    $relationName,
2480
-                    $query_params
2481
-                );
2482
-            } else {
2483
-                // did we already cache the result of this query?
2484
-                $cached_results = $this->get_all_from_cache($relationName);
2485
-                if (! $cached_results) {
2486
-                    $related_model_objects = $this->get_model()->get_all_related(
2487
-                        $this,
2488
-                        $relationName,
2489
-                        $query_params
2490
-                    );
2491
-                    // if no query parameters were passed, then we got all the related model objects
2492
-                    // for that relation. We can cache them then.
2493
-                    foreach ($related_model_objects as $related_model_object) {
2494
-                        $this->cache($relationName, $related_model_object);
2495
-                    }
2496
-                } else {
2497
-                    $related_model_objects = $cached_results;
2498
-                }
2499
-            }
2500
-        } else {
2501
-            // this doesn't exist in the DB, so just get the related things from the cache
2502
-            $related_model_objects = $this->get_all_from_cache($relationName);
2503
-        }
2504
-        return $related_model_objects;
2505
-    }
2506
-
2507
-
2508
-    /**
2509
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2510
-     * unless otherwise specified in the $query_params
2511
-     *
2512
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2513
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2514
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2515
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2516
-     *                               that by the setting $distinct to TRUE;
2517
-     * @return int
2518
-     * @throws ReflectionException
2519
-     * @throws InvalidArgumentException
2520
-     * @throws InvalidInterfaceException
2521
-     * @throws InvalidDataTypeException
2522
-     * @throws EE_Error
2523
-     */
2524
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2525
-    {
2526
-        return $this->get_model()->count_related(
2527
-            $this,
2528
-            $relation_name,
2529
-            $query_params,
2530
-            $field_to_count,
2531
-            $distinct
2532
-        );
2533
-    }
2534
-
2535
-
2536
-    /**
2537
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2538
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2539
-     *
2540
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2541
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2542
-     * @param string $field_to_sum  name of field to count by.
2543
-     *                              By default, uses primary key
2544
-     *                              (which doesn't make much sense, so you should probably change it)
2545
-     * @return int
2546
-     * @throws ReflectionException
2547
-     * @throws InvalidArgumentException
2548
-     * @throws InvalidInterfaceException
2549
-     * @throws InvalidDataTypeException
2550
-     * @throws EE_Error
2551
-     */
2552
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2553
-    {
2554
-        return $this->get_model()->sum_related(
2555
-            $this,
2556
-            $relation_name,
2557
-            $query_params,
2558
-            $field_to_sum
2559
-        );
2560
-    }
2561
-
2562
-
2563
-    /**
2564
-     * Gets the first (ie, one) related model object of the specified type.
2565
-     *
2566
-     * @param string $relationName key in the model's _model_relations array
2567
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2568
-     * @return EE_Base_Class (not an array, a single object)
2569
-     * @throws ReflectionException
2570
-     * @throws InvalidArgumentException
2571
-     * @throws InvalidInterfaceException
2572
-     * @throws InvalidDataTypeException
2573
-     * @throws EE_Error
2574
-     */
2575
-    public function get_first_related($relationName, $query_params = array())
2576
-    {
2577
-        $model = $this->get_model();
2578
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2579
-            // if they've provided some query parameters, don't bother trying to cache the result
2580
-            // also make sure we're not caching the result of get_first_related
2581
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2582
-            if (
2583
-                $query_params
2584
-                || ! $model->related_settings_for($relationName)
2585
-                     instanceof
2586
-                     EE_Belongs_To_Relation
2587
-            ) {
2588
-                $related_model_object = $model->get_first_related(
2589
-                    $this,
2590
-                    $relationName,
2591
-                    $query_params
2592
-                );
2593
-            } else {
2594
-                // first, check if we've already cached the result of this query
2595
-                $cached_result = $this->get_one_from_cache($relationName);
2596
-                if (! $cached_result) {
2597
-                    $related_model_object = $model->get_first_related(
2598
-                        $this,
2599
-                        $relationName,
2600
-                        $query_params
2601
-                    );
2602
-                    $this->cache($relationName, $related_model_object);
2603
-                } else {
2604
-                    $related_model_object = $cached_result;
2605
-                }
2606
-            }
2607
-        } else {
2608
-            $related_model_object = null;
2609
-            // this doesn't exist in the Db,
2610
-            // but maybe the relation is of type belongs to, and so the related thing might
2611
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2612
-                $related_model_object = $model->get_first_related(
2613
-                    $this,
2614
-                    $relationName,
2615
-                    $query_params
2616
-                );
2617
-            }
2618
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2619
-            // just get what's cached on this object
2620
-            if (! $related_model_object) {
2621
-                $related_model_object = $this->get_one_from_cache($relationName);
2622
-            }
2623
-        }
2624
-        return $related_model_object;
2625
-    }
2626
-
2627
-
2628
-    /**
2629
-     * Does a delete on all related objects of type $relationName and removes
2630
-     * the current model object's relation to them. If they can't be deleted (because
2631
-     * of blocking related model objects) does nothing. If the related model objects are
2632
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2633
-     * If this model object doesn't exist yet in the DB, just removes its related things
2634
-     *
2635
-     * @param string $relationName
2636
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2637
-     * @return int how many deleted
2638
-     * @throws ReflectionException
2639
-     * @throws InvalidArgumentException
2640
-     * @throws InvalidInterfaceException
2641
-     * @throws InvalidDataTypeException
2642
-     * @throws EE_Error
2643
-     */
2644
-    public function delete_related($relationName, $query_params = array())
2645
-    {
2646
-        if ($this->ID()) {
2647
-            $count = $this->get_model()->delete_related(
2648
-                $this,
2649
-                $relationName,
2650
-                $query_params
2651
-            );
2652
-        } else {
2653
-            $count = count($this->get_all_from_cache($relationName));
2654
-            $this->clear_cache($relationName, null, true);
2655
-        }
2656
-        return $count;
2657
-    }
2658
-
2659
-
2660
-    /**
2661
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2662
-     * the current model object's relation to them. If they can't be deleted (because
2663
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2664
-     * If the related thing isn't a soft-deletable model object, this function is identical
2665
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2666
-     *
2667
-     * @param string $relationName
2668
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2669
-     * @return int how many deleted (including those soft deleted)
2670
-     * @throws ReflectionException
2671
-     * @throws InvalidArgumentException
2672
-     * @throws InvalidInterfaceException
2673
-     * @throws InvalidDataTypeException
2674
-     * @throws EE_Error
2675
-     */
2676
-    public function delete_related_permanently($relationName, $query_params = array())
2677
-    {
2678
-        if ($this->ID()) {
2679
-            $count = $this->get_model()->delete_related_permanently(
2680
-                $this,
2681
-                $relationName,
2682
-                $query_params
2683
-            );
2684
-        } else {
2685
-            $count = count($this->get_all_from_cache($relationName));
2686
-        }
2687
-        $this->clear_cache($relationName, null, true);
2688
-        return $count;
2689
-    }
2690
-
2691
-
2692
-    /**
2693
-     * is_set
2694
-     * Just a simple utility function children can use for checking if property exists
2695
-     *
2696
-     * @access  public
2697
-     * @param  string $field_name property to check
2698
-     * @return bool                              TRUE if existing,FALSE if not.
2699
-     */
2700
-    public function is_set($field_name)
2701
-    {
2702
-        return isset($this->_fields[ $field_name ]);
2703
-    }
2704
-
2705
-
2706
-    /**
2707
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2708
-     * EE_Error exception if they don't
2709
-     *
2710
-     * @param  mixed (string|array) $properties properties to check
2711
-     * @throws EE_Error
2712
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2713
-     */
2714
-    protected function _property_exists($properties)
2715
-    {
2716
-        foreach ((array) $properties as $property_name) {
2717
-            // first make sure this property exists
2718
-            if (! $this->_fields[ $property_name ]) {
2719
-                throw new EE_Error(
2720
-                    sprintf(
2721
-                        esc_html__(
2722
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2723
-                            'event_espresso'
2724
-                        ),
2725
-                        $property_name
2726
-                    )
2727
-                );
2728
-            }
2729
-        }
2730
-        return true;
2731
-    }
2732
-
2733
-
2734
-    /**
2735
-     * This simply returns an array of model fields for this object
2736
-     *
2737
-     * @return array
2738
-     * @throws ReflectionException
2739
-     * @throws InvalidArgumentException
2740
-     * @throws InvalidInterfaceException
2741
-     * @throws InvalidDataTypeException
2742
-     * @throws EE_Error
2743
-     */
2744
-    public function model_field_array()
2745
-    {
2746
-        $fields = $this->get_model()->field_settings(false);
2747
-        $properties = array();
2748
-        // remove prepended underscore
2749
-        foreach ($fields as $field_name => $settings) {
2750
-            $properties[ $field_name ] = $this->get($field_name);
2751
-        }
2752
-        return $properties;
2753
-    }
2754
-
2755
-
2756
-    /**
2757
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2758
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2759
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2760
-     * Instead of requiring a plugin to extend the EE_Base_Class
2761
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2762
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2763
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2764
-     * and accepts 2 arguments: the object on which the function was called,
2765
-     * and an array of the original arguments passed to the function.
2766
-     * Whatever their callback function returns will be returned by this function.
2767
-     * Example: in functions.php (or in a plugin):
2768
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2769
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2770
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2771
-     *          return $previousReturnValue.$returnString;
2772
-     *      }
2773
-     * require('EE_Answer.class.php');
2774
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2775
-     *      ->my_callback('monkeys',100);
2776
-     * // will output "you called my_callback! and passed args:monkeys,100"
2777
-     *
2778
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2779
-     * @param array  $args       array of original arguments passed to the function
2780
-     * @throws EE_Error
2781
-     * @return mixed whatever the plugin which calls add_filter decides
2782
-     */
2783
-    public function __call($methodName, $args)
2784
-    {
2785
-        $className = get_class($this);
2786
-        $tagName = "FHEE__{$className}__{$methodName}";
2787
-        if (! has_filter($tagName)) {
2788
-            throw new EE_Error(
2789
-                sprintf(
2790
-                    esc_html__(
2791
-                        "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;}",
2792
-                        'event_espresso'
2793
-                    ),
2794
-                    $methodName,
2795
-                    $className,
2796
-                    $tagName
2797
-                )
2798
-            );
2799
-        }
2800
-        return apply_filters($tagName, null, $this, $args);
2801
-    }
2802
-
2803
-
2804
-    /**
2805
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2806
-     * A $previous_value can be specified in case there are many meta rows with the same key
2807
-     *
2808
-     * @param string $meta_key
2809
-     * @param mixed  $meta_value
2810
-     * @param mixed  $previous_value
2811
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2812
-     *                  NOTE: if the values haven't changed, returns 0
2813
-     * @throws InvalidArgumentException
2814
-     * @throws InvalidInterfaceException
2815
-     * @throws InvalidDataTypeException
2816
-     * @throws EE_Error
2817
-     * @throws ReflectionException
2818
-     */
2819
-    public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2820
-    {
2821
-        $query_params = [
2822
-            [
2823
-                'EXM_key'  => $meta_key,
2824
-                'OBJ_ID'   => $this->ID(),
2825
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2826
-            ],
2827
-        ];
2828
-        if ($previous_value !== null) {
2829
-            $query_params[0]['EXM_value'] = $meta_value;
2830
-        }
2831
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2832
-        if (! $existing_rows_like_that) {
2833
-            return $this->add_extra_meta($meta_key, $meta_value);
2834
-        }
2835
-        foreach ($existing_rows_like_that as $existing_row) {
2836
-            $existing_row->save(['EXM_value' => $meta_value]);
2837
-        }
2838
-        return count($existing_rows_like_that);
2839
-    }
2840
-
2841
-
2842
-    /**
2843
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2844
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2845
-     * extra meta row was entered, false if not
2846
-     *
2847
-     * @param string $meta_key
2848
-     * @param mixed  $meta_value
2849
-     * @param bool   $unique
2850
-     * @return bool
2851
-     * @throws InvalidArgumentException
2852
-     * @throws InvalidInterfaceException
2853
-     * @throws InvalidDataTypeException
2854
-     * @throws EE_Error
2855
-     * @throws ReflectionException
2856
-     * @throws ReflectionException
2857
-     */
2858
-    public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2859
-    {
2860
-        if ($unique) {
2861
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2862
-                [
2863
-                    [
2864
-                        'EXM_key'  => $meta_key,
2865
-                        'OBJ_ID'   => $this->ID(),
2866
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2867
-                    ],
2868
-                ]
2869
-            );
2870
-            if ($existing_extra_meta) {
2871
-                return false;
2872
-            }
2873
-        }
2874
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2875
-            [
2876
-                'EXM_key'   => $meta_key,
2877
-                'EXM_value' => $meta_value,
2878
-                'OBJ_ID'    => $this->ID(),
2879
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2880
-            ]
2881
-        );
2882
-        $new_extra_meta->save();
2883
-        return true;
2884
-    }
2885
-
2886
-
2887
-    /**
2888
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2889
-     * is specified, only deletes extra meta records with that value.
2890
-     *
2891
-     * @param string $meta_key
2892
-     * @param mixed  $meta_value
2893
-     * @return int|bool number of extra meta rows deleted
2894
-     * @throws InvalidArgumentException
2895
-     * @throws InvalidInterfaceException
2896
-     * @throws InvalidDataTypeException
2897
-     * @throws EE_Error
2898
-     * @throws ReflectionException
2899
-     */
2900
-    public function delete_extra_meta(string $meta_key, $meta_value = null)
2901
-    {
2902
-        $query_params = [
2903
-            [
2904
-                'EXM_key'  => $meta_key,
2905
-                'OBJ_ID'   => $this->ID(),
2906
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2907
-            ],
2908
-        ];
2909
-        if ($meta_value !== null) {
2910
-            $query_params[0]['EXM_value'] = $meta_value;
2911
-        }
2912
-        return EEM_Extra_Meta::instance()->delete($query_params);
2913
-    }
2914
-
2915
-
2916
-    /**
2917
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2918
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2919
-     * You can specify $default is case you haven't found the extra meta
2920
-     *
2921
-     * @param string     $meta_key
2922
-     * @param bool       $single
2923
-     * @param mixed      $default if we don't find anything, what should we return?
2924
-     * @param array|null $extra_where
2925
-     * @return mixed single value if $single; array if ! $single
2926
-     * @throws ReflectionException
2927
-     * @throws EE_Error
2928
-     */
2929
-    public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2930
-    {
2931
-        $query_params = [ $extra_where + ['EXM_key' => $meta_key] ];
2932
-        if ($single) {
2933
-            $result = $this->get_first_related('Extra_Meta', $query_params);
2934
-            if ($result instanceof EE_Extra_Meta) {
2935
-                return $result->value();
2936
-            }
2937
-        } else {
2938
-            $results = $this->get_many_related('Extra_Meta', $query_params);
2939
-            if ($results) {
2940
-                $values = [];
2941
-                foreach ($results as $result) {
2942
-                    if ($result instanceof EE_Extra_Meta) {
2943
-                        $values[ $result->ID() ] = $result->value();
2944
-                    }
2945
-                }
2946
-                return $values;
2947
-            }
2948
-        }
2949
-        // if nothing discovered yet return default.
2950
-        return apply_filters(
2951
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2952
-            $default,
2953
-            $meta_key,
2954
-            $single,
2955
-            $this
2956
-        );
2957
-    }
2958
-
2959
-
2960
-    /**
2961
-     * Returns a simple array of all the extra meta associated with this model object.
2962
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2963
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2964
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2965
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2966
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2967
-     * finally the extra meta's value as each sub-value. (eg
2968
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2969
-     *
2970
-     * @param bool $one_of_each_key
2971
-     * @return array
2972
-     * @throws ReflectionException
2973
-     * @throws InvalidArgumentException
2974
-     * @throws InvalidInterfaceException
2975
-     * @throws InvalidDataTypeException
2976
-     * @throws EE_Error
2977
-     */
2978
-    public function all_extra_meta_array(bool $one_of_each_key = true): array
2979
-    {
2980
-        $return_array = [];
2981
-        if ($one_of_each_key) {
2982
-            $extra_meta_objs = $this->get_many_related(
2983
-                'Extra_Meta',
2984
-                ['group_by' => 'EXM_key']
2985
-            );
2986
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2987
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2988
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2989
-                }
2990
-            }
2991
-        } else {
2992
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2993
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2994
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2995
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2996
-                        $return_array[ $extra_meta_obj->key() ] = [];
2997
-                    }
2998
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2999
-                }
3000
-            }
3001
-        }
3002
-        return $return_array;
3003
-    }
3004
-
3005
-
3006
-    /**
3007
-     * Gets a pretty nice displayable nice for this model object. Often overridden
3008
-     *
3009
-     * @return string
3010
-     * @throws ReflectionException
3011
-     * @throws InvalidArgumentException
3012
-     * @throws InvalidInterfaceException
3013
-     * @throws InvalidDataTypeException
3014
-     * @throws EE_Error
3015
-     */
3016
-    public function name()
3017
-    {
3018
-        // find a field that's not a text field
3019
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3020
-        if ($field_we_can_use) {
3021
-            return $this->get($field_we_can_use->get_name());
3022
-        }
3023
-        $first_few_properties = $this->model_field_array();
3024
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3025
-        $name_parts = array();
3026
-        foreach ($first_few_properties as $name => $value) {
3027
-            $name_parts[] = "$name:$value";
3028
-        }
3029
-        return implode(',', $name_parts);
3030
-    }
3031
-
3032
-
3033
-    /**
3034
-     * in_entity_map
3035
-     * Checks if this model object has been proven to already be in the entity map
3036
-     *
3037
-     * @return boolean
3038
-     * @throws ReflectionException
3039
-     * @throws InvalidArgumentException
3040
-     * @throws InvalidInterfaceException
3041
-     * @throws InvalidDataTypeException
3042
-     * @throws EE_Error
3043
-     */
3044
-    public function in_entity_map()
3045
-    {
3046
-        // well, if we looked, did we find it in the entity map?
3047
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3048
-    }
3049
-
3050
-
3051
-    /**
3052
-     * refresh_from_db
3053
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3054
-     *
3055
-     * @throws ReflectionException
3056
-     * @throws InvalidArgumentException
3057
-     * @throws InvalidInterfaceException
3058
-     * @throws InvalidDataTypeException
3059
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3060
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3061
-     */
3062
-    public function refresh_from_db()
3063
-    {
3064
-        if ($this->ID() && $this->in_entity_map()) {
3065
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3066
-        } else {
3067
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3068
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3069
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3070
-            // absolutely nothing in it for this ID
3071
-            if (WP_DEBUG) {
3072
-                throw new EE_Error(
3073
-                    sprintf(
3074
-                        esc_html__(
3075
-                            '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.',
3076
-                            'event_espresso'
3077
-                        ),
3078
-                        $this->ID(),
3079
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3080
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3081
-                    )
3082
-                );
3083
-            }
3084
-        }
3085
-    }
3086
-
3087
-
3088
-    /**
3089
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3090
-     *
3091
-     * @since 4.9.80.p
3092
-     * @param EE_Model_Field_Base[] $fields
3093
-     * @param string $new_value_sql
3094
-     *      example: 'column_name=123',
3095
-     *      or 'column_name=column_name+1',
3096
-     *      or 'column_name= CASE
3097
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3098
-     *          THEN `column_name` + 5
3099
-     *          ELSE `column_name`
3100
-     *      END'
3101
-     *      Also updates $field on this model object with the latest value from the database.
3102
-     * @return bool
3103
-     * @throws EE_Error
3104
-     * @throws InvalidArgumentException
3105
-     * @throws InvalidDataTypeException
3106
-     * @throws InvalidInterfaceException
3107
-     * @throws ReflectionException
3108
-     */
3109
-    protected function updateFieldsInDB($fields, $new_value_sql)
3110
-    {
3111
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3112
-        // if it wasn't even there to start off.
3113
-        if (! $this->ID()) {
3114
-            $this->save();
3115
-        }
3116
-        global $wpdb;
3117
-        if (empty($fields)) {
3118
-            throw new InvalidArgumentException(
3119
-                esc_html__(
3120
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3121
-                    'event_espresso'
3122
-                )
3123
-            );
3124
-        }
3125
-        $first_field = reset($fields);
3126
-        $table_alias = $first_field->get_table_alias();
3127
-        foreach ($fields as $field) {
3128
-            if ($table_alias !== $field->get_table_alias()) {
3129
-                throw new InvalidArgumentException(
3130
-                    sprintf(
3131
-                        esc_html__(
3132
-                            // @codingStandardsIgnoreStart
3133
-                            '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.',
3134
-                            // @codingStandardsIgnoreEnd
3135
-                            'event_espresso'
3136
-                        ),
3137
-                        $table_alias,
3138
-                        $field->get_table_alias()
3139
-                    )
3140
-                );
3141
-            }
3142
-        }
3143
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3144
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3145
-        $table_pk_value = $this->ID();
3146
-        $table_name = $table_obj->get_table_name();
3147
-        if ($table_obj instanceof EE_Secondary_Table) {
3148
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3149
-        } else {
3150
-            $table_pk_field_name = $table_obj->get_pk_column();
3151
-        }
3152
-
3153
-        $query =
3154
-            "UPDATE `{$table_name}`
348
+			$this->_props_n_values_provided_in_constructor
349
+			&& $field_value
350
+			&& $field_name === $model->primary_key_name()
351
+		) {
352
+			// if so, we want all this object's fields to be filled either with
353
+			// what we've explicitly set on this model
354
+			// or what we have in the db
355
+			// echo "setting primary key!";
356
+			$fields_on_model = self::_get_model(get_class($this))->field_settings();
357
+			$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
358
+			foreach ($fields_on_model as $field_obj) {
359
+				if (
360
+					! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
361
+					&& $field_obj->get_name() !== $field_name
362
+				) {
363
+					$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
364
+				}
365
+			}
366
+			// oh this model object has an ID? well make sure its in the entity mapper
367
+			$model->add_to_entity_map($this);
368
+		}
369
+		// let's unset any cache for this field_name from the $_cached_properties property.
370
+		$this->_clear_cached_property($field_name);
371
+	}
372
+
373
+
374
+	/**
375
+	 * Overrides parent because parent expects old models.
376
+	 * This also doesn't do any validation, and won't work for serialized arrays
377
+	 *
378
+	 * @param string $field_name
379
+	 * @param mixed  $field_value_from_db
380
+	 * @throws ReflectionException
381
+	 * @throws InvalidArgumentException
382
+	 * @throws InvalidInterfaceException
383
+	 * @throws InvalidDataTypeException
384
+	 * @throws EE_Error
385
+	 */
386
+	public function set_from_db(string $field_name, $field_value_from_db)
387
+	{
388
+		$field_obj = $this->get_model()->field_settings_for($field_name);
389
+		if ($field_obj instanceof EE_Model_Field_Base) {
390
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
391
+			// eg, a CPT model object could have an entry in the posts table, but no
392
+			// entry in the meta table. Meaning that all its columns in the meta table
393
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
394
+			if ($field_value_from_db === null) {
395
+				if ($field_obj->is_nullable()) {
396
+					// if the field allows nulls, then let it be null
397
+					$field_value = null;
398
+				} else {
399
+					$field_value = $field_obj->get_default_value();
400
+				}
401
+			} else {
402
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
403
+			}
404
+			$this->_fields[ $field_name ] = $field_value;
405
+			$this->_clear_cached_property($field_name);
406
+		}
407
+	}
408
+
409
+
410
+	/**
411
+	 * Set custom select values for model.
412
+	 *
413
+	 * @param array $custom_select_values
414
+	 */
415
+	public function setCustomSelectsValues(array $custom_select_values)
416
+	{
417
+		$this->custom_selection_results = $custom_select_values;
418
+	}
419
+
420
+
421
+	/**
422
+	 * Returns the custom select value for the provided alias if its set.
423
+	 * If not set, returns null.
424
+	 *
425
+	 * @param string $alias
426
+	 * @return string|int|float|null
427
+	 */
428
+	public function getCustomSelect($alias)
429
+	{
430
+		return isset($this->custom_selection_results[ $alias ])
431
+			? $this->custom_selection_results[ $alias ]
432
+			: null;
433
+	}
434
+
435
+
436
+	/**
437
+	 * This sets the field value on the db column if it exists for the given $column_name or
438
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
439
+	 *
440
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
441
+	 * @param string $field_name  Must be the exact column name.
442
+	 * @param mixed  $field_value The value to set.
443
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
444
+	 * @throws InvalidArgumentException
445
+	 * @throws InvalidInterfaceException
446
+	 * @throws InvalidDataTypeException
447
+	 * @throws EE_Error
448
+	 * @throws ReflectionException
449
+	 */
450
+	public function set_field_or_extra_meta($field_name, $field_value)
451
+	{
452
+		if ($this->get_model()->has_field($field_name)) {
453
+			$this->set($field_name, $field_value);
454
+			return true;
455
+		}
456
+		// ensure this object is saved first so that extra meta can be properly related.
457
+		$this->save();
458
+		return $this->update_extra_meta($field_name, $field_value);
459
+	}
460
+
461
+
462
+	/**
463
+	 * This retrieves the value of the db column set on this class or if that's not present
464
+	 * it will attempt to retrieve from extra_meta if found.
465
+	 * Example Usage:
466
+	 * Via EE_Message child class:
467
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
468
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
469
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
470
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
471
+	 * value for those extra fields dynamically via the EE_message object.
472
+	 *
473
+	 * @param  string $field_name expecting the fully qualified field name.
474
+	 * @return mixed|null  value for the field if found.  null if not found.
475
+	 * @throws ReflectionException
476
+	 * @throws InvalidArgumentException
477
+	 * @throws InvalidInterfaceException
478
+	 * @throws InvalidDataTypeException
479
+	 * @throws EE_Error
480
+	 */
481
+	public function get_field_or_extra_meta($field_name)
482
+	{
483
+		if ($this->get_model()->has_field($field_name)) {
484
+			$column_value = $this->get($field_name);
485
+		} else {
486
+			// This isn't a column in the main table, let's see if it is in the extra meta.
487
+			$column_value = $this->get_extra_meta($field_name, true, null);
488
+		}
489
+		return $column_value;
490
+	}
491
+
492
+
493
+	/**
494
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
495
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
496
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
497
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
498
+	 *
499
+	 * @access public
500
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
501
+	 * @return void
502
+	 * @throws InvalidArgumentException
503
+	 * @throws InvalidInterfaceException
504
+	 * @throws InvalidDataTypeException
505
+	 * @throws EE_Error
506
+	 * @throws ReflectionException
507
+	 */
508
+	public function set_timezone($timezone = '')
509
+	{
510
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
511
+		// make sure we clear all cached properties because they won't be relevant now
512
+		$this->_clear_cached_properties();
513
+		// make sure we update field settings and the date for all EE_Datetime_Fields
514
+		$model_fields = $this->get_model()->field_settings(false);
515
+		foreach ($model_fields as $field_name => $field_obj) {
516
+			if ($field_obj instanceof EE_Datetime_Field) {
517
+				$field_obj->set_timezone($this->_timezone);
518
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
519
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
520
+				}
521
+			}
522
+		}
523
+	}
524
+
525
+
526
+	/**
527
+	 * This just returns whatever is set for the current timezone.
528
+	 *
529
+	 * @access public
530
+	 * @return string timezone string
531
+	 */
532
+	public function get_timezone()
533
+	{
534
+		return $this->_timezone;
535
+	}
536
+
537
+
538
+	/**
539
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
540
+	 * internally instead of wp set date format options
541
+	 *
542
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
543
+	 * @since 4.6
544
+	 */
545
+	public function set_date_format(?string $format = 'Y-m-d')
546
+	{
547
+		$format = $format ?: 'Y-m-d';
548
+		$this->_dt_frmt = new DateFormat($format);
549
+		// clear cached_properties because they won't be relevant now.
550
+		$this->_clear_cached_properties();
551
+	}
552
+
553
+
554
+	/**
555
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
556
+	 * class internally instead of wp set time format options.
557
+	 *
558
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
559
+	 * @since 4.6
560
+	 */
561
+	public function set_time_format(?string $format = 'H:i:s')
562
+	{
563
+		$format = $format ?: 'H:i:s';
564
+		$this->_tm_frmt = new TimeFormat($format);
565
+		// clear cached_properties because they won't be relevant now.
566
+		$this->_clear_cached_properties();
567
+	}
568
+
569
+
570
+	/**
571
+	 * This returns the current internal set format for the date and time formats.
572
+	 *
573
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
574
+	 *                             where the first value is the date format and the second value is the time format.
575
+	 * @return mixed string|array
576
+	 */
577
+	public function get_format($full = true)
578
+	{
579
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
580
+	}
581
+
582
+
583
+	/**
584
+	 * cache
585
+	 * stores the passed model object on the current model object.
586
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
587
+	 *
588
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
589
+	 *                                       'Registration' associated with this model object
590
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
591
+	 *                                       that could be a payment or a registration)
592
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
593
+	 *                                       items which will be stored in an array on this object
594
+	 * @throws ReflectionException
595
+	 * @throws InvalidArgumentException
596
+	 * @throws InvalidInterfaceException
597
+	 * @throws InvalidDataTypeException
598
+	 * @throws EE_Error
599
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
600
+	 *                                       related thing, no array)
601
+	 */
602
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
603
+	{
604
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
605
+		if (! $object_to_cache instanceof EE_Base_Class) {
606
+			return false;
607
+		}
608
+		// also get "how" the object is related, or throw an error
609
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
610
+			throw new EE_Error(
611
+				sprintf(
612
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
613
+					$relationName,
614
+					get_class($this)
615
+				)
616
+			);
617
+		}
618
+		// how many things are related ?
619
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
620
+			// if it's a "belongs to" relationship, then there's only one related model object
621
+			// eg, if this is a registration, there's only 1 attendee for it
622
+			// so for these model objects just set it to be cached
623
+			$this->_model_relations[ $relationName ] = $object_to_cache;
624
+			$return = true;
625
+		} else {
626
+			// otherwise, this is the "many" side of a one to many relationship,
627
+			// so we'll add the object to the array of related objects for that type.
628
+			// eg: if this is an event, there are many registrations for that event,
629
+			// so we cache the registrations in an array
630
+			if (! is_array($this->_model_relations[ $relationName ])) {
631
+				// if for some reason, the cached item is a model object,
632
+				// then stick that in the array, otherwise start with an empty array
633
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
634
+														   instanceof
635
+														   EE_Base_Class
636
+					? array($this->_model_relations[ $relationName ]) : array();
637
+			}
638
+			// first check for a cache_id which is normally empty
639
+			if (! empty($cache_id)) {
640
+				// if the cache_id exists, then it means we are purposely trying to cache this
641
+				// with a known key that can then be used to retrieve the object later on
642
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
643
+				$return = $cache_id;
644
+			} elseif ($object_to_cache->ID()) {
645
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
646
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
647
+				$return = $object_to_cache->ID();
648
+			} else {
649
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
650
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
651
+				// move the internal pointer to the end of the array
652
+				end($this->_model_relations[ $relationName ]);
653
+				// and grab the key so that we can return it
654
+				$return = key($this->_model_relations[ $relationName ]);
655
+			}
656
+		}
657
+		return $return;
658
+	}
659
+
660
+
661
+	/**
662
+	 * For adding an item to the cached_properties property.
663
+	 *
664
+	 * @access protected
665
+	 * @param string      $fieldname the property item the corresponding value is for.
666
+	 * @param mixed       $value     The value we are caching.
667
+	 * @param string|null $cache_type
668
+	 * @return void
669
+	 * @throws ReflectionException
670
+	 * @throws InvalidArgumentException
671
+	 * @throws InvalidInterfaceException
672
+	 * @throws InvalidDataTypeException
673
+	 * @throws EE_Error
674
+	 */
675
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
676
+	{
677
+		// first make sure this property exists
678
+		$this->get_model()->field_settings_for($fieldname);
679
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
680
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
681
+	}
682
+
683
+
684
+	/**
685
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
686
+	 * This also SETS the cache if we return the actual property!
687
+	 *
688
+	 * @param string $fieldname        the name of the property we're trying to retrieve
689
+	 * @param bool   $pretty
690
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
691
+	 *                                 (in cases where the same property may be used for different outputs
692
+	 *                                 - i.e. datetime, money etc.)
693
+	 *                                 It can also accept certain pre-defined "schema" strings
694
+	 *                                 to define how to output the property.
695
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
696
+	 * @return mixed                   whatever the value for the property is we're retrieving
697
+	 * @throws ReflectionException
698
+	 * @throws InvalidArgumentException
699
+	 * @throws InvalidInterfaceException
700
+	 * @throws InvalidDataTypeException
701
+	 * @throws EE_Error
702
+	 */
703
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
704
+	{
705
+		// verify the field exists
706
+		$model = $this->get_model();
707
+		$model->field_settings_for($fieldname);
708
+		$cache_type = $pretty ? 'pretty' : 'standard';
709
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
710
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
711
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
712
+		}
713
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
714
+		$this->_set_cached_property($fieldname, $value, $cache_type);
715
+		return $value;
716
+	}
717
+
718
+
719
+	/**
720
+	 * If the cache didn't fetch the needed item, this fetches it.
721
+	 *
722
+	 * @param string $fieldname
723
+	 * @param bool   $pretty
724
+	 * @param string $extra_cache_ref
725
+	 * @return mixed
726
+	 * @throws InvalidArgumentException
727
+	 * @throws InvalidInterfaceException
728
+	 * @throws InvalidDataTypeException
729
+	 * @throws EE_Error
730
+	 * @throws ReflectionException
731
+	 */
732
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
733
+	{
734
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
735
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
736
+		if ($field_obj instanceof EE_Datetime_Field) {
737
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
738
+		}
739
+		if (! isset($this->_fields[ $fieldname ])) {
740
+			$this->_fields[ $fieldname ] = null;
741
+		}
742
+		return $pretty
743
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
744
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
745
+	}
746
+
747
+
748
+	/**
749
+	 * set timezone, formats, and output for EE_Datetime_Field objects
750
+	 *
751
+	 * @param EE_Datetime_Field $datetime_field
752
+	 * @param bool              $pretty
753
+	 * @param null              $date_or_time
754
+	 * @return void
755
+	 * @throws InvalidArgumentException
756
+	 * @throws InvalidInterfaceException
757
+	 * @throws InvalidDataTypeException
758
+	 */
759
+	protected function _prepare_datetime_field(
760
+		EE_Datetime_Field $datetime_field,
761
+		$pretty = false,
762
+		$date_or_time = null
763
+	) {
764
+		$datetime_field->set_timezone($this->_timezone);
765
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
766
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
767
+		// set the output returned
768
+		switch ($date_or_time) {
769
+			case 'D':
770
+				$datetime_field->set_date_time_output('date');
771
+				break;
772
+			case 'T':
773
+				$datetime_field->set_date_time_output('time');
774
+				break;
775
+			default:
776
+				$datetime_field->set_date_time_output();
777
+		}
778
+	}
779
+
780
+
781
+	/**
782
+	 * This just takes care of clearing out the cached_properties
783
+	 *
784
+	 * @return void
785
+	 */
786
+	protected function _clear_cached_properties()
787
+	{
788
+		$this->_cached_properties = array();
789
+	}
790
+
791
+
792
+	/**
793
+	 * This just clears out ONE property if it exists in the cache
794
+	 *
795
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
796
+	 * @return void
797
+	 */
798
+	protected function _clear_cached_property($property_name)
799
+	{
800
+		if (isset($this->_cached_properties[ $property_name ])) {
801
+			unset($this->_cached_properties[ $property_name ]);
802
+		}
803
+	}
804
+
805
+
806
+	/**
807
+	 * Ensures that this related thing is a model object.
808
+	 *
809
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
810
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
811
+	 * @return EE_Base_Class
812
+	 * @throws ReflectionException
813
+	 * @throws InvalidArgumentException
814
+	 * @throws InvalidInterfaceException
815
+	 * @throws InvalidDataTypeException
816
+	 * @throws EE_Error
817
+	 */
818
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
819
+	{
820
+		$other_model_instance = self::_get_model_instance_with_name(
821
+			self::_get_model_classname($model_name),
822
+			$this->_timezone
823
+		);
824
+		return $other_model_instance->ensure_is_obj($object_or_id);
825
+	}
826
+
827
+
828
+	/**
829
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
830
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
831
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
832
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
833
+	 *
834
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
835
+	 *                                                     Eg 'Registration'
836
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
837
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
838
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
839
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
840
+	 *                                                     this is HasMany or HABTM.
841
+	 * @throws ReflectionException
842
+	 * @throws InvalidArgumentException
843
+	 * @throws InvalidInterfaceException
844
+	 * @throws InvalidDataTypeException
845
+	 * @throws EE_Error
846
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
847
+	 *                                                     relation from all
848
+	 */
849
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
850
+	{
851
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
852
+		$index_in_cache = '';
853
+		if (! $relationship_to_model) {
854
+			throw new EE_Error(
855
+				sprintf(
856
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
857
+					$relationName,
858
+					get_class($this)
859
+				)
860
+			);
861
+		}
862
+		if ($clear_all) {
863
+			$obj_removed = true;
864
+			$this->_model_relations[ $relationName ] = null;
865
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
866
+			$obj_removed = $this->_model_relations[ $relationName ];
867
+			$this->_model_relations[ $relationName ] = null;
868
+		} else {
869
+			if (
870
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
871
+				&& $object_to_remove_or_index_into_array->ID()
872
+			) {
873
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
874
+				if (
875
+					is_array($this->_model_relations[ $relationName ])
876
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
877
+				) {
878
+					$index_found_at = null;
879
+					// find this object in the array even though it has a different key
880
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
881
+						/** @noinspection TypeUnsafeComparisonInspection */
882
+						if (
883
+							$obj instanceof EE_Base_Class
884
+							&& (
885
+								$obj == $object_to_remove_or_index_into_array
886
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
887
+							)
888
+						) {
889
+							$index_found_at = $index;
890
+							break;
891
+						}
892
+					}
893
+					if ($index_found_at) {
894
+						$index_in_cache = $index_found_at;
895
+					} else {
896
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
897
+						// if it wasn't in it to begin with. So we're done
898
+						return $object_to_remove_or_index_into_array;
899
+					}
900
+				}
901
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
902
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
903
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
904
+					/** @noinspection TypeUnsafeComparisonInspection */
905
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
906
+						$index_in_cache = $index;
907
+					}
908
+				}
909
+			} else {
910
+				$index_in_cache = $object_to_remove_or_index_into_array;
911
+			}
912
+			// supposedly we've found it. But it could just be that the client code
913
+			// provided a bad index/object
914
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
915
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
916
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
917
+			} else {
918
+				// that thing was never cached anyways.
919
+				$obj_removed = null;
920
+			}
921
+		}
922
+		return $obj_removed;
923
+	}
924
+
925
+
926
+	/**
927
+	 * update_cache_after_object_save
928
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
929
+	 * obtained after being saved to the db
930
+	 *
931
+	 * @param string        $relationName       - the type of object that is cached
932
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
933
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
934
+	 * @return boolean TRUE on success, FALSE on fail
935
+	 * @throws ReflectionException
936
+	 * @throws InvalidArgumentException
937
+	 * @throws InvalidInterfaceException
938
+	 * @throws InvalidDataTypeException
939
+	 * @throws EE_Error
940
+	 */
941
+	public function update_cache_after_object_save(
942
+		$relationName,
943
+		EE_Base_Class $newly_saved_object,
944
+		$current_cache_id = ''
945
+	) {
946
+		// verify that incoming object is of the correct type
947
+		$obj_class = 'EE_' . $relationName;
948
+		if ($newly_saved_object instanceof $obj_class) {
949
+			/* @type EE_Base_Class $newly_saved_object */
950
+			// now get the type of relation
951
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
952
+			// if this is a 1:1 relationship
953
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
954
+				// then just replace the cached object with the newly saved object
955
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
956
+				return true;
957
+				// or if it's some kind of sordid feral polyamorous relationship...
958
+			}
959
+			if (
960
+				is_array($this->_model_relations[ $relationName ])
961
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
962
+			) {
963
+				// then remove the current cached item
964
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
965
+				// and cache the newly saved object using it's new ID
966
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
967
+				return true;
968
+			}
969
+		}
970
+		return false;
971
+	}
972
+
973
+
974
+	/**
975
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
976
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
977
+	 *
978
+	 * @param string $relationName
979
+	 * @return EE_Base_Class
980
+	 */
981
+	public function get_one_from_cache($relationName)
982
+	{
983
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
984
+			? $this->_model_relations[ $relationName ]
985
+			: null;
986
+		if (is_array($cached_array_or_object)) {
987
+			return array_shift($cached_array_or_object);
988
+		}
989
+		return $cached_array_or_object;
990
+	}
991
+
992
+
993
+	/**
994
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
995
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
996
+	 *
997
+	 * @param string $relationName
998
+	 * @throws ReflectionException
999
+	 * @throws InvalidArgumentException
1000
+	 * @throws InvalidInterfaceException
1001
+	 * @throws InvalidDataTypeException
1002
+	 * @throws EE_Error
1003
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
1004
+	 */
1005
+	public function get_all_from_cache($relationName)
1006
+	{
1007
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
1008
+		// if the result is not an array, but exists, make it an array
1009
+		$objects = is_array($objects) ? $objects : array($objects);
1010
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
1011
+		// basically, if this model object was stored in the session, and these cached model objects
1012
+		// already have IDs, let's make sure they're in their model's entity mapper
1013
+		// otherwise we will have duplicates next time we call
1014
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
1015
+		$model = EE_Registry::instance()->load_model($relationName);
1016
+		foreach ($objects as $model_object) {
1017
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
1018
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
1019
+				if ($model_object->ID()) {
1020
+					$model->add_to_entity_map($model_object);
1021
+				}
1022
+			} else {
1023
+				throw new EE_Error(
1024
+					sprintf(
1025
+						esc_html__(
1026
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
1027
+							'event_espresso'
1028
+						),
1029
+						$relationName,
1030
+						gettype($model_object)
1031
+					)
1032
+				);
1033
+			}
1034
+		}
1035
+		return $objects;
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1041
+	 * matching the given query conditions.
1042
+	 *
1043
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1044
+	 * @param int   $limit              How many objects to return.
1045
+	 * @param array $query_params       Any additional conditions on the query.
1046
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1047
+	 *                                  you can indicate just the columns you want returned
1048
+	 * @return array|EE_Base_Class[]
1049
+	 * @throws ReflectionException
1050
+	 * @throws InvalidArgumentException
1051
+	 * @throws InvalidInterfaceException
1052
+	 * @throws InvalidDataTypeException
1053
+	 * @throws EE_Error
1054
+	 */
1055
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1056
+	{
1057
+		$model = $this->get_model();
1058
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1059
+			? $model->get_primary_key_field()->get_name()
1060
+			: $field_to_order_by;
1061
+		$current_value = ! empty($field) ? $this->get($field) : null;
1062
+		if (empty($field) || empty($current_value)) {
1063
+			return array();
1064
+		}
1065
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1066
+	}
1067
+
1068
+
1069
+	/**
1070
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1071
+	 * matching the given query conditions.
1072
+	 *
1073
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1074
+	 * @param int   $limit              How many objects to return.
1075
+	 * @param array $query_params       Any additional conditions on the query.
1076
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1077
+	 *                                  you can indicate just the columns you want returned
1078
+	 * @return array|EE_Base_Class[]
1079
+	 * @throws ReflectionException
1080
+	 * @throws InvalidArgumentException
1081
+	 * @throws InvalidInterfaceException
1082
+	 * @throws InvalidDataTypeException
1083
+	 * @throws EE_Error
1084
+	 */
1085
+	public function previous_x(
1086
+		$field_to_order_by = null,
1087
+		$limit = 1,
1088
+		$query_params = array(),
1089
+		$columns_to_select = null
1090
+	) {
1091
+		$model = $this->get_model();
1092
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1093
+			? $model->get_primary_key_field()->get_name()
1094
+			: $field_to_order_by;
1095
+		$current_value = ! empty($field) ? $this->get($field) : null;
1096
+		if (empty($field) || empty($current_value)) {
1097
+			return array();
1098
+		}
1099
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1100
+	}
1101
+
1102
+
1103
+	/**
1104
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1105
+	 * matching the given query conditions.
1106
+	 *
1107
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1108
+	 * @param array $query_params       Any additional conditions on the query.
1109
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1110
+	 *                                  you can indicate just the columns you want returned
1111
+	 * @return array|EE_Base_Class
1112
+	 * @throws ReflectionException
1113
+	 * @throws InvalidArgumentException
1114
+	 * @throws InvalidInterfaceException
1115
+	 * @throws InvalidDataTypeException
1116
+	 * @throws EE_Error
1117
+	 */
1118
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1119
+	{
1120
+		$model = $this->get_model();
1121
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1122
+			? $model->get_primary_key_field()->get_name()
1123
+			: $field_to_order_by;
1124
+		$current_value = ! empty($field) ? $this->get($field) : null;
1125
+		if (empty($field) || empty($current_value)) {
1126
+			return array();
1127
+		}
1128
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1129
+	}
1130
+
1131
+
1132
+	/**
1133
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1134
+	 * matching the given query conditions.
1135
+	 *
1136
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1137
+	 * @param array $query_params       Any additional conditions on the query.
1138
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1139
+	 *                                  you can indicate just the column you want returned
1140
+	 * @return array|EE_Base_Class
1141
+	 * @throws ReflectionException
1142
+	 * @throws InvalidArgumentException
1143
+	 * @throws InvalidInterfaceException
1144
+	 * @throws InvalidDataTypeException
1145
+	 * @throws EE_Error
1146
+	 */
1147
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1148
+	{
1149
+		$model = $this->get_model();
1150
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1151
+			? $model->get_primary_key_field()->get_name()
1152
+			: $field_to_order_by;
1153
+		$current_value = ! empty($field) ? $this->get($field) : null;
1154
+		if (empty($field) || empty($current_value)) {
1155
+			return array();
1156
+		}
1157
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 * verifies that the specified field is of the correct type
1163
+	 *
1164
+	 * @param string $field_name
1165
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1166
+	 *                                (in cases where the same property may be used for different outputs
1167
+	 *                                - i.e. datetime, money etc.)
1168
+	 * @return mixed
1169
+	 * @throws ReflectionException
1170
+	 * @throws InvalidArgumentException
1171
+	 * @throws InvalidInterfaceException
1172
+	 * @throws InvalidDataTypeException
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	public function get($field_name, $extra_cache_ref = null)
1176
+	{
1177
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1183
+	 *
1184
+	 * @param  string $field_name A valid fieldname
1185
+	 * @return mixed              Whatever the raw value stored on the property is.
1186
+	 * @throws ReflectionException
1187
+	 * @throws InvalidArgumentException
1188
+	 * @throws InvalidInterfaceException
1189
+	 * @throws InvalidDataTypeException
1190
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1191
+	 */
1192
+	public function get_raw($field_name)
1193
+	{
1194
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1195
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
+			? $this->_fields[ $field_name ]->format('U')
1197
+			: $this->_fields[ $field_name ];
1198
+	}
1199
+
1200
+
1201
+	/**
1202
+	 * This is used to return the internal DateTime object used for a field that is a
1203
+	 * EE_Datetime_Field.
1204
+	 *
1205
+	 * @param string $field_name               The field name retrieving the DateTime object.
1206
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1207
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1208
+	 *                                         EE_Datetime_Field and but the field value is null, then
1209
+	 *                                         just null is returned (because that indicates that likely
1210
+	 *                                         this field is nullable).
1211
+	 * @throws InvalidArgumentException
1212
+	 * @throws InvalidDataTypeException
1213
+	 * @throws InvalidInterfaceException
1214
+	 * @throws ReflectionException
1215
+	 */
1216
+	public function get_DateTime_object($field_name)
1217
+	{
1218
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1219
+		if (! $field_settings instanceof EE_Datetime_Field) {
1220
+			EE_Error::add_error(
1221
+				sprintf(
1222
+					esc_html__(
1223
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1224
+						'event_espresso'
1225
+					),
1226
+					$field_name
1227
+				),
1228
+				__FILE__,
1229
+				__FUNCTION__,
1230
+				__LINE__
1231
+			);
1232
+			return false;
1233
+		}
1234
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
+			? clone $this->_fields[ $field_name ]
1236
+			: null;
1237
+	}
1238
+
1239
+
1240
+	/**
1241
+	 * To be used in template to immediately echo out the value, and format it for output.
1242
+	 * Eg, should call stripslashes and whatnot before echoing
1243
+	 *
1244
+	 * @param string $field_name      the name of the field as it appears in the DB
1245
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1246
+	 *                                (in cases where the same property may be used for different outputs
1247
+	 *                                - i.e. datetime, money etc.)
1248
+	 * @return void
1249
+	 * @throws ReflectionException
1250
+	 * @throws InvalidArgumentException
1251
+	 * @throws InvalidInterfaceException
1252
+	 * @throws InvalidDataTypeException
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function e($field_name, $extra_cache_ref = null)
1256
+	{
1257
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1258
+	}
1259
+
1260
+
1261
+	/**
1262
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1263
+	 * can be easily used as the value of form input.
1264
+	 *
1265
+	 * @param string $field_name
1266
+	 * @return void
1267
+	 * @throws ReflectionException
1268
+	 * @throws InvalidArgumentException
1269
+	 * @throws InvalidInterfaceException
1270
+	 * @throws InvalidDataTypeException
1271
+	 * @throws EE_Error
1272
+	 */
1273
+	public function f($field_name)
1274
+	{
1275
+		$this->e($field_name, 'form_input');
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * Same as `f()` but just returns the value instead of echoing it
1281
+	 *
1282
+	 * @param string $field_name
1283
+	 * @return string
1284
+	 * @throws ReflectionException
1285
+	 * @throws InvalidArgumentException
1286
+	 * @throws InvalidInterfaceException
1287
+	 * @throws InvalidDataTypeException
1288
+	 * @throws EE_Error
1289
+	 */
1290
+	public function get_f($field_name)
1291
+	{
1292
+		return (string) $this->get_pretty($field_name, 'form_input');
1293
+	}
1294
+
1295
+
1296
+	/**
1297
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1298
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1299
+	 * to see what options are available.
1300
+	 *
1301
+	 * @param string $field_name
1302
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1303
+	 *                                (in cases where the same property may be used for different outputs
1304
+	 *                                - i.e. datetime, money etc.)
1305
+	 * @return mixed
1306
+	 * @throws ReflectionException
1307
+	 * @throws InvalidArgumentException
1308
+	 * @throws InvalidInterfaceException
1309
+	 * @throws InvalidDataTypeException
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	public function get_pretty($field_name, $extra_cache_ref = null)
1313
+	{
1314
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1315
+	}
1316
+
1317
+
1318
+	/**
1319
+	 * This simply returns the datetime for the given field name
1320
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1321
+	 * (and the equivalent e_date, e_time, e_datetime).
1322
+	 *
1323
+	 * @access   protected
1324
+	 * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1325
+	 * @param string|null $date_format  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|null $time_format  Same as above except this is for time format
1329
+	 * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1330
+	 * @param bool|null   $echo         Whether the datetime is 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 EE_Error
1334
+	 * @throws ReflectionException
1335
+	 */
1336
+	protected function _get_datetime(
1337
+		string $field_name,
1338
+		?string $date_format = '',
1339
+		?string $time_format = '',
1340
+		?string $date_or_time = '',
1341
+		?bool $echo = false
1342
+	) {
1343
+		// clear cached property
1344
+		$this->_clear_cached_property($field_name);
1345
+		// reset format properties because they are used in get()
1346
+		$this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1347
+		$this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1348
+		if ($echo) {
1349
+			$this->e($field_name, $date_or_time);
1350
+			return '';
1351
+		}
1352
+		return $this->get($field_name, $date_or_time);
1353
+	}
1354
+
1355
+
1356
+	/**
1357
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1358
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1359
+	 * other echoes the pretty value for dtt)
1360
+	 *
1361
+	 * @param  string $field_name name of model object datetime field holding the value
1362
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1363
+	 * @return string            datetime value formatted
1364
+	 * @throws ReflectionException
1365
+	 * @throws InvalidArgumentException
1366
+	 * @throws InvalidInterfaceException
1367
+	 * @throws InvalidDataTypeException
1368
+	 * @throws EE_Error
1369
+	 */
1370
+	public function get_date($field_name, $format = '')
1371
+	{
1372
+		return $this->_get_datetime($field_name, $format, null, 'D');
1373
+	}
1374
+
1375
+
1376
+	/**
1377
+	 * @param        $field_name
1378
+	 * @param string $format
1379
+	 * @throws ReflectionException
1380
+	 * @throws InvalidArgumentException
1381
+	 * @throws InvalidInterfaceException
1382
+	 * @throws InvalidDataTypeException
1383
+	 * @throws EE_Error
1384
+	 */
1385
+	public function e_date($field_name, $format = '')
1386
+	{
1387
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1388
+	}
1389
+
1390
+
1391
+	/**
1392
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1393
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1394
+	 * other echoes the pretty value for dtt)
1395
+	 *
1396
+	 * @param  string $field_name name of model object datetime field holding the value
1397
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1398
+	 * @return string             datetime value formatted
1399
+	 * @throws ReflectionException
1400
+	 * @throws InvalidArgumentException
1401
+	 * @throws InvalidInterfaceException
1402
+	 * @throws InvalidDataTypeException
1403
+	 * @throws EE_Error
1404
+	 */
1405
+	public function get_time($field_name, $format = '')
1406
+	{
1407
+		return $this->_get_datetime($field_name, null, $format, 'T');
1408
+	}
1409
+
1410
+
1411
+	/**
1412
+	 * @param        $field_name
1413
+	 * @param string $format
1414
+	 * @throws ReflectionException
1415
+	 * @throws InvalidArgumentException
1416
+	 * @throws InvalidInterfaceException
1417
+	 * @throws InvalidDataTypeException
1418
+	 * @throws EE_Error
1419
+	 */
1420
+	public function e_time($field_name, $format = '')
1421
+	{
1422
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1423
+	}
1424
+
1425
+
1426
+	/**
1427
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1428
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1429
+	 * other echoes the pretty value for dtt)
1430
+	 *
1431
+	 * @param  string $field_name name of model object datetime field holding the value
1432
+	 * @param  string $date_format    format for the date returned (if NULL we use default in dt_frmt property)
1433
+	 * @param  string $time_format    format for the time returned (if NULL we use default in tm_frmt property)
1434
+	 * @return string             datetime value formatted
1435
+	 * @throws ReflectionException
1436
+	 * @throws InvalidArgumentException
1437
+	 * @throws InvalidInterfaceException
1438
+	 * @throws InvalidDataTypeException
1439
+	 * @throws EE_Error
1440
+	 */
1441
+	public function get_datetime($field_name, $date_format = '', $time_format = '')
1442
+	{
1443
+		return $this->_get_datetime($field_name, $date_format, $time_format);
1444
+	}
1445
+
1446
+
1447
+	/**
1448
+	 * @param string $field_name
1449
+	 * @param string $date_format
1450
+	 * @param string $time_format
1451
+	 * @throws ReflectionException
1452
+	 * @throws InvalidArgumentException
1453
+	 * @throws InvalidInterfaceException
1454
+	 * @throws InvalidDataTypeException
1455
+	 * @throws EE_Error
1456
+	 */
1457
+	public function e_datetime($field_name, $date_format = '', $time_format = '')
1458
+	{
1459
+		$this->_get_datetime($field_name, $date_format, $time_format, null, true);
1460
+	}
1461
+
1462
+
1463
+	/**
1464
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1465
+	 *
1466
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1467
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1468
+	 *                           on the object will be used.
1469
+	 * @return string Date and time string in set locale or false if no field exists for the given
1470
+	 * @throws ReflectionException
1471
+	 * @throws InvalidArgumentException
1472
+	 * @throws InvalidInterfaceException
1473
+	 * @throws InvalidDataTypeException
1474
+	 * @throws EE_Error
1475
+	 *                           field name.
1476
+	 */
1477
+	public function get_i18n_datetime($field_name, $format = '')
1478
+	{
1479
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1480
+		return date_i18n(
1481
+			$format,
1482
+			EEH_DTT_Helper::get_timestamp_with_offset(
1483
+				$this->get_raw($field_name),
1484
+				$this->_timezone
1485
+			)
1486
+		);
1487
+	}
1488
+
1489
+
1490
+	/**
1491
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1492
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1493
+	 * thrown.
1494
+	 *
1495
+	 * @param  string $field_name The field name being checked
1496
+	 * @throws ReflectionException
1497
+	 * @throws InvalidArgumentException
1498
+	 * @throws InvalidInterfaceException
1499
+	 * @throws InvalidDataTypeException
1500
+	 * @throws EE_Error
1501
+	 * @return EE_Datetime_Field
1502
+	 */
1503
+	protected function _get_dtt_field_settings($field_name)
1504
+	{
1505
+		$field = $this->get_model()->field_settings_for($field_name);
1506
+		// check if field is dtt
1507
+		if ($field instanceof EE_Datetime_Field) {
1508
+			return $field;
1509
+		}
1510
+		throw new EE_Error(
1511
+			sprintf(
1512
+				esc_html__(
1513
+					'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',
1514
+					'event_espresso'
1515
+				),
1516
+				$field_name,
1517
+				self::_get_model_classname(get_class($this))
1518
+			)
1519
+		);
1520
+	}
1521
+
1522
+
1523
+
1524
+
1525
+	/**
1526
+	 * NOTE ABOUT BELOW:
1527
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1528
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1529
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1530
+	 * method and make sure you send the entire datetime value for setting.
1531
+	 */
1532
+	/**
1533
+	 * sets the time on a datetime property
1534
+	 *
1535
+	 * @access protected
1536
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1537
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1538
+	 * @throws ReflectionException
1539
+	 * @throws InvalidArgumentException
1540
+	 * @throws InvalidInterfaceException
1541
+	 * @throws InvalidDataTypeException
1542
+	 * @throws EE_Error
1543
+	 */
1544
+	protected function _set_time_for($time, $fieldname)
1545
+	{
1546
+		$this->_set_date_time('T', $time, $fieldname);
1547
+	}
1548
+
1549
+
1550
+	/**
1551
+	 * sets the date on a datetime property
1552
+	 *
1553
+	 * @access protected
1554
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1555
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1556
+	 * @throws ReflectionException
1557
+	 * @throws InvalidArgumentException
1558
+	 * @throws InvalidInterfaceException
1559
+	 * @throws InvalidDataTypeException
1560
+	 * @throws EE_Error
1561
+	 */
1562
+	protected function _set_date_for($date, $fieldname)
1563
+	{
1564
+		$this->_set_date_time('D', $date, $fieldname);
1565
+	}
1566
+
1567
+
1568
+	/**
1569
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1570
+	 * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1571
+	 *
1572
+	 * @access protected
1573
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1574
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1575
+	 * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1576
+	 *                                        EE_Datetime_Field property)
1577
+	 * @throws ReflectionException
1578
+	 * @throws InvalidArgumentException
1579
+	 * @throws InvalidInterfaceException
1580
+	 * @throws InvalidDataTypeException
1581
+	 * @throws EE_Error
1582
+	 */
1583
+	protected function _set_date_time(string $what, $datetime_value, string $field_name)
1584
+	{
1585
+		$field = $this->_get_dtt_field_settings($field_name);
1586
+		$field->set_timezone($this->_timezone);
1587
+		$field->set_date_format($this->_dt_frmt);
1588
+		$field->set_time_format($this->_tm_frmt);
1589
+		switch ($what) {
1590
+			case 'T':
1591
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1592
+					$datetime_value,
1593
+					$this->_fields[ $field_name ]
1594
+				);
1595
+				$this->_has_changes = true;
1596
+				break;
1597
+			case 'D':
1598
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1599
+					$datetime_value,
1600
+					$this->_fields[ $field_name ]
1601
+				);
1602
+				$this->_has_changes = true;
1603
+				break;
1604
+			case 'B':
1605
+				$this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1606
+				$this->_has_changes = true;
1607
+				break;
1608
+		}
1609
+		$this->_clear_cached_property($field_name);
1610
+	}
1611
+
1612
+
1613
+	/**
1614
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1615
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1616
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1617
+	 * that could lead to some unexpected results!
1618
+	 *
1619
+	 * @access public
1620
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1621
+	 *                                         value being returned.
1622
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1623
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1624
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1625
+	 * @param string $append                   You can include something to append on the timestamp
1626
+	 * @throws ReflectionException
1627
+	 * @throws InvalidArgumentException
1628
+	 * @throws InvalidInterfaceException
1629
+	 * @throws InvalidDataTypeException
1630
+	 * @throws EE_Error
1631
+	 * @return string timestamp
1632
+	 */
1633
+	public function display_in_my_timezone(
1634
+		$field_name,
1635
+		$callback = 'get_datetime',
1636
+		$args = null,
1637
+		$prepend = '',
1638
+		$append = ''
1639
+	) {
1640
+		$timezone = EEH_DTT_Helper::get_timezone();
1641
+		if ($timezone === $this->_timezone) {
1642
+			return '';
1643
+		}
1644
+		$original_timezone = $this->_timezone;
1645
+		$this->set_timezone($timezone);
1646
+		$fn = (array) $field_name;
1647
+		$args = array_merge($fn, (array) $args);
1648
+		if (! method_exists($this, $callback)) {
1649
+			throw new EE_Error(
1650
+				sprintf(
1651
+					esc_html__(
1652
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1653
+						'event_espresso'
1654
+					),
1655
+					$callback
1656
+				)
1657
+			);
1658
+		}
1659
+		$args = (array) $args;
1660
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1661
+		$this->set_timezone($original_timezone);
1662
+		return $return;
1663
+	}
1664
+
1665
+
1666
+	/**
1667
+	 * Deletes this model object.
1668
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1669
+	 * override
1670
+	 * `EE_Base_Class::_delete` NOT this class.
1671
+	 *
1672
+	 * @return boolean | int
1673
+	 * @throws ReflectionException
1674
+	 * @throws InvalidArgumentException
1675
+	 * @throws InvalidInterfaceException
1676
+	 * @throws InvalidDataTypeException
1677
+	 * @throws EE_Error
1678
+	 */
1679
+	public function delete()
1680
+	{
1681
+		/**
1682
+		 * Called just before the `EE_Base_Class::_delete` method call.
1683
+		 * Note:
1684
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1685
+		 * should be aware that `_delete` may not always result in a permanent delete.
1686
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1687
+		 * soft deletes (trash) the object and does not permanently delete it.
1688
+		 *
1689
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1690
+		 */
1691
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1692
+		$result = $this->_delete();
1693
+		/**
1694
+		 * Called just after the `EE_Base_Class::_delete` method call.
1695
+		 * Note:
1696
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1697
+		 * should be aware that `_delete` may not always result in a permanent delete.
1698
+		 * For example `EE_Soft_Base_Class::_delete`
1699
+		 * soft deletes (trash) the object and does not permanently delete it.
1700
+		 *
1701
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1702
+		 * @param boolean       $result
1703
+		 */
1704
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1705
+		return $result;
1706
+	}
1707
+
1708
+
1709
+	/**
1710
+	 * Calls the specific delete method for the instantiated class.
1711
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1712
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1713
+	 * `EE_Base_Class::delete`
1714
+	 *
1715
+	 * @return bool|int
1716
+	 * @throws ReflectionException
1717
+	 * @throws InvalidArgumentException
1718
+	 * @throws InvalidInterfaceException
1719
+	 * @throws InvalidDataTypeException
1720
+	 * @throws EE_Error
1721
+	 */
1722
+	protected function _delete()
1723
+	{
1724
+		return $this->delete_permanently();
1725
+	}
1726
+
1727
+
1728
+	/**
1729
+	 * Deletes this model object permanently from db
1730
+	 * (but keep in mind related models may block the delete and return an error)
1731
+	 *
1732
+	 * @return bool | int
1733
+	 * @throws ReflectionException
1734
+	 * @throws InvalidArgumentException
1735
+	 * @throws InvalidInterfaceException
1736
+	 * @throws InvalidDataTypeException
1737
+	 * @throws EE_Error
1738
+	 */
1739
+	public function delete_permanently()
1740
+	{
1741
+		/**
1742
+		 * Called just before HARD deleting a model object
1743
+		 *
1744
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1745
+		 */
1746
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1747
+		$model = $this->get_model();
1748
+		$result = $model->delete_permanently_by_ID($this->ID());
1749
+		$this->refresh_cache_of_related_objects();
1750
+		/**
1751
+		 * Called just after HARD deleting a model object
1752
+		 *
1753
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1754
+		 * @param boolean       $result
1755
+		 */
1756
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1757
+		return $result;
1758
+	}
1759
+
1760
+
1761
+	/**
1762
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1763
+	 * related model objects
1764
+	 *
1765
+	 * @throws ReflectionException
1766
+	 * @throws InvalidArgumentException
1767
+	 * @throws InvalidInterfaceException
1768
+	 * @throws InvalidDataTypeException
1769
+	 * @throws EE_Error
1770
+	 */
1771
+	public function refresh_cache_of_related_objects()
1772
+	{
1773
+		$model = $this->get_model();
1774
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1775
+			if (! empty($this->_model_relations[ $relation_name ])) {
1776
+				$related_objects = $this->_model_relations[ $relation_name ];
1777
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1778
+					// this relation only stores a single model object, not an array
1779
+					// but let's make it consistent
1780
+					$related_objects = array($related_objects);
1781
+				}
1782
+				foreach ($related_objects as $related_object) {
1783
+					// only refresh their cache if they're in memory
1784
+					if ($related_object instanceof EE_Base_Class) {
1785
+						$related_object->clear_cache(
1786
+							$model->get_this_model_name(),
1787
+							$this
1788
+						);
1789
+					}
1790
+				}
1791
+			}
1792
+		}
1793
+	}
1794
+
1795
+
1796
+	/**
1797
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1798
+	 * object just before saving.
1799
+	 *
1800
+	 * @access public
1801
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1802
+	 *                                 if provided during the save() method (often client code will change the fields'
1803
+	 *                                 values before calling save)
1804
+	 * @return bool|int|string         1 on a successful update
1805
+	 *                                 the ID of the new entry on insert
1806
+	 *                                 0 on failure or if the model object isn't allowed to persist
1807
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1808
+	 * @throws InvalidInterfaceException
1809
+	 * @throws InvalidDataTypeException
1810
+	 * @throws EE_Error
1811
+	 * @throws InvalidArgumentException
1812
+	 * @throws ReflectionException
1813
+	 * @throws ReflectionException
1814
+	 * @throws ReflectionException
1815
+	 */
1816
+	public function save($set_cols_n_values = array())
1817
+	{
1818
+		$model = $this->get_model();
1819
+		/**
1820
+		 * Filters the fields we're about to save on the model object
1821
+		 *
1822
+		 * @param array         $set_cols_n_values
1823
+		 * @param EE_Base_Class $model_object
1824
+		 */
1825
+		$set_cols_n_values = (array) apply_filters(
1826
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1827
+			$set_cols_n_values,
1828
+			$this
1829
+		);
1830
+		// set attributes as provided in $set_cols_n_values
1831
+		foreach ($set_cols_n_values as $column => $value) {
1832
+			$this->set($column, $value);
1833
+		}
1834
+		// no changes ? then don't do anything
1835
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1836
+			return 0;
1837
+		}
1838
+		/**
1839
+		 * Saving a model object.
1840
+		 * Before we perform a save, this action is fired.
1841
+		 *
1842
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1843
+		 */
1844
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1845
+		if (! $this->allow_persist()) {
1846
+			return 0;
1847
+		}
1848
+		// now get current attribute values
1849
+		$save_cols_n_values = $this->_fields;
1850
+		// if the object already has an ID, update it. Otherwise, insert it
1851
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1852
+		// They have been
1853
+		$old_assumption_concerning_value_preparation = $model
1854
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1855
+		$model->assume_values_already_prepared_by_model_object(true);
1856
+		// does this model have an autoincrement PK?
1857
+		if ($model->has_primary_key_field()) {
1858
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1859
+				// ok check if it's set, if so: update; if not, insert
1860
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1861
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1862
+				} else {
1863
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1864
+					$results = $model->insert($save_cols_n_values);
1865
+					if ($results) {
1866
+						// if successful, set the primary key
1867
+						// but don't use the normal SET method, because it will check if
1868
+						// an item with the same ID exists in the mapper & db, then
1869
+						// will find it in the db (because we just added it) and THAT object
1870
+						// will get added to the mapper before we can add this one!
1871
+						// but if we just avoid using the SET method, all that headache can be avoided
1872
+						$pk_field_name = $model->primary_key_name();
1873
+						$this->_fields[ $pk_field_name ] = $results;
1874
+						$this->_clear_cached_property($pk_field_name);
1875
+						$model->add_to_entity_map($this);
1876
+						$this->_update_cached_related_model_objs_fks();
1877
+					}
1878
+				}
1879
+			} else {// PK is NOT auto-increment
1880
+				// so check if one like it already exists in the db
1881
+				if ($model->exists_by_ID($this->ID())) {
1882
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1883
+						throw new EE_Error(
1884
+							sprintf(
1885
+								esc_html__(
1886
+									'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',
1887
+									'event_espresso'
1888
+								),
1889
+								get_class($this),
1890
+								get_class($model) . '::instance()->add_to_entity_map()',
1891
+								get_class($model) . '::instance()->get_one_by_ID()',
1892
+								'<br />'
1893
+							)
1894
+						);
1895
+					}
1896
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1897
+				} else {
1898
+					$results = $model->insert($save_cols_n_values);
1899
+					$this->_update_cached_related_model_objs_fks();
1900
+				}
1901
+			}
1902
+		} else {// there is NO primary key
1903
+			$already_in_db = false;
1904
+			foreach ($model->unique_indexes() as $index) {
1905
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1906
+				if ($model->exists(array($uniqueness_where_params))) {
1907
+					$already_in_db = true;
1908
+				}
1909
+			}
1910
+			if ($already_in_db) {
1911
+				$combined_pk_fields_n_values = array_intersect_key(
1912
+					$save_cols_n_values,
1913
+					$model->get_combined_primary_key_fields()
1914
+				);
1915
+				$results = $model->update(
1916
+					$save_cols_n_values,
1917
+					$combined_pk_fields_n_values
1918
+				);
1919
+			} else {
1920
+				$results = $model->insert($save_cols_n_values);
1921
+			}
1922
+		}
1923
+		// restore the old assumption about values being prepared by the model object
1924
+		$model->assume_values_already_prepared_by_model_object(
1925
+			$old_assumption_concerning_value_preparation
1926
+		);
1927
+		/**
1928
+		 * After saving the model object this action is called
1929
+		 *
1930
+		 * @param EE_Base_Class $model_object which was just saved
1931
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1932
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1933
+		 */
1934
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1935
+		$this->_has_changes = false;
1936
+		return $results;
1937
+	}
1938
+
1939
+
1940
+	/**
1941
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1942
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1943
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1944
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1945
+	 * 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
1946
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1947
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1948
+	 *
1949
+	 * @return void
1950
+	 * @throws ReflectionException
1951
+	 * @throws InvalidArgumentException
1952
+	 * @throws InvalidInterfaceException
1953
+	 * @throws InvalidDataTypeException
1954
+	 * @throws EE_Error
1955
+	 */
1956
+	protected function _update_cached_related_model_objs_fks()
1957
+	{
1958
+		$model = $this->get_model();
1959
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1960
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1961
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1962
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1963
+						$model->get_this_model_name()
1964
+					);
1965
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1966
+					if ($related_model_obj_in_cache->ID()) {
1967
+						$related_model_obj_in_cache->save();
1968
+					}
1969
+				}
1970
+			}
1971
+		}
1972
+	}
1973
+
1974
+
1975
+	/**
1976
+	 * Saves this model object and its NEW cached relations to the database.
1977
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1978
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1979
+	 * because otherwise, there's a potential for infinite looping of saving
1980
+	 * Saves the cached related model objects, and ensures the relation between them
1981
+	 * and this object and properly setup
1982
+	 *
1983
+	 * @return int ID of new model object on save; 0 on failure+
1984
+	 * @throws ReflectionException
1985
+	 * @throws InvalidArgumentException
1986
+	 * @throws InvalidInterfaceException
1987
+	 * @throws InvalidDataTypeException
1988
+	 * @throws EE_Error
1989
+	 */
1990
+	public function save_new_cached_related_model_objs()
1991
+	{
1992
+		// make sure this has been saved
1993
+		if (! $this->ID()) {
1994
+			$id = $this->save();
1995
+		} else {
1996
+			$id = $this->ID();
1997
+		}
1998
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1999
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
2000
+			if ($this->_model_relations[ $relationName ]) {
2001
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2002
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2003
+				/* @var $related_model_obj EE_Base_Class */
2004
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2005
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2006
+					// but ONLY if it DOES NOT exist in the DB
2007
+					$related_model_obj = $this->_model_relations[ $relationName ];
2008
+					// if( ! $related_model_obj->ID()){
2009
+					$this->_add_relation_to($related_model_obj, $relationName);
2010
+					$related_model_obj->save_new_cached_related_model_objs();
2011
+					// }
2012
+				} else {
2013
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2014
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2015
+						// but ONLY if it DOES NOT exist in the DB
2016
+						// if( ! $related_model_obj->ID()){
2017
+						$this->_add_relation_to($related_model_obj, $relationName);
2018
+						$related_model_obj->save_new_cached_related_model_objs();
2019
+						// }
2020
+					}
2021
+				}
2022
+			}
2023
+		}
2024
+		return $id;
2025
+	}
2026
+
2027
+
2028
+	/**
2029
+	 * for getting a model while instantiated.
2030
+	 *
2031
+	 * @return EEM_Base | EEM_CPT_Base
2032
+	 * @throws ReflectionException
2033
+	 * @throws InvalidArgumentException
2034
+	 * @throws InvalidInterfaceException
2035
+	 * @throws InvalidDataTypeException
2036
+	 * @throws EE_Error
2037
+	 */
2038
+	public function get_model()
2039
+	{
2040
+		if (! $this->_model) {
2041
+			$modelName = self::_get_model_classname(get_class($this));
2042
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2043
+		} else {
2044
+			$this->_model->set_timezone($this->_timezone);
2045
+		}
2046
+		return $this->_model;
2047
+	}
2048
+
2049
+
2050
+	/**
2051
+	 * @param $props_n_values
2052
+	 * @param $classname
2053
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2054
+	 * @throws ReflectionException
2055
+	 * @throws InvalidArgumentException
2056
+	 * @throws InvalidInterfaceException
2057
+	 * @throws InvalidDataTypeException
2058
+	 * @throws EE_Error
2059
+	 */
2060
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2061
+	{
2062
+		// TODO: will not work for Term_Relationships because they have no PK!
2063
+		$primary_id_ref = self::_get_primary_key_name($classname);
2064
+		if (
2065
+			array_key_exists($primary_id_ref, $props_n_values)
2066
+			&& ! empty($props_n_values[ $primary_id_ref ])
2067
+		) {
2068
+			$id = $props_n_values[ $primary_id_ref ];
2069
+			return self::_get_model($classname)->get_from_entity_map($id);
2070
+		}
2071
+		return false;
2072
+	}
2073
+
2074
+
2075
+	/**
2076
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2077
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2078
+	 * 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
2079
+	 * we return false.
2080
+	 *
2081
+	 * @param  array  $props_n_values   incoming array of properties and their values
2082
+	 * @param  string $classname        the classname of the child class
2083
+	 * @param null    $timezone
2084
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2085
+	 *                                  date_format and the second value is the time format
2086
+	 * @return mixed (EE_Base_Class|bool)
2087
+	 * @throws InvalidArgumentException
2088
+	 * @throws InvalidInterfaceException
2089
+	 * @throws InvalidDataTypeException
2090
+	 * @throws EE_Error
2091
+	 * @throws ReflectionException
2092
+	 * @throws ReflectionException
2093
+	 * @throws ReflectionException
2094
+	 */
2095
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2096
+	{
2097
+		$existing = null;
2098
+		$model = self::_get_model($classname, $timezone);
2099
+		if ($model->has_primary_key_field()) {
2100
+			$primary_id_ref = self::_get_primary_key_name($classname);
2101
+			if (
2102
+				array_key_exists($primary_id_ref, $props_n_values)
2103
+				&& ! empty($props_n_values[ $primary_id_ref ])
2104
+			) {
2105
+				$existing = $model->get_one_by_ID(
2106
+					$props_n_values[ $primary_id_ref ]
2107
+				);
2108
+			}
2109
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2110
+			// no primary key on this model, but there's still a matching item in the DB
2111
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2112
+				self::_get_model($classname, $timezone)
2113
+					->get_index_primary_key_string($props_n_values)
2114
+			);
2115
+		}
2116
+		if ($existing) {
2117
+			// set date formats if present before setting values
2118
+			if (! empty($date_formats) && is_array($date_formats)) {
2119
+				$existing->set_date_format($date_formats[0]);
2120
+				$existing->set_time_format($date_formats[1]);
2121
+			} else {
2122
+				// set default formats for date and time
2123
+				$existing->set_date_format(get_option('date_format'));
2124
+				$existing->set_time_format(get_option('time_format'));
2125
+			}
2126
+			foreach ($props_n_values as $property => $field_value) {
2127
+				$existing->set($property, $field_value);
2128
+			}
2129
+			return $existing;
2130
+		}
2131
+		return false;
2132
+	}
2133
+
2134
+
2135
+	/**
2136
+	 * Gets the EEM_*_Model for this class
2137
+	 *
2138
+	 * @access public now, as this is more convenient
2139
+	 * @param      $classname
2140
+	 * @param null $timezone
2141
+	 * @throws ReflectionException
2142
+	 * @throws InvalidArgumentException
2143
+	 * @throws InvalidInterfaceException
2144
+	 * @throws InvalidDataTypeException
2145
+	 * @throws EE_Error
2146
+	 * @return EEM_Base
2147
+	 */
2148
+	protected static function _get_model($classname, $timezone = null)
2149
+	{
2150
+		// find model for this class
2151
+		if (! $classname) {
2152
+			throw new EE_Error(
2153
+				sprintf(
2154
+					esc_html__(
2155
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2156
+						'event_espresso'
2157
+					),
2158
+					$classname
2159
+				)
2160
+			);
2161
+		}
2162
+		$modelName = self::_get_model_classname($classname);
2163
+		return self::_get_model_instance_with_name($modelName, $timezone);
2164
+	}
2165
+
2166
+
2167
+	/**
2168
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2169
+	 *
2170
+	 * @param string $model_classname
2171
+	 * @param null   $timezone
2172
+	 * @return EEM_Base
2173
+	 * @throws ReflectionException
2174
+	 * @throws InvalidArgumentException
2175
+	 * @throws InvalidInterfaceException
2176
+	 * @throws InvalidDataTypeException
2177
+	 * @throws EE_Error
2178
+	 */
2179
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2180
+	{
2181
+		$model_classname = str_replace('EEM_', '', $model_classname);
2182
+		$model = EE_Registry::instance()->load_model($model_classname);
2183
+		$model->set_timezone($timezone);
2184
+		return $model;
2185
+	}
2186
+
2187
+
2188
+	/**
2189
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2190
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2191
+	 *
2192
+	 * @param string|null $model_name
2193
+	 * @return string like EEM_Attendee
2194
+	 */
2195
+	private static function _get_model_classname($model_name = '')
2196
+	{
2197
+		return strpos((string) $model_name, 'EE_') === 0
2198
+			? str_replace('EE_', 'EEM_', $model_name)
2199
+			: 'EEM_' . $model_name;
2200
+	}
2201
+
2202
+
2203
+	/**
2204
+	 * returns the name of the primary key attribute
2205
+	 *
2206
+	 * @param null $classname
2207
+	 * @throws ReflectionException
2208
+	 * @throws InvalidArgumentException
2209
+	 * @throws InvalidInterfaceException
2210
+	 * @throws InvalidDataTypeException
2211
+	 * @throws EE_Error
2212
+	 * @return string
2213
+	 */
2214
+	protected static function _get_primary_key_name($classname = null)
2215
+	{
2216
+		if (! $classname) {
2217
+			throw new EE_Error(
2218
+				sprintf(
2219
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2220
+					$classname
2221
+				)
2222
+			);
2223
+		}
2224
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2225
+	}
2226
+
2227
+
2228
+	/**
2229
+	 * Gets the value of the primary key.
2230
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2231
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2232
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2233
+	 *
2234
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2235
+	 * @throws ReflectionException
2236
+	 * @throws InvalidArgumentException
2237
+	 * @throws InvalidInterfaceException
2238
+	 * @throws InvalidDataTypeException
2239
+	 * @throws EE_Error
2240
+	 */
2241
+	public function ID()
2242
+	{
2243
+		$model = $this->get_model();
2244
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2245
+		if ($model->has_primary_key_field()) {
2246
+			return $this->_fields[ $model->primary_key_name() ];
2247
+		}
2248
+		return $model->get_index_primary_key_string($this->_fields);
2249
+	}
2250
+
2251
+
2252
+	/**
2253
+	 * @param EE_Base_Class|int|string $otherModelObjectOrID
2254
+	 * @param string                   $relationName
2255
+	 * @return bool
2256
+	 * @throws EE_Error
2257
+	 * @throws ReflectionException
2258
+	 * @since   5.0.0.p
2259
+	 */
2260
+	public function hasRelation($otherModelObjectOrID, string $relationName): bool
2261
+	{
2262
+		$other_model = self::_get_model_instance_with_name(
2263
+			self::_get_model_classname($relationName),
2264
+			$this->_timezone
2265
+		);
2266
+		$primary_key = $other_model->primary_key_name();
2267
+		/** @var EE_Base_Class $otherModelObject */
2268
+		$otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2269
+		return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2270
+	}
2271
+
2272
+
2273
+	/**
2274
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2275
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2276
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2277
+	 *
2278
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2279
+	 * @param string $relationName                     eg 'Events','Question',etc.
2280
+	 *                                                 an attendee to a group, you also want to specify which role they
2281
+	 *                                                 will have in that group. So you would use this parameter to
2282
+	 *                                                 specify array('role-column-name'=>'role-id')
2283
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2284
+	 *                                                 allow you to further constrict the relation to being added.
2285
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2286
+	 *                                                 column on the JOIN table and currently only the HABTM models
2287
+	 *                                                 accept these additional conditions.  Also remember that if an
2288
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2289
+	 *                                                 NEW row is created in the join table.
2290
+	 * @param null   $cache_id
2291
+	 * @throws ReflectionException
2292
+	 * @throws InvalidArgumentException
2293
+	 * @throws InvalidInterfaceException
2294
+	 * @throws InvalidDataTypeException
2295
+	 * @throws EE_Error
2296
+	 * @return EE_Base_Class the object the relation was added to
2297
+	 */
2298
+	public function _add_relation_to(
2299
+		$otherObjectModelObjectOrID,
2300
+		$relationName,
2301
+		$extra_join_model_fields_n_values = array(),
2302
+		$cache_id = null
2303
+	) {
2304
+		$model = $this->get_model();
2305
+		// if this thing exists in the DB, save the relation to the DB
2306
+		if ($this->ID()) {
2307
+			$otherObject = $model->add_relationship_to(
2308
+				$this,
2309
+				$otherObjectModelObjectOrID,
2310
+				$relationName,
2311
+				$extra_join_model_fields_n_values
2312
+			);
2313
+			// clear cache so future get_many_related and get_first_related() return new results.
2314
+			$this->clear_cache($relationName, $otherObject, true);
2315
+			if ($otherObject instanceof EE_Base_Class) {
2316
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2317
+			}
2318
+		} else {
2319
+			// this thing doesn't exist in the DB,  so just cache it
2320
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2321
+				throw new EE_Error(
2322
+					sprintf(
2323
+						esc_html__(
2324
+							'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',
2325
+							'event_espresso'
2326
+						),
2327
+						$otherObjectModelObjectOrID,
2328
+						get_class($this)
2329
+					)
2330
+				);
2331
+			}
2332
+			$otherObject = $otherObjectModelObjectOrID;
2333
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2334
+		}
2335
+		if ($otherObject instanceof EE_Base_Class) {
2336
+			// fix the reciprocal relation too
2337
+			if ($otherObject->ID()) {
2338
+				// its saved so assumed relations exist in the DB, so we can just
2339
+				// clear the cache so future queries use the updated info in the DB
2340
+				$otherObject->clear_cache(
2341
+					$model->get_this_model_name(),
2342
+					null,
2343
+					true
2344
+				);
2345
+			} else {
2346
+				// it's not saved, so it caches relations like this
2347
+				$otherObject->cache($model->get_this_model_name(), $this);
2348
+			}
2349
+		}
2350
+		return $otherObject;
2351
+	}
2352
+
2353
+
2354
+	/**
2355
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2356
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2357
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2358
+	 * from the cache
2359
+	 *
2360
+	 * @param mixed  $otherObjectModelObjectOrID
2361
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2362
+	 *                to the DB yet
2363
+	 * @param string $relationName
2364
+	 * @param array  $where_query
2365
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2366
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2367
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2368
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2369
+	 *                deleted.
2370
+	 * @return EE_Base_Class the relation was removed from
2371
+	 * @throws ReflectionException
2372
+	 * @throws InvalidArgumentException
2373
+	 * @throws InvalidInterfaceException
2374
+	 * @throws InvalidDataTypeException
2375
+	 * @throws EE_Error
2376
+	 */
2377
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2378
+	{
2379
+		if ($this->ID()) {
2380
+			// if this exists in the DB, save the relation change to the DB too
2381
+			$otherObject = $this->get_model()->remove_relationship_to(
2382
+				$this,
2383
+				$otherObjectModelObjectOrID,
2384
+				$relationName,
2385
+				$where_query
2386
+			);
2387
+			$this->clear_cache(
2388
+				$relationName,
2389
+				$otherObject
2390
+			);
2391
+		} else {
2392
+			// this doesn't exist in the DB, just remove it from the cache
2393
+			$otherObject = $this->clear_cache(
2394
+				$relationName,
2395
+				$otherObjectModelObjectOrID
2396
+			);
2397
+		}
2398
+		if ($otherObject instanceof EE_Base_Class) {
2399
+			$otherObject->clear_cache(
2400
+				$this->get_model()->get_this_model_name(),
2401
+				$this
2402
+			);
2403
+		}
2404
+		return $otherObject;
2405
+	}
2406
+
2407
+
2408
+	/**
2409
+	 * Removes ALL the related things for the $relationName.
2410
+	 *
2411
+	 * @param string $relationName
2412
+	 * @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
2413
+	 * @return EE_Base_Class
2414
+	 * @throws ReflectionException
2415
+	 * @throws InvalidArgumentException
2416
+	 * @throws InvalidInterfaceException
2417
+	 * @throws InvalidDataTypeException
2418
+	 * @throws EE_Error
2419
+	 */
2420
+	public function _remove_relations($relationName, $where_query_params = array())
2421
+	{
2422
+		if ($this->ID()) {
2423
+			// if this exists in the DB, save the relation change to the DB too
2424
+			$otherObjects = $this->get_model()->remove_relations(
2425
+				$this,
2426
+				$relationName,
2427
+				$where_query_params
2428
+			);
2429
+			$this->clear_cache(
2430
+				$relationName,
2431
+				null,
2432
+				true
2433
+			);
2434
+		} else {
2435
+			// this doesn't exist in the DB, just remove it from the cache
2436
+			$otherObjects = $this->clear_cache(
2437
+				$relationName,
2438
+				null,
2439
+				true
2440
+			);
2441
+		}
2442
+		if (is_array($otherObjects)) {
2443
+			foreach ($otherObjects as $otherObject) {
2444
+				$otherObject->clear_cache(
2445
+					$this->get_model()->get_this_model_name(),
2446
+					$this
2447
+				);
2448
+			}
2449
+		}
2450
+		return $otherObjects;
2451
+	}
2452
+
2453
+
2454
+	/**
2455
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2456
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2457
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2458
+	 * because we want to get even deleted items etc.
2459
+	 *
2460
+	 * @param string $relationName key in the model's _model_relations array
2461
+	 * @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
2462
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2463
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2464
+	 *                             results if you want IDs
2465
+	 * @throws ReflectionException
2466
+	 * @throws InvalidArgumentException
2467
+	 * @throws InvalidInterfaceException
2468
+	 * @throws InvalidDataTypeException
2469
+	 * @throws EE_Error
2470
+	 */
2471
+	public function get_many_related($relationName, $query_params = array())
2472
+	{
2473
+		if ($this->ID()) {
2474
+			// this exists in the DB, so get the related things from either the cache or the DB
2475
+			// if there are query parameters, forget about caching the related model objects.
2476
+			if ($query_params) {
2477
+				$related_model_objects = $this->get_model()->get_all_related(
2478
+					$this,
2479
+					$relationName,
2480
+					$query_params
2481
+				);
2482
+			} else {
2483
+				// did we already cache the result of this query?
2484
+				$cached_results = $this->get_all_from_cache($relationName);
2485
+				if (! $cached_results) {
2486
+					$related_model_objects = $this->get_model()->get_all_related(
2487
+						$this,
2488
+						$relationName,
2489
+						$query_params
2490
+					);
2491
+					// if no query parameters were passed, then we got all the related model objects
2492
+					// for that relation. We can cache them then.
2493
+					foreach ($related_model_objects as $related_model_object) {
2494
+						$this->cache($relationName, $related_model_object);
2495
+					}
2496
+				} else {
2497
+					$related_model_objects = $cached_results;
2498
+				}
2499
+			}
2500
+		} else {
2501
+			// this doesn't exist in the DB, so just get the related things from the cache
2502
+			$related_model_objects = $this->get_all_from_cache($relationName);
2503
+		}
2504
+		return $related_model_objects;
2505
+	}
2506
+
2507
+
2508
+	/**
2509
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2510
+	 * unless otherwise specified in the $query_params
2511
+	 *
2512
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2513
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2514
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2515
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2516
+	 *                               that by the setting $distinct to TRUE;
2517
+	 * @return int
2518
+	 * @throws ReflectionException
2519
+	 * @throws InvalidArgumentException
2520
+	 * @throws InvalidInterfaceException
2521
+	 * @throws InvalidDataTypeException
2522
+	 * @throws EE_Error
2523
+	 */
2524
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2525
+	{
2526
+		return $this->get_model()->count_related(
2527
+			$this,
2528
+			$relation_name,
2529
+			$query_params,
2530
+			$field_to_count,
2531
+			$distinct
2532
+		);
2533
+	}
2534
+
2535
+
2536
+	/**
2537
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2538
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2539
+	 *
2540
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2541
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2542
+	 * @param string $field_to_sum  name of field to count by.
2543
+	 *                              By default, uses primary key
2544
+	 *                              (which doesn't make much sense, so you should probably change it)
2545
+	 * @return int
2546
+	 * @throws ReflectionException
2547
+	 * @throws InvalidArgumentException
2548
+	 * @throws InvalidInterfaceException
2549
+	 * @throws InvalidDataTypeException
2550
+	 * @throws EE_Error
2551
+	 */
2552
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2553
+	{
2554
+		return $this->get_model()->sum_related(
2555
+			$this,
2556
+			$relation_name,
2557
+			$query_params,
2558
+			$field_to_sum
2559
+		);
2560
+	}
2561
+
2562
+
2563
+	/**
2564
+	 * Gets the first (ie, one) related model object of the specified type.
2565
+	 *
2566
+	 * @param string $relationName key in the model's _model_relations array
2567
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2568
+	 * @return EE_Base_Class (not an array, a single object)
2569
+	 * @throws ReflectionException
2570
+	 * @throws InvalidArgumentException
2571
+	 * @throws InvalidInterfaceException
2572
+	 * @throws InvalidDataTypeException
2573
+	 * @throws EE_Error
2574
+	 */
2575
+	public function get_first_related($relationName, $query_params = array())
2576
+	{
2577
+		$model = $this->get_model();
2578
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2579
+			// if they've provided some query parameters, don't bother trying to cache the result
2580
+			// also make sure we're not caching the result of get_first_related
2581
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2582
+			if (
2583
+				$query_params
2584
+				|| ! $model->related_settings_for($relationName)
2585
+					 instanceof
2586
+					 EE_Belongs_To_Relation
2587
+			) {
2588
+				$related_model_object = $model->get_first_related(
2589
+					$this,
2590
+					$relationName,
2591
+					$query_params
2592
+				);
2593
+			} else {
2594
+				// first, check if we've already cached the result of this query
2595
+				$cached_result = $this->get_one_from_cache($relationName);
2596
+				if (! $cached_result) {
2597
+					$related_model_object = $model->get_first_related(
2598
+						$this,
2599
+						$relationName,
2600
+						$query_params
2601
+					);
2602
+					$this->cache($relationName, $related_model_object);
2603
+				} else {
2604
+					$related_model_object = $cached_result;
2605
+				}
2606
+			}
2607
+		} else {
2608
+			$related_model_object = null;
2609
+			// this doesn't exist in the Db,
2610
+			// but maybe the relation is of type belongs to, and so the related thing might
2611
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2612
+				$related_model_object = $model->get_first_related(
2613
+					$this,
2614
+					$relationName,
2615
+					$query_params
2616
+				);
2617
+			}
2618
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2619
+			// just get what's cached on this object
2620
+			if (! $related_model_object) {
2621
+				$related_model_object = $this->get_one_from_cache($relationName);
2622
+			}
2623
+		}
2624
+		return $related_model_object;
2625
+	}
2626
+
2627
+
2628
+	/**
2629
+	 * Does a delete on all related objects of type $relationName and removes
2630
+	 * the current model object's relation to them. If they can't be deleted (because
2631
+	 * of blocking related model objects) does nothing. If the related model objects are
2632
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2633
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2634
+	 *
2635
+	 * @param string $relationName
2636
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2637
+	 * @return int how many deleted
2638
+	 * @throws ReflectionException
2639
+	 * @throws InvalidArgumentException
2640
+	 * @throws InvalidInterfaceException
2641
+	 * @throws InvalidDataTypeException
2642
+	 * @throws EE_Error
2643
+	 */
2644
+	public function delete_related($relationName, $query_params = array())
2645
+	{
2646
+		if ($this->ID()) {
2647
+			$count = $this->get_model()->delete_related(
2648
+				$this,
2649
+				$relationName,
2650
+				$query_params
2651
+			);
2652
+		} else {
2653
+			$count = count($this->get_all_from_cache($relationName));
2654
+			$this->clear_cache($relationName, null, true);
2655
+		}
2656
+		return $count;
2657
+	}
2658
+
2659
+
2660
+	/**
2661
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2662
+	 * the current model object's relation to them. If they can't be deleted (because
2663
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2664
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2665
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2666
+	 *
2667
+	 * @param string $relationName
2668
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2669
+	 * @return int how many deleted (including those soft deleted)
2670
+	 * @throws ReflectionException
2671
+	 * @throws InvalidArgumentException
2672
+	 * @throws InvalidInterfaceException
2673
+	 * @throws InvalidDataTypeException
2674
+	 * @throws EE_Error
2675
+	 */
2676
+	public function delete_related_permanently($relationName, $query_params = array())
2677
+	{
2678
+		if ($this->ID()) {
2679
+			$count = $this->get_model()->delete_related_permanently(
2680
+				$this,
2681
+				$relationName,
2682
+				$query_params
2683
+			);
2684
+		} else {
2685
+			$count = count($this->get_all_from_cache($relationName));
2686
+		}
2687
+		$this->clear_cache($relationName, null, true);
2688
+		return $count;
2689
+	}
2690
+
2691
+
2692
+	/**
2693
+	 * is_set
2694
+	 * Just a simple utility function children can use for checking if property exists
2695
+	 *
2696
+	 * @access  public
2697
+	 * @param  string $field_name property to check
2698
+	 * @return bool                              TRUE if existing,FALSE if not.
2699
+	 */
2700
+	public function is_set($field_name)
2701
+	{
2702
+		return isset($this->_fields[ $field_name ]);
2703
+	}
2704
+
2705
+
2706
+	/**
2707
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2708
+	 * EE_Error exception if they don't
2709
+	 *
2710
+	 * @param  mixed (string|array) $properties properties to check
2711
+	 * @throws EE_Error
2712
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2713
+	 */
2714
+	protected function _property_exists($properties)
2715
+	{
2716
+		foreach ((array) $properties as $property_name) {
2717
+			// first make sure this property exists
2718
+			if (! $this->_fields[ $property_name ]) {
2719
+				throw new EE_Error(
2720
+					sprintf(
2721
+						esc_html__(
2722
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2723
+							'event_espresso'
2724
+						),
2725
+						$property_name
2726
+					)
2727
+				);
2728
+			}
2729
+		}
2730
+		return true;
2731
+	}
2732
+
2733
+
2734
+	/**
2735
+	 * This simply returns an array of model fields for this object
2736
+	 *
2737
+	 * @return array
2738
+	 * @throws ReflectionException
2739
+	 * @throws InvalidArgumentException
2740
+	 * @throws InvalidInterfaceException
2741
+	 * @throws InvalidDataTypeException
2742
+	 * @throws EE_Error
2743
+	 */
2744
+	public function model_field_array()
2745
+	{
2746
+		$fields = $this->get_model()->field_settings(false);
2747
+		$properties = array();
2748
+		// remove prepended underscore
2749
+		foreach ($fields as $field_name => $settings) {
2750
+			$properties[ $field_name ] = $this->get($field_name);
2751
+		}
2752
+		return $properties;
2753
+	}
2754
+
2755
+
2756
+	/**
2757
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2758
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2759
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2760
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2761
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2762
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2763
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2764
+	 * and accepts 2 arguments: the object on which the function was called,
2765
+	 * and an array of the original arguments passed to the function.
2766
+	 * Whatever their callback function returns will be returned by this function.
2767
+	 * Example: in functions.php (or in a plugin):
2768
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2769
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2770
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2771
+	 *          return $previousReturnValue.$returnString;
2772
+	 *      }
2773
+	 * require('EE_Answer.class.php');
2774
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2775
+	 *      ->my_callback('monkeys',100);
2776
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2777
+	 *
2778
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2779
+	 * @param array  $args       array of original arguments passed to the function
2780
+	 * @throws EE_Error
2781
+	 * @return mixed whatever the plugin which calls add_filter decides
2782
+	 */
2783
+	public function __call($methodName, $args)
2784
+	{
2785
+		$className = get_class($this);
2786
+		$tagName = "FHEE__{$className}__{$methodName}";
2787
+		if (! has_filter($tagName)) {
2788
+			throw new EE_Error(
2789
+				sprintf(
2790
+					esc_html__(
2791
+						"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;}",
2792
+						'event_espresso'
2793
+					),
2794
+					$methodName,
2795
+					$className,
2796
+					$tagName
2797
+				)
2798
+			);
2799
+		}
2800
+		return apply_filters($tagName, null, $this, $args);
2801
+	}
2802
+
2803
+
2804
+	/**
2805
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2806
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2807
+	 *
2808
+	 * @param string $meta_key
2809
+	 * @param mixed  $meta_value
2810
+	 * @param mixed  $previous_value
2811
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2812
+	 *                  NOTE: if the values haven't changed, returns 0
2813
+	 * @throws InvalidArgumentException
2814
+	 * @throws InvalidInterfaceException
2815
+	 * @throws InvalidDataTypeException
2816
+	 * @throws EE_Error
2817
+	 * @throws ReflectionException
2818
+	 */
2819
+	public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2820
+	{
2821
+		$query_params = [
2822
+			[
2823
+				'EXM_key'  => $meta_key,
2824
+				'OBJ_ID'   => $this->ID(),
2825
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2826
+			],
2827
+		];
2828
+		if ($previous_value !== null) {
2829
+			$query_params[0]['EXM_value'] = $meta_value;
2830
+		}
2831
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2832
+		if (! $existing_rows_like_that) {
2833
+			return $this->add_extra_meta($meta_key, $meta_value);
2834
+		}
2835
+		foreach ($existing_rows_like_that as $existing_row) {
2836
+			$existing_row->save(['EXM_value' => $meta_value]);
2837
+		}
2838
+		return count($existing_rows_like_that);
2839
+	}
2840
+
2841
+
2842
+	/**
2843
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2844
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2845
+	 * extra meta row was entered, false if not
2846
+	 *
2847
+	 * @param string $meta_key
2848
+	 * @param mixed  $meta_value
2849
+	 * @param bool   $unique
2850
+	 * @return bool
2851
+	 * @throws InvalidArgumentException
2852
+	 * @throws InvalidInterfaceException
2853
+	 * @throws InvalidDataTypeException
2854
+	 * @throws EE_Error
2855
+	 * @throws ReflectionException
2856
+	 * @throws ReflectionException
2857
+	 */
2858
+	public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2859
+	{
2860
+		if ($unique) {
2861
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2862
+				[
2863
+					[
2864
+						'EXM_key'  => $meta_key,
2865
+						'OBJ_ID'   => $this->ID(),
2866
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2867
+					],
2868
+				]
2869
+			);
2870
+			if ($existing_extra_meta) {
2871
+				return false;
2872
+			}
2873
+		}
2874
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2875
+			[
2876
+				'EXM_key'   => $meta_key,
2877
+				'EXM_value' => $meta_value,
2878
+				'OBJ_ID'    => $this->ID(),
2879
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2880
+			]
2881
+		);
2882
+		$new_extra_meta->save();
2883
+		return true;
2884
+	}
2885
+
2886
+
2887
+	/**
2888
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2889
+	 * is specified, only deletes extra meta records with that value.
2890
+	 *
2891
+	 * @param string $meta_key
2892
+	 * @param mixed  $meta_value
2893
+	 * @return int|bool number of extra meta rows deleted
2894
+	 * @throws InvalidArgumentException
2895
+	 * @throws InvalidInterfaceException
2896
+	 * @throws InvalidDataTypeException
2897
+	 * @throws EE_Error
2898
+	 * @throws ReflectionException
2899
+	 */
2900
+	public function delete_extra_meta(string $meta_key, $meta_value = null)
2901
+	{
2902
+		$query_params = [
2903
+			[
2904
+				'EXM_key'  => $meta_key,
2905
+				'OBJ_ID'   => $this->ID(),
2906
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2907
+			],
2908
+		];
2909
+		if ($meta_value !== null) {
2910
+			$query_params[0]['EXM_value'] = $meta_value;
2911
+		}
2912
+		return EEM_Extra_Meta::instance()->delete($query_params);
2913
+	}
2914
+
2915
+
2916
+	/**
2917
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2918
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2919
+	 * You can specify $default is case you haven't found the extra meta
2920
+	 *
2921
+	 * @param string     $meta_key
2922
+	 * @param bool       $single
2923
+	 * @param mixed      $default if we don't find anything, what should we return?
2924
+	 * @param array|null $extra_where
2925
+	 * @return mixed single value if $single; array if ! $single
2926
+	 * @throws ReflectionException
2927
+	 * @throws EE_Error
2928
+	 */
2929
+	public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2930
+	{
2931
+		$query_params = [ $extra_where + ['EXM_key' => $meta_key] ];
2932
+		if ($single) {
2933
+			$result = $this->get_first_related('Extra_Meta', $query_params);
2934
+			if ($result instanceof EE_Extra_Meta) {
2935
+				return $result->value();
2936
+			}
2937
+		} else {
2938
+			$results = $this->get_many_related('Extra_Meta', $query_params);
2939
+			if ($results) {
2940
+				$values = [];
2941
+				foreach ($results as $result) {
2942
+					if ($result instanceof EE_Extra_Meta) {
2943
+						$values[ $result->ID() ] = $result->value();
2944
+					}
2945
+				}
2946
+				return $values;
2947
+			}
2948
+		}
2949
+		// if nothing discovered yet return default.
2950
+		return apply_filters(
2951
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2952
+			$default,
2953
+			$meta_key,
2954
+			$single,
2955
+			$this
2956
+		);
2957
+	}
2958
+
2959
+
2960
+	/**
2961
+	 * Returns a simple array of all the extra meta associated with this model object.
2962
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2963
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2964
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2965
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2966
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2967
+	 * finally the extra meta's value as each sub-value. (eg
2968
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2969
+	 *
2970
+	 * @param bool $one_of_each_key
2971
+	 * @return array
2972
+	 * @throws ReflectionException
2973
+	 * @throws InvalidArgumentException
2974
+	 * @throws InvalidInterfaceException
2975
+	 * @throws InvalidDataTypeException
2976
+	 * @throws EE_Error
2977
+	 */
2978
+	public function all_extra_meta_array(bool $one_of_each_key = true): array
2979
+	{
2980
+		$return_array = [];
2981
+		if ($one_of_each_key) {
2982
+			$extra_meta_objs = $this->get_many_related(
2983
+				'Extra_Meta',
2984
+				['group_by' => 'EXM_key']
2985
+			);
2986
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2987
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2988
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2989
+				}
2990
+			}
2991
+		} else {
2992
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2993
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2994
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2995
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2996
+						$return_array[ $extra_meta_obj->key() ] = [];
2997
+					}
2998
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2999
+				}
3000
+			}
3001
+		}
3002
+		return $return_array;
3003
+	}
3004
+
3005
+
3006
+	/**
3007
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
3008
+	 *
3009
+	 * @return string
3010
+	 * @throws ReflectionException
3011
+	 * @throws InvalidArgumentException
3012
+	 * @throws InvalidInterfaceException
3013
+	 * @throws InvalidDataTypeException
3014
+	 * @throws EE_Error
3015
+	 */
3016
+	public function name()
3017
+	{
3018
+		// find a field that's not a text field
3019
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3020
+		if ($field_we_can_use) {
3021
+			return $this->get($field_we_can_use->get_name());
3022
+		}
3023
+		$first_few_properties = $this->model_field_array();
3024
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3025
+		$name_parts = array();
3026
+		foreach ($first_few_properties as $name => $value) {
3027
+			$name_parts[] = "$name:$value";
3028
+		}
3029
+		return implode(',', $name_parts);
3030
+	}
3031
+
3032
+
3033
+	/**
3034
+	 * in_entity_map
3035
+	 * Checks if this model object has been proven to already be in the entity map
3036
+	 *
3037
+	 * @return boolean
3038
+	 * @throws ReflectionException
3039
+	 * @throws InvalidArgumentException
3040
+	 * @throws InvalidInterfaceException
3041
+	 * @throws InvalidDataTypeException
3042
+	 * @throws EE_Error
3043
+	 */
3044
+	public function in_entity_map()
3045
+	{
3046
+		// well, if we looked, did we find it in the entity map?
3047
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3048
+	}
3049
+
3050
+
3051
+	/**
3052
+	 * refresh_from_db
3053
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3054
+	 *
3055
+	 * @throws ReflectionException
3056
+	 * @throws InvalidArgumentException
3057
+	 * @throws InvalidInterfaceException
3058
+	 * @throws InvalidDataTypeException
3059
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3060
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3061
+	 */
3062
+	public function refresh_from_db()
3063
+	{
3064
+		if ($this->ID() && $this->in_entity_map()) {
3065
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3066
+		} else {
3067
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3068
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3069
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3070
+			// absolutely nothing in it for this ID
3071
+			if (WP_DEBUG) {
3072
+				throw new EE_Error(
3073
+					sprintf(
3074
+						esc_html__(
3075
+							'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.',
3076
+							'event_espresso'
3077
+						),
3078
+						$this->ID(),
3079
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3080
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3081
+					)
3082
+				);
3083
+			}
3084
+		}
3085
+	}
3086
+
3087
+
3088
+	/**
3089
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3090
+	 *
3091
+	 * @since 4.9.80.p
3092
+	 * @param EE_Model_Field_Base[] $fields
3093
+	 * @param string $new_value_sql
3094
+	 *      example: 'column_name=123',
3095
+	 *      or 'column_name=column_name+1',
3096
+	 *      or 'column_name= CASE
3097
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3098
+	 *          THEN `column_name` + 5
3099
+	 *          ELSE `column_name`
3100
+	 *      END'
3101
+	 *      Also updates $field on this model object with the latest value from the database.
3102
+	 * @return bool
3103
+	 * @throws EE_Error
3104
+	 * @throws InvalidArgumentException
3105
+	 * @throws InvalidDataTypeException
3106
+	 * @throws InvalidInterfaceException
3107
+	 * @throws ReflectionException
3108
+	 */
3109
+	protected function updateFieldsInDB($fields, $new_value_sql)
3110
+	{
3111
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3112
+		// if it wasn't even there to start off.
3113
+		if (! $this->ID()) {
3114
+			$this->save();
3115
+		}
3116
+		global $wpdb;
3117
+		if (empty($fields)) {
3118
+			throw new InvalidArgumentException(
3119
+				esc_html__(
3120
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3121
+					'event_espresso'
3122
+				)
3123
+			);
3124
+		}
3125
+		$first_field = reset($fields);
3126
+		$table_alias = $first_field->get_table_alias();
3127
+		foreach ($fields as $field) {
3128
+			if ($table_alias !== $field->get_table_alias()) {
3129
+				throw new InvalidArgumentException(
3130
+					sprintf(
3131
+						esc_html__(
3132
+							// @codingStandardsIgnoreStart
3133
+							'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.',
3134
+							// @codingStandardsIgnoreEnd
3135
+							'event_espresso'
3136
+						),
3137
+						$table_alias,
3138
+						$field->get_table_alias()
3139
+					)
3140
+				);
3141
+			}
3142
+		}
3143
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3144
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3145
+		$table_pk_value = $this->ID();
3146
+		$table_name = $table_obj->get_table_name();
3147
+		if ($table_obj instanceof EE_Secondary_Table) {
3148
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3149
+		} else {
3150
+			$table_pk_field_name = $table_obj->get_pk_column();
3151
+		}
3152
+
3153
+		$query =
3154
+			"UPDATE `{$table_name}`
3155 3155
             SET "
3156
-            . $new_value_sql
3157
-            . $wpdb->prepare(
3158
-                "
3156
+			. $new_value_sql
3157
+			. $wpdb->prepare(
3158
+				"
3159 3159
             WHERE `{$table_pk_field_name}` = %d;",
3160
-                $table_pk_value
3161
-            );
3162
-        $result = $wpdb->query($query);
3163
-        foreach ($fields as $field) {
3164
-            // If it was successful, we'd like to know the new value.
3165
-            // If it failed, we'd also like to know the new value.
3166
-            $new_value = $this->get_model()->get_var(
3167
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3168
-                    $this->get_model()->get_index_primary_key_string(
3169
-                        $this->model_field_array()
3170
-                    ),
3171
-                    array(
3172
-                        'default_where_conditions' => 'minimum',
3173
-                    )
3174
-                ),
3175
-                $field->get_name()
3176
-            );
3177
-            $this->set_from_db(
3178
-                $field->get_name(),
3179
-                $new_value
3180
-            );
3181
-        }
3182
-        return (bool) $result;
3183
-    }
3184
-
3185
-
3186
-    /**
3187
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3188
-     * Does not allow negative values, however.
3189
-     *
3190
-     * @since 4.9.80.p
3191
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3192
-     *                                   (positive or negative). One important gotcha: all these values must be
3193
-     *                                   on the same table (eg don't pass in one field for the posts table and
3194
-     *                                   another for the event meta table.)
3195
-     * @return bool
3196
-     * @throws EE_Error
3197
-     * @throws InvalidArgumentException
3198
-     * @throws InvalidDataTypeException
3199
-     * @throws InvalidInterfaceException
3200
-     * @throws ReflectionException
3201
-     */
3202
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3203
-    {
3204
-        global $wpdb;
3205
-        if (empty($fields_n_quantities)) {
3206
-            // No fields to update? Well sure, we updated them to that value just fine.
3207
-            return true;
3208
-        }
3209
-        $fields = [];
3210
-        $set_sql_statements = [];
3211
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3212
-            $field = $this->get_model()->field_settings_for($field_name, true);
3213
-            $fields[] = $field;
3214
-            $column_name = $field->get_table_column();
3215
-
3216
-            $abs_qty = absint($quantity);
3217
-            if ($quantity > 0) {
3218
-                // don't let the value be negative as often these fields are unsigned
3219
-                $set_sql_statements[] = $wpdb->prepare(
3220
-                    "`{$column_name}` = `{$column_name}` + %d",
3221
-                    $abs_qty
3222
-                );
3223
-            } else {
3224
-                $set_sql_statements[] = $wpdb->prepare(
3225
-                    "`{$column_name}` = CASE
3160
+				$table_pk_value
3161
+			);
3162
+		$result = $wpdb->query($query);
3163
+		foreach ($fields as $field) {
3164
+			// If it was successful, we'd like to know the new value.
3165
+			// If it failed, we'd also like to know the new value.
3166
+			$new_value = $this->get_model()->get_var(
3167
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3168
+					$this->get_model()->get_index_primary_key_string(
3169
+						$this->model_field_array()
3170
+					),
3171
+					array(
3172
+						'default_where_conditions' => 'minimum',
3173
+					)
3174
+				),
3175
+				$field->get_name()
3176
+			);
3177
+			$this->set_from_db(
3178
+				$field->get_name(),
3179
+				$new_value
3180
+			);
3181
+		}
3182
+		return (bool) $result;
3183
+	}
3184
+
3185
+
3186
+	/**
3187
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3188
+	 * Does not allow negative values, however.
3189
+	 *
3190
+	 * @since 4.9.80.p
3191
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3192
+	 *                                   (positive or negative). One important gotcha: all these values must be
3193
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3194
+	 *                                   another for the event meta table.)
3195
+	 * @return bool
3196
+	 * @throws EE_Error
3197
+	 * @throws InvalidArgumentException
3198
+	 * @throws InvalidDataTypeException
3199
+	 * @throws InvalidInterfaceException
3200
+	 * @throws ReflectionException
3201
+	 */
3202
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3203
+	{
3204
+		global $wpdb;
3205
+		if (empty($fields_n_quantities)) {
3206
+			// No fields to update? Well sure, we updated them to that value just fine.
3207
+			return true;
3208
+		}
3209
+		$fields = [];
3210
+		$set_sql_statements = [];
3211
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3212
+			$field = $this->get_model()->field_settings_for($field_name, true);
3213
+			$fields[] = $field;
3214
+			$column_name = $field->get_table_column();
3215
+
3216
+			$abs_qty = absint($quantity);
3217
+			if ($quantity > 0) {
3218
+				// don't let the value be negative as often these fields are unsigned
3219
+				$set_sql_statements[] = $wpdb->prepare(
3220
+					"`{$column_name}` = `{$column_name}` + %d",
3221
+					$abs_qty
3222
+				);
3223
+			} else {
3224
+				$set_sql_statements[] = $wpdb->prepare(
3225
+					"`{$column_name}` = CASE
3226 3226
                        WHEN (`{$column_name}` >= %d)
3227 3227
                        THEN `{$column_name}` - %d
3228 3228
                        ELSE 0
3229 3229
                     END",
3230
-                    $abs_qty,
3231
-                    $abs_qty
3232
-                );
3233
-            }
3234
-        }
3235
-        return $this->updateFieldsInDB(
3236
-            $fields,
3237
-            implode(', ', $set_sql_statements)
3238
-        );
3239
-    }
3240
-
3241
-
3242
-    /**
3243
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3244
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3245
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3246
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3247
-     * Otherwise returns false.
3248
-     *
3249
-     * @since 4.9.80.p
3250
-     * @param string $field_name_to_bump
3251
-     * @param string $field_name_affecting_total
3252
-     * @param string $limit_field_name
3253
-     * @param int    $quantity
3254
-     * @return bool
3255
-     * @throws EE_Error
3256
-     * @throws InvalidArgumentException
3257
-     * @throws InvalidDataTypeException
3258
-     * @throws InvalidInterfaceException
3259
-     * @throws ReflectionException
3260
-     */
3261
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3262
-    {
3263
-        global $wpdb;
3264
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3265
-        $column_name = $field->get_table_column();
3266
-
3267
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3268
-        $column_affecting_total = $field_affecting_total->get_table_column();
3269
-
3270
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3271
-        $limiting_column = $limiting_field->get_table_column();
3272
-        return $this->updateFieldsInDB(
3273
-            [$field],
3274
-            $wpdb->prepare(
3275
-                "`{$column_name}` =
3230
+					$abs_qty,
3231
+					$abs_qty
3232
+				);
3233
+			}
3234
+		}
3235
+		return $this->updateFieldsInDB(
3236
+			$fields,
3237
+			implode(', ', $set_sql_statements)
3238
+		);
3239
+	}
3240
+
3241
+
3242
+	/**
3243
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3244
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3245
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3246
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3247
+	 * Otherwise returns false.
3248
+	 *
3249
+	 * @since 4.9.80.p
3250
+	 * @param string $field_name_to_bump
3251
+	 * @param string $field_name_affecting_total
3252
+	 * @param string $limit_field_name
3253
+	 * @param int    $quantity
3254
+	 * @return bool
3255
+	 * @throws EE_Error
3256
+	 * @throws InvalidArgumentException
3257
+	 * @throws InvalidDataTypeException
3258
+	 * @throws InvalidInterfaceException
3259
+	 * @throws ReflectionException
3260
+	 */
3261
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3262
+	{
3263
+		global $wpdb;
3264
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3265
+		$column_name = $field->get_table_column();
3266
+
3267
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3268
+		$column_affecting_total = $field_affecting_total->get_table_column();
3269
+
3270
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3271
+		$limiting_column = $limiting_field->get_table_column();
3272
+		return $this->updateFieldsInDB(
3273
+			[$field],
3274
+			$wpdb->prepare(
3275
+				"`{$column_name}` =
3276 3276
             CASE
3277 3277
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3278 3278
                THEN `{$column_name}` + %d
3279 3279
                ELSE `{$column_name}`
3280 3280
             END",
3281
-                $quantity,
3282
-                EE_INF_IN_DB,
3283
-                $quantity
3284
-            )
3285
-        );
3286
-    }
3287
-
3288
-
3289
-    /**
3290
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3291
-     * (probably a bad assumption they have made, oh well)
3292
-     *
3293
-     * @return string
3294
-     */
3295
-    public function __toString()
3296
-    {
3297
-        try {
3298
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3299
-        } catch (Exception $e) {
3300
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3301
-            return '';
3302
-        }
3303
-    }
3304
-
3305
-
3306
-    /**
3307
-     * Clear related model objects if they're already in the DB, because otherwise when we
3308
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3309
-     * This means if we have made changes to those related model objects, and want to unserialize
3310
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3311
-     * Instead, those related model objects should be directly serialized and stored.
3312
-     * Eg, the following won't work:
3313
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3314
-     * $att = $reg->attendee();
3315
-     * $att->set( 'ATT_fname', 'Dirk' );
3316
-     * update_option( 'my_option', serialize( $reg ) );
3317
-     * //END REQUEST
3318
-     * //START NEXT REQUEST
3319
-     * $reg = get_option( 'my_option' );
3320
-     * $reg->attendee()->save();
3321
-     * And would need to be replace with:
3322
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3323
-     * $att = $reg->attendee();
3324
-     * $att->set( 'ATT_fname', 'Dirk' );
3325
-     * update_option( 'my_option', serialize( $reg ) );
3326
-     * //END REQUEST
3327
-     * //START NEXT REQUEST
3328
-     * $att = get_option( 'my_option' );
3329
-     * $att->save();
3330
-     *
3331
-     * @return array
3332
-     * @throws ReflectionException
3333
-     * @throws InvalidArgumentException
3334
-     * @throws InvalidInterfaceException
3335
-     * @throws InvalidDataTypeException
3336
-     * @throws EE_Error
3337
-     */
3338
-    public function __sleep()
3339
-    {
3340
-        $model = $this->get_model();
3341
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3342
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3343
-                $classname = 'EE_' . $model->get_this_model_name();
3344
-                if (
3345
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3346
-                    && $this->get_one_from_cache($relation_name)->ID()
3347
-                ) {
3348
-                    $this->clear_cache(
3349
-                        $relation_name,
3350
-                        $this->get_one_from_cache($relation_name)->ID()
3351
-                    );
3352
-                }
3353
-            }
3354
-        }
3355
-        $this->_props_n_values_provided_in_constructor = array();
3356
-        $properties_to_serialize = get_object_vars($this);
3357
-        // don't serialize the model. It's big and that risks recursion
3358
-        unset($properties_to_serialize['_model']);
3359
-        return array_keys($properties_to_serialize);
3360
-    }
3361
-
3362
-
3363
-    /**
3364
-     * restore _props_n_values_provided_in_constructor
3365
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3366
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3367
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3368
-     */
3369
-    public function __wakeup()
3370
-    {
3371
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3372
-    }
3373
-
3374
-
3375
-    /**
3376
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3377
-     * distinct with the clone host instance are also cloned.
3378
-     */
3379
-    public function __clone()
3380
-    {
3381
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3382
-        foreach ($this->_fields as $field => $value) {
3383
-            if ($value instanceof DateTime) {
3384
-                $this->_fields[ $field ] = clone $value;
3385
-            }
3386
-        }
3387
-    }
3281
+				$quantity,
3282
+				EE_INF_IN_DB,
3283
+				$quantity
3284
+			)
3285
+		);
3286
+	}
3287
+
3288
+
3289
+	/**
3290
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3291
+	 * (probably a bad assumption they have made, oh well)
3292
+	 *
3293
+	 * @return string
3294
+	 */
3295
+	public function __toString()
3296
+	{
3297
+		try {
3298
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3299
+		} catch (Exception $e) {
3300
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3301
+			return '';
3302
+		}
3303
+	}
3304
+
3305
+
3306
+	/**
3307
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3308
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3309
+	 * This means if we have made changes to those related model objects, and want to unserialize
3310
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3311
+	 * Instead, those related model objects should be directly serialized and stored.
3312
+	 * Eg, the following won't work:
3313
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3314
+	 * $att = $reg->attendee();
3315
+	 * $att->set( 'ATT_fname', 'Dirk' );
3316
+	 * update_option( 'my_option', serialize( $reg ) );
3317
+	 * //END REQUEST
3318
+	 * //START NEXT REQUEST
3319
+	 * $reg = get_option( 'my_option' );
3320
+	 * $reg->attendee()->save();
3321
+	 * And would need to be replace with:
3322
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3323
+	 * $att = $reg->attendee();
3324
+	 * $att->set( 'ATT_fname', 'Dirk' );
3325
+	 * update_option( 'my_option', serialize( $reg ) );
3326
+	 * //END REQUEST
3327
+	 * //START NEXT REQUEST
3328
+	 * $att = get_option( 'my_option' );
3329
+	 * $att->save();
3330
+	 *
3331
+	 * @return array
3332
+	 * @throws ReflectionException
3333
+	 * @throws InvalidArgumentException
3334
+	 * @throws InvalidInterfaceException
3335
+	 * @throws InvalidDataTypeException
3336
+	 * @throws EE_Error
3337
+	 */
3338
+	public function __sleep()
3339
+	{
3340
+		$model = $this->get_model();
3341
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3342
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3343
+				$classname = 'EE_' . $model->get_this_model_name();
3344
+				if (
3345
+					$this->get_one_from_cache($relation_name) instanceof $classname
3346
+					&& $this->get_one_from_cache($relation_name)->ID()
3347
+				) {
3348
+					$this->clear_cache(
3349
+						$relation_name,
3350
+						$this->get_one_from_cache($relation_name)->ID()
3351
+					);
3352
+				}
3353
+			}
3354
+		}
3355
+		$this->_props_n_values_provided_in_constructor = array();
3356
+		$properties_to_serialize = get_object_vars($this);
3357
+		// don't serialize the model. It's big and that risks recursion
3358
+		unset($properties_to_serialize['_model']);
3359
+		return array_keys($properties_to_serialize);
3360
+	}
3361
+
3362
+
3363
+	/**
3364
+	 * restore _props_n_values_provided_in_constructor
3365
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3366
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3367
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3368
+	 */
3369
+	public function __wakeup()
3370
+	{
3371
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3372
+	}
3373
+
3374
+
3375
+	/**
3376
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3377
+	 * distinct with the clone host instance are also cloned.
3378
+	 */
3379
+	public function __clone()
3380
+	{
3381
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3382
+		foreach ($this->_fields as $field => $value) {
3383
+			if ($value instanceof DateTime) {
3384
+				$this->_fields[ $field ] = clone $value;
3385
+			}
3386
+		}
3387
+	}
3388 3388
 }
Please login to merge, or discard this patch.
Spacing   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
         $this->_props_n_values_provided_in_constructor = $fieldValues;
151 151
         // verify client code has not passed any invalid field names
152 152
         foreach ($fieldValues as $field_name => $field_value) {
153
-            if (! isset($model_fields[ $field_name ])) {
153
+            if ( ! isset($model_fields[$field_name])) {
154 154
                 throw new EE_Error(
155 155
                     sprintf(
156 156
                         esc_html__(
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
         $date_format = null;
169 169
         $time_format = null;
170 170
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
171
-        if (! empty($date_formats) && is_array($date_formats)) {
171
+        if ( ! empty($date_formats) && is_array($date_formats)) {
172 172
             [$date_format, $time_format] = $date_formats;
173 173
         }
174 174
         $this->set_date_format($date_format);
@@ -179,28 +179,28 @@  discard block
 block discarded – undo
179 179
                 // client code has indicated these field values are from the database
180 180
                     $this->set_from_db(
181 181
                         $fieldName,
182
-                        $fieldValues[ $fieldName ] ?? null
182
+                        $fieldValues[$fieldName] ?? null
183 183
                     );
184 184
             } else {
185 185
                 // we're constructing a brand new instance of the model object.
186 186
                 // Generally, this means we'll need to do more field validation
187 187
                     $this->set(
188 188
                     $fieldName,
189
-                    $fieldValues[ $fieldName ] ?? null,
189
+                    $fieldValues[$fieldName] ?? null,
190 190
                     true
191 191
                 );
192 192
             }
193 193
         }
194 194
         // remember in entity mapper
195
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
196 196
             $model->add_to_entity_map($this);
197 197
         }
198 198
         // setup all the relations
199 199
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200 200
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
201
+                $this->_model_relations[$relation_name] = null;
202 202
             } else {
203
-                $this->_model_relations[ $relation_name ] = array();
203
+                $this->_model_relations[$relation_name] = array();
204 204
             }
205 205
         }
206 206
         /**
@@ -252,10 +252,10 @@  discard block
 block discarded – undo
252 252
     public function get_original($field_name)
253 253
     {
254 254
         if (
255
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
256 256
             && $field_settings = $this->get_model()->field_settings_for($field_name)
257 257
         ) {
258
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
259 259
         }
260 260
         return null;
261 261
     }
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
         // then don't do anything
293 293
         if (
294 294
             ! $use_default
295
-            && $this->_fields[ $field_name ] === $field_value
295
+            && $this->_fields[$field_name] === $field_value
296 296
             && $this->ID()
297 297
         ) {
298 298
             return;
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
         $model = $this->get_model();
301 301
         $this->_has_changes = true;
302 302
         $field_obj = $model->field_settings_for($field_name);
303
-        if (! $field_obj instanceof EE_Model_Field_Base) {
303
+        if ( ! $field_obj instanceof EE_Model_Field_Base) {
304 304
             throw new EE_Error(
305 305
                 sprintf(
306 306
                     esc_html__(
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
         $holder_of_value = $field_obj->prepare_for_set($field_value);
321 321
         // should the value be null?
322 322
         if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
323
-            $this->_fields[ $field_name ] = $field_obj->get_default_value();
323
+            $this->_fields[$field_name] = $field_obj->get_default_value();
324 324
             /**
325 325
              * To save having to refactor all the models, if a default value is used for a
326 326
              * EE_Datetime_Field, and that value is not null nor is it a DateTime
@@ -331,15 +331,15 @@  discard block
 block discarded – undo
331 331
              */
332 332
             if (
333 333
                 $field_obj instanceof EE_Datetime_Field
334
-                && $this->_fields[ $field_name ] !== null
335
-                && ! $this->_fields[ $field_name ] instanceof DateTime
334
+                && $this->_fields[$field_name] !== null
335
+                && ! $this->_fields[$field_name] instanceof DateTime
336 336
             ) {
337
-                empty($this->_fields[ $field_name ])
337
+                empty($this->_fields[$field_name])
338 338
                     ? $this->set($field_name, time())
339
-                    : $this->set($field_name, $this->_fields[ $field_name ]);
339
+                    : $this->set($field_name, $this->_fields[$field_name]);
340 340
             }
341 341
         } else {
342
-            $this->_fields[ $field_name ] = $holder_of_value;
342
+            $this->_fields[$field_name] = $holder_of_value;
343 343
         }
344 344
         // if we're not in the constructor...
345 345
         // now check if what we set was a primary key
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
             } else {
402 402
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
403 403
             }
404
-            $this->_fields[ $field_name ] = $field_value;
404
+            $this->_fields[$field_name] = $field_value;
405 405
             $this->_clear_cached_property($field_name);
406 406
         }
407 407
     }
@@ -427,8 +427,8 @@  discard block
 block discarded – undo
427 427
      */
428 428
     public function getCustomSelect($alias)
429 429
     {
430
-        return isset($this->custom_selection_results[ $alias ])
431
-            ? $this->custom_selection_results[ $alias ]
430
+        return isset($this->custom_selection_results[$alias])
431
+            ? $this->custom_selection_results[$alias]
432 432
             : null;
433 433
     }
434 434
 
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
         foreach ($model_fields as $field_name => $field_obj) {
516 516
             if ($field_obj instanceof EE_Datetime_Field) {
517 517
                 $field_obj->set_timezone($this->_timezone);
518
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
519
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
518
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
519
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
520 520
                 }
521 521
             }
522 522
         }
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
      */
577 577
     public function get_format($full = true)
578 578
     {
579
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
579
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
580 580
     }
581 581
 
582 582
 
@@ -602,11 +602,11 @@  discard block
 block discarded – undo
602 602
     public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
603 603
     {
604 604
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
605
-        if (! $object_to_cache instanceof EE_Base_Class) {
605
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
606 606
             return false;
607 607
         }
608 608
         // also get "how" the object is related, or throw an error
609
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
609
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
610 610
             throw new EE_Error(
611 611
                 sprintf(
612 612
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -620,38 +620,38 @@  discard block
 block discarded – undo
620 620
             // if it's a "belongs to" relationship, then there's only one related model object
621 621
             // eg, if this is a registration, there's only 1 attendee for it
622 622
             // so for these model objects just set it to be cached
623
-            $this->_model_relations[ $relationName ] = $object_to_cache;
623
+            $this->_model_relations[$relationName] = $object_to_cache;
624 624
             $return = true;
625 625
         } else {
626 626
             // otherwise, this is the "many" side of a one to many relationship,
627 627
             // so we'll add the object to the array of related objects for that type.
628 628
             // eg: if this is an event, there are many registrations for that event,
629 629
             // so we cache the registrations in an array
630
-            if (! is_array($this->_model_relations[ $relationName ])) {
630
+            if ( ! is_array($this->_model_relations[$relationName])) {
631 631
                 // if for some reason, the cached item is a model object,
632 632
                 // then stick that in the array, otherwise start with an empty array
633
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
633
+                $this->_model_relations[$relationName] = $this->_model_relations[$relationName]
634 634
                                                            instanceof
635 635
                                                            EE_Base_Class
636
-                    ? array($this->_model_relations[ $relationName ]) : array();
636
+                    ? array($this->_model_relations[$relationName]) : array();
637 637
             }
638 638
             // first check for a cache_id which is normally empty
639
-            if (! empty($cache_id)) {
639
+            if ( ! empty($cache_id)) {
640 640
                 // if the cache_id exists, then it means we are purposely trying to cache this
641 641
                 // with a known key that can then be used to retrieve the object later on
642
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
642
+                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
643 643
                 $return = $cache_id;
644 644
             } elseif ($object_to_cache->ID()) {
645 645
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
646
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
646
+                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
647 647
                 $return = $object_to_cache->ID();
648 648
             } else {
649 649
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
650
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
650
+                $this->_model_relations[$relationName][] = $object_to_cache;
651 651
                 // move the internal pointer to the end of the array
652
-                end($this->_model_relations[ $relationName ]);
652
+                end($this->_model_relations[$relationName]);
653 653
                 // and grab the key so that we can return it
654
-                $return = key($this->_model_relations[ $relationName ]);
654
+                $return = key($this->_model_relations[$relationName]);
655 655
             }
656 656
         }
657 657
         return $return;
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
         // first make sure this property exists
678 678
         $this->get_model()->field_settings_for($fieldname);
679 679
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
680
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
680
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
681 681
     }
682 682
 
683 683
 
@@ -706,9 +706,9 @@  discard block
 block discarded – undo
706 706
         $model = $this->get_model();
707 707
         $model->field_settings_for($fieldname);
708 708
         $cache_type = $pretty ? 'pretty' : 'standard';
709
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
710
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
711
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
709
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
710
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
711
+            return $this->_cached_properties[$fieldname][$cache_type];
712 712
         }
713 713
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
714 714
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -736,12 +736,12 @@  discard block
 block discarded – undo
736 736
         if ($field_obj instanceof EE_Datetime_Field) {
737 737
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
738 738
         }
739
-        if (! isset($this->_fields[ $fieldname ])) {
740
-            $this->_fields[ $fieldname ] = null;
739
+        if ( ! isset($this->_fields[$fieldname])) {
740
+            $this->_fields[$fieldname] = null;
741 741
         }
742 742
         return $pretty
743
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
744
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
743
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
744
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
745 745
     }
746 746
 
747 747
 
@@ -797,8 +797,8 @@  discard block
 block discarded – undo
797 797
      */
798 798
     protected function _clear_cached_property($property_name)
799 799
     {
800
-        if (isset($this->_cached_properties[ $property_name ])) {
801
-            unset($this->_cached_properties[ $property_name ]);
800
+        if (isset($this->_cached_properties[$property_name])) {
801
+            unset($this->_cached_properties[$property_name]);
802 802
         }
803 803
     }
804 804
 
@@ -850,7 +850,7 @@  discard block
 block discarded – undo
850 850
     {
851 851
         $relationship_to_model = $this->get_model()->related_settings_for($relationName);
852 852
         $index_in_cache = '';
853
-        if (! $relationship_to_model) {
853
+        if ( ! $relationship_to_model) {
854 854
             throw new EE_Error(
855 855
                 sprintf(
856 856
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -861,10 +861,10 @@  discard block
 block discarded – undo
861 861
         }
862 862
         if ($clear_all) {
863 863
             $obj_removed = true;
864
-            $this->_model_relations[ $relationName ] = null;
864
+            $this->_model_relations[$relationName] = null;
865 865
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
866
-            $obj_removed = $this->_model_relations[ $relationName ];
867
-            $this->_model_relations[ $relationName ] = null;
866
+            $obj_removed = $this->_model_relations[$relationName];
867
+            $this->_model_relations[$relationName] = null;
868 868
         } else {
869 869
             if (
870 870
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -872,12 +872,12 @@  discard block
 block discarded – undo
872 872
             ) {
873 873
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
874 874
                 if (
875
-                    is_array($this->_model_relations[ $relationName ])
876
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
875
+                    is_array($this->_model_relations[$relationName])
876
+                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
877 877
                 ) {
878 878
                     $index_found_at = null;
879 879
                     // find this object in the array even though it has a different key
880
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
880
+                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
881 881
                         /** @noinspection TypeUnsafeComparisonInspection */
882 882
                         if (
883 883
                             $obj instanceof EE_Base_Class
@@ -911,9 +911,9 @@  discard block
 block discarded – undo
911 911
             }
912 912
             // supposedly we've found it. But it could just be that the client code
913 913
             // provided a bad index/object
914
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
915
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
916
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
914
+            if (isset($this->_model_relations[$relationName][$index_in_cache])) {
915
+                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
916
+                unset($this->_model_relations[$relationName][$index_in_cache]);
917 917
             } else {
918 918
                 // that thing was never cached anyways.
919 919
                 $obj_removed = null;
@@ -944,7 +944,7 @@  discard block
 block discarded – undo
944 944
         $current_cache_id = ''
945 945
     ) {
946 946
         // verify that incoming object is of the correct type
947
-        $obj_class = 'EE_' . $relationName;
947
+        $obj_class = 'EE_'.$relationName;
948 948
         if ($newly_saved_object instanceof $obj_class) {
949 949
             /* @type EE_Base_Class $newly_saved_object */
950 950
             // now get the type of relation
@@ -952,18 +952,18 @@  discard block
 block discarded – undo
952 952
             // if this is a 1:1 relationship
953 953
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
954 954
                 // then just replace the cached object with the newly saved object
955
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
955
+                $this->_model_relations[$relationName] = $newly_saved_object;
956 956
                 return true;
957 957
                 // or if it's some kind of sordid feral polyamorous relationship...
958 958
             }
959 959
             if (
960
-                is_array($this->_model_relations[ $relationName ])
961
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
960
+                is_array($this->_model_relations[$relationName])
961
+                && isset($this->_model_relations[$relationName][$current_cache_id])
962 962
             ) {
963 963
                 // then remove the current cached item
964
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
964
+                unset($this->_model_relations[$relationName][$current_cache_id]);
965 965
                 // and cache the newly saved object using it's new ID
966
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
966
+                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
967 967
                 return true;
968 968
             }
969 969
         }
@@ -980,8 +980,8 @@  discard block
 block discarded – undo
980 980
      */
981 981
     public function get_one_from_cache($relationName)
982 982
     {
983
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
984
-            ? $this->_model_relations[ $relationName ]
983
+        $cached_array_or_object = isset($this->_model_relations[$relationName])
984
+            ? $this->_model_relations[$relationName]
985 985
             : null;
986 986
         if (is_array($cached_array_or_object)) {
987 987
             return array_shift($cached_array_or_object);
@@ -1004,7 +1004,7 @@  discard block
 block discarded – undo
1004 1004
      */
1005 1005
     public function get_all_from_cache($relationName)
1006 1006
     {
1007
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
1007
+        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
1008 1008
         // if the result is not an array, but exists, make it an array
1009 1009
         $objects = is_array($objects) ? $objects : array($objects);
1010 1010
         // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
@@ -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
 
@@ -1476,7 +1476,7 @@  discard block
 block discarded – undo
1476 1476
      */
1477 1477
     public function get_i18n_datetime($field_name, $format = '')
1478 1478
     {
1479
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1479
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1480 1480
         return date_i18n(
1481 1481
             $format,
1482 1482
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1588,21 +1588,21 @@  discard block
 block discarded – undo
1588 1588
         $field->set_time_format($this->_tm_frmt);
1589 1589
         switch ($what) {
1590 1590
             case 'T':
1591
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1591
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_time(
1592 1592
                     $datetime_value,
1593
-                    $this->_fields[ $field_name ]
1593
+                    $this->_fields[$field_name]
1594 1594
                 );
1595 1595
                 $this->_has_changes = true;
1596 1596
                 break;
1597 1597
             case 'D':
1598
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1598
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_date(
1599 1599
                     $datetime_value,
1600
-                    $this->_fields[ $field_name ]
1600
+                    $this->_fields[$field_name]
1601 1601
                 );
1602 1602
                 $this->_has_changes = true;
1603 1603
                 break;
1604 1604
             case 'B':
1605
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1605
+                $this->_fields[$field_name] = $field->prepare_for_set($datetime_value);
1606 1606
                 $this->_has_changes = true;
1607 1607
                 break;
1608 1608
         }
@@ -1645,7 +1645,7 @@  discard block
 block discarded – undo
1645 1645
         $this->set_timezone($timezone);
1646 1646
         $fn = (array) $field_name;
1647 1647
         $args = array_merge($fn, (array) $args);
1648
-        if (! method_exists($this, $callback)) {
1648
+        if ( ! method_exists($this, $callback)) {
1649 1649
             throw new EE_Error(
1650 1650
                 sprintf(
1651 1651
                     esc_html__(
@@ -1657,7 +1657,7 @@  discard block
 block discarded – undo
1657 1657
             );
1658 1658
         }
1659 1659
         $args = (array) $args;
1660
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1660
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1661 1661
         $this->set_timezone($original_timezone);
1662 1662
         return $return;
1663 1663
     }
@@ -1772,8 +1772,8 @@  discard block
 block discarded – undo
1772 1772
     {
1773 1773
         $model = $this->get_model();
1774 1774
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1775
-            if (! empty($this->_model_relations[ $relation_name ])) {
1776
-                $related_objects = $this->_model_relations[ $relation_name ];
1775
+            if ( ! empty($this->_model_relations[$relation_name])) {
1776
+                $related_objects = $this->_model_relations[$relation_name];
1777 1777
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1778 1778
                     // this relation only stores a single model object, not an array
1779 1779
                     // but let's make it consistent
@@ -1832,7 +1832,7 @@  discard block
 block discarded – undo
1832 1832
             $this->set($column, $value);
1833 1833
         }
1834 1834
         // no changes ? then don't do anything
1835
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1835
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1836 1836
             return 0;
1837 1837
         }
1838 1838
         /**
@@ -1842,7 +1842,7 @@  discard block
 block discarded – undo
1842 1842
          * @param EE_Base_Class $model_object the model object about to be saved.
1843 1843
          */
1844 1844
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1845
-        if (! $this->allow_persist()) {
1845
+        if ( ! $this->allow_persist()) {
1846 1846
             return 0;
1847 1847
         }
1848 1848
         // now get current attribute values
@@ -1857,10 +1857,10 @@  discard block
 block discarded – undo
1857 1857
         if ($model->has_primary_key_field()) {
1858 1858
             if ($model->get_primary_key_field()->is_auto_increment()) {
1859 1859
                 // ok check if it's set, if so: update; if not, insert
1860
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1860
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1861 1861
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1862 1862
                 } else {
1863
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1863
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1864 1864
                     $results = $model->insert($save_cols_n_values);
1865 1865
                     if ($results) {
1866 1866
                         // if successful, set the primary key
@@ -1870,7 +1870,7 @@  discard block
 block discarded – undo
1870 1870
                         // will get added to the mapper before we can add this one!
1871 1871
                         // but if we just avoid using the SET method, all that headache can be avoided
1872 1872
                         $pk_field_name = $model->primary_key_name();
1873
-                        $this->_fields[ $pk_field_name ] = $results;
1873
+                        $this->_fields[$pk_field_name] = $results;
1874 1874
                         $this->_clear_cached_property($pk_field_name);
1875 1875
                         $model->add_to_entity_map($this);
1876 1876
                         $this->_update_cached_related_model_objs_fks();
@@ -1887,8 +1887,8 @@  discard block
 block discarded – undo
1887 1887
                                     'event_espresso'
1888 1888
                                 ),
1889 1889
                                 get_class($this),
1890
-                                get_class($model) . '::instance()->add_to_entity_map()',
1891
-                                get_class($model) . '::instance()->get_one_by_ID()',
1890
+                                get_class($model).'::instance()->add_to_entity_map()',
1891
+                                get_class($model).'::instance()->get_one_by_ID()',
1892 1892
                                 '<br />'
1893 1893
                             )
1894 1894
                         );
@@ -1990,27 +1990,27 @@  discard block
 block discarded – undo
1990 1990
     public function save_new_cached_related_model_objs()
1991 1991
     {
1992 1992
         // make sure this has been saved
1993
-        if (! $this->ID()) {
1993
+        if ( ! $this->ID()) {
1994 1994
             $id = $this->save();
1995 1995
         } else {
1996 1996
             $id = $this->ID();
1997 1997
         }
1998 1998
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1999 1999
         foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
2000
-            if ($this->_model_relations[ $relationName ]) {
2000
+            if ($this->_model_relations[$relationName]) {
2001 2001
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2002 2002
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2003 2003
                 /* @var $related_model_obj EE_Base_Class */
2004 2004
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
2005 2005
                     // add a relation to that relation type (which saves the appropriate thing in the process)
2006 2006
                     // but ONLY if it DOES NOT exist in the DB
2007
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2007
+                    $related_model_obj = $this->_model_relations[$relationName];
2008 2008
                     // if( ! $related_model_obj->ID()){
2009 2009
                     $this->_add_relation_to($related_model_obj, $relationName);
2010 2010
                     $related_model_obj->save_new_cached_related_model_objs();
2011 2011
                     // }
2012 2012
                 } else {
2013
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2013
+                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
2014 2014
                         // add a relation to that relation type (which saves the appropriate thing in the process)
2015 2015
                         // but ONLY if it DOES NOT exist in the DB
2016 2016
                         // if( ! $related_model_obj->ID()){
@@ -2037,7 +2037,7 @@  discard block
 block discarded – undo
2037 2037
      */
2038 2038
     public function get_model()
2039 2039
     {
2040
-        if (! $this->_model) {
2040
+        if ( ! $this->_model) {
2041 2041
             $modelName = self::_get_model_classname(get_class($this));
2042 2042
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2043 2043
         } else {
@@ -2063,9 +2063,9 @@  discard block
 block discarded – undo
2063 2063
         $primary_id_ref = self::_get_primary_key_name($classname);
2064 2064
         if (
2065 2065
             array_key_exists($primary_id_ref, $props_n_values)
2066
-            && ! empty($props_n_values[ $primary_id_ref ])
2066
+            && ! empty($props_n_values[$primary_id_ref])
2067 2067
         ) {
2068
-            $id = $props_n_values[ $primary_id_ref ];
2068
+            $id = $props_n_values[$primary_id_ref];
2069 2069
             return self::_get_model($classname)->get_from_entity_map($id);
2070 2070
         }
2071 2071
         return false;
@@ -2100,10 +2100,10 @@  discard block
 block discarded – undo
2100 2100
             $primary_id_ref = self::_get_primary_key_name($classname);
2101 2101
             if (
2102 2102
                 array_key_exists($primary_id_ref, $props_n_values)
2103
-                && ! empty($props_n_values[ $primary_id_ref ])
2103
+                && ! empty($props_n_values[$primary_id_ref])
2104 2104
             ) {
2105 2105
                 $existing = $model->get_one_by_ID(
2106
-                    $props_n_values[ $primary_id_ref ]
2106
+                    $props_n_values[$primary_id_ref]
2107 2107
                 );
2108 2108
             }
2109 2109
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2115,7 +2115,7 @@  discard block
 block discarded – undo
2115 2115
         }
2116 2116
         if ($existing) {
2117 2117
             // set date formats if present before setting values
2118
-            if (! empty($date_formats) && is_array($date_formats)) {
2118
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2119 2119
                 $existing->set_date_format($date_formats[0]);
2120 2120
                 $existing->set_time_format($date_formats[1]);
2121 2121
             } else {
@@ -2148,7 +2148,7 @@  discard block
 block discarded – undo
2148 2148
     protected static function _get_model($classname, $timezone = null)
2149 2149
     {
2150 2150
         // find model for this class
2151
-        if (! $classname) {
2151
+        if ( ! $classname) {
2152 2152
             throw new EE_Error(
2153 2153
                 sprintf(
2154 2154
                     esc_html__(
@@ -2196,7 +2196,7 @@  discard block
 block discarded – undo
2196 2196
     {
2197 2197
         return strpos((string) $model_name, 'EE_') === 0
2198 2198
             ? str_replace('EE_', 'EEM_', $model_name)
2199
-            : 'EEM_' . $model_name;
2199
+            : 'EEM_'.$model_name;
2200 2200
     }
2201 2201
 
2202 2202
 
@@ -2213,7 +2213,7 @@  discard block
 block discarded – undo
2213 2213
      */
2214 2214
     protected static function _get_primary_key_name($classname = null)
2215 2215
     {
2216
-        if (! $classname) {
2216
+        if ( ! $classname) {
2217 2217
             throw new EE_Error(
2218 2218
                 sprintf(
2219 2219
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2243,7 +2243,7 @@  discard block
 block discarded – undo
2243 2243
         $model = $this->get_model();
2244 2244
         // now that we know the name of the variable, use a variable variable to get its value and return its
2245 2245
         if ($model->has_primary_key_field()) {
2246
-            return $this->_fields[ $model->primary_key_name() ];
2246
+            return $this->_fields[$model->primary_key_name()];
2247 2247
         }
2248 2248
         return $model->get_index_primary_key_string($this->_fields);
2249 2249
     }
@@ -2317,7 +2317,7 @@  discard block
 block discarded – undo
2317 2317
             }
2318 2318
         } else {
2319 2319
             // this thing doesn't exist in the DB,  so just cache it
2320
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2320
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2321 2321
                 throw new EE_Error(
2322 2322
                     sprintf(
2323 2323
                         esc_html__(
@@ -2482,7 +2482,7 @@  discard block
 block discarded – undo
2482 2482
             } else {
2483 2483
                 // did we already cache the result of this query?
2484 2484
                 $cached_results = $this->get_all_from_cache($relationName);
2485
-                if (! $cached_results) {
2485
+                if ( ! $cached_results) {
2486 2486
                     $related_model_objects = $this->get_model()->get_all_related(
2487 2487
                         $this,
2488 2488
                         $relationName,
@@ -2593,7 +2593,7 @@  discard block
 block discarded – undo
2593 2593
             } else {
2594 2594
                 // first, check if we've already cached the result of this query
2595 2595
                 $cached_result = $this->get_one_from_cache($relationName);
2596
-                if (! $cached_result) {
2596
+                if ( ! $cached_result) {
2597 2597
                     $related_model_object = $model->get_first_related(
2598 2598
                         $this,
2599 2599
                         $relationName,
@@ -2617,7 +2617,7 @@  discard block
 block discarded – undo
2617 2617
             }
2618 2618
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2619 2619
             // just get what's cached on this object
2620
-            if (! $related_model_object) {
2620
+            if ( ! $related_model_object) {
2621 2621
                 $related_model_object = $this->get_one_from_cache($relationName);
2622 2622
             }
2623 2623
         }
@@ -2699,7 +2699,7 @@  discard block
 block discarded – undo
2699 2699
      */
2700 2700
     public function is_set($field_name)
2701 2701
     {
2702
-        return isset($this->_fields[ $field_name ]);
2702
+        return isset($this->_fields[$field_name]);
2703 2703
     }
2704 2704
 
2705 2705
 
@@ -2715,7 +2715,7 @@  discard block
 block discarded – undo
2715 2715
     {
2716 2716
         foreach ((array) $properties as $property_name) {
2717 2717
             // first make sure this property exists
2718
-            if (! $this->_fields[ $property_name ]) {
2718
+            if ( ! $this->_fields[$property_name]) {
2719 2719
                 throw new EE_Error(
2720 2720
                     sprintf(
2721 2721
                         esc_html__(
@@ -2747,7 +2747,7 @@  discard block
 block discarded – undo
2747 2747
         $properties = array();
2748 2748
         // remove prepended underscore
2749 2749
         foreach ($fields as $field_name => $settings) {
2750
-            $properties[ $field_name ] = $this->get($field_name);
2750
+            $properties[$field_name] = $this->get($field_name);
2751 2751
         }
2752 2752
         return $properties;
2753 2753
     }
@@ -2784,7 +2784,7 @@  discard block
 block discarded – undo
2784 2784
     {
2785 2785
         $className = get_class($this);
2786 2786
         $tagName = "FHEE__{$className}__{$methodName}";
2787
-        if (! has_filter($tagName)) {
2787
+        if ( ! has_filter($tagName)) {
2788 2788
             throw new EE_Error(
2789 2789
                 sprintf(
2790 2790
                     esc_html__(
@@ -2829,7 +2829,7 @@  discard block
 block discarded – undo
2829 2829
             $query_params[0]['EXM_value'] = $meta_value;
2830 2830
         }
2831 2831
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2832
-        if (! $existing_rows_like_that) {
2832
+        if ( ! $existing_rows_like_that) {
2833 2833
             return $this->add_extra_meta($meta_key, $meta_value);
2834 2834
         }
2835 2835
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2928,7 +2928,7 @@  discard block
 block discarded – undo
2928 2928
      */
2929 2929
     public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2930 2930
     {
2931
-        $query_params = [ $extra_where + ['EXM_key' => $meta_key] ];
2931
+        $query_params = [$extra_where + ['EXM_key' => $meta_key]];
2932 2932
         if ($single) {
2933 2933
             $result = $this->get_first_related('Extra_Meta', $query_params);
2934 2934
             if ($result instanceof EE_Extra_Meta) {
@@ -2940,7 +2940,7 @@  discard block
 block discarded – undo
2940 2940
                 $values = [];
2941 2941
                 foreach ($results as $result) {
2942 2942
                     if ($result instanceof EE_Extra_Meta) {
2943
-                        $values[ $result->ID() ] = $result->value();
2943
+                        $values[$result->ID()] = $result->value();
2944 2944
                     }
2945 2945
                 }
2946 2946
                 return $values;
@@ -2985,17 +2985,17 @@  discard block
 block discarded – undo
2985 2985
             );
2986 2986
             foreach ($extra_meta_objs as $extra_meta_obj) {
2987 2987
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2988
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2988
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2989 2989
                 }
2990 2990
             }
2991 2991
         } else {
2992 2992
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2993 2993
             foreach ($extra_meta_objs as $extra_meta_obj) {
2994 2994
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2995
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2996
-                        $return_array[ $extra_meta_obj->key() ] = [];
2995
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2996
+                        $return_array[$extra_meta_obj->key()] = [];
2997 2997
                     }
2998
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2998
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2999 2999
                 }
3000 3000
             }
3001 3001
         }
@@ -3076,8 +3076,8 @@  discard block
 block discarded – undo
3076 3076
                             'event_espresso'
3077 3077
                         ),
3078 3078
                         $this->ID(),
3079
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3080
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3079
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3080
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3081 3081
                     )
3082 3082
                 );
3083 3083
             }
@@ -3110,7 +3110,7 @@  discard block
 block discarded – undo
3110 3110
     {
3111 3111
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3112 3112
         // if it wasn't even there to start off.
3113
-        if (! $this->ID()) {
3113
+        if ( ! $this->ID()) {
3114 3114
             $this->save();
3115 3115
         }
3116 3116
         global $wpdb;
@@ -3340,7 +3340,7 @@  discard block
 block discarded – undo
3340 3340
         $model = $this->get_model();
3341 3341
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3342 3342
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3343
-                $classname = 'EE_' . $model->get_this_model_name();
3343
+                $classname = 'EE_'.$model->get_this_model_name();
3344 3344
                 if (
3345 3345
                     $this->get_one_from_cache($relation_name) instanceof $classname
3346 3346
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3381,7 +3381,7 @@  discard block
 block discarded – undo
3381 3381
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3382 3382
         foreach ($this->_fields as $field => $value) {
3383 3383
             if ($value instanceof DateTime) {
3384
-                $this->_fields[ $field ] = clone $value;
3384
+                $this->_fields[$field] = clone $value;
3385 3385
             }
3386 3386
         }
3387 3387
     }
Please login to merge, or discard this patch.
core/db_classes/EE_Line_Item.class.php 1 patch
Indentation   +1659 added lines, -1659 removed lines patch added patch discarded remove patch
@@ -15,1663 +15,1663 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Line_Item extends EE_Base_Class
17 17
 {
18
-    /**
19
-     * for children line items (currently not a normal relation)
20
-     *
21
-     * @type EE_Line_Item[]
22
-     */
23
-    protected $_children = array();
24
-
25
-    /**
26
-     * for the parent line item
27
-     *
28
-     * @var EE_Line_Item
29
-     */
30
-    protected $_parent;
31
-
32
-    /**
33
-     * @var LineItemCalculator
34
-     */
35
-    protected $calculator;
36
-
37
-
38
-    /**
39
-     * @param array  $props_n_values          incoming values
40
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
41
-     *                                        used.)
42
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
43
-     *                                        date_format and the second value is the time format
44
-     * @return EE_Line_Item
45
-     * @throws EE_Error
46
-     * @throws InvalidArgumentException
47
-     * @throws InvalidDataTypeException
48
-     * @throws InvalidInterfaceException
49
-     * @throws ReflectionException
50
-     */
51
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
-    {
53
-        $has_object = parent::_check_for_object(
54
-            $props_n_values,
55
-            __CLASS__,
56
-            $timezone,
57
-            $date_formats
58
-        );
59
-        return $has_object
60
-            ? $has_object
61
-            : new self($props_n_values, false, $timezone);
62
-    }
63
-
64
-
65
-    /**
66
-     * @param array  $props_n_values  incoming values from the database
67
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
68
-     *                                the website will be used.
69
-     * @return EE_Line_Item
70
-     * @throws EE_Error
71
-     * @throws InvalidArgumentException
72
-     * @throws InvalidDataTypeException
73
-     * @throws InvalidInterfaceException
74
-     * @throws ReflectionException
75
-     */
76
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
77
-    {
78
-        return new self($props_n_values, true, $timezone);
79
-    }
80
-
81
-
82
-    /**
83
-     * Adds some defaults if they're not specified
84
-     *
85
-     * @param array  $fieldValues
86
-     * @param bool   $bydb
87
-     * @param string $timezone
88
-     * @throws EE_Error
89
-     * @throws InvalidArgumentException
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     * @throws ReflectionException
93
-     */
94
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
95
-    {
96
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
97
-        parent::__construct($fieldValues, $bydb, $timezone);
98
-        if (! $this->get('LIN_code')) {
99
-            $this->set_code($this->generate_code());
100
-        }
101
-    }
102
-
103
-
104
-    public function __wakeup()
105
-    {
106
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
107
-        parent::__wakeup();
108
-    }
109
-
110
-
111
-    /**
112
-     * Gets ID
113
-     *
114
-     * @return int
115
-     * @throws EE_Error
116
-     * @throws InvalidArgumentException
117
-     * @throws InvalidDataTypeException
118
-     * @throws InvalidInterfaceException
119
-     * @throws ReflectionException
120
-     */
121
-    public function ID()
122
-    {
123
-        return $this->get('LIN_ID');
124
-    }
125
-
126
-
127
-    /**
128
-     * Gets TXN_ID
129
-     *
130
-     * @return int
131
-     * @throws EE_Error
132
-     * @throws InvalidArgumentException
133
-     * @throws InvalidDataTypeException
134
-     * @throws InvalidInterfaceException
135
-     * @throws ReflectionException
136
-     */
137
-    public function TXN_ID()
138
-    {
139
-        return $this->get('TXN_ID');
140
-    }
141
-
142
-
143
-    /**
144
-     * Sets TXN_ID
145
-     *
146
-     * @param int $TXN_ID
147
-     * @throws EE_Error
148
-     * @throws InvalidArgumentException
149
-     * @throws InvalidDataTypeException
150
-     * @throws InvalidInterfaceException
151
-     * @throws ReflectionException
152
-     */
153
-    public function set_TXN_ID($TXN_ID)
154
-    {
155
-        $this->set('TXN_ID', $TXN_ID);
156
-    }
157
-
158
-
159
-    /**
160
-     * Gets name
161
-     *
162
-     * @return string
163
-     * @throws EE_Error
164
-     * @throws InvalidArgumentException
165
-     * @throws InvalidDataTypeException
166
-     * @throws InvalidInterfaceException
167
-     * @throws ReflectionException
168
-     */
169
-    public function name()
170
-    {
171
-        $name = $this->get('LIN_name');
172
-        if (! $name) {
173
-            $name = ucwords(str_replace('-', ' ', $this->type()));
174
-        }
175
-        return $name;
176
-    }
177
-
178
-
179
-    /**
180
-     * Sets name
181
-     *
182
-     * @param string $name
183
-     * @throws EE_Error
184
-     * @throws InvalidArgumentException
185
-     * @throws InvalidDataTypeException
186
-     * @throws InvalidInterfaceException
187
-     * @throws ReflectionException
188
-     */
189
-    public function set_name($name)
190
-    {
191
-        $this->set('LIN_name', $name);
192
-    }
193
-
194
-
195
-    /**
196
-     * Gets desc
197
-     *
198
-     * @return string
199
-     * @throws EE_Error
200
-     * @throws InvalidArgumentException
201
-     * @throws InvalidDataTypeException
202
-     * @throws InvalidInterfaceException
203
-     * @throws ReflectionException
204
-     */
205
-    public function desc()
206
-    {
207
-        return $this->get('LIN_desc');
208
-    }
209
-
210
-
211
-    /**
212
-     * Sets desc
213
-     *
214
-     * @param string $desc
215
-     * @throws EE_Error
216
-     * @throws InvalidArgumentException
217
-     * @throws InvalidDataTypeException
218
-     * @throws InvalidInterfaceException
219
-     * @throws ReflectionException
220
-     */
221
-    public function set_desc($desc)
222
-    {
223
-        $this->set('LIN_desc', $desc);
224
-    }
225
-
226
-
227
-    /**
228
-     * Gets quantity
229
-     *
230
-     * @return int
231
-     * @throws EE_Error
232
-     * @throws InvalidArgumentException
233
-     * @throws InvalidDataTypeException
234
-     * @throws InvalidInterfaceException
235
-     * @throws ReflectionException
236
-     */
237
-    public function quantity(): int
238
-    {
239
-        return (int) $this->get('LIN_quantity');
240
-    }
241
-
242
-
243
-    /**
244
-     * Sets quantity
245
-     *
246
-     * @param int $quantity
247
-     * @throws EE_Error
248
-     * @throws InvalidArgumentException
249
-     * @throws InvalidDataTypeException
250
-     * @throws InvalidInterfaceException
251
-     * @throws ReflectionException
252
-     */
253
-    public function set_quantity($quantity)
254
-    {
255
-        $this->set('LIN_quantity', max($quantity, 0));
256
-    }
257
-
258
-
259
-    /**
260
-     * Gets item_id
261
-     *
262
-     * @return int
263
-     * @throws EE_Error
264
-     * @throws InvalidArgumentException
265
-     * @throws InvalidDataTypeException
266
-     * @throws InvalidInterfaceException
267
-     * @throws ReflectionException
268
-     */
269
-    public function OBJ_ID()
270
-    {
271
-        return $this->get('OBJ_ID');
272
-    }
273
-
274
-
275
-    /**
276
-     * Sets item_id
277
-     *
278
-     * @param int $item_id
279
-     * @throws EE_Error
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidDataTypeException
282
-     * @throws InvalidInterfaceException
283
-     * @throws ReflectionException
284
-     */
285
-    public function set_OBJ_ID($item_id)
286
-    {
287
-        $this->set('OBJ_ID', $item_id);
288
-    }
289
-
290
-
291
-    /**
292
-     * Gets item_type
293
-     *
294
-     * @return string
295
-     * @throws EE_Error
296
-     * @throws InvalidArgumentException
297
-     * @throws InvalidDataTypeException
298
-     * @throws InvalidInterfaceException
299
-     * @throws ReflectionException
300
-     */
301
-    public function OBJ_type()
302
-    {
303
-        return $this->get('OBJ_type');
304
-    }
305
-
306
-
307
-    /**
308
-     * Gets item_type
309
-     *
310
-     * @return string
311
-     * @throws EE_Error
312
-     * @throws InvalidArgumentException
313
-     * @throws InvalidDataTypeException
314
-     * @throws InvalidInterfaceException
315
-     * @throws ReflectionException
316
-     */
317
-    public function OBJ_type_i18n()
318
-    {
319
-        $obj_type = $this->OBJ_type();
320
-        switch ($obj_type) {
321
-            case EEM_Line_Item::OBJ_TYPE_EVENT:
322
-                $obj_type = esc_html__('Event', 'event_espresso');
323
-                break;
324
-            case EEM_Line_Item::OBJ_TYPE_PRICE:
325
-                $obj_type = esc_html__('Price', 'event_espresso');
326
-                break;
327
-            case EEM_Line_Item::OBJ_TYPE_PROMOTION:
328
-                $obj_type = esc_html__('Promotion', 'event_espresso');
329
-                break;
330
-            case EEM_Line_Item::OBJ_TYPE_TICKET:
331
-                $obj_type = esc_html__('Ticket', 'event_espresso');
332
-                break;
333
-            case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
334
-                $obj_type = esc_html__('Transaction', 'event_espresso');
335
-                break;
336
-        }
337
-        return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
338
-    }
339
-
340
-
341
-    /**
342
-     * Sets item_type
343
-     *
344
-     * @param string $OBJ_type
345
-     * @throws EE_Error
346
-     * @throws InvalidArgumentException
347
-     * @throws InvalidDataTypeException
348
-     * @throws InvalidInterfaceException
349
-     * @throws ReflectionException
350
-     */
351
-    public function set_OBJ_type($OBJ_type)
352
-    {
353
-        $this->set('OBJ_type', $OBJ_type);
354
-    }
355
-
356
-
357
-    /**
358
-     * Gets unit_price
359
-     *
360
-     * @return float
361
-     * @throws EE_Error
362
-     * @throws InvalidArgumentException
363
-     * @throws InvalidDataTypeException
364
-     * @throws InvalidInterfaceException
365
-     * @throws ReflectionException
366
-     */
367
-    public function unit_price()
368
-    {
369
-        return $this->get('LIN_unit_price');
370
-    }
371
-
372
-
373
-    /**
374
-     * Sets unit_price
375
-     *
376
-     * @param float $unit_price
377
-     * @throws EE_Error
378
-     * @throws InvalidArgumentException
379
-     * @throws InvalidDataTypeException
380
-     * @throws InvalidInterfaceException
381
-     * @throws ReflectionException
382
-     */
383
-    public function set_unit_price($unit_price)
384
-    {
385
-        $this->set('LIN_unit_price', $unit_price);
386
-    }
387
-
388
-
389
-    /**
390
-     * Checks if this item is a percentage modifier or not
391
-     *
392
-     * @return boolean
393
-     * @throws EE_Error
394
-     * @throws InvalidArgumentException
395
-     * @throws InvalidDataTypeException
396
-     * @throws InvalidInterfaceException
397
-     * @throws ReflectionException
398
-     */
399
-    public function is_percent()
400
-    {
401
-        if ($this->is_tax_sub_total()) {
402
-            // tax subtotals HAVE a percent on them, that percentage only applies
403
-            // to taxable items, so its' an exception. Treat it like a flat line item
404
-            return false;
405
-        }
406
-        $unit_price = abs($this->get('LIN_unit_price'));
407
-        $percent = abs($this->get('LIN_percent'));
408
-        if ($unit_price < .001 && $percent) {
409
-            return true;
410
-        }
411
-        if ($unit_price >= .001 && ! $percent) {
412
-            return false;
413
-        }
414
-        if ($unit_price >= .001 && $percent) {
415
-            throw new EE_Error(
416
-                sprintf(
417
-                    esc_html__(
418
-                        'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
419
-                        'event_espresso'
420
-                    ),
421
-                    $unit_price,
422
-                    $percent
423
-                )
424
-            );
425
-        }
426
-        // if they're both 0, assume its not a percent item
427
-        return false;
428
-    }
429
-
430
-
431
-    /**
432
-     * Gets percent (between 100-.001)
433
-     *
434
-     * @return float
435
-     * @throws EE_Error
436
-     * @throws InvalidArgumentException
437
-     * @throws InvalidDataTypeException
438
-     * @throws InvalidInterfaceException
439
-     * @throws ReflectionException
440
-     */
441
-    public function percent()
442
-    {
443
-        return $this->get('LIN_percent');
444
-    }
445
-
446
-
447
-    /**
448
-     * @return string
449
-     * @throws EE_Error
450
-     * @throws ReflectionException
451
-     * @since 5.0.0.p
452
-     */
453
-    public function prettyPercent(): string
454
-    {
455
-        return $this->get_pretty('LIN_percent');
456
-    }
457
-
458
-
459
-    /**
460
-     * Sets percent (between 100-0.01)
461
-     *
462
-     * @param float $percent
463
-     * @throws EE_Error
464
-     * @throws InvalidArgumentException
465
-     * @throws InvalidDataTypeException
466
-     * @throws InvalidInterfaceException
467
-     * @throws ReflectionException
468
-     */
469
-    public function set_percent($percent)
470
-    {
471
-        $this->set('LIN_percent', $percent);
472
-    }
473
-
474
-
475
-    /**
476
-     * Gets total
477
-     *
478
-     * @return float
479
-     * @throws EE_Error
480
-     * @throws InvalidArgumentException
481
-     * @throws InvalidDataTypeException
482
-     * @throws InvalidInterfaceException
483
-     * @throws ReflectionException
484
-     */
485
-    public function pretaxTotal(): float
486
-    {
487
-        return (float) $this->get('LIN_pretax');
488
-    }
489
-
490
-
491
-    /**
492
-     * Sets total
493
-     *
494
-     * @param float $pretax_total
495
-     * @throws EE_Error
496
-     * @throws InvalidArgumentException
497
-     * @throws InvalidDataTypeException
498
-     * @throws InvalidInterfaceException
499
-     * @throws ReflectionException
500
-     */
501
-    public function setPretaxTotal(float $pretax_total)
502
-    {
503
-        $this->set('LIN_pretax', $pretax_total);
504
-    }
505
-
506
-
507
-    /**
508
-     * @return float
509
-     * @throws EE_Error
510
-     * @throws ReflectionException
511
-     * @since  5.0.0.p
512
-     */
513
-    public function totalWithTax(): float
514
-    {
515
-        return (float) $this->get('LIN_total');
516
-    }
517
-
518
-
519
-    /**
520
-     * Sets total
521
-     *
522
-     * @param float $total
523
-     * @throws EE_Error
524
-     * @throws ReflectionException
525
-     * @since  5.0.0.p
526
-     */
527
-    public function setTotalWithTax(float $total)
528
-    {
529
-        $this->set('LIN_total', $total);
530
-    }
531
-
532
-
533
-    /**
534
-     * Gets total
535
-     *
536
-     * @return float
537
-     * @throws EE_Error
538
-     * @throws ReflectionException
539
-     * @deprecatd 5.0.0.p
540
-     */
541
-    public function total(): float
542
-    {
543
-        return $this->totalWithTax();
544
-    }
545
-
546
-
547
-    /**
548
-     * Sets total
549
-     *
550
-     * @param float $total
551
-     * @throws EE_Error
552
-     * @throws ReflectionException
553
-     * @deprecatd 5.0.0.p
554
-     */
555
-    public function set_total($total)
556
-    {
557
-        $this->setTotalWithTax($total);
558
-    }
559
-
560
-
561
-    /**
562
-     * Gets order
563
-     *
564
-     * @return int
565
-     * @throws EE_Error
566
-     * @throws InvalidArgumentException
567
-     * @throws InvalidDataTypeException
568
-     * @throws InvalidInterfaceException
569
-     * @throws ReflectionException
570
-     */
571
-    public function order()
572
-    {
573
-        return $this->get('LIN_order');
574
-    }
575
-
576
-
577
-    /**
578
-     * Sets order
579
-     *
580
-     * @param int $order
581
-     * @throws EE_Error
582
-     * @throws InvalidArgumentException
583
-     * @throws InvalidDataTypeException
584
-     * @throws InvalidInterfaceException
585
-     * @throws ReflectionException
586
-     */
587
-    public function set_order($order)
588
-    {
589
-        $this->set('LIN_order', $order);
590
-    }
591
-
592
-
593
-    /**
594
-     * Gets parent
595
-     *
596
-     * @return int
597
-     * @throws EE_Error
598
-     * @throws InvalidArgumentException
599
-     * @throws InvalidDataTypeException
600
-     * @throws InvalidInterfaceException
601
-     * @throws ReflectionException
602
-     */
603
-    public function parent_ID()
604
-    {
605
-        return $this->get('LIN_parent');
606
-    }
607
-
608
-
609
-    /**
610
-     * Sets parent
611
-     *
612
-     * @param int $parent
613
-     * @throws EE_Error
614
-     * @throws InvalidArgumentException
615
-     * @throws InvalidDataTypeException
616
-     * @throws InvalidInterfaceException
617
-     * @throws ReflectionException
618
-     */
619
-    public function set_parent_ID($parent)
620
-    {
621
-        $this->set('LIN_parent', $parent);
622
-    }
623
-
624
-
625
-    /**
626
-     * Gets type
627
-     *
628
-     * @return string
629
-     * @throws EE_Error
630
-     * @throws InvalidArgumentException
631
-     * @throws InvalidDataTypeException
632
-     * @throws InvalidInterfaceException
633
-     * @throws ReflectionException
634
-     */
635
-    public function type()
636
-    {
637
-        return $this->get('LIN_type');
638
-    }
639
-
640
-
641
-    /**
642
-     * Sets type
643
-     *
644
-     * @param string $type
645
-     * @throws EE_Error
646
-     * @throws InvalidArgumentException
647
-     * @throws InvalidDataTypeException
648
-     * @throws InvalidInterfaceException
649
-     * @throws ReflectionException
650
-     */
651
-    public function set_type($type)
652
-    {
653
-        $this->set('LIN_type', $type);
654
-    }
655
-
656
-
657
-    /**
658
-     * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
659
-     * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
660
-     * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
661
-     * or indirectly by `EE_Line_item::add_child_line_item()`)
662
-     *
663
-     * @return EE_Base_Class|EE_Line_Item
664
-     * @throws EE_Error
665
-     * @throws InvalidArgumentException
666
-     * @throws InvalidDataTypeException
667
-     * @throws InvalidInterfaceException
668
-     * @throws ReflectionException
669
-     */
670
-    public function parent()
671
-    {
672
-        return $this->ID()
673
-            ? $this->get_model()->get_one_by_ID($this->parent_ID())
674
-            : $this->_parent;
675
-    }
676
-
677
-
678
-    /**
679
-     * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
680
-     *
681
-     * @return EE_Line_Item[]
682
-     * @throws EE_Error
683
-     * @throws InvalidArgumentException
684
-     * @throws InvalidDataTypeException
685
-     * @throws InvalidInterfaceException
686
-     * @throws ReflectionException
687
-     */
688
-    public function children(array $query_params = []): array
689
-    {
690
-        if ($this->ID()) {
691
-            // ensure where params are an array
692
-            $query_params[0] = $query_params[0] ?? [];
693
-            // add defaults for line item parent and orderby
694
-            $query_params[0] += ['LIN_parent' => $this->ID()];
695
-            $query_params += ['order_by' => ['LIN_order' => 'ASC']];
696
-            return $this->get_model()->get_all($query_params);
697
-        }
698
-        if (! is_array($this->_children)) {
699
-            $this->_children = array();
700
-        }
701
-        return $this->_children;
702
-    }
703
-
704
-
705
-    /**
706
-     * Gets code
707
-     *
708
-     * @return string
709
-     * @throws EE_Error
710
-     * @throws InvalidArgumentException
711
-     * @throws InvalidDataTypeException
712
-     * @throws InvalidInterfaceException
713
-     * @throws ReflectionException
714
-     */
715
-    public function code()
716
-    {
717
-        return $this->get('LIN_code');
718
-    }
719
-
720
-
721
-    /**
722
-     * Sets code
723
-     *
724
-     * @param string $code
725
-     * @throws EE_Error
726
-     * @throws InvalidArgumentException
727
-     * @throws InvalidDataTypeException
728
-     * @throws InvalidInterfaceException
729
-     * @throws ReflectionException
730
-     */
731
-    public function set_code($code)
732
-    {
733
-        $this->set('LIN_code', $code);
734
-    }
735
-
736
-
737
-    /**
738
-     * Gets is_taxable
739
-     *
740
-     * @return boolean
741
-     * @throws EE_Error
742
-     * @throws InvalidArgumentException
743
-     * @throws InvalidDataTypeException
744
-     * @throws InvalidInterfaceException
745
-     * @throws ReflectionException
746
-     */
747
-    public function is_taxable()
748
-    {
749
-        return $this->get('LIN_is_taxable');
750
-    }
751
-
752
-
753
-    /**
754
-     * Sets is_taxable
755
-     *
756
-     * @param boolean $is_taxable
757
-     * @throws EE_Error
758
-     * @throws InvalidArgumentException
759
-     * @throws InvalidDataTypeException
760
-     * @throws InvalidInterfaceException
761
-     * @throws ReflectionException
762
-     */
763
-    public function set_is_taxable($is_taxable)
764
-    {
765
-        $this->set('LIN_is_taxable', $is_taxable);
766
-    }
767
-
768
-
769
-    /**
770
-     * @param int $timestamp
771
-     * @throws EE_Error
772
-     * @throws ReflectionException
773
-     * @since 5.0.0.p
774
-     */
775
-    public function setTimestamp(int $timestamp)
776
-    {
777
-        $this->set('LIN_timestamp', $timestamp);
778
-    }
779
-
780
-
781
-    /**
782
-     * Gets the object that this model-joins-to.
783
-     * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
784
-     * EEM_Promotion_Object
785
-     *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
786
-     *
787
-     * @return EE_Base_Class | NULL
788
-     * @throws EE_Error
789
-     * @throws InvalidArgumentException
790
-     * @throws InvalidDataTypeException
791
-     * @throws InvalidInterfaceException
792
-     * @throws ReflectionException
793
-     */
794
-    public function get_object()
795
-    {
796
-        $model_name_of_related_obj = $this->OBJ_type();
797
-        return $this->get_model()->has_relation($model_name_of_related_obj)
798
-            ? $this->get_first_related($model_name_of_related_obj)
799
-            : null;
800
-    }
801
-
802
-
803
-    /**
804
-     * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
805
-     * (IE, if this line item is for a price or something else, will return NULL)
806
-     *
807
-     * @param array $query_params
808
-     * @return EE_Base_Class|EE_Ticket
809
-     * @throws EE_Error
810
-     * @throws InvalidArgumentException
811
-     * @throws InvalidDataTypeException
812
-     * @throws InvalidInterfaceException
813
-     * @throws ReflectionException
814
-     */
815
-    public function ticket($query_params = array())
816
-    {
817
-        // we're going to assume that when this method is called
818
-        // we always want to receive the attached ticket EVEN if that ticket is archived.
819
-        // This can be overridden via the incoming $query_params argument
820
-        $remove_defaults = array('default_where_conditions' => 'none');
821
-        $query_params = array_merge($remove_defaults, $query_params);
822
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
823
-    }
824
-
825
-
826
-    /**
827
-     * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
828
-     *
829
-     * @return EE_Datetime | NULL
830
-     * @throws EE_Error
831
-     * @throws InvalidArgumentException
832
-     * @throws InvalidDataTypeException
833
-     * @throws InvalidInterfaceException
834
-     * @throws ReflectionException
835
-     */
836
-    public function get_ticket_datetime()
837
-    {
838
-        if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
839
-            $ticket = $this->ticket();
840
-            if ($ticket instanceof EE_Ticket) {
841
-                $datetime = $ticket->first_datetime();
842
-                if ($datetime instanceof EE_Datetime) {
843
-                    return $datetime;
844
-                }
845
-            }
846
-        }
847
-        return null;
848
-    }
849
-
850
-
851
-    /**
852
-     * Gets the event's name that's related to the ticket, if this is for
853
-     * a ticket
854
-     *
855
-     * @return string
856
-     * @throws EE_Error
857
-     * @throws InvalidArgumentException
858
-     * @throws InvalidDataTypeException
859
-     * @throws InvalidInterfaceException
860
-     * @throws ReflectionException
861
-     */
862
-    public function ticket_event_name()
863
-    {
864
-        $event_name = esc_html__('Unknown', 'event_espresso');
865
-        $event = $this->ticket_event();
866
-        if ($event instanceof EE_Event) {
867
-            $event_name = $event->name();
868
-        }
869
-        return $event_name;
870
-    }
871
-
872
-
873
-    /**
874
-     * Gets the event that's related to the ticket, if this line item represents a ticket.
875
-     *
876
-     * @return EE_Event|null
877
-     * @throws EE_Error
878
-     * @throws InvalidArgumentException
879
-     * @throws InvalidDataTypeException
880
-     * @throws InvalidInterfaceException
881
-     * @throws ReflectionException
882
-     */
883
-    public function ticket_event()
884
-    {
885
-        $event = null;
886
-        $ticket = $this->ticket();
887
-        if ($ticket instanceof EE_Ticket) {
888
-            $datetime = $ticket->first_datetime();
889
-            if ($datetime instanceof EE_Datetime) {
890
-                $event = $datetime->event();
891
-            }
892
-        }
893
-        return $event;
894
-    }
895
-
896
-
897
-    /**
898
-     * Gets the first datetime for this lien item, assuming it's for a ticket
899
-     *
900
-     * @param string $date_format
901
-     * @param string $time_format
902
-     * @return string
903
-     * @throws EE_Error
904
-     * @throws InvalidArgumentException
905
-     * @throws InvalidDataTypeException
906
-     * @throws InvalidInterfaceException
907
-     * @throws ReflectionException
908
-     */
909
-    public function ticket_datetime_start($date_format = '', $time_format = '')
910
-    {
911
-        $first_datetime_string = esc_html__('Unknown', 'event_espresso');
912
-        $datetime = $this->get_ticket_datetime();
913
-        if ($datetime) {
914
-            $first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
915
-        }
916
-        return $first_datetime_string;
917
-    }
918
-
919
-
920
-    /**
921
-     * Adds the line item as a child to this line item. If there is another child line
922
-     * item with the same LIN_code, it is overwritten by this new one
923
-     *
924
-     * @param EE_Line_Item $line_item
925
-     * @param bool          $set_order
926
-     * @return bool success
927
-     * @throws EE_Error
928
-     * @throws InvalidArgumentException
929
-     * @throws InvalidDataTypeException
930
-     * @throws InvalidInterfaceException
931
-     * @throws ReflectionException
932
-     */
933
-    public function add_child_line_item(EE_Line_Item $line_item, $set_order = true)
934
-    {
935
-        // should we calculate the LIN_order for this line item ?
936
-        if ($set_order || $line_item->order() === null) {
937
-            $line_item->set_order(count($this->children()));
938
-        }
939
-        if ($this->ID()) {
940
-            // check for any duplicate line items (with the same code), if so, this replaces it
941
-            $line_item_with_same_code = $this->get_child_line_item($line_item->code());
942
-            if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
943
-                $this->delete_child_line_item($line_item_with_same_code->code());
944
-            }
945
-            $line_item->set_parent_ID($this->ID());
946
-            if ($this->TXN_ID()) {
947
-                $line_item->set_TXN_ID($this->TXN_ID());
948
-            }
949
-            return $line_item->save();
950
-        }
951
-        $this->_children[ $line_item->code() ] = $line_item;
952
-        if ($line_item->parent() !== $this) {
953
-            $line_item->set_parent($this);
954
-        }
955
-        return true;
956
-    }
957
-
958
-
959
-    /**
960
-     * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
961
-     * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
962
-     * However, if this line item is NOT saved to the DB, this just caches the parent on
963
-     * the EE_Line_Item::_parent property.
964
-     *
965
-     * @param EE_Line_Item $line_item
966
-     * @throws EE_Error
967
-     * @throws InvalidArgumentException
968
-     * @throws InvalidDataTypeException
969
-     * @throws InvalidInterfaceException
970
-     * @throws ReflectionException
971
-     */
972
-    public function set_parent($line_item)
973
-    {
974
-        if ($this->ID()) {
975
-            if (! $line_item->ID()) {
976
-                $line_item->save();
977
-            }
978
-            $this->set_parent_ID($line_item->ID());
979
-            $this->save();
980
-        } else {
981
-            $this->_parent = $line_item;
982
-            $this->set_parent_ID($line_item->ID());
983
-        }
984
-    }
985
-
986
-
987
-    /**
988
-     * Gets the child line item as specified by its code. Because this returns an object (by reference)
989
-     * you can modify this child line item and the parent (this object) can know about them
990
-     * because it also has a reference to that line item
991
-     *
992
-     * @param string $code
993
-     * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
994
-     * @throws EE_Error
995
-     * @throws InvalidArgumentException
996
-     * @throws InvalidDataTypeException
997
-     * @throws InvalidInterfaceException
998
-     * @throws ReflectionException
999
-     */
1000
-    public function get_child_line_item($code)
1001
-    {
1002
-        if ($this->ID()) {
1003
-            return $this->get_model()->get_one(
1004
-                array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
1005
-            );
1006
-        }
1007
-        return isset($this->_children[ $code ])
1008
-            ? $this->_children[ $code ]
1009
-            : null;
1010
-    }
1011
-
1012
-
1013
-    /**
1014
-     * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1015
-     * cached on it)
1016
-     *
1017
-     * @return int
1018
-     * @throws EE_Error
1019
-     * @throws InvalidArgumentException
1020
-     * @throws InvalidDataTypeException
1021
-     * @throws InvalidInterfaceException
1022
-     * @throws ReflectionException
1023
-     */
1024
-    public function delete_children_line_items()
1025
-    {
1026
-        if ($this->ID()) {
1027
-            return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
1028
-        }
1029
-        $count = count($this->_children);
1030
-        $this->_children = array();
1031
-        return $count;
1032
-    }
1033
-
1034
-
1035
-    /**
1036
-     * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1037
-     * HAS NOT been saved to the DB, removes the child line item with index $code.
1038
-     * Also searches through the child's children for a matching line item. However, once a line item has been found
1039
-     * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1040
-     * deleted)
1041
-     *
1042
-     * @param string $code
1043
-     * @param bool   $stop_search_once_found
1044
-     * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1045
-     *             the DB yet)
1046
-     * @throws EE_Error
1047
-     * @throws InvalidArgumentException
1048
-     * @throws InvalidDataTypeException
1049
-     * @throws InvalidInterfaceException
1050
-     * @throws ReflectionException
1051
-     */
1052
-    public function delete_child_line_item($code, $stop_search_once_found = true)
1053
-    {
1054
-        if ($this->ID()) {
1055
-            $items_deleted = 0;
1056
-            if ($this->code() === $code) {
1057
-                $items_deleted += EEH_Line_Item::delete_all_child_items($this);
1058
-                $items_deleted += (int) $this->delete();
1059
-                if ($stop_search_once_found) {
1060
-                    return $items_deleted;
1061
-                }
1062
-            }
1063
-            foreach ($this->children() as $child_line_item) {
1064
-                $items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1065
-            }
1066
-            return $items_deleted;
1067
-        }
1068
-        if (isset($this->_children[ $code ])) {
1069
-            unset($this->_children[ $code ]);
1070
-            return 1;
1071
-        }
1072
-        return 0;
1073
-    }
1074
-
1075
-
1076
-    /**
1077
-     * If this line item is in the database, is of the type subtotal, and
1078
-     * has no children, why do we have it? It should be deleted so this function
1079
-     * does that
1080
-     *
1081
-     * @return boolean
1082
-     * @throws EE_Error
1083
-     * @throws InvalidArgumentException
1084
-     * @throws InvalidDataTypeException
1085
-     * @throws InvalidInterfaceException
1086
-     * @throws ReflectionException
1087
-     */
1088
-    public function delete_if_childless_subtotal()
1089
-    {
1090
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1091
-            return $this->delete();
1092
-        }
1093
-        return false;
1094
-    }
1095
-
1096
-
1097
-    /**
1098
-     * Creates a code and returns a string. doesn't assign the code to this model object
1099
-     *
1100
-     * @return string
1101
-     * @throws EE_Error
1102
-     * @throws InvalidArgumentException
1103
-     * @throws InvalidDataTypeException
1104
-     * @throws InvalidInterfaceException
1105
-     * @throws ReflectionException
1106
-     */
1107
-    public function generate_code()
1108
-    {
1109
-        // each line item in the cart requires a unique identifier
1110
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1111
-    }
1112
-
1113
-
1114
-    /**
1115
-     * @return bool
1116
-     * @throws EE_Error
1117
-     * @throws InvalidArgumentException
1118
-     * @throws InvalidDataTypeException
1119
-     * @throws InvalidInterfaceException
1120
-     * @throws ReflectionException
1121
-     */
1122
-    public function isGlobalTax(): bool
1123
-    {
1124
-        return $this->type() === EEM_Line_Item::type_tax;
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * @return bool
1130
-     * @throws EE_Error
1131
-     * @throws InvalidArgumentException
1132
-     * @throws InvalidDataTypeException
1133
-     * @throws InvalidInterfaceException
1134
-     * @throws ReflectionException
1135
-     */
1136
-    public function isSubTax(): bool
1137
-    {
1138
-        return $this->type() === EEM_Line_Item::type_sub_tax;
1139
-    }
1140
-
1141
-
1142
-    /**
1143
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1144
-     *
1145
-     * @return array
1146
-     * @throws EE_Error
1147
-     * @throws InvalidArgumentException
1148
-     * @throws InvalidDataTypeException
1149
-     * @throws InvalidInterfaceException
1150
-     * @throws ReflectionException
1151
-     */
1152
-    public function getSubTaxes(): array
1153
-    {
1154
-        if (! $this->is_line_item()) {
1155
-            return [];
1156
-        }
1157
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1163
-     *
1164
-     * @return bool
1165
-     * @throws EE_Error
1166
-     * @throws InvalidArgumentException
1167
-     * @throws InvalidDataTypeException
1168
-     * @throws InvalidInterfaceException
1169
-     * @throws ReflectionException
1170
-     */
1171
-    public function hasSubTaxes(): bool
1172
-    {
1173
-        if (! $this->is_line_item()) {
1174
-            return false;
1175
-        }
1176
-        $sub_taxes = $this->getSubTaxes();
1177
-        return ! empty($sub_taxes);
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * @return bool
1183
-     * @throws EE_Error
1184
-     * @throws ReflectionException
1185
-     * @deprecated   5.0.0.p
1186
-     */
1187
-    public function is_tax(): bool
1188
-    {
1189
-        return $this->isGlobalTax();
1190
-    }
1191
-
1192
-
1193
-    /**
1194
-     * @return bool
1195
-     * @throws EE_Error
1196
-     * @throws InvalidArgumentException
1197
-     * @throws InvalidDataTypeException
1198
-     * @throws InvalidInterfaceException
1199
-     * @throws ReflectionException
1200
-     */
1201
-    public function is_tax_sub_total()
1202
-    {
1203
-        return $this->type() === EEM_Line_Item::type_tax_sub_total;
1204
-    }
1205
-
1206
-
1207
-    /**
1208
-     * @return bool
1209
-     * @throws EE_Error
1210
-     * @throws InvalidArgumentException
1211
-     * @throws InvalidDataTypeException
1212
-     * @throws InvalidInterfaceException
1213
-     * @throws ReflectionException
1214
-     */
1215
-    public function is_line_item()
1216
-    {
1217
-        return $this->type() === EEM_Line_Item::type_line_item;
1218
-    }
1219
-
1220
-
1221
-    /**
1222
-     * @return bool
1223
-     * @throws EE_Error
1224
-     * @throws InvalidArgumentException
1225
-     * @throws InvalidDataTypeException
1226
-     * @throws InvalidInterfaceException
1227
-     * @throws ReflectionException
1228
-     */
1229
-    public function is_sub_line_item()
1230
-    {
1231
-        return $this->type() === EEM_Line_Item::type_sub_line_item;
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     * @return bool
1237
-     * @throws EE_Error
1238
-     * @throws InvalidArgumentException
1239
-     * @throws InvalidDataTypeException
1240
-     * @throws InvalidInterfaceException
1241
-     * @throws ReflectionException
1242
-     */
1243
-    public function is_sub_total()
1244
-    {
1245
-        return $this->type() === EEM_Line_Item::type_sub_total;
1246
-    }
1247
-
1248
-
1249
-    /**
1250
-     * Whether or not this line item is a cancellation line item
1251
-     *
1252
-     * @return boolean
1253
-     * @throws EE_Error
1254
-     * @throws InvalidArgumentException
1255
-     * @throws InvalidDataTypeException
1256
-     * @throws InvalidInterfaceException
1257
-     * @throws ReflectionException
1258
-     */
1259
-    public function is_cancellation()
1260
-    {
1261
-        return EEM_Line_Item::type_cancellation === $this->type();
1262
-    }
1263
-
1264
-
1265
-    /**
1266
-     * @return bool
1267
-     * @throws EE_Error
1268
-     * @throws InvalidArgumentException
1269
-     * @throws InvalidDataTypeException
1270
-     * @throws InvalidInterfaceException
1271
-     * @throws ReflectionException
1272
-     */
1273
-    public function is_total()
1274
-    {
1275
-        return $this->type() === EEM_Line_Item::type_total;
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * @return bool
1281
-     * @throws EE_Error
1282
-     * @throws InvalidArgumentException
1283
-     * @throws InvalidDataTypeException
1284
-     * @throws InvalidInterfaceException
1285
-     * @throws ReflectionException
1286
-     */
1287
-    public function is_cancelled()
1288
-    {
1289
-        return $this->type() === EEM_Line_Item::type_cancellation;
1290
-    }
1291
-
1292
-
1293
-    /**
1294
-     * @return string like '2, 004.00', formatted according to the localized currency
1295
-     * @throws EE_Error
1296
-     * @throws ReflectionException
1297
-     */
1298
-    public function unit_price_no_code(): string
1299
-    {
1300
-        return $this->prettyUnitPrice();
1301
-    }
1302
-
1303
-
1304
-    /**
1305
-     * @return string like '2, 004.00', formatted according to the localized currency
1306
-     * @throws EE_Error
1307
-     * @throws ReflectionException
1308
-     * @since 5.0.0.p
1309
-     */
1310
-    public function prettyUnitPrice(): string
1311
-    {
1312
-        return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1313
-    }
1314
-
1315
-
1316
-    /**
1317
-     * @return string like '2, 004.00', formatted according to the localized currency
1318
-     * @throws EE_Error
1319
-     * @throws ReflectionException
1320
-     */
1321
-    public function total_no_code(): string
1322
-    {
1323
-        return $this->prettyTotal();
1324
-    }
1325
-
1326
-
1327
-    /**
1328
-     * @return string like '2, 004.00', formatted according to the localized currency
1329
-     * @throws EE_Error
1330
-     * @throws ReflectionException
1331
-     * @since 5.0.0.p
1332
-     */
1333
-    public function prettyTotal(): string
1334
-    {
1335
-        return $this->get_pretty('LIN_total', 'no_currency_code');
1336
-    }
1337
-
1338
-
1339
-    /**
1340
-     * Gets the final total on this item, taking taxes into account.
1341
-     * Has the side-effect of setting the sub-total as it was just calculated.
1342
-     * If this is used on a grand-total line item, also updates the transaction's
1343
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
1344
-     * want to change a persistable transaction with info from a non-persistent line item)
1345
-     *
1346
-     * @param bool $update_txn_status
1347
-     * @return float
1348
-     * @throws EE_Error
1349
-     * @throws InvalidArgumentException
1350
-     * @throws InvalidDataTypeException
1351
-     * @throws InvalidInterfaceException
1352
-     * @throws ReflectionException
1353
-     * @throws RuntimeException
1354
-     */
1355
-    public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1356
-    {
1357
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1358
-        return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1359
-    }
1360
-
1361
-
1362
-    /**
1363
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1364
-     * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1365
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1366
-     * when this is called on the grand total
1367
-     *
1368
-     * @return float
1369
-     * @throws EE_Error
1370
-     * @throws InvalidArgumentException
1371
-     * @throws InvalidDataTypeException
1372
-     * @throws InvalidInterfaceException
1373
-     * @throws ReflectionException
1374
-     */
1375
-    public function recalculate_pre_tax_total(): float
1376
-    {
1377
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1378
-        [$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1379
-        return (float) $total;
1380
-    }
1381
-
1382
-
1383
-    /**
1384
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1385
-     * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1386
-     * and tax sub-total if already in the DB
1387
-     *
1388
-     * @return float
1389
-     * @throws EE_Error
1390
-     * @throws InvalidArgumentException
1391
-     * @throws InvalidDataTypeException
1392
-     * @throws InvalidInterfaceException
1393
-     * @throws ReflectionException
1394
-     */
1395
-    public function recalculate_taxes_and_tax_total(): float
1396
-    {
1397
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1398
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1399
-    }
1400
-
1401
-
1402
-    /**
1403
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
1404
-     * recalculate_taxes_and_total
1405
-     *
1406
-     * @return float
1407
-     * @throws EE_Error
1408
-     * @throws InvalidArgumentException
1409
-     * @throws InvalidDataTypeException
1410
-     * @throws InvalidInterfaceException
1411
-     * @throws ReflectionException
1412
-     */
1413
-    public function get_total_tax()
1414
-    {
1415
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1416
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1417
-    }
1418
-
1419
-
1420
-    /**
1421
-     * Gets the total for all the items purchased only
1422
-     *
1423
-     * @return float
1424
-     * @throws EE_Error
1425
-     * @throws InvalidArgumentException
1426
-     * @throws InvalidDataTypeException
1427
-     * @throws InvalidInterfaceException
1428
-     * @throws ReflectionException
1429
-     */
1430
-    public function get_items_total()
1431
-    {
1432
-        // by default, let's make sure we're consistent with the existing line item
1433
-        if ($this->is_total()) {
1434
-            return $this->pretaxTotal();
1435
-        }
1436
-        $total = 0;
1437
-        foreach ($this->get_items() as $item) {
1438
-            if ($item instanceof EE_Line_Item) {
1439
-                $total += $item->pretaxTotal();
1440
-            }
1441
-        }
1442
-        return $total;
1443
-    }
1444
-
1445
-
1446
-    /**
1447
-     * Gets all the descendants (ie, children or children of children etc) that
1448
-     * are of the type 'tax'
1449
-     *
1450
-     * @return EE_Line_Item[]
1451
-     * @throws EE_Error
1452
-     */
1453
-    public function tax_descendants()
1454
-    {
1455
-        return EEH_Line_Item::get_tax_descendants($this);
1456
-    }
1457
-
1458
-
1459
-    /**
1460
-     * Gets all the real items purchased which are children of this item
1461
-     *
1462
-     * @return EE_Line_Item[]
1463
-     * @throws EE_Error
1464
-     */
1465
-    public function get_items()
1466
-    {
1467
-        return EEH_Line_Item::get_line_item_descendants($this);
1468
-    }
1469
-
1470
-
1471
-    /**
1472
-     * Returns the amount taxable among this line item's children (or if it has no children,
1473
-     * how much of it is taxable). Does not recalculate totals or subtotals.
1474
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
1475
-     * but there is a "Taxable" discount), returns 0.
1476
-     *
1477
-     * @return float
1478
-     * @throws EE_Error
1479
-     * @throws InvalidArgumentException
1480
-     * @throws InvalidDataTypeException
1481
-     * @throws InvalidInterfaceException
1482
-     * @throws ReflectionException
1483
-     */
1484
-    public function taxable_total(): float
1485
-    {
1486
-        return $this->calculator->taxableAmountForGlobalTaxes($this);
1487
-    }
1488
-
1489
-
1490
-    /**
1491
-     * Gets the transaction for this line item
1492
-     *
1493
-     * @return EE_Base_Class|EE_Transaction
1494
-     * @throws EE_Error
1495
-     * @throws InvalidArgumentException
1496
-     * @throws InvalidDataTypeException
1497
-     * @throws InvalidInterfaceException
1498
-     * @throws ReflectionException
1499
-     */
1500
-    public function transaction()
1501
-    {
1502
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1503
-    }
1504
-
1505
-
1506
-    /**
1507
-     * Saves this line item to the DB, and recursively saves its descendants.
1508
-     * Because there currently is no proper parent-child relation on the model,
1509
-     * save_this_and_cached() will NOT save the descendants.
1510
-     * Also sets the transaction on this line item and all its descendants before saving
1511
-     *
1512
-     * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1513
-     * @return int count of items saved
1514
-     * @throws EE_Error
1515
-     * @throws InvalidArgumentException
1516
-     * @throws InvalidDataTypeException
1517
-     * @throws InvalidInterfaceException
1518
-     * @throws ReflectionException
1519
-     */
1520
-    public function save_this_and_descendants_to_txn($txn_id = null)
1521
-    {
1522
-        $count = 0;
1523
-        if (! $txn_id) {
1524
-            $txn_id = $this->TXN_ID();
1525
-        }
1526
-        $this->set_TXN_ID($txn_id);
1527
-        $children = $this->children();
1528
-        $count += $this->save()
1529
-            ? 1
1530
-            : 0;
1531
-        foreach ($children as $child_line_item) {
1532
-            if ($child_line_item instanceof EE_Line_Item) {
1533
-                $child_line_item->set_parent_ID($this->ID());
1534
-                $count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1535
-            }
1536
-        }
1537
-        return $count;
1538
-    }
1539
-
1540
-
1541
-    /**
1542
-     * Saves this line item to the DB, and recursively saves its descendants.
1543
-     *
1544
-     * @return int count of items saved
1545
-     * @throws EE_Error
1546
-     * @throws InvalidArgumentException
1547
-     * @throws InvalidDataTypeException
1548
-     * @throws InvalidInterfaceException
1549
-     * @throws ReflectionException
1550
-     */
1551
-    public function save_this_and_descendants()
1552
-    {
1553
-        $count = 0;
1554
-        $children = $this->children();
1555
-        $count += $this->save()
1556
-            ? 1
1557
-            : 0;
1558
-        foreach ($children as $child_line_item) {
1559
-            if ($child_line_item instanceof EE_Line_Item) {
1560
-                $child_line_item->set_parent_ID($this->ID());
1561
-                $count += $child_line_item->save_this_and_descendants();
1562
-            }
1563
-        }
1564
-        return $count;
1565
-    }
1566
-
1567
-
1568
-    /**
1569
-     * returns the cancellation line item if this item was cancelled
1570
-     *
1571
-     * @return EE_Line_Item[]
1572
-     * @throws InvalidArgumentException
1573
-     * @throws InvalidInterfaceException
1574
-     * @throws InvalidDataTypeException
1575
-     * @throws ReflectionException
1576
-     * @throws EE_Error
1577
-     */
1578
-    public function get_cancellations()
1579
-    {
1580
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1581
-    }
1582
-
1583
-
1584
-    /**
1585
-     * If this item has an ID, then this saves it again to update the db
1586
-     *
1587
-     * @return int count of items saved
1588
-     * @throws EE_Error
1589
-     * @throws InvalidArgumentException
1590
-     * @throws InvalidDataTypeException
1591
-     * @throws InvalidInterfaceException
1592
-     * @throws ReflectionException
1593
-     */
1594
-    public function maybe_save()
1595
-    {
1596
-        if ($this->ID()) {
1597
-            return $this->save();
1598
-        }
1599
-        return false;
1600
-    }
1601
-
1602
-
1603
-    /**
1604
-     * clears the cached children and parent from the line item
1605
-     *
1606
-     * @return void
1607
-     */
1608
-    public function clear_related_line_item_cache()
1609
-    {
1610
-        $this->_children = array();
1611
-        $this->_parent = null;
1612
-    }
1613
-
1614
-
1615
-    /**
1616
-     * @param bool $raw
1617
-     * @return int
1618
-     * @throws EE_Error
1619
-     * @throws InvalidArgumentException
1620
-     * @throws InvalidDataTypeException
1621
-     * @throws InvalidInterfaceException
1622
-     * @throws ReflectionException
1623
-     */
1624
-    public function timestamp($raw = false)
1625
-    {
1626
-        return $raw
1627
-            ? $this->get_raw('LIN_timestamp')
1628
-            : $this->get('LIN_timestamp');
1629
-    }
1630
-
1631
-
1632
-
1633
-
1634
-    /************************* DEPRECATED *************************/
1635
-    /**
1636
-     * @deprecated 4.6.0
1637
-     * @param string $type one of the constants on EEM_Line_Item
1638
-     * @return EE_Line_Item[]
1639
-     * @throws EE_Error
1640
-     */
1641
-    protected function _get_descendants_of_type($type)
1642
-    {
1643
-        EE_Error::doing_it_wrong(
1644
-            'EE_Line_Item::_get_descendants_of_type()',
1645
-            sprintf(
1646
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1647
-                'EEH_Line_Item::get_descendants_of_type()'
1648
-            ),
1649
-            '4.6.0'
1650
-        );
1651
-        return EEH_Line_Item::get_descendants_of_type($this, $type);
1652
-    }
1653
-
1654
-
1655
-    /**
1656
-     * @deprecated 4.6.0
1657
-     * @param string $type like one of the EEM_Line_Item::type_*
1658
-     * @return EE_Line_Item
1659
-     * @throws EE_Error
1660
-     * @throws InvalidArgumentException
1661
-     * @throws InvalidDataTypeException
1662
-     * @throws InvalidInterfaceException
1663
-     * @throws ReflectionException
1664
-     */
1665
-    public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1666
-    {
1667
-        EE_Error::doing_it_wrong(
1668
-            'EE_Line_Item::get_nearest_descendant_of_type()',
1669
-            sprintf(
1670
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1671
-                'EEH_Line_Item::get_nearest_descendant_of_type()'
1672
-            ),
1673
-            '4.6.0'
1674
-        );
1675
-        return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1676
-    }
18
+	/**
19
+	 * for children line items (currently not a normal relation)
20
+	 *
21
+	 * @type EE_Line_Item[]
22
+	 */
23
+	protected $_children = array();
24
+
25
+	/**
26
+	 * for the parent line item
27
+	 *
28
+	 * @var EE_Line_Item
29
+	 */
30
+	protected $_parent;
31
+
32
+	/**
33
+	 * @var LineItemCalculator
34
+	 */
35
+	protected $calculator;
36
+
37
+
38
+	/**
39
+	 * @param array  $props_n_values          incoming values
40
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
41
+	 *                                        used.)
42
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
43
+	 *                                        date_format and the second value is the time format
44
+	 * @return EE_Line_Item
45
+	 * @throws EE_Error
46
+	 * @throws InvalidArgumentException
47
+	 * @throws InvalidDataTypeException
48
+	 * @throws InvalidInterfaceException
49
+	 * @throws ReflectionException
50
+	 */
51
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
+	{
53
+		$has_object = parent::_check_for_object(
54
+			$props_n_values,
55
+			__CLASS__,
56
+			$timezone,
57
+			$date_formats
58
+		);
59
+		return $has_object
60
+			? $has_object
61
+			: new self($props_n_values, false, $timezone);
62
+	}
63
+
64
+
65
+	/**
66
+	 * @param array  $props_n_values  incoming values from the database
67
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
68
+	 *                                the website will be used.
69
+	 * @return EE_Line_Item
70
+	 * @throws EE_Error
71
+	 * @throws InvalidArgumentException
72
+	 * @throws InvalidDataTypeException
73
+	 * @throws InvalidInterfaceException
74
+	 * @throws ReflectionException
75
+	 */
76
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
77
+	{
78
+		return new self($props_n_values, true, $timezone);
79
+	}
80
+
81
+
82
+	/**
83
+	 * Adds some defaults if they're not specified
84
+	 *
85
+	 * @param array  $fieldValues
86
+	 * @param bool   $bydb
87
+	 * @param string $timezone
88
+	 * @throws EE_Error
89
+	 * @throws InvalidArgumentException
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 * @throws ReflectionException
93
+	 */
94
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
95
+	{
96
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
97
+		parent::__construct($fieldValues, $bydb, $timezone);
98
+		if (! $this->get('LIN_code')) {
99
+			$this->set_code($this->generate_code());
100
+		}
101
+	}
102
+
103
+
104
+	public function __wakeup()
105
+	{
106
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
107
+		parent::__wakeup();
108
+	}
109
+
110
+
111
+	/**
112
+	 * Gets ID
113
+	 *
114
+	 * @return int
115
+	 * @throws EE_Error
116
+	 * @throws InvalidArgumentException
117
+	 * @throws InvalidDataTypeException
118
+	 * @throws InvalidInterfaceException
119
+	 * @throws ReflectionException
120
+	 */
121
+	public function ID()
122
+	{
123
+		return $this->get('LIN_ID');
124
+	}
125
+
126
+
127
+	/**
128
+	 * Gets TXN_ID
129
+	 *
130
+	 * @return int
131
+	 * @throws EE_Error
132
+	 * @throws InvalidArgumentException
133
+	 * @throws InvalidDataTypeException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws ReflectionException
136
+	 */
137
+	public function TXN_ID()
138
+	{
139
+		return $this->get('TXN_ID');
140
+	}
141
+
142
+
143
+	/**
144
+	 * Sets TXN_ID
145
+	 *
146
+	 * @param int $TXN_ID
147
+	 * @throws EE_Error
148
+	 * @throws InvalidArgumentException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws InvalidInterfaceException
151
+	 * @throws ReflectionException
152
+	 */
153
+	public function set_TXN_ID($TXN_ID)
154
+	{
155
+		$this->set('TXN_ID', $TXN_ID);
156
+	}
157
+
158
+
159
+	/**
160
+	 * Gets name
161
+	 *
162
+	 * @return string
163
+	 * @throws EE_Error
164
+	 * @throws InvalidArgumentException
165
+	 * @throws InvalidDataTypeException
166
+	 * @throws InvalidInterfaceException
167
+	 * @throws ReflectionException
168
+	 */
169
+	public function name()
170
+	{
171
+		$name = $this->get('LIN_name');
172
+		if (! $name) {
173
+			$name = ucwords(str_replace('-', ' ', $this->type()));
174
+		}
175
+		return $name;
176
+	}
177
+
178
+
179
+	/**
180
+	 * Sets name
181
+	 *
182
+	 * @param string $name
183
+	 * @throws EE_Error
184
+	 * @throws InvalidArgumentException
185
+	 * @throws InvalidDataTypeException
186
+	 * @throws InvalidInterfaceException
187
+	 * @throws ReflectionException
188
+	 */
189
+	public function set_name($name)
190
+	{
191
+		$this->set('LIN_name', $name);
192
+	}
193
+
194
+
195
+	/**
196
+	 * Gets desc
197
+	 *
198
+	 * @return string
199
+	 * @throws EE_Error
200
+	 * @throws InvalidArgumentException
201
+	 * @throws InvalidDataTypeException
202
+	 * @throws InvalidInterfaceException
203
+	 * @throws ReflectionException
204
+	 */
205
+	public function desc()
206
+	{
207
+		return $this->get('LIN_desc');
208
+	}
209
+
210
+
211
+	/**
212
+	 * Sets desc
213
+	 *
214
+	 * @param string $desc
215
+	 * @throws EE_Error
216
+	 * @throws InvalidArgumentException
217
+	 * @throws InvalidDataTypeException
218
+	 * @throws InvalidInterfaceException
219
+	 * @throws ReflectionException
220
+	 */
221
+	public function set_desc($desc)
222
+	{
223
+		$this->set('LIN_desc', $desc);
224
+	}
225
+
226
+
227
+	/**
228
+	 * Gets quantity
229
+	 *
230
+	 * @return int
231
+	 * @throws EE_Error
232
+	 * @throws InvalidArgumentException
233
+	 * @throws InvalidDataTypeException
234
+	 * @throws InvalidInterfaceException
235
+	 * @throws ReflectionException
236
+	 */
237
+	public function quantity(): int
238
+	{
239
+		return (int) $this->get('LIN_quantity');
240
+	}
241
+
242
+
243
+	/**
244
+	 * Sets quantity
245
+	 *
246
+	 * @param int $quantity
247
+	 * @throws EE_Error
248
+	 * @throws InvalidArgumentException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws InvalidInterfaceException
251
+	 * @throws ReflectionException
252
+	 */
253
+	public function set_quantity($quantity)
254
+	{
255
+		$this->set('LIN_quantity', max($quantity, 0));
256
+	}
257
+
258
+
259
+	/**
260
+	 * Gets item_id
261
+	 *
262
+	 * @return int
263
+	 * @throws EE_Error
264
+	 * @throws InvalidArgumentException
265
+	 * @throws InvalidDataTypeException
266
+	 * @throws InvalidInterfaceException
267
+	 * @throws ReflectionException
268
+	 */
269
+	public function OBJ_ID()
270
+	{
271
+		return $this->get('OBJ_ID');
272
+	}
273
+
274
+
275
+	/**
276
+	 * Sets item_id
277
+	 *
278
+	 * @param int $item_id
279
+	 * @throws EE_Error
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidDataTypeException
282
+	 * @throws InvalidInterfaceException
283
+	 * @throws ReflectionException
284
+	 */
285
+	public function set_OBJ_ID($item_id)
286
+	{
287
+		$this->set('OBJ_ID', $item_id);
288
+	}
289
+
290
+
291
+	/**
292
+	 * Gets item_type
293
+	 *
294
+	 * @return string
295
+	 * @throws EE_Error
296
+	 * @throws InvalidArgumentException
297
+	 * @throws InvalidDataTypeException
298
+	 * @throws InvalidInterfaceException
299
+	 * @throws ReflectionException
300
+	 */
301
+	public function OBJ_type()
302
+	{
303
+		return $this->get('OBJ_type');
304
+	}
305
+
306
+
307
+	/**
308
+	 * Gets item_type
309
+	 *
310
+	 * @return string
311
+	 * @throws EE_Error
312
+	 * @throws InvalidArgumentException
313
+	 * @throws InvalidDataTypeException
314
+	 * @throws InvalidInterfaceException
315
+	 * @throws ReflectionException
316
+	 */
317
+	public function OBJ_type_i18n()
318
+	{
319
+		$obj_type = $this->OBJ_type();
320
+		switch ($obj_type) {
321
+			case EEM_Line_Item::OBJ_TYPE_EVENT:
322
+				$obj_type = esc_html__('Event', 'event_espresso');
323
+				break;
324
+			case EEM_Line_Item::OBJ_TYPE_PRICE:
325
+				$obj_type = esc_html__('Price', 'event_espresso');
326
+				break;
327
+			case EEM_Line_Item::OBJ_TYPE_PROMOTION:
328
+				$obj_type = esc_html__('Promotion', 'event_espresso');
329
+				break;
330
+			case EEM_Line_Item::OBJ_TYPE_TICKET:
331
+				$obj_type = esc_html__('Ticket', 'event_espresso');
332
+				break;
333
+			case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
334
+				$obj_type = esc_html__('Transaction', 'event_espresso');
335
+				break;
336
+		}
337
+		return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
338
+	}
339
+
340
+
341
+	/**
342
+	 * Sets item_type
343
+	 *
344
+	 * @param string $OBJ_type
345
+	 * @throws EE_Error
346
+	 * @throws InvalidArgumentException
347
+	 * @throws InvalidDataTypeException
348
+	 * @throws InvalidInterfaceException
349
+	 * @throws ReflectionException
350
+	 */
351
+	public function set_OBJ_type($OBJ_type)
352
+	{
353
+		$this->set('OBJ_type', $OBJ_type);
354
+	}
355
+
356
+
357
+	/**
358
+	 * Gets unit_price
359
+	 *
360
+	 * @return float
361
+	 * @throws EE_Error
362
+	 * @throws InvalidArgumentException
363
+	 * @throws InvalidDataTypeException
364
+	 * @throws InvalidInterfaceException
365
+	 * @throws ReflectionException
366
+	 */
367
+	public function unit_price()
368
+	{
369
+		return $this->get('LIN_unit_price');
370
+	}
371
+
372
+
373
+	/**
374
+	 * Sets unit_price
375
+	 *
376
+	 * @param float $unit_price
377
+	 * @throws EE_Error
378
+	 * @throws InvalidArgumentException
379
+	 * @throws InvalidDataTypeException
380
+	 * @throws InvalidInterfaceException
381
+	 * @throws ReflectionException
382
+	 */
383
+	public function set_unit_price($unit_price)
384
+	{
385
+		$this->set('LIN_unit_price', $unit_price);
386
+	}
387
+
388
+
389
+	/**
390
+	 * Checks if this item is a percentage modifier or not
391
+	 *
392
+	 * @return boolean
393
+	 * @throws EE_Error
394
+	 * @throws InvalidArgumentException
395
+	 * @throws InvalidDataTypeException
396
+	 * @throws InvalidInterfaceException
397
+	 * @throws ReflectionException
398
+	 */
399
+	public function is_percent()
400
+	{
401
+		if ($this->is_tax_sub_total()) {
402
+			// tax subtotals HAVE a percent on them, that percentage only applies
403
+			// to taxable items, so its' an exception. Treat it like a flat line item
404
+			return false;
405
+		}
406
+		$unit_price = abs($this->get('LIN_unit_price'));
407
+		$percent = abs($this->get('LIN_percent'));
408
+		if ($unit_price < .001 && $percent) {
409
+			return true;
410
+		}
411
+		if ($unit_price >= .001 && ! $percent) {
412
+			return false;
413
+		}
414
+		if ($unit_price >= .001 && $percent) {
415
+			throw new EE_Error(
416
+				sprintf(
417
+					esc_html__(
418
+						'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
419
+						'event_espresso'
420
+					),
421
+					$unit_price,
422
+					$percent
423
+				)
424
+			);
425
+		}
426
+		// if they're both 0, assume its not a percent item
427
+		return false;
428
+	}
429
+
430
+
431
+	/**
432
+	 * Gets percent (between 100-.001)
433
+	 *
434
+	 * @return float
435
+	 * @throws EE_Error
436
+	 * @throws InvalidArgumentException
437
+	 * @throws InvalidDataTypeException
438
+	 * @throws InvalidInterfaceException
439
+	 * @throws ReflectionException
440
+	 */
441
+	public function percent()
442
+	{
443
+		return $this->get('LIN_percent');
444
+	}
445
+
446
+
447
+	/**
448
+	 * @return string
449
+	 * @throws EE_Error
450
+	 * @throws ReflectionException
451
+	 * @since 5.0.0.p
452
+	 */
453
+	public function prettyPercent(): string
454
+	{
455
+		return $this->get_pretty('LIN_percent');
456
+	}
457
+
458
+
459
+	/**
460
+	 * Sets percent (between 100-0.01)
461
+	 *
462
+	 * @param float $percent
463
+	 * @throws EE_Error
464
+	 * @throws InvalidArgumentException
465
+	 * @throws InvalidDataTypeException
466
+	 * @throws InvalidInterfaceException
467
+	 * @throws ReflectionException
468
+	 */
469
+	public function set_percent($percent)
470
+	{
471
+		$this->set('LIN_percent', $percent);
472
+	}
473
+
474
+
475
+	/**
476
+	 * Gets total
477
+	 *
478
+	 * @return float
479
+	 * @throws EE_Error
480
+	 * @throws InvalidArgumentException
481
+	 * @throws InvalidDataTypeException
482
+	 * @throws InvalidInterfaceException
483
+	 * @throws ReflectionException
484
+	 */
485
+	public function pretaxTotal(): float
486
+	{
487
+		return (float) $this->get('LIN_pretax');
488
+	}
489
+
490
+
491
+	/**
492
+	 * Sets total
493
+	 *
494
+	 * @param float $pretax_total
495
+	 * @throws EE_Error
496
+	 * @throws InvalidArgumentException
497
+	 * @throws InvalidDataTypeException
498
+	 * @throws InvalidInterfaceException
499
+	 * @throws ReflectionException
500
+	 */
501
+	public function setPretaxTotal(float $pretax_total)
502
+	{
503
+		$this->set('LIN_pretax', $pretax_total);
504
+	}
505
+
506
+
507
+	/**
508
+	 * @return float
509
+	 * @throws EE_Error
510
+	 * @throws ReflectionException
511
+	 * @since  5.0.0.p
512
+	 */
513
+	public function totalWithTax(): float
514
+	{
515
+		return (float) $this->get('LIN_total');
516
+	}
517
+
518
+
519
+	/**
520
+	 * Sets total
521
+	 *
522
+	 * @param float $total
523
+	 * @throws EE_Error
524
+	 * @throws ReflectionException
525
+	 * @since  5.0.0.p
526
+	 */
527
+	public function setTotalWithTax(float $total)
528
+	{
529
+		$this->set('LIN_total', $total);
530
+	}
531
+
532
+
533
+	/**
534
+	 * Gets total
535
+	 *
536
+	 * @return float
537
+	 * @throws EE_Error
538
+	 * @throws ReflectionException
539
+	 * @deprecatd 5.0.0.p
540
+	 */
541
+	public function total(): float
542
+	{
543
+		return $this->totalWithTax();
544
+	}
545
+
546
+
547
+	/**
548
+	 * Sets total
549
+	 *
550
+	 * @param float $total
551
+	 * @throws EE_Error
552
+	 * @throws ReflectionException
553
+	 * @deprecatd 5.0.0.p
554
+	 */
555
+	public function set_total($total)
556
+	{
557
+		$this->setTotalWithTax($total);
558
+	}
559
+
560
+
561
+	/**
562
+	 * Gets order
563
+	 *
564
+	 * @return int
565
+	 * @throws EE_Error
566
+	 * @throws InvalidArgumentException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws InvalidInterfaceException
569
+	 * @throws ReflectionException
570
+	 */
571
+	public function order()
572
+	{
573
+		return $this->get('LIN_order');
574
+	}
575
+
576
+
577
+	/**
578
+	 * Sets order
579
+	 *
580
+	 * @param int $order
581
+	 * @throws EE_Error
582
+	 * @throws InvalidArgumentException
583
+	 * @throws InvalidDataTypeException
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws ReflectionException
586
+	 */
587
+	public function set_order($order)
588
+	{
589
+		$this->set('LIN_order', $order);
590
+	}
591
+
592
+
593
+	/**
594
+	 * Gets parent
595
+	 *
596
+	 * @return int
597
+	 * @throws EE_Error
598
+	 * @throws InvalidArgumentException
599
+	 * @throws InvalidDataTypeException
600
+	 * @throws InvalidInterfaceException
601
+	 * @throws ReflectionException
602
+	 */
603
+	public function parent_ID()
604
+	{
605
+		return $this->get('LIN_parent');
606
+	}
607
+
608
+
609
+	/**
610
+	 * Sets parent
611
+	 *
612
+	 * @param int $parent
613
+	 * @throws EE_Error
614
+	 * @throws InvalidArgumentException
615
+	 * @throws InvalidDataTypeException
616
+	 * @throws InvalidInterfaceException
617
+	 * @throws ReflectionException
618
+	 */
619
+	public function set_parent_ID($parent)
620
+	{
621
+		$this->set('LIN_parent', $parent);
622
+	}
623
+
624
+
625
+	/**
626
+	 * Gets type
627
+	 *
628
+	 * @return string
629
+	 * @throws EE_Error
630
+	 * @throws InvalidArgumentException
631
+	 * @throws InvalidDataTypeException
632
+	 * @throws InvalidInterfaceException
633
+	 * @throws ReflectionException
634
+	 */
635
+	public function type()
636
+	{
637
+		return $this->get('LIN_type');
638
+	}
639
+
640
+
641
+	/**
642
+	 * Sets type
643
+	 *
644
+	 * @param string $type
645
+	 * @throws EE_Error
646
+	 * @throws InvalidArgumentException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws InvalidInterfaceException
649
+	 * @throws ReflectionException
650
+	 */
651
+	public function set_type($type)
652
+	{
653
+		$this->set('LIN_type', $type);
654
+	}
655
+
656
+
657
+	/**
658
+	 * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
659
+	 * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
660
+	 * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
661
+	 * or indirectly by `EE_Line_item::add_child_line_item()`)
662
+	 *
663
+	 * @return EE_Base_Class|EE_Line_Item
664
+	 * @throws EE_Error
665
+	 * @throws InvalidArgumentException
666
+	 * @throws InvalidDataTypeException
667
+	 * @throws InvalidInterfaceException
668
+	 * @throws ReflectionException
669
+	 */
670
+	public function parent()
671
+	{
672
+		return $this->ID()
673
+			? $this->get_model()->get_one_by_ID($this->parent_ID())
674
+			: $this->_parent;
675
+	}
676
+
677
+
678
+	/**
679
+	 * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
680
+	 *
681
+	 * @return EE_Line_Item[]
682
+	 * @throws EE_Error
683
+	 * @throws InvalidArgumentException
684
+	 * @throws InvalidDataTypeException
685
+	 * @throws InvalidInterfaceException
686
+	 * @throws ReflectionException
687
+	 */
688
+	public function children(array $query_params = []): array
689
+	{
690
+		if ($this->ID()) {
691
+			// ensure where params are an array
692
+			$query_params[0] = $query_params[0] ?? [];
693
+			// add defaults for line item parent and orderby
694
+			$query_params[0] += ['LIN_parent' => $this->ID()];
695
+			$query_params += ['order_by' => ['LIN_order' => 'ASC']];
696
+			return $this->get_model()->get_all($query_params);
697
+		}
698
+		if (! is_array($this->_children)) {
699
+			$this->_children = array();
700
+		}
701
+		return $this->_children;
702
+	}
703
+
704
+
705
+	/**
706
+	 * Gets code
707
+	 *
708
+	 * @return string
709
+	 * @throws EE_Error
710
+	 * @throws InvalidArgumentException
711
+	 * @throws InvalidDataTypeException
712
+	 * @throws InvalidInterfaceException
713
+	 * @throws ReflectionException
714
+	 */
715
+	public function code()
716
+	{
717
+		return $this->get('LIN_code');
718
+	}
719
+
720
+
721
+	/**
722
+	 * Sets code
723
+	 *
724
+	 * @param string $code
725
+	 * @throws EE_Error
726
+	 * @throws InvalidArgumentException
727
+	 * @throws InvalidDataTypeException
728
+	 * @throws InvalidInterfaceException
729
+	 * @throws ReflectionException
730
+	 */
731
+	public function set_code($code)
732
+	{
733
+		$this->set('LIN_code', $code);
734
+	}
735
+
736
+
737
+	/**
738
+	 * Gets is_taxable
739
+	 *
740
+	 * @return boolean
741
+	 * @throws EE_Error
742
+	 * @throws InvalidArgumentException
743
+	 * @throws InvalidDataTypeException
744
+	 * @throws InvalidInterfaceException
745
+	 * @throws ReflectionException
746
+	 */
747
+	public function is_taxable()
748
+	{
749
+		return $this->get('LIN_is_taxable');
750
+	}
751
+
752
+
753
+	/**
754
+	 * Sets is_taxable
755
+	 *
756
+	 * @param boolean $is_taxable
757
+	 * @throws EE_Error
758
+	 * @throws InvalidArgumentException
759
+	 * @throws InvalidDataTypeException
760
+	 * @throws InvalidInterfaceException
761
+	 * @throws ReflectionException
762
+	 */
763
+	public function set_is_taxable($is_taxable)
764
+	{
765
+		$this->set('LIN_is_taxable', $is_taxable);
766
+	}
767
+
768
+
769
+	/**
770
+	 * @param int $timestamp
771
+	 * @throws EE_Error
772
+	 * @throws ReflectionException
773
+	 * @since 5.0.0.p
774
+	 */
775
+	public function setTimestamp(int $timestamp)
776
+	{
777
+		$this->set('LIN_timestamp', $timestamp);
778
+	}
779
+
780
+
781
+	/**
782
+	 * Gets the object that this model-joins-to.
783
+	 * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
784
+	 * EEM_Promotion_Object
785
+	 *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
786
+	 *
787
+	 * @return EE_Base_Class | NULL
788
+	 * @throws EE_Error
789
+	 * @throws InvalidArgumentException
790
+	 * @throws InvalidDataTypeException
791
+	 * @throws InvalidInterfaceException
792
+	 * @throws ReflectionException
793
+	 */
794
+	public function get_object()
795
+	{
796
+		$model_name_of_related_obj = $this->OBJ_type();
797
+		return $this->get_model()->has_relation($model_name_of_related_obj)
798
+			? $this->get_first_related($model_name_of_related_obj)
799
+			: null;
800
+	}
801
+
802
+
803
+	/**
804
+	 * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
805
+	 * (IE, if this line item is for a price or something else, will return NULL)
806
+	 *
807
+	 * @param array $query_params
808
+	 * @return EE_Base_Class|EE_Ticket
809
+	 * @throws EE_Error
810
+	 * @throws InvalidArgumentException
811
+	 * @throws InvalidDataTypeException
812
+	 * @throws InvalidInterfaceException
813
+	 * @throws ReflectionException
814
+	 */
815
+	public function ticket($query_params = array())
816
+	{
817
+		// we're going to assume that when this method is called
818
+		// we always want to receive the attached ticket EVEN if that ticket is archived.
819
+		// This can be overridden via the incoming $query_params argument
820
+		$remove_defaults = array('default_where_conditions' => 'none');
821
+		$query_params = array_merge($remove_defaults, $query_params);
822
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
823
+	}
824
+
825
+
826
+	/**
827
+	 * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
828
+	 *
829
+	 * @return EE_Datetime | NULL
830
+	 * @throws EE_Error
831
+	 * @throws InvalidArgumentException
832
+	 * @throws InvalidDataTypeException
833
+	 * @throws InvalidInterfaceException
834
+	 * @throws ReflectionException
835
+	 */
836
+	public function get_ticket_datetime()
837
+	{
838
+		if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
839
+			$ticket = $this->ticket();
840
+			if ($ticket instanceof EE_Ticket) {
841
+				$datetime = $ticket->first_datetime();
842
+				if ($datetime instanceof EE_Datetime) {
843
+					return $datetime;
844
+				}
845
+			}
846
+		}
847
+		return null;
848
+	}
849
+
850
+
851
+	/**
852
+	 * Gets the event's name that's related to the ticket, if this is for
853
+	 * a ticket
854
+	 *
855
+	 * @return string
856
+	 * @throws EE_Error
857
+	 * @throws InvalidArgumentException
858
+	 * @throws InvalidDataTypeException
859
+	 * @throws InvalidInterfaceException
860
+	 * @throws ReflectionException
861
+	 */
862
+	public function ticket_event_name()
863
+	{
864
+		$event_name = esc_html__('Unknown', 'event_espresso');
865
+		$event = $this->ticket_event();
866
+		if ($event instanceof EE_Event) {
867
+			$event_name = $event->name();
868
+		}
869
+		return $event_name;
870
+	}
871
+
872
+
873
+	/**
874
+	 * Gets the event that's related to the ticket, if this line item represents a ticket.
875
+	 *
876
+	 * @return EE_Event|null
877
+	 * @throws EE_Error
878
+	 * @throws InvalidArgumentException
879
+	 * @throws InvalidDataTypeException
880
+	 * @throws InvalidInterfaceException
881
+	 * @throws ReflectionException
882
+	 */
883
+	public function ticket_event()
884
+	{
885
+		$event = null;
886
+		$ticket = $this->ticket();
887
+		if ($ticket instanceof EE_Ticket) {
888
+			$datetime = $ticket->first_datetime();
889
+			if ($datetime instanceof EE_Datetime) {
890
+				$event = $datetime->event();
891
+			}
892
+		}
893
+		return $event;
894
+	}
895
+
896
+
897
+	/**
898
+	 * Gets the first datetime for this lien item, assuming it's for a ticket
899
+	 *
900
+	 * @param string $date_format
901
+	 * @param string $time_format
902
+	 * @return string
903
+	 * @throws EE_Error
904
+	 * @throws InvalidArgumentException
905
+	 * @throws InvalidDataTypeException
906
+	 * @throws InvalidInterfaceException
907
+	 * @throws ReflectionException
908
+	 */
909
+	public function ticket_datetime_start($date_format = '', $time_format = '')
910
+	{
911
+		$first_datetime_string = esc_html__('Unknown', 'event_espresso');
912
+		$datetime = $this->get_ticket_datetime();
913
+		if ($datetime) {
914
+			$first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
915
+		}
916
+		return $first_datetime_string;
917
+	}
918
+
919
+
920
+	/**
921
+	 * Adds the line item as a child to this line item. If there is another child line
922
+	 * item with the same LIN_code, it is overwritten by this new one
923
+	 *
924
+	 * @param EE_Line_Item $line_item
925
+	 * @param bool          $set_order
926
+	 * @return bool success
927
+	 * @throws EE_Error
928
+	 * @throws InvalidArgumentException
929
+	 * @throws InvalidDataTypeException
930
+	 * @throws InvalidInterfaceException
931
+	 * @throws ReflectionException
932
+	 */
933
+	public function add_child_line_item(EE_Line_Item $line_item, $set_order = true)
934
+	{
935
+		// should we calculate the LIN_order for this line item ?
936
+		if ($set_order || $line_item->order() === null) {
937
+			$line_item->set_order(count($this->children()));
938
+		}
939
+		if ($this->ID()) {
940
+			// check for any duplicate line items (with the same code), if so, this replaces it
941
+			$line_item_with_same_code = $this->get_child_line_item($line_item->code());
942
+			if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
943
+				$this->delete_child_line_item($line_item_with_same_code->code());
944
+			}
945
+			$line_item->set_parent_ID($this->ID());
946
+			if ($this->TXN_ID()) {
947
+				$line_item->set_TXN_ID($this->TXN_ID());
948
+			}
949
+			return $line_item->save();
950
+		}
951
+		$this->_children[ $line_item->code() ] = $line_item;
952
+		if ($line_item->parent() !== $this) {
953
+			$line_item->set_parent($this);
954
+		}
955
+		return true;
956
+	}
957
+
958
+
959
+	/**
960
+	 * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
961
+	 * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
962
+	 * However, if this line item is NOT saved to the DB, this just caches the parent on
963
+	 * the EE_Line_Item::_parent property.
964
+	 *
965
+	 * @param EE_Line_Item $line_item
966
+	 * @throws EE_Error
967
+	 * @throws InvalidArgumentException
968
+	 * @throws InvalidDataTypeException
969
+	 * @throws InvalidInterfaceException
970
+	 * @throws ReflectionException
971
+	 */
972
+	public function set_parent($line_item)
973
+	{
974
+		if ($this->ID()) {
975
+			if (! $line_item->ID()) {
976
+				$line_item->save();
977
+			}
978
+			$this->set_parent_ID($line_item->ID());
979
+			$this->save();
980
+		} else {
981
+			$this->_parent = $line_item;
982
+			$this->set_parent_ID($line_item->ID());
983
+		}
984
+	}
985
+
986
+
987
+	/**
988
+	 * Gets the child line item as specified by its code. Because this returns an object (by reference)
989
+	 * you can modify this child line item and the parent (this object) can know about them
990
+	 * because it also has a reference to that line item
991
+	 *
992
+	 * @param string $code
993
+	 * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
994
+	 * @throws EE_Error
995
+	 * @throws InvalidArgumentException
996
+	 * @throws InvalidDataTypeException
997
+	 * @throws InvalidInterfaceException
998
+	 * @throws ReflectionException
999
+	 */
1000
+	public function get_child_line_item($code)
1001
+	{
1002
+		if ($this->ID()) {
1003
+			return $this->get_model()->get_one(
1004
+				array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
1005
+			);
1006
+		}
1007
+		return isset($this->_children[ $code ])
1008
+			? $this->_children[ $code ]
1009
+			: null;
1010
+	}
1011
+
1012
+
1013
+	/**
1014
+	 * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1015
+	 * cached on it)
1016
+	 *
1017
+	 * @return int
1018
+	 * @throws EE_Error
1019
+	 * @throws InvalidArgumentException
1020
+	 * @throws InvalidDataTypeException
1021
+	 * @throws InvalidInterfaceException
1022
+	 * @throws ReflectionException
1023
+	 */
1024
+	public function delete_children_line_items()
1025
+	{
1026
+		if ($this->ID()) {
1027
+			return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
1028
+		}
1029
+		$count = count($this->_children);
1030
+		$this->_children = array();
1031
+		return $count;
1032
+	}
1033
+
1034
+
1035
+	/**
1036
+	 * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1037
+	 * HAS NOT been saved to the DB, removes the child line item with index $code.
1038
+	 * Also searches through the child's children for a matching line item. However, once a line item has been found
1039
+	 * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1040
+	 * deleted)
1041
+	 *
1042
+	 * @param string $code
1043
+	 * @param bool   $stop_search_once_found
1044
+	 * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1045
+	 *             the DB yet)
1046
+	 * @throws EE_Error
1047
+	 * @throws InvalidArgumentException
1048
+	 * @throws InvalidDataTypeException
1049
+	 * @throws InvalidInterfaceException
1050
+	 * @throws ReflectionException
1051
+	 */
1052
+	public function delete_child_line_item($code, $stop_search_once_found = true)
1053
+	{
1054
+		if ($this->ID()) {
1055
+			$items_deleted = 0;
1056
+			if ($this->code() === $code) {
1057
+				$items_deleted += EEH_Line_Item::delete_all_child_items($this);
1058
+				$items_deleted += (int) $this->delete();
1059
+				if ($stop_search_once_found) {
1060
+					return $items_deleted;
1061
+				}
1062
+			}
1063
+			foreach ($this->children() as $child_line_item) {
1064
+				$items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1065
+			}
1066
+			return $items_deleted;
1067
+		}
1068
+		if (isset($this->_children[ $code ])) {
1069
+			unset($this->_children[ $code ]);
1070
+			return 1;
1071
+		}
1072
+		return 0;
1073
+	}
1074
+
1075
+
1076
+	/**
1077
+	 * If this line item is in the database, is of the type subtotal, and
1078
+	 * has no children, why do we have it? It should be deleted so this function
1079
+	 * does that
1080
+	 *
1081
+	 * @return boolean
1082
+	 * @throws EE_Error
1083
+	 * @throws InvalidArgumentException
1084
+	 * @throws InvalidDataTypeException
1085
+	 * @throws InvalidInterfaceException
1086
+	 * @throws ReflectionException
1087
+	 */
1088
+	public function delete_if_childless_subtotal()
1089
+	{
1090
+		if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1091
+			return $this->delete();
1092
+		}
1093
+		return false;
1094
+	}
1095
+
1096
+
1097
+	/**
1098
+	 * Creates a code and returns a string. doesn't assign the code to this model object
1099
+	 *
1100
+	 * @return string
1101
+	 * @throws EE_Error
1102
+	 * @throws InvalidArgumentException
1103
+	 * @throws InvalidDataTypeException
1104
+	 * @throws InvalidInterfaceException
1105
+	 * @throws ReflectionException
1106
+	 */
1107
+	public function generate_code()
1108
+	{
1109
+		// each line item in the cart requires a unique identifier
1110
+		return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1111
+	}
1112
+
1113
+
1114
+	/**
1115
+	 * @return bool
1116
+	 * @throws EE_Error
1117
+	 * @throws InvalidArgumentException
1118
+	 * @throws InvalidDataTypeException
1119
+	 * @throws InvalidInterfaceException
1120
+	 * @throws ReflectionException
1121
+	 */
1122
+	public function isGlobalTax(): bool
1123
+	{
1124
+		return $this->type() === EEM_Line_Item::type_tax;
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * @return bool
1130
+	 * @throws EE_Error
1131
+	 * @throws InvalidArgumentException
1132
+	 * @throws InvalidDataTypeException
1133
+	 * @throws InvalidInterfaceException
1134
+	 * @throws ReflectionException
1135
+	 */
1136
+	public function isSubTax(): bool
1137
+	{
1138
+		return $this->type() === EEM_Line_Item::type_sub_tax;
1139
+	}
1140
+
1141
+
1142
+	/**
1143
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1144
+	 *
1145
+	 * @return array
1146
+	 * @throws EE_Error
1147
+	 * @throws InvalidArgumentException
1148
+	 * @throws InvalidDataTypeException
1149
+	 * @throws InvalidInterfaceException
1150
+	 * @throws ReflectionException
1151
+	 */
1152
+	public function getSubTaxes(): array
1153
+	{
1154
+		if (! $this->is_line_item()) {
1155
+			return [];
1156
+		}
1157
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1163
+	 *
1164
+	 * @return bool
1165
+	 * @throws EE_Error
1166
+	 * @throws InvalidArgumentException
1167
+	 * @throws InvalidDataTypeException
1168
+	 * @throws InvalidInterfaceException
1169
+	 * @throws ReflectionException
1170
+	 */
1171
+	public function hasSubTaxes(): bool
1172
+	{
1173
+		if (! $this->is_line_item()) {
1174
+			return false;
1175
+		}
1176
+		$sub_taxes = $this->getSubTaxes();
1177
+		return ! empty($sub_taxes);
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * @return bool
1183
+	 * @throws EE_Error
1184
+	 * @throws ReflectionException
1185
+	 * @deprecated   5.0.0.p
1186
+	 */
1187
+	public function is_tax(): bool
1188
+	{
1189
+		return $this->isGlobalTax();
1190
+	}
1191
+
1192
+
1193
+	/**
1194
+	 * @return bool
1195
+	 * @throws EE_Error
1196
+	 * @throws InvalidArgumentException
1197
+	 * @throws InvalidDataTypeException
1198
+	 * @throws InvalidInterfaceException
1199
+	 * @throws ReflectionException
1200
+	 */
1201
+	public function is_tax_sub_total()
1202
+	{
1203
+		return $this->type() === EEM_Line_Item::type_tax_sub_total;
1204
+	}
1205
+
1206
+
1207
+	/**
1208
+	 * @return bool
1209
+	 * @throws EE_Error
1210
+	 * @throws InvalidArgumentException
1211
+	 * @throws InvalidDataTypeException
1212
+	 * @throws InvalidInterfaceException
1213
+	 * @throws ReflectionException
1214
+	 */
1215
+	public function is_line_item()
1216
+	{
1217
+		return $this->type() === EEM_Line_Item::type_line_item;
1218
+	}
1219
+
1220
+
1221
+	/**
1222
+	 * @return bool
1223
+	 * @throws EE_Error
1224
+	 * @throws InvalidArgumentException
1225
+	 * @throws InvalidDataTypeException
1226
+	 * @throws InvalidInterfaceException
1227
+	 * @throws ReflectionException
1228
+	 */
1229
+	public function is_sub_line_item()
1230
+	{
1231
+		return $this->type() === EEM_Line_Item::type_sub_line_item;
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 * @return bool
1237
+	 * @throws EE_Error
1238
+	 * @throws InvalidArgumentException
1239
+	 * @throws InvalidDataTypeException
1240
+	 * @throws InvalidInterfaceException
1241
+	 * @throws ReflectionException
1242
+	 */
1243
+	public function is_sub_total()
1244
+	{
1245
+		return $this->type() === EEM_Line_Item::type_sub_total;
1246
+	}
1247
+
1248
+
1249
+	/**
1250
+	 * Whether or not this line item is a cancellation line item
1251
+	 *
1252
+	 * @return boolean
1253
+	 * @throws EE_Error
1254
+	 * @throws InvalidArgumentException
1255
+	 * @throws InvalidDataTypeException
1256
+	 * @throws InvalidInterfaceException
1257
+	 * @throws ReflectionException
1258
+	 */
1259
+	public function is_cancellation()
1260
+	{
1261
+		return EEM_Line_Item::type_cancellation === $this->type();
1262
+	}
1263
+
1264
+
1265
+	/**
1266
+	 * @return bool
1267
+	 * @throws EE_Error
1268
+	 * @throws InvalidArgumentException
1269
+	 * @throws InvalidDataTypeException
1270
+	 * @throws InvalidInterfaceException
1271
+	 * @throws ReflectionException
1272
+	 */
1273
+	public function is_total()
1274
+	{
1275
+		return $this->type() === EEM_Line_Item::type_total;
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * @return bool
1281
+	 * @throws EE_Error
1282
+	 * @throws InvalidArgumentException
1283
+	 * @throws InvalidDataTypeException
1284
+	 * @throws InvalidInterfaceException
1285
+	 * @throws ReflectionException
1286
+	 */
1287
+	public function is_cancelled()
1288
+	{
1289
+		return $this->type() === EEM_Line_Item::type_cancellation;
1290
+	}
1291
+
1292
+
1293
+	/**
1294
+	 * @return string like '2, 004.00', formatted according to the localized currency
1295
+	 * @throws EE_Error
1296
+	 * @throws ReflectionException
1297
+	 */
1298
+	public function unit_price_no_code(): string
1299
+	{
1300
+		return $this->prettyUnitPrice();
1301
+	}
1302
+
1303
+
1304
+	/**
1305
+	 * @return string like '2, 004.00', formatted according to the localized currency
1306
+	 * @throws EE_Error
1307
+	 * @throws ReflectionException
1308
+	 * @since 5.0.0.p
1309
+	 */
1310
+	public function prettyUnitPrice(): string
1311
+	{
1312
+		return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1313
+	}
1314
+
1315
+
1316
+	/**
1317
+	 * @return string like '2, 004.00', formatted according to the localized currency
1318
+	 * @throws EE_Error
1319
+	 * @throws ReflectionException
1320
+	 */
1321
+	public function total_no_code(): string
1322
+	{
1323
+		return $this->prettyTotal();
1324
+	}
1325
+
1326
+
1327
+	/**
1328
+	 * @return string like '2, 004.00', formatted according to the localized currency
1329
+	 * @throws EE_Error
1330
+	 * @throws ReflectionException
1331
+	 * @since 5.0.0.p
1332
+	 */
1333
+	public function prettyTotal(): string
1334
+	{
1335
+		return $this->get_pretty('LIN_total', 'no_currency_code');
1336
+	}
1337
+
1338
+
1339
+	/**
1340
+	 * Gets the final total on this item, taking taxes into account.
1341
+	 * Has the side-effect of setting the sub-total as it was just calculated.
1342
+	 * If this is used on a grand-total line item, also updates the transaction's
1343
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
1344
+	 * want to change a persistable transaction with info from a non-persistent line item)
1345
+	 *
1346
+	 * @param bool $update_txn_status
1347
+	 * @return float
1348
+	 * @throws EE_Error
1349
+	 * @throws InvalidArgumentException
1350
+	 * @throws InvalidDataTypeException
1351
+	 * @throws InvalidInterfaceException
1352
+	 * @throws ReflectionException
1353
+	 * @throws RuntimeException
1354
+	 */
1355
+	public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1356
+	{
1357
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1358
+		return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1359
+	}
1360
+
1361
+
1362
+	/**
1363
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1364
+	 * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1365
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1366
+	 * when this is called on the grand total
1367
+	 *
1368
+	 * @return float
1369
+	 * @throws EE_Error
1370
+	 * @throws InvalidArgumentException
1371
+	 * @throws InvalidDataTypeException
1372
+	 * @throws InvalidInterfaceException
1373
+	 * @throws ReflectionException
1374
+	 */
1375
+	public function recalculate_pre_tax_total(): float
1376
+	{
1377
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1378
+		[$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1379
+		return (float) $total;
1380
+	}
1381
+
1382
+
1383
+	/**
1384
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1385
+	 * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1386
+	 * and tax sub-total if already in the DB
1387
+	 *
1388
+	 * @return float
1389
+	 * @throws EE_Error
1390
+	 * @throws InvalidArgumentException
1391
+	 * @throws InvalidDataTypeException
1392
+	 * @throws InvalidInterfaceException
1393
+	 * @throws ReflectionException
1394
+	 */
1395
+	public function recalculate_taxes_and_tax_total(): float
1396
+	{
1397
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1398
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1399
+	}
1400
+
1401
+
1402
+	/**
1403
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
1404
+	 * recalculate_taxes_and_total
1405
+	 *
1406
+	 * @return float
1407
+	 * @throws EE_Error
1408
+	 * @throws InvalidArgumentException
1409
+	 * @throws InvalidDataTypeException
1410
+	 * @throws InvalidInterfaceException
1411
+	 * @throws ReflectionException
1412
+	 */
1413
+	public function get_total_tax()
1414
+	{
1415
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1416
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1417
+	}
1418
+
1419
+
1420
+	/**
1421
+	 * Gets the total for all the items purchased only
1422
+	 *
1423
+	 * @return float
1424
+	 * @throws EE_Error
1425
+	 * @throws InvalidArgumentException
1426
+	 * @throws InvalidDataTypeException
1427
+	 * @throws InvalidInterfaceException
1428
+	 * @throws ReflectionException
1429
+	 */
1430
+	public function get_items_total()
1431
+	{
1432
+		// by default, let's make sure we're consistent with the existing line item
1433
+		if ($this->is_total()) {
1434
+			return $this->pretaxTotal();
1435
+		}
1436
+		$total = 0;
1437
+		foreach ($this->get_items() as $item) {
1438
+			if ($item instanceof EE_Line_Item) {
1439
+				$total += $item->pretaxTotal();
1440
+			}
1441
+		}
1442
+		return $total;
1443
+	}
1444
+
1445
+
1446
+	/**
1447
+	 * Gets all the descendants (ie, children or children of children etc) that
1448
+	 * are of the type 'tax'
1449
+	 *
1450
+	 * @return EE_Line_Item[]
1451
+	 * @throws EE_Error
1452
+	 */
1453
+	public function tax_descendants()
1454
+	{
1455
+		return EEH_Line_Item::get_tax_descendants($this);
1456
+	}
1457
+
1458
+
1459
+	/**
1460
+	 * Gets all the real items purchased which are children of this item
1461
+	 *
1462
+	 * @return EE_Line_Item[]
1463
+	 * @throws EE_Error
1464
+	 */
1465
+	public function get_items()
1466
+	{
1467
+		return EEH_Line_Item::get_line_item_descendants($this);
1468
+	}
1469
+
1470
+
1471
+	/**
1472
+	 * Returns the amount taxable among this line item's children (or if it has no children,
1473
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
1474
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
1475
+	 * but there is a "Taxable" discount), returns 0.
1476
+	 *
1477
+	 * @return float
1478
+	 * @throws EE_Error
1479
+	 * @throws InvalidArgumentException
1480
+	 * @throws InvalidDataTypeException
1481
+	 * @throws InvalidInterfaceException
1482
+	 * @throws ReflectionException
1483
+	 */
1484
+	public function taxable_total(): float
1485
+	{
1486
+		return $this->calculator->taxableAmountForGlobalTaxes($this);
1487
+	}
1488
+
1489
+
1490
+	/**
1491
+	 * Gets the transaction for this line item
1492
+	 *
1493
+	 * @return EE_Base_Class|EE_Transaction
1494
+	 * @throws EE_Error
1495
+	 * @throws InvalidArgumentException
1496
+	 * @throws InvalidDataTypeException
1497
+	 * @throws InvalidInterfaceException
1498
+	 * @throws ReflectionException
1499
+	 */
1500
+	public function transaction()
1501
+	{
1502
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1503
+	}
1504
+
1505
+
1506
+	/**
1507
+	 * Saves this line item to the DB, and recursively saves its descendants.
1508
+	 * Because there currently is no proper parent-child relation on the model,
1509
+	 * save_this_and_cached() will NOT save the descendants.
1510
+	 * Also sets the transaction on this line item and all its descendants before saving
1511
+	 *
1512
+	 * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1513
+	 * @return int count of items saved
1514
+	 * @throws EE_Error
1515
+	 * @throws InvalidArgumentException
1516
+	 * @throws InvalidDataTypeException
1517
+	 * @throws InvalidInterfaceException
1518
+	 * @throws ReflectionException
1519
+	 */
1520
+	public function save_this_and_descendants_to_txn($txn_id = null)
1521
+	{
1522
+		$count = 0;
1523
+		if (! $txn_id) {
1524
+			$txn_id = $this->TXN_ID();
1525
+		}
1526
+		$this->set_TXN_ID($txn_id);
1527
+		$children = $this->children();
1528
+		$count += $this->save()
1529
+			? 1
1530
+			: 0;
1531
+		foreach ($children as $child_line_item) {
1532
+			if ($child_line_item instanceof EE_Line_Item) {
1533
+				$child_line_item->set_parent_ID($this->ID());
1534
+				$count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1535
+			}
1536
+		}
1537
+		return $count;
1538
+	}
1539
+
1540
+
1541
+	/**
1542
+	 * Saves this line item to the DB, and recursively saves its descendants.
1543
+	 *
1544
+	 * @return int count of items saved
1545
+	 * @throws EE_Error
1546
+	 * @throws InvalidArgumentException
1547
+	 * @throws InvalidDataTypeException
1548
+	 * @throws InvalidInterfaceException
1549
+	 * @throws ReflectionException
1550
+	 */
1551
+	public function save_this_and_descendants()
1552
+	{
1553
+		$count = 0;
1554
+		$children = $this->children();
1555
+		$count += $this->save()
1556
+			? 1
1557
+			: 0;
1558
+		foreach ($children as $child_line_item) {
1559
+			if ($child_line_item instanceof EE_Line_Item) {
1560
+				$child_line_item->set_parent_ID($this->ID());
1561
+				$count += $child_line_item->save_this_and_descendants();
1562
+			}
1563
+		}
1564
+		return $count;
1565
+	}
1566
+
1567
+
1568
+	/**
1569
+	 * returns the cancellation line item if this item was cancelled
1570
+	 *
1571
+	 * @return EE_Line_Item[]
1572
+	 * @throws InvalidArgumentException
1573
+	 * @throws InvalidInterfaceException
1574
+	 * @throws InvalidDataTypeException
1575
+	 * @throws ReflectionException
1576
+	 * @throws EE_Error
1577
+	 */
1578
+	public function get_cancellations()
1579
+	{
1580
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1581
+	}
1582
+
1583
+
1584
+	/**
1585
+	 * If this item has an ID, then this saves it again to update the db
1586
+	 *
1587
+	 * @return int count of items saved
1588
+	 * @throws EE_Error
1589
+	 * @throws InvalidArgumentException
1590
+	 * @throws InvalidDataTypeException
1591
+	 * @throws InvalidInterfaceException
1592
+	 * @throws ReflectionException
1593
+	 */
1594
+	public function maybe_save()
1595
+	{
1596
+		if ($this->ID()) {
1597
+			return $this->save();
1598
+		}
1599
+		return false;
1600
+	}
1601
+
1602
+
1603
+	/**
1604
+	 * clears the cached children and parent from the line item
1605
+	 *
1606
+	 * @return void
1607
+	 */
1608
+	public function clear_related_line_item_cache()
1609
+	{
1610
+		$this->_children = array();
1611
+		$this->_parent = null;
1612
+	}
1613
+
1614
+
1615
+	/**
1616
+	 * @param bool $raw
1617
+	 * @return int
1618
+	 * @throws EE_Error
1619
+	 * @throws InvalidArgumentException
1620
+	 * @throws InvalidDataTypeException
1621
+	 * @throws InvalidInterfaceException
1622
+	 * @throws ReflectionException
1623
+	 */
1624
+	public function timestamp($raw = false)
1625
+	{
1626
+		return $raw
1627
+			? $this->get_raw('LIN_timestamp')
1628
+			: $this->get('LIN_timestamp');
1629
+	}
1630
+
1631
+
1632
+
1633
+
1634
+	/************************* DEPRECATED *************************/
1635
+	/**
1636
+	 * @deprecated 4.6.0
1637
+	 * @param string $type one of the constants on EEM_Line_Item
1638
+	 * @return EE_Line_Item[]
1639
+	 * @throws EE_Error
1640
+	 */
1641
+	protected function _get_descendants_of_type($type)
1642
+	{
1643
+		EE_Error::doing_it_wrong(
1644
+			'EE_Line_Item::_get_descendants_of_type()',
1645
+			sprintf(
1646
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1647
+				'EEH_Line_Item::get_descendants_of_type()'
1648
+			),
1649
+			'4.6.0'
1650
+		);
1651
+		return EEH_Line_Item::get_descendants_of_type($this, $type);
1652
+	}
1653
+
1654
+
1655
+	/**
1656
+	 * @deprecated 4.6.0
1657
+	 * @param string $type like one of the EEM_Line_Item::type_*
1658
+	 * @return EE_Line_Item
1659
+	 * @throws EE_Error
1660
+	 * @throws InvalidArgumentException
1661
+	 * @throws InvalidDataTypeException
1662
+	 * @throws InvalidInterfaceException
1663
+	 * @throws ReflectionException
1664
+	 */
1665
+	public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1666
+	{
1667
+		EE_Error::doing_it_wrong(
1668
+			'EE_Line_Item::get_nearest_descendant_of_type()',
1669
+			sprintf(
1670
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1671
+				'EEH_Line_Item::get_nearest_descendant_of_type()'
1672
+			),
1673
+			'4.6.0'
1674
+		);
1675
+		return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1676
+	}
1677 1677
 }
Please login to merge, or discard this patch.