Completed
Branch master (de4804)
by
unknown
34:50 queued 28:45
created
core/db_models/strategies/EE_Default_Where_Conditions.strategy.php 2 patches
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -16,248 +16,248 @@
 block discarded – undo
16 16
 class EE_Default_Where_Conditions
17 17
 {
18 18
 
19
-    /**
20
-     * Constant for 'default_where_conditions' to apply default where conditions to ALL queried models
21
-     * ex: if retrieving registrations ordered by their datetimes,
22
-     * this will only return non-trashed registrations for non-trashed tickets for non-trashed datetimes
23
-     */
24
-    public const ALL = 'all';
19
+	/**
20
+	 * Constant for 'default_where_conditions' to apply default where conditions to ALL queried models
21
+	 * ex: if retrieving registrations ordered by their datetimes,
22
+	 * this will only return non-trashed registrations for non-trashed tickets for non-trashed datetimes
23
+	 */
24
+	public const ALL = 'all';
25 25
 
26
-    /**
27
-     * Constant for 'default_where_conditions' to apply default where conditions to THIS model only,
28
-     * but no other models which are joined to (ex: if retrieving registrations ordered by their datetimes,
29
-     * this will return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
30
-     * It is preferred to use EE_Default_Where_Conditions::MINIMUM_OTHERS because, when joining to
31
-     * models which share tables with other models, this can return data for the wrong model.
32
-     */
33
-    public const THIS_MODEL_ONLY = 'this_model_only';
26
+	/**
27
+	 * Constant for 'default_where_conditions' to apply default where conditions to THIS model only,
28
+	 * but no other models which are joined to (ex: if retrieving registrations ordered by their datetimes,
29
+	 * this will return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
30
+	 * It is preferred to use EE_Default_Where_Conditions::MINIMUM_OTHERS because, when joining to
31
+	 * models which share tables with other models, this can return data for the wrong model.
32
+	 */
33
+	public const THIS_MODEL_ONLY = 'this_model_only';
34 34
 
35
-    /**
36
-     * Constant for 'default_where_conditions' to apply default where conditions to other models queried,
37
-     * but not the current model (ex: if retrieving registrations ordered by their datetimes,
38
-     * this will return all registrations related to non-trashed tickets and non-trashed datetimes)
39
-     */
40
-    public const OTHER_MODELS_ONLY = 'other_models_only';
35
+	/**
36
+	 * Constant for 'default_where_conditions' to apply default where conditions to other models queried,
37
+	 * but not the current model (ex: if retrieving registrations ordered by their datetimes,
38
+	 * this will return all registrations related to non-trashed tickets and non-trashed datetimes)
39
+	 */
40
+	public const OTHER_MODELS_ONLY = 'other_models_only';
41 41
 
42
-    /**
43
-     * Constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
44
-     * For most models this is the same as EE_Default_Where_Conditions::NONE,
45
-     * except for models which share their table with other models, like the Event and Venue models.
46
-     * For example, when querying for events ordered by their venues' name,
47
-     * this will be sure to only return real events with associated real venues
48
-     * (regardless of whether those events and venues are trashed).
49
-     * In contrast, using EE_Default_Where_Conditions::NONE could return WP posts other than EE events.
50
-     */
51
-    public const MINIMUM_ALL = 'minimum';
42
+	/**
43
+	 * Constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
44
+	 * For most models this is the same as EE_Default_Where_Conditions::NONE,
45
+	 * except for models which share their table with other models, like the Event and Venue models.
46
+	 * For example, when querying for events ordered by their venues' name,
47
+	 * this will be sure to only return real events with associated real venues
48
+	 * (regardless of whether those events and venues are trashed).
49
+	 * In contrast, using EE_Default_Where_Conditions::NONE could return WP posts other than EE events.
50
+	 */
51
+	public const MINIMUM_ALL = 'minimum';
52 52
 
53
-    /**
54
-     * Constant for 'default_where_conditions' to apply where conditions to other models,
55
-     * and full default where conditions for the queried model
56
-     * (ex: when querying events ordered by venues' names,
57
-     * this will return non-trashed events for any venues,
58
-     * regardless of whether those associated venues are trashed or not)
59
-     */
60
-    public const MINIMUM_OTHERS = 'full_this_minimum_others';
53
+	/**
54
+	 * Constant for 'default_where_conditions' to apply where conditions to other models,
55
+	 * and full default where conditions for the queried model
56
+	 * (ex: when querying events ordered by venues' names,
57
+	 * this will return non-trashed events for any venues,
58
+	 * regardless of whether those associated venues are trashed or not)
59
+	 */
60
+	public const MINIMUM_OTHERS = 'full_this_minimum_others';
61 61
 
62
-    /**
63
-     * Constant for 'default_where_conditions' to NOT apply any where conditions at all.
64
-     * This should very rarely be used, because when querying from a model which shares its table with another model
65
-     * (ex: Events and Venues) it's possible it will return table entries for other models.
66
-     * You should use EE_Default_Where_Conditions::MINIMUM_ALL instead.
67
-     */
68
-    public const NONE = 'none';
62
+	/**
63
+	 * Constant for 'default_where_conditions' to NOT apply any where conditions at all.
64
+	 * This should very rarely be used, because when querying from a model which shares its table with another model
65
+	 * (ex: Events and Venues) it's possible it will return table entries for other models.
66
+	 * You should use EE_Default_Where_Conditions::MINIMUM_ALL instead.
67
+	 */
68
+	public const NONE = 'none';
69 69
 
70
-    /**
71
-     * This const can be used in EE_Default_Where_Conditions values.
72
-     * At the time of querying it will be replaced with the current user's ID
73
-     * (because we don't want to use the current user's ID at time of initializing the
74
-     * models because it's too early).
75
-     */
76
-    public const current_user_placeholder = '%$current_user_placeholder_should_be_replaced_automatically$%';
70
+	/**
71
+	 * This const can be used in EE_Default_Where_Conditions values.
72
+	 * At the time of querying it will be replaced with the current user's ID
73
+	 * (because we don't want to use the current user's ID at time of initializing the
74
+	 * models because it's too early).
75
+	 */
76
+	public const current_user_placeholder = '%$current_user_placeholder_should_be_replaced_automatically$%';
77 77
 
78
-    /**
79
-     * This const can be used in EE_Default_Where_Conditions where parameters
80
-     * as the name of the user field. When we are actually generating the where
81
-     * conditions, it will be replaced with the model's wp user field name
82
-     */
83
-    public const user_field_name_placeholder = '%$user_field_name_placeholder$%';
78
+	/**
79
+	 * This const can be used in EE_Default_Where_Conditions where parameters
80
+	 * as the name of the user field. When we are actually generating the where
81
+	 * conditions, it will be replaced with the model's wp user field name
82
+	 */
83
+	public const user_field_name_placeholder = '%$user_field_name_placeholder$%';
84 84
 
85
-    /**
86
-     * Model for which this strategy find default where conditions
87
-     *
88
-     * @var EEM_Base
89
-     */
90
-    protected EEM_Base $_model;
85
+	/**
86
+	 * Model for which this strategy find default where conditions
87
+	 *
88
+	 * @var EEM_Base
89
+	 */
90
+	protected EEM_Base $_model;
91 91
 
92
-    /**
93
-     * Where conditions specified on construction
94
-     *
95
-     * @var array
96
-     */
97
-    protected array $_where_conditions_provided = [];
92
+	/**
93
+	 * Where conditions specified on construction
94
+	 *
95
+	 * @var array
96
+	 */
97
+	protected array $_where_conditions_provided = [];
98 98
 
99 99
 
100
-    /**
101
-     * Custom where conditions. Model relation chains will be automatically
102
-     * added onto any field names
103
-     *
104
-     * @param array $custom_where_conditions
105
-     */
106
-    public function __construct(array $custom_where_conditions = [])
107
-    {
108
-        $this->_where_conditions_provided = $custom_where_conditions;
109
-    }
100
+	/**
101
+	 * Custom where conditions. Model relation chains will be automatically
102
+	 * added onto any field names
103
+	 *
104
+	 * @param array $custom_where_conditions
105
+	 */
106
+	public function __construct(array $custom_where_conditions = [])
107
+	{
108
+		$this->_where_conditions_provided = $custom_where_conditions;
109
+	}
110 110
 
111 111
 
112
-    /**
113
-     * finalizes construction of the strategy for use in getting default where
114
-     * conditions for querying of the model.
115
-     *
116
-     * @param EEM_Base $model
117
-     */
118
-    public function _finalize_construct(EEM_Base $model)
119
-    {
120
-        $this->_model = $model;
121
-    }
112
+	/**
113
+	 * finalizes construction of the strategy for use in getting default where
114
+	 * conditions for querying of the model.
115
+	 *
116
+	 * @param EEM_Base $model
117
+	 */
118
+	public function _finalize_construct(EEM_Base $model)
119
+	{
120
+		$this->_model = $model;
121
+	}
122 122
 
123 123
 
124
-    /**
125
-     * Returns the where conditions explicitly passed in the constructor
126
-     *
127
-     * @return array
128
-     */
129
-    public function get_where_conditions_provided(): array
130
-    {
131
-        return $this->_where_conditions_provided;
132
-    }
124
+	/**
125
+	 * Returns the where conditions explicitly passed in the constructor
126
+	 *
127
+	 * @return array
128
+	 */
129
+	public function get_where_conditions_provided(): array
130
+	{
131
+		return $this->_where_conditions_provided;
132
+	}
133 133
 
134 134
 
135
-    /**
136
-     * Gets the where conditions to be added onto the query
137
-     *
138
-     * @param string $model_relation_chain
139
-     * @return array
140
-     * @throws EE_Error
141
-     * @throws ReflectionException
142
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
143
-     */
144
-    public function get_default_where_conditions(
145
-        string $model_relation_chain = ''
146
-    ): array {
147
-        return $this->prepare_where_conditions_for_querying(
148
-            array_merge(
149
-                $this->_get_default_where_conditions(),
150
-                $this->get_where_conditions_provided()
151
-            ),
152
-            $model_relation_chain
153
-        );
154
-    }
135
+	/**
136
+	 * Gets the where conditions to be added onto the query
137
+	 *
138
+	 * @param string $model_relation_chain
139
+	 * @return array
140
+	 * @throws EE_Error
141
+	 * @throws ReflectionException
142
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
143
+	 */
144
+	public function get_default_where_conditions(
145
+		string $model_relation_chain = ''
146
+	): array {
147
+		return $this->prepare_where_conditions_for_querying(
148
+			array_merge(
149
+				$this->_get_default_where_conditions(),
150
+				$this->get_where_conditions_provided()
151
+			),
152
+			$model_relation_chain
153
+		);
154
+	}
155 155
 
156 156
 
157
-    /**
158
-     * Gets the default where conditions that are specific to this child of
159
-     * EE_Default_Where_Conditions. Adding model relation chains is handled by
160
-     * the public method get_default_where_conditions
161
-     *
162
-     * @return array
163
-     */
164
-    protected function _get_default_where_conditions(): array
165
-    {
166
-        return [];
167
-    }
157
+	/**
158
+	 * Gets the default where conditions that are specific to this child of
159
+	 * EE_Default_Where_Conditions. Adding model relation chains is handled by
160
+	 * the public method get_default_where_conditions
161
+	 *
162
+	 * @return array
163
+	 */
164
+	protected function _get_default_where_conditions(): array
165
+	{
166
+		return [];
167
+	}
168 168
 
169 169
 
170
-    /**
171
-     * Takes the default query parameters, and traverses them, adding the model
172
-     * relation chain onto them (intelligently doesn't do that to logic query
173
-     * params like 'NOT', 'OR', and 'AND')
174
-     *
175
-     * @param array  $where_conditions
176
-     * @param string $model_relation_chain
177
-     * @return array
178
-     * @throws EE_Error
179
-     * @throws ReflectionException
180
-     */
181
-    public function prepare_where_conditions_for_querying(
182
-        array $where_conditions = [],
183
-        string $model_relation_chain = ''
184
-    ): array {
185
-        $qualified_where_conditions = [];
186
-        foreach ($where_conditions as $key => $value) {
187
-            if ($this->isOrHasQueryOperator($key)) {
188
-                $qualified_where_conditions[ $key ] =
189
-                    $this->prepare_where_conditions_for_querying(
190
-                        $value,
191
-                        $model_relation_chain
192
-                    );
193
-            } else {
194
-                $qualified_where_conditions =
195
-                    $this->prepare_where_condition(
196
-                        $qualified_where_conditions,
197
-                        $model_relation_chain,
198
-                        $key,
199
-                        $value
200
-                    );
201
-            }
202
-        }
203
-        return $qualified_where_conditions;
204
-    }
170
+	/**
171
+	 * Takes the default query parameters, and traverses them, adding the model
172
+	 * relation chain onto them (intelligently doesn't do that to logic query
173
+	 * params like 'NOT', 'OR', and 'AND')
174
+	 *
175
+	 * @param array  $where_conditions
176
+	 * @param string $model_relation_chain
177
+	 * @return array
178
+	 * @throws EE_Error
179
+	 * @throws ReflectionException
180
+	 */
181
+	public function prepare_where_conditions_for_querying(
182
+		array $where_conditions = [],
183
+		string $model_relation_chain = ''
184
+	): array {
185
+		$qualified_where_conditions = [];
186
+		foreach ($where_conditions as $key => $value) {
187
+			if ($this->isOrHasQueryOperator($key)) {
188
+				$qualified_where_conditions[ $key ] =
189
+					$this->prepare_where_conditions_for_querying(
190
+						$value,
191
+						$model_relation_chain
192
+					);
193
+			} else {
194
+				$qualified_where_conditions =
195
+					$this->prepare_where_condition(
196
+						$qualified_where_conditions,
197
+						$model_relation_chain,
198
+						$key,
199
+						$value
200
+					);
201
+			}
202
+		}
203
+		return $qualified_where_conditions;
204
+	}
205 205
 
206 206
 
207
-    /**
208
-     * @param string $query_string
209
-     * @return bool
210
-     */
211
-    private function isOrHasQueryOperator(string $query_string): bool
212
-    {
213
-        return in_array($query_string, ['OR', 'AND', 'NOT'])
214
-            || strpos($query_string, 'OR*') !== false
215
-            || strpos($query_string, 'AND*') !== false
216
-            || strpos($query_string, 'NOT*') !== false;
217
-    }
207
+	/**
208
+	 * @param string $query_string
209
+	 * @return bool
210
+	 */
211
+	private function isOrHasQueryOperator(string $query_string): bool
212
+	{
213
+		return in_array($query_string, ['OR', 'AND', 'NOT'])
214
+			|| strpos($query_string, 'OR*') !== false
215
+			|| strpos($query_string, 'AND*') !== false
216
+			|| strpos($query_string, 'NOT*') !== false;
217
+	}
218 218
 
219 219
 
220
-    /**
221
-     * ensures relation name is fully qualified
222
-     * and swaps placeholders for expected values
223
-     *
224
-     * @param array  $qualified_where_conditions
225
-     * @param string $model_relation_chain
226
-     * @param string $key
227
-     * @param mixed  $value
228
-     * @return array
229
-     * @throws EE_Error
230
-     * @throws ReflectionException
231
-     */
232
-    private function prepare_where_condition(
233
-        array $qualified_where_conditions,
234
-        string $model_relation_chain,
235
-        string $key,
236
-        $value
237
-    ): array {
238
-        $model_relation_chain = $model_relation_chain !== ''
239
-            ? rtrim($model_relation_chain, '.') . '.'
240
-            : $model_relation_chain;
241
-        // check for the current user id placeholder, and if present, change it
242
-        if ($value === self::current_user_placeholder) {
243
-            $value = get_current_user_id();
244
-        }
245
-        // check for user field placeholder
246
-        if ($key === self::user_field_name_placeholder) {
247
-            if (! $this->_model->wp_user_field_name()) {
248
-                throw new EE_Error(
249
-                    sprintf(
250
-                        esc_html__(
251
-                            'There is no foreign key to the WP_User model on model %s. Please either modify your default where conditions, add a _model_chain_to_wp_user onto the model, or a proper EE_WP_User_Field onto the model',
252
-                            'event_espresso'
253
-                        ),
254
-                        $this->_model->get_this_model_name()
255
-                    )
256
-                );
257
-            }
258
-            $key = $this->_model->wp_user_field_name();
259
-        }
260
-        $qualified_where_conditions[ $model_relation_chain . $key ] = $value;
261
-        return $qualified_where_conditions;
262
-    }
220
+	/**
221
+	 * ensures relation name is fully qualified
222
+	 * and swaps placeholders for expected values
223
+	 *
224
+	 * @param array  $qualified_where_conditions
225
+	 * @param string $model_relation_chain
226
+	 * @param string $key
227
+	 * @param mixed  $value
228
+	 * @return array
229
+	 * @throws EE_Error
230
+	 * @throws ReflectionException
231
+	 */
232
+	private function prepare_where_condition(
233
+		array $qualified_where_conditions,
234
+		string $model_relation_chain,
235
+		string $key,
236
+		$value
237
+	): array {
238
+		$model_relation_chain = $model_relation_chain !== ''
239
+			? rtrim($model_relation_chain, '.') . '.'
240
+			: $model_relation_chain;
241
+		// check for the current user id placeholder, and if present, change it
242
+		if ($value === self::current_user_placeholder) {
243
+			$value = get_current_user_id();
244
+		}
245
+		// check for user field placeholder
246
+		if ($key === self::user_field_name_placeholder) {
247
+			if (! $this->_model->wp_user_field_name()) {
248
+				throw new EE_Error(
249
+					sprintf(
250
+						esc_html__(
251
+							'There is no foreign key to the WP_User model on model %s. Please either modify your default where conditions, add a _model_chain_to_wp_user onto the model, or a proper EE_WP_User_Field onto the model',
252
+							'event_espresso'
253
+						),
254
+						$this->_model->get_this_model_name()
255
+					)
256
+				);
257
+			}
258
+			$key = $this->_model->wp_user_field_name();
259
+		}
260
+		$qualified_where_conditions[ $model_relation_chain . $key ] = $value;
261
+		return $qualified_where_conditions;
262
+	}
263 263
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
         $qualified_where_conditions = [];
186 186
         foreach ($where_conditions as $key => $value) {
187 187
             if ($this->isOrHasQueryOperator($key)) {
188
-                $qualified_where_conditions[ $key ] =
188
+                $qualified_where_conditions[$key] =
189 189
                     $this->prepare_where_conditions_for_querying(
190 190
                         $value,
191 191
                         $model_relation_chain
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
         $value
237 237
     ): array {
238 238
         $model_relation_chain = $model_relation_chain !== ''
239
-            ? rtrim($model_relation_chain, '.') . '.'
239
+            ? rtrim($model_relation_chain, '.').'.'
240 240
             : $model_relation_chain;
241 241
         // check for the current user id placeholder, and if present, change it
242 242
         if ($value === self::current_user_placeholder) {
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
         }
245 245
         // check for user field placeholder
246 246
         if ($key === self::user_field_name_placeholder) {
247
-            if (! $this->_model->wp_user_field_name()) {
247
+            if ( ! $this->_model->wp_user_field_name()) {
248 248
                 throw new EE_Error(
249 249
                     sprintf(
250 250
                         esc_html__(
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
             }
258 258
             $key = $this->_model->wp_user_field_name();
259 259
         }
260
-        $qualified_where_conditions[ $model_relation_chain . $key ] = $value;
260
+        $qualified_where_conditions[$model_relation_chain.$key] = $value;
261 261
         return $qualified_where_conditions;
262 262
     }
263 263
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Datetime.model.php 2 patches
Indentation   +836 added lines, -836 removed lines patch added patch discarded remove patch
@@ -16,840 +16,840 @@
 block discarded – undo
16 16
  */
17 17
 class EEM_Datetime extends EEM_Soft_Delete_Base
18 18
 {
19
-    protected static ?EEM_Datetime $_instance = null;
20
-
21
-
22
-    /**
23
-     * private constructor to prevent direct creation
24
-     *
25
-     * @param string|null $timezone A string representing the timezone we want to set for returned Date Time Strings
26
-     *                              (and any incoming timezone data that gets saved).
27
-     *                              Note this just sends the timezone info to the date time model field objects.
28
-     *                              Default is NULL
29
-     *                              (and will be assumed using the set timezone in the 'timezone_string' wp option)
30
-     * @throws EE_Error
31
-     */
32
-    protected function __construct(?string $timezone = '')
33
-    {
34
-        $this->singular_item           = esc_html__('Datetime', 'event_espresso');
35
-        $this->plural_item             = esc_html__('Datetimes', 'event_espresso');
36
-        $this->_tables                 = [
37
-            'Datetime' => new EE_Primary_Table('esp_datetime', 'DTT_ID'),
38
-        ];
39
-        $this->_fields                 = [
40
-            'Datetime' => [
41
-                'DTT_ID'          => new EE_Primary_Key_Int_Field(
42
-                    'DTT_ID',
43
-                    esc_html__('Datetime ID', 'event_espresso')
44
-                ),
45
-                'EVT_ID'          => new EE_Foreign_Key_Int_Field(
46
-                    'EVT_ID',
47
-                    esc_html__('Event ID', 'event_espresso'),
48
-                    false,
49
-                    0,
50
-                    'Event'
51
-                ),
52
-                'VNU_ID'          => new EE_Foreign_Key_Int_Field(
53
-                    'VNU_ID',
54
-                    __('Venue ID', 'event_espresso'),
55
-                    false,
56
-                    0,
57
-                    'Venue'
58
-                ),
59
-                'DTT_name'        => new EE_Plain_Text_Field(
60
-                    'DTT_name',
61
-                    esc_html__('Datetime Name', 'event_espresso'),
62
-                    false,
63
-                    ''
64
-                ),
65
-                'DTT_description' => new EE_Post_Content_Field(
66
-                    'DTT_description',
67
-                    esc_html__('Description for Datetime', 'event_espresso'),
68
-                    false,
69
-                    ''
70
-                ),
71
-                'DTT_EVT_start'   => new EE_Datetime_Field(
72
-                    'DTT_EVT_start',
73
-                    esc_html__('Start time/date of Event', 'event_espresso'),
74
-                    false,
75
-                    EE_Datetime_Field::now,
76
-                    $timezone
77
-                ),
78
-                'DTT_EVT_end'     => new EE_Datetime_Field(
79
-                    'DTT_EVT_end',
80
-                    esc_html__('End time/date of Event', 'event_espresso'),
81
-                    false,
82
-                    EE_Datetime_Field::now,
83
-                    $timezone
84
-                ),
85
-                'DTT_reg_limit'   => new EE_Infinite_Integer_Field(
86
-                    'DTT_reg_limit',
87
-                    esc_html__('Registration Limit for this time', 'event_espresso'),
88
-                    false,
89
-                    EE_INF
90
-                ),
91
-                'DTT_sold'        => new EE_Integer_Field(
92
-                    'DTT_sold',
93
-                    esc_html__('How many sales for this Datetime that have occurred', 'event_espresso'),
94
-                    false,
95
-                    0
96
-                ),
97
-                'DTT_reserved'    => new EE_Integer_Field(
98
-                    'DTT_reserved',
99
-                    esc_html__('Quantity of tickets reserved, but not yet fully purchased', 'event_espresso'),
100
-                    false,
101
-                    0
102
-                ),
103
-                'DTT_is_primary'  => new EE_Boolean_Field(
104
-                    'DTT_is_primary',
105
-                    esc_html__('Flag indicating datetime is primary one for event', 'event_espresso'),
106
-                    false,
107
-                    false
108
-                ),
109
-                'DTT_order'       => new EE_Integer_Field(
110
-                    'DTT_order',
111
-                    esc_html__('The order in which the Datetime is displayed', 'event_espresso'),
112
-                    false,
113
-                    0
114
-                ),
115
-                'DTT_parent'      => new EE_Integer_Field(
116
-                    'DTT_parent',
117
-                    esc_html__('Indicates what DTT_ID is the parent of this DTT_ID', 'event_espresso'),
118
-                    true,
119
-                    0
120
-                ),
121
-                'DTT_deleted'     => new EE_Trashed_Flag_Field(
122
-                    'DTT_deleted',
123
-                    esc_html__('Flag indicating datetime is archived', 'event_espresso'),
124
-                    false,
125
-                    false
126
-                ),
127
-            ],
128
-        ];
129
-        $this->_model_relations        = [
130
-            'Ticket'          => new EE_HABTM_Relation('Datetime_Ticket'),
131
-            'Event'           => new EE_Belongs_To_Relation(),
132
-            'Checkin'         => new EE_Has_Many_Relation(),
133
-            'Datetime_Ticket' => new EE_Has_Many_Relation(),
134
-            'Venue'           => new EE_Belongs_To_Relation(),
135
-        ];
136
-        $path_to_event_model           = 'Event';
137
-        $this->model_chain_to_password = $path_to_event_model;
138
-        $this->_model_chain_to_wp_user = $path_to_event_model;
139
-        // this model is generally available for reading
140
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ]       =
141
-            new EE_Restriction_Generator_Event_Related_Public(
142
-                $path_to_event_model
143
-            );
144
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
145
-            new EE_Restriction_Generator_Event_Related_Protected(
146
-                $path_to_event_model
147
-            );
148
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
149
-            new EE_Restriction_Generator_Event_Related_Protected(
150
-                $path_to_event_model
151
-            );
152
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
153
-            new EE_Restriction_Generator_Event_Related_Protected(
154
-                $path_to_event_model,
155
-                EEM_Base::caps_edit
156
-            );
157
-        parent::__construct($timezone);
158
-    }
159
-
160
-
161
-    /**
162
-     * create new blank datetime
163
-     *
164
-     * @access public
165
-     * @return EE_Datetime[] array on success, FALSE on fail
166
-     * @throws EE_Error
167
-     * @throws InvalidArgumentException
168
-     * @throws InvalidDataTypeException
169
-     * @throws ReflectionException
170
-     * @throws InvalidInterfaceException
171
-     */
172
-    public function create_new_blank_datetime()
173
-    {
174
-        // makes sure timezone is always set.
175
-        $timezone_string = $this->get_timezone();
176
-        /**
177
-         * Filters the initial start date for the new datetime.
178
-         * Any time included in this value will be overridden later so use additional filters to modify the time.
179
-         *
180
-         * @param int $start_date Unix timestamp representing now + 30 days in seconds.
181
-         * @return int Unix timestamp
182
-         */
183
-        $start_date = apply_filters(
184
-            'FHEE__EEM_Datetime__create_new_blank_datetime__start_date',
185
-            $this->current_time_for_query('DTT_EVT_start', true) + MONTH_IN_SECONDS
186
-        );
187
-        /**
188
-         * Filters the initial end date for the new datetime.
189
-         * Any time included in this value will be overridden later so use additional filters to modify the time.
190
-         *
191
-         * @param int $end_data Unix timestamp representing now + 30 days in seconds.
192
-         * @return int Unix timestamp
193
-         */
194
-        $end_date       = apply_filters(
195
-            'FHEE__EEM_Datetime__create_new_blank_datetime__end_date',
196
-            $this->current_time_for_query('DTT_EVT_end', true) + MONTH_IN_SECONDS
197
-        );
198
-        $blank_datetime = EE_Datetime::new_instance(
199
-            [
200
-                'DTT_EVT_start' => $start_date,
201
-                'DTT_EVT_end'   => $end_date,
202
-                'DTT_order'     => 1,
203
-                'DTT_reg_limit' => EE_INF_IN_DB,
204
-            ],
205
-            $timezone_string
206
-        );
207
-        /**
208
-         * Filters the initial start time and format for the new EE_Datetime instance.
209
-         *
210
-         * @param array $start_time An array having size 2.  First element is the time, second element is the time
211
-         *                          format.
212
-         * @return array
213
-         */
214
-        $start_time = apply_filters(
215
-            'FHEE__EEM_Datetime__create_new_blank_datetime__start_time',
216
-            ['8am', 'ga']
217
-        );
218
-        /**
219
-         * Filters the initial end time and format for the new EE_Datetime instance.
220
-         *
221
-         * @param array $end_time An array having size 2.  First element is the time, second element is the time
222
-         *                        format
223
-         * @return array
224
-         */
225
-        $end_time = apply_filters(
226
-            'FHEE__EEM_Datetime__create_new_blank_datetime__end_time',
227
-            ['5pm', 'ga']
228
-        );
229
-        $this->validateStartAndEndTimeForBlankDate($start_time, $end_time);
230
-        $blank_datetime->set_start_time(
231
-            $this->convert_datetime_for_query(
232
-                'DTT_EVT_start',
233
-                $start_time[0],
234
-                $start_time[1],
235
-                $timezone_string
236
-            )
237
-        );
238
-        $blank_datetime->set_end_time(
239
-            $this->convert_datetime_for_query(
240
-                'DTT_EVT_end',
241
-                $end_time[0],
242
-                $end_time[1],
243
-                $timezone_string
244
-            )
245
-        );
246
-        return [$blank_datetime];
247
-    }
248
-
249
-
250
-    /**
251
-     * Validates whether the start_time and end_time are in the expected format.
252
-     *
253
-     * @param array $start_time
254
-     * @param array $end_time
255
-     * @throws InvalidArgumentException
256
-     * @throws InvalidDataTypeException
257
-     */
258
-    private function validateStartAndEndTimeForBlankDate(array $start_time, array $end_time)
259
-    {
260
-        if (! is_array($start_time)) {
261
-            throw new InvalidDataTypeException('start_time', $start_time, 'array');
262
-        }
263
-        if (! is_array($end_time)) {
264
-            throw new InvalidDataTypeException('end_time', $end_time, 'array');
265
-        }
266
-        if (count($start_time) !== 2) {
267
-            throw new InvalidArgumentException(
268
-                sprintf(
269
-                    'The variable %1$s is expected to be an array with two elements.  The first item in the '
270
-                    . 'array should be a valid time string, the second item in the array should be a valid time format',
271
-                    '$start_time'
272
-                )
273
-            );
274
-        }
275
-        if (count($end_time) !== 2) {
276
-            throw new InvalidArgumentException(
277
-                sprintf(
278
-                    'The variable %1$s is expected to be an array with two elements.  The first item in the '
279
-                    . 'array should be a valid time string, the second item in the array should be a valid time format',
280
-                    '$end_time'
281
-                )
282
-            );
283
-        }
284
-    }
285
-
286
-
287
-    /**
288
-     * get event start date from db
289
-     *
290
-     * @access public
291
-     * @param int $EVT_ID
292
-     * @return EE_Datetime[] array on success, FALSE on fail
293
-     * @throws EE_Error
294
-     * @throws ReflectionException
295
-     */
296
-    public function get_all_event_dates($EVT_ID = 0)
297
-    {
298
-        if (! $EVT_ID) { // on add_new_event event_id gets set to 0
299
-            return $this->create_new_blank_datetime();
300
-        }
301
-        $results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
302
-        if (empty($results)) {
303
-            return $this->create_new_blank_datetime();
304
-        }
305
-        return $results;
306
-    }
307
-
308
-
309
-    /**
310
-     * get all datetimes attached to an event ordered by the DTT_order field
311
-     *
312
-     * @public
313
-     * @param int     $EVT_ID     event id
314
-     * @param boolean $include_expired
315
-     * @param boolean $include_deleted
316
-     * @param int     $limit      If included then limit the count of results by
317
-     *                            the given number
318
-     * @return EE_Datetime[]
319
-     * @throws EE_Error
320
-     */
321
-    public function get_datetimes_for_event_ordered_by_DTT_order(
322
-        int $EVT_ID,
323
-        bool $include_expired = true,
324
-        bool $include_deleted = true,
325
-        $limit = 0
326
-    ) {
327
-        $prev_data_prep_value = $this->prepModelForQuery();
328
-        $where_params         = ['Event.EVT_ID' => absint($EVT_ID)];
329
-        $query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
330
-        $query_params         = $this->addDefaultWhereConditions($query_params);
331
-        $query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
332
-        return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
333
-    }
334
-
335
-
336
-    /**
337
-     * Gets the datetimes for the event (with the given limit), and orders them by "importance".
338
-     * By importance, we mean that the primary datetimes are most important (DEPRECATED FOR NOW),
339
-     * and then the earlier datetimes are the most important.
340
-     * Maybe we'll want this to take into account datetimes that haven't already passed, but we don't yet.
341
-     *
342
-     * @param int $EVT_ID
343
-     * @param int $limit
344
-     * @return EE_Datetime[]|EE_Base_Class[]
345
-     * @throws EE_Error
346
-     */
347
-    public function get_datetimes_for_event_ordered_by_importance(int $EVT_ID, $limit = 0)
348
-    {
349
-        $query_params[0] = ['Event.EVT_ID' => absint($EVT_ID)];
350
-        $query_params    = $this->addDefaultWhereConditions($query_params);
351
-        $query_params    = $this->addDefaultQueryParams($query_params, $limit);
352
-        return $this->get_all($query_params);
353
-    }
354
-
355
-
356
-    /**
357
-     * @param int     $EVT_ID
358
-     * @param boolean $include_expired
359
-     * @param boolean $include_deleted
360
-     * @return EE_Datetime
361
-     * @throws EE_Error
362
-     */
363
-    public function get_oldest_datetime_for_event(
364
-        int $EVT_ID,
365
-        bool $include_expired = false,
366
-        bool $include_deleted = false
367
-    ) {
368
-        $results = $this->get_datetimes_for_event_ordered_by_start_time(
369
-            $EVT_ID,
370
-            $include_expired,
371
-            $include_deleted,
372
-            1
373
-        );
374
-        if ($results) {
375
-            return array_shift($results);
376
-        }
377
-        return null;
378
-    }
379
-
380
-
381
-    /**
382
-     * Gets the 'primary' datetime for an event.
383
-     *
384
-     * @param int  $EVT_ID
385
-     * @param bool $try_to_exclude_expired
386
-     * @param bool $try_to_exclude_deleted
387
-     * @return EE_Datetime
388
-     * @throws EE_Error
389
-     */
390
-    public function get_primary_datetime_for_event(
391
-        int $EVT_ID,
392
-        bool $try_to_exclude_expired = true,
393
-        bool $try_to_exclude_deleted = true
394
-    ) {
395
-        if ($try_to_exclude_expired) {
396
-            $non_expired = $this->get_oldest_datetime_for_event($EVT_ID, false, false);
397
-            if ($non_expired) {
398
-                return $non_expired;
399
-            }
400
-        }
401
-        if ($try_to_exclude_deleted) {
402
-            $expired_even = $this->get_oldest_datetime_for_event($EVT_ID, true);
403
-            if ($expired_even) {
404
-                return $expired_even;
405
-            }
406
-        }
407
-        return $this->get_oldest_datetime_for_event($EVT_ID, true, true);
408
-    }
409
-
410
-
411
-    /**
412
-     * Gets ALL the datetimes for an event (including trashed ones, for now), ordered
413
-     * only by start date
414
-     *
415
-     * @param int     $EVT_ID
416
-     * @param boolean $include_expired
417
-     * @param boolean $include_deleted
418
-     * @param int     $limit
419
-     * @return EE_Datetime[]
420
-     * @throws EE_Error
421
-     */
422
-    public function get_datetimes_for_event_ordered_by_start_time(
423
-        int $EVT_ID,
424
-        bool $include_expired = true,
425
-        bool $include_deleted = true,
426
-        $limit = 0
427
-    ) {
428
-        $prev_data_prep_value = $this->prepModelForQuery();
429
-        $where_params         = ['Event.EVT_ID' => absint($EVT_ID)];
430
-        $query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
431
-        $query_params         = $this->addDefaultWhereConditions(
432
-            $query_params,
433
-            EE_Default_Where_Conditions::THIS_MODEL_ONLY
434
-        );
435
-        $query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
436
-        return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
437
-    }
438
-
439
-
440
-    /**
441
-     * Gets ALL the datetimes for an ticket (including trashed ones, for now), ordered
442
-     * only by start date
443
-     *
444
-     * @param int     $TKT_ID
445
-     * @param boolean $include_expired
446
-     * @param boolean $include_deleted
447
-     * @param int     $limit
448
-     * @return EE_Datetime[]
449
-     * @throws EE_Error
450
-     */
451
-    public function get_datetimes_for_ticket_ordered_by_start_time(
452
-        int $TKT_ID,
453
-        bool $include_expired = true,
454
-        bool $include_deleted = true,
455
-        $limit = 0
456
-    ) {
457
-        $prev_data_prep_value = $this->prepModelForQuery();
458
-        $where_params         = ['Ticket.TKT_ID' => absint($TKT_ID)];
459
-        $query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
460
-        $query_params         = $this->addDefaultQueryParams($query_params, $limit);
461
-        return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
462
-    }
463
-
464
-
465
-    /**
466
-     * Gets all the datetimes for a ticket (including trashed ones, for now), ordered by the DTT_order for the
467
-     * datetimes.
468
-     *
469
-     * @param int      $TKT_ID           ID of ticket to retrieve the datetimes for
470
-     * @param boolean  $include_expired  whether to include expired datetimes or not
471
-     * @param boolean  $include_deleted  whether to include trashed datetimes or not.
472
-     * @param int|null $limit            if null, no limit, if int then limit results by
473
-     *                                   that number
474
-     * @return EE_Datetime[]
475
-     * @throws EE_Error
476
-     */
477
-    public function get_datetimes_for_ticket_ordered_by_DTT_order(
478
-        int $TKT_ID,
479
-        bool $include_expired = true,
480
-        bool $include_deleted = true,
481
-        $limit = 0
482
-    ) {
483
-        $prev_data_prep_value = $this->prepModelForQuery();
484
-        $where_params         = ['Ticket.TKT_ID' => absint($TKT_ID)];
485
-        $query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
486
-        $query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
487
-        return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
488
-    }
489
-
490
-
491
-    /**
492
-     * Gets the most important datetime for a particular event (ie, the primary event usually. But if for some WACK
493
-     * reason it doesn't exist, we consider the earliest event the most important)
494
-     *
495
-     * @param int $EVT_ID
496
-     * @return EE_Datetime
497
-     * @throws EE_Error
498
-     */
499
-    public function get_most_important_datetime_for_event(int $EVT_ID)
500
-    {
501
-        $results = $this->get_datetimes_for_event_ordered_by_importance($EVT_ID, 1);
502
-        if ($results) {
503
-            return array_shift($results);
504
-        }
505
-        return null;
506
-    }
507
-
508
-
509
-    /**
510
-     * This returns a wpdb->results        Array of all DTT month and years matching the incoming query params and
511
-     * grouped by month and year.
512
-     *
513
-     * @param array  $where_params       @see
514
-     *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
515
-     * @param string $evt_active_status  A string representing the evt active status to filter the months by.
516
-     *                                   Can be:
517
-     *                                   - '' = no filter
518
-     *                                   - upcoming = Published events with at least one upcoming datetime.
519
-     *                                   - expired = Events with all datetimes expired.
520
-     *                                   - active = Events that are published and have at least one datetime that
521
-     *                                   starts before now and ends after now.
522
-     *                                   - inactive = Events that are either not published.
523
-     * @return stdClass[]
524
-     * @throws EE_Error
525
-     * @throws InvalidArgumentException
526
-     * @throws InvalidArgumentException
527
-     */
528
-    public function get_dtt_months_and_years(array $where_params, $evt_active_status = '')
529
-    {
530
-        $current_time_for_DTT_EVT_start = $this->current_time_for_query('DTT_EVT_start');
531
-        $current_time_for_DTT_EVT_end   = $this->current_time_for_query('DTT_EVT_end');
532
-        switch ($evt_active_status) {
533
-            case 'upcoming':
534
-                $where_params['Event.status'] = 'publish';
535
-                // if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
536
-                if (isset($where_params['DTT_EVT_start'])) {
537
-                    $where_params['DTT_EVT_start*****'] = $where_params['DTT_EVT_start'];
538
-                }
539
-                $where_params['DTT_EVT_start'] = ['>', $current_time_for_DTT_EVT_start];
540
-                break;
541
-            case 'expired':
542
-                if (isset($where_params['Event.status'])) {
543
-                    unset($where_params['Event.status']);
544
-                }
545
-                // get events to exclude
546
-                $exclude_query[0] = array_merge(
547
-                    $where_params,
548
-                    ['DTT_EVT_end' => ['>', $current_time_for_DTT_EVT_end]]
549
-                );
550
-                // first get all events that have datetimes where its not expired.
551
-                $event_ids = $this->_get_all_wpdb_results(
552
-                    $exclude_query,
553
-                    OBJECT_K,
554
-                    'Datetime.EVT_ID'
555
-                );
556
-                $event_ids = array_keys($event_ids);
557
-                if (isset($where_params['DTT_EVT_end'])) {
558
-                    $where_params['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
559
-                }
560
-                $where_params['DTT_EVT_end']  = ['<', $current_time_for_DTT_EVT_end];
561
-                $where_params['Event.EVT_ID'] = ['NOT IN', $event_ids];
562
-                break;
563
-            case 'active':
564
-                $where_params['Event.status'] = 'publish';
565
-                if (isset($where_params['DTT_EVT_start'])) {
566
-                    $where_params['Datetime.DTT_EVT_start******'] = $where_params['DTT_EVT_start'];
567
-                }
568
-                if (isset($where_params['Datetime.DTT_EVT_end'])) {
569
-                    $where_params['Datetime.DTT_EVT_end*****'] = $where_params['DTT_EVT_end'];
570
-                }
571
-                $where_params['DTT_EVT_start'] = ['<', $current_time_for_DTT_EVT_start];
572
-                $where_params['DTT_EVT_end']   = ['>', $current_time_for_DTT_EVT_end];
573
-                break;
574
-            case 'inactive':
575
-                if (isset($where_params['Event.status'])) {
576
-                    unset($where_params['Event.status']);
577
-                }
578
-                if (isset($where_params['OR'])) {
579
-                    $where_params['AND']['OR'] = $where_params['OR'];
580
-                }
581
-                if (isset($where_params['DTT_EVT_end'])) {
582
-                    $where_params['AND']['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
583
-                    unset($where_params['DTT_EVT_end']);
584
-                }
585
-                if (isset($where_params['DTT_EVT_start'])) {
586
-                    $where_params['AND']['DTT_EVT_start'] = $where_params['DTT_EVT_start'];
587
-                    unset($where_params['DTT_EVT_start']);
588
-                }
589
-                $where_params['AND']['Event.status'] = ['!=', 'publish'];
590
-                break;
591
-        }
592
-        $query_params[0]          = $where_params;
593
-        $query_params['group_by'] = ['dtt_year', 'dtt_month'];
594
-        $query_params             = $this->addOrderByQueryParams($query_params, 'DTT_EVT_start', 'DESC');
595
-
596
-        $query_interval    = EEH_DTT_Helper::get_sql_query_interval_for_offset(
597
-            $this->get_timezone(),
598
-            'DTT_EVT_start'
599
-        );
600
-        $columns_to_select = [
601
-            'dtt_year'      => ['YEAR(' . $query_interval . ')', '%s'],
602
-            'dtt_month'     => ['MONTHNAME(' . $query_interval . ')', '%s'],
603
-            'dtt_month_num' => ['MONTH(' . $query_interval . ')', '%s'],
604
-        ];
605
-        return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
606
-    }
607
-
608
-
609
-    /**
610
-     * Updates the DTT_sold attribute on each datetime (based on the registrations
611
-     * for the tickets for each datetime)
612
-     *
613
-     * @param EE_Base_Class[]|EE_Datetime[] $datetimes
614
-     * @throws EE_Error
615
-     * @throws ReflectionException
616
-     */
617
-    public function update_sold(array $datetimes)
618
-    {
619
-        EE_Error::doing_it_wrong(
620
-            __FUNCTION__,
621
-            esc_html__(
622
-                'Please use \EEM_Ticket::update_tickets_sold() instead which will in turn correctly update both the Ticket AND Datetime counts.',
623
-                'event_espresso'
624
-            ),
625
-            '4.9.32.rc.005'
626
-        );
627
-        foreach ($datetimes as $datetime) {
628
-            $datetime->update_sold();
629
-        }
630
-    }
631
-
632
-
633
-    /**
634
-     *    Gets the total number of tickets available at a particular datetime
635
-     *    (does NOT take into account the datetime's spaces available)
636
-     *
637
-     * @param int   $DTT_ID
638
-     * @param array $query_params
639
-     * @return int of tickets available. If sold out, return less than 1. If infinite, returns EE_INF,  IF there are NO
640
-     *             tickets attached to datetime then FALSE is returned.
641
-     * @throws EE_Error
642
-     * @throws ReflectionException
643
-     */
644
-    public function sum_tickets_currently_available_at_datetime(int $DTT_ID, array $query_params = [])
645
-    {
646
-        $datetime = $this->get_one_by_ID($DTT_ID);
647
-        if ($datetime instanceof EE_Datetime) {
648
-            return $datetime->tickets_remaining($query_params);
649
-        }
650
-        return 0;
651
-    }
652
-
653
-
654
-    /**
655
-     * This returns an array of counts of datetimes in the database for each Datetime status that can be queried.
656
-     *
657
-     * @param array $stati_to_include  If included you can restrict the statuses we return counts for by including the
658
-     *                                 stati you want counts for as values in the array.  An empty array returns counts
659
-     *                                 for all valid stati.
660
-     * @param array $query_params      If included can be used to refine the conditions for returning the count (i.e.
661
-     *                                 only for Datetimes connected to a specific event, or specific ticket.
662
-     * @return array  The value returned is an array indexed by Datetime Status and the values are the counts.  The
663
-     * @throws EE_Error
664
-     *                                 stati used as index keys are: EE_Datetime::active EE_Datetime::upcoming
665
-     *                                 EE_Datetime::expired
666
-     */
667
-    public function get_datetime_counts_by_status(array $stati_to_include = [], array $query_params = [])
668
-    {
669
-        // only accept where conditions for this query.
670
-        $_where            = isset($query_params[0]) ? $query_params[0] : [];
671
-        $status_query_args = [
672
-            EE_Datetime::active   => array_merge(
673
-                $_where,
674
-                ['DTT_EVT_start' => ['<', time()], 'DTT_EVT_end' => ['>', time()]]
675
-            ),
676
-            EE_Datetime::upcoming => array_merge(
677
-                $_where,
678
-                ['DTT_EVT_start' => ['>', time()]]
679
-            ),
680
-            EE_Datetime::expired  => array_merge(
681
-                $_where,
682
-                ['DTT_EVT_end' => ['<', time()]]
683
-            ),
684
-        ];
685
-        if (! empty($stati_to_include)) {
686
-            foreach (array_keys($status_query_args) as $status) {
687
-                if (! in_array($status, $stati_to_include, true)) {
688
-                    unset($status_query_args[ $status ]);
689
-                }
690
-            }
691
-        }
692
-        // loop through and query counts for each stati.
693
-        $status_query_results = [];
694
-        foreach ($status_query_args as $status => $status_where_conditions) {
695
-            $status_query_results[ $status ] = EEM_Datetime::count(
696
-                [$status_where_conditions],
697
-                'DTT_ID',
698
-                true
699
-            );
700
-        }
701
-        return $status_query_results;
702
-    }
703
-
704
-
705
-    /**
706
-     * Returns the specific count for a given Datetime status matching any given query_params.
707
-     *
708
-     * @param string $status Valid string representation for Datetime status requested. (Defaults to Active).
709
-     * @param array  $query_params
710
-     * @return int
711
-     * @throws EE_Error
712
-     */
713
-    public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = [])
714
-    {
715
-        $count = $this->get_datetime_counts_by_status([$status], $query_params);
716
-        return ! empty($count[ $status ]) ? $count[ $status ] : 0;
717
-    }
718
-
719
-
720
-    /**
721
-     * @return bool|int
722
-     * @since   5.0.0.p
723
-     */
724
-    private function prepModelForQuery()
725
-    {
726
-        $prev_data_prep_value = $this->get_assumption_concerning_values_already_prepared_by_model_object();
727
-        $this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
728
-        return $prev_data_prep_value;
729
-    }
730
-
731
-
732
-    /**
733
-     * @param array    $query_params
734
-     * @param bool|int $prev_data_prep_value
735
-     * @return EE_Base_Class[]|EE_Datetime[]
736
-     * @throws EE_Error
737
-     * @since   5.0.0.p
738
-     */
739
-    private function getDatetimesAndRestoreModel(array $query_params, $prev_data_prep_value)
740
-    {
741
-        $result = $this->get_all($query_params);
742
-        $this->assume_values_already_prepared_by_model_object($prev_data_prep_value);
743
-        return $result;
744
-    }
745
-
746
-
747
-    /**
748
-     * @param array  $query_params
749
-     * @param int    $limit
750
-     * @param string $order_by
751
-     * @param string $order
752
-     * @return array
753
-     * @since   5.0.0.p
754
-     */
755
-    private function addDefaultQueryParams(array $query_params, $limit = 0, $order_by = 'DTT_EVT_start', $order = 'ASC')
756
-    {
757
-        $query_params = $this->addOrderByQueryParams($query_params, $order_by, $order);
758
-        $query_params = $this->addLimitQueryParams($query_params, $limit);
759
-        return $query_params;
760
-    }
761
-
762
-
763
-    /**
764
-     * @param array  $query_params
765
-     * @param string $default_where_conditions
766
-     * @return array
767
-     * @since   5.0.0.p
768
-     */
769
-    private function addDefaultWhereConditions(
770
-        array $query_params,
771
-        $default_where_conditions = EE_Default_Where_Conditions::NONE
772
-    ) {
773
-        $query_params['default_where_conditions'] = $default_where_conditions;
774
-        return $query_params;
775
-    }
776
-
777
-
778
-    /**
779
-     * @param array $where_params
780
-     * @param bool  $include_deleted
781
-     * @param bool  $include_expired
782
-     * @return array
783
-     * @since   5.0.0.p
784
-     */
785
-    private function addDefaultWhereParams(
786
-        array $where_params,
787
-        bool $include_deleted = true,
788
-        bool $include_expired = true
789
-    ) {
790
-        $where_params = $this->addExpiredWhereParams($where_params, $include_expired);
791
-        $where_params = $this->addDeletedWhereParams($where_params, $include_deleted);
792
-        return $where_params;
793
-    }
794
-
795
-
796
-    /**
797
-     * @param array $where_params
798
-     * @param bool  $include_deleted
799
-     * @return array
800
-     * @since   5.0.0.p
801
-     */
802
-    private function addDeletedWhereParams(array $where_params, bool $include_deleted = true)
803
-    {
804
-        $deleted                     = $include_deleted ? [true, false] : [false];
805
-        $where_params['DTT_deleted'] = ['IN', $deleted];
806
-        return $where_params;
807
-    }
808
-
809
-
810
-    /**
811
-     * @param array $where_params
812
-     * @param bool  $include_expired
813
-     * @return array
814
-     * @since   5.0.0.p
815
-     */
816
-    private function addExpiredWhereParams(array $where_params, bool $include_expired = true)
817
-    {
818
-        if (! $include_expired) {
819
-            $where_params['DTT_EVT_end'] = ['>=', current_time('mysql', true)];
820
-        }
821
-        return $where_params;
822
-    }
823
-
824
-
825
-    /**
826
-     * @param array $query_params
827
-     * @param int   $limit
828
-     * @return array
829
-     * @since   5.0.0.p
830
-     */
831
-    private function addLimitQueryParams(array $query_params, $limit = 0)
832
-    {
833
-        if ($limit) {
834
-            $query_params['limit'] = $limit;
835
-        }
836
-        return $query_params;
837
-    }
838
-
839
-
840
-    /**
841
-     * @param array  $query_params
842
-     * @param string $order_by
843
-     * @param string $order
844
-     * @return array
845
-     * @since   5.0.0.p
846
-     */
847
-    private function addOrderByQueryParams(array $query_params, $order_by = 'DTT_EVT_start', $order = 'ASC')
848
-    {
849
-        $order                    = $order === 'ASC' ? 'ASC' : 'DESC';
850
-        $valid_order_columns      = ['DTT_ID', 'DTT_EVT_start', 'DTT_EVT_end', 'DTT_order'];
851
-        $order_by                 = in_array($order_by, $valid_order_columns, true) ? $order_by : 'DTT_EVT_start';
852
-        $query_params['order_by'] = [$order_by => $order];
853
-        return $query_params;
854
-    }
19
+	protected static ?EEM_Datetime $_instance = null;
20
+
21
+
22
+	/**
23
+	 * private constructor to prevent direct creation
24
+	 *
25
+	 * @param string|null $timezone A string representing the timezone we want to set for returned Date Time Strings
26
+	 *                              (and any incoming timezone data that gets saved).
27
+	 *                              Note this just sends the timezone info to the date time model field objects.
28
+	 *                              Default is NULL
29
+	 *                              (and will be assumed using the set timezone in the 'timezone_string' wp option)
30
+	 * @throws EE_Error
31
+	 */
32
+	protected function __construct(?string $timezone = '')
33
+	{
34
+		$this->singular_item           = esc_html__('Datetime', 'event_espresso');
35
+		$this->plural_item             = esc_html__('Datetimes', 'event_espresso');
36
+		$this->_tables                 = [
37
+			'Datetime' => new EE_Primary_Table('esp_datetime', 'DTT_ID'),
38
+		];
39
+		$this->_fields                 = [
40
+			'Datetime' => [
41
+				'DTT_ID'          => new EE_Primary_Key_Int_Field(
42
+					'DTT_ID',
43
+					esc_html__('Datetime ID', 'event_espresso')
44
+				),
45
+				'EVT_ID'          => new EE_Foreign_Key_Int_Field(
46
+					'EVT_ID',
47
+					esc_html__('Event ID', 'event_espresso'),
48
+					false,
49
+					0,
50
+					'Event'
51
+				),
52
+				'VNU_ID'          => new EE_Foreign_Key_Int_Field(
53
+					'VNU_ID',
54
+					__('Venue ID', 'event_espresso'),
55
+					false,
56
+					0,
57
+					'Venue'
58
+				),
59
+				'DTT_name'        => new EE_Plain_Text_Field(
60
+					'DTT_name',
61
+					esc_html__('Datetime Name', 'event_espresso'),
62
+					false,
63
+					''
64
+				),
65
+				'DTT_description' => new EE_Post_Content_Field(
66
+					'DTT_description',
67
+					esc_html__('Description for Datetime', 'event_espresso'),
68
+					false,
69
+					''
70
+				),
71
+				'DTT_EVT_start'   => new EE_Datetime_Field(
72
+					'DTT_EVT_start',
73
+					esc_html__('Start time/date of Event', 'event_espresso'),
74
+					false,
75
+					EE_Datetime_Field::now,
76
+					$timezone
77
+				),
78
+				'DTT_EVT_end'     => new EE_Datetime_Field(
79
+					'DTT_EVT_end',
80
+					esc_html__('End time/date of Event', 'event_espresso'),
81
+					false,
82
+					EE_Datetime_Field::now,
83
+					$timezone
84
+				),
85
+				'DTT_reg_limit'   => new EE_Infinite_Integer_Field(
86
+					'DTT_reg_limit',
87
+					esc_html__('Registration Limit for this time', 'event_espresso'),
88
+					false,
89
+					EE_INF
90
+				),
91
+				'DTT_sold'        => new EE_Integer_Field(
92
+					'DTT_sold',
93
+					esc_html__('How many sales for this Datetime that have occurred', 'event_espresso'),
94
+					false,
95
+					0
96
+				),
97
+				'DTT_reserved'    => new EE_Integer_Field(
98
+					'DTT_reserved',
99
+					esc_html__('Quantity of tickets reserved, but not yet fully purchased', 'event_espresso'),
100
+					false,
101
+					0
102
+				),
103
+				'DTT_is_primary'  => new EE_Boolean_Field(
104
+					'DTT_is_primary',
105
+					esc_html__('Flag indicating datetime is primary one for event', 'event_espresso'),
106
+					false,
107
+					false
108
+				),
109
+				'DTT_order'       => new EE_Integer_Field(
110
+					'DTT_order',
111
+					esc_html__('The order in which the Datetime is displayed', 'event_espresso'),
112
+					false,
113
+					0
114
+				),
115
+				'DTT_parent'      => new EE_Integer_Field(
116
+					'DTT_parent',
117
+					esc_html__('Indicates what DTT_ID is the parent of this DTT_ID', 'event_espresso'),
118
+					true,
119
+					0
120
+				),
121
+				'DTT_deleted'     => new EE_Trashed_Flag_Field(
122
+					'DTT_deleted',
123
+					esc_html__('Flag indicating datetime is archived', 'event_espresso'),
124
+					false,
125
+					false
126
+				),
127
+			],
128
+		];
129
+		$this->_model_relations        = [
130
+			'Ticket'          => new EE_HABTM_Relation('Datetime_Ticket'),
131
+			'Event'           => new EE_Belongs_To_Relation(),
132
+			'Checkin'         => new EE_Has_Many_Relation(),
133
+			'Datetime_Ticket' => new EE_Has_Many_Relation(),
134
+			'Venue'           => new EE_Belongs_To_Relation(),
135
+		];
136
+		$path_to_event_model           = 'Event';
137
+		$this->model_chain_to_password = $path_to_event_model;
138
+		$this->_model_chain_to_wp_user = $path_to_event_model;
139
+		// this model is generally available for reading
140
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ]       =
141
+			new EE_Restriction_Generator_Event_Related_Public(
142
+				$path_to_event_model
143
+			);
144
+		$this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
145
+			new EE_Restriction_Generator_Event_Related_Protected(
146
+				$path_to_event_model
147
+			);
148
+		$this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
149
+			new EE_Restriction_Generator_Event_Related_Protected(
150
+				$path_to_event_model
151
+			);
152
+		$this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
153
+			new EE_Restriction_Generator_Event_Related_Protected(
154
+				$path_to_event_model,
155
+				EEM_Base::caps_edit
156
+			);
157
+		parent::__construct($timezone);
158
+	}
159
+
160
+
161
+	/**
162
+	 * create new blank datetime
163
+	 *
164
+	 * @access public
165
+	 * @return EE_Datetime[] array on success, FALSE on fail
166
+	 * @throws EE_Error
167
+	 * @throws InvalidArgumentException
168
+	 * @throws InvalidDataTypeException
169
+	 * @throws ReflectionException
170
+	 * @throws InvalidInterfaceException
171
+	 */
172
+	public function create_new_blank_datetime()
173
+	{
174
+		// makes sure timezone is always set.
175
+		$timezone_string = $this->get_timezone();
176
+		/**
177
+		 * Filters the initial start date for the new datetime.
178
+		 * Any time included in this value will be overridden later so use additional filters to modify the time.
179
+		 *
180
+		 * @param int $start_date Unix timestamp representing now + 30 days in seconds.
181
+		 * @return int Unix timestamp
182
+		 */
183
+		$start_date = apply_filters(
184
+			'FHEE__EEM_Datetime__create_new_blank_datetime__start_date',
185
+			$this->current_time_for_query('DTT_EVT_start', true) + MONTH_IN_SECONDS
186
+		);
187
+		/**
188
+		 * Filters the initial end date for the new datetime.
189
+		 * Any time included in this value will be overridden later so use additional filters to modify the time.
190
+		 *
191
+		 * @param int $end_data Unix timestamp representing now + 30 days in seconds.
192
+		 * @return int Unix timestamp
193
+		 */
194
+		$end_date       = apply_filters(
195
+			'FHEE__EEM_Datetime__create_new_blank_datetime__end_date',
196
+			$this->current_time_for_query('DTT_EVT_end', true) + MONTH_IN_SECONDS
197
+		);
198
+		$blank_datetime = EE_Datetime::new_instance(
199
+			[
200
+				'DTT_EVT_start' => $start_date,
201
+				'DTT_EVT_end'   => $end_date,
202
+				'DTT_order'     => 1,
203
+				'DTT_reg_limit' => EE_INF_IN_DB,
204
+			],
205
+			$timezone_string
206
+		);
207
+		/**
208
+		 * Filters the initial start time and format for the new EE_Datetime instance.
209
+		 *
210
+		 * @param array $start_time An array having size 2.  First element is the time, second element is the time
211
+		 *                          format.
212
+		 * @return array
213
+		 */
214
+		$start_time = apply_filters(
215
+			'FHEE__EEM_Datetime__create_new_blank_datetime__start_time',
216
+			['8am', 'ga']
217
+		);
218
+		/**
219
+		 * Filters the initial end time and format for the new EE_Datetime instance.
220
+		 *
221
+		 * @param array $end_time An array having size 2.  First element is the time, second element is the time
222
+		 *                        format
223
+		 * @return array
224
+		 */
225
+		$end_time = apply_filters(
226
+			'FHEE__EEM_Datetime__create_new_blank_datetime__end_time',
227
+			['5pm', 'ga']
228
+		);
229
+		$this->validateStartAndEndTimeForBlankDate($start_time, $end_time);
230
+		$blank_datetime->set_start_time(
231
+			$this->convert_datetime_for_query(
232
+				'DTT_EVT_start',
233
+				$start_time[0],
234
+				$start_time[1],
235
+				$timezone_string
236
+			)
237
+		);
238
+		$blank_datetime->set_end_time(
239
+			$this->convert_datetime_for_query(
240
+				'DTT_EVT_end',
241
+				$end_time[0],
242
+				$end_time[1],
243
+				$timezone_string
244
+			)
245
+		);
246
+		return [$blank_datetime];
247
+	}
248
+
249
+
250
+	/**
251
+	 * Validates whether the start_time and end_time are in the expected format.
252
+	 *
253
+	 * @param array $start_time
254
+	 * @param array $end_time
255
+	 * @throws InvalidArgumentException
256
+	 * @throws InvalidDataTypeException
257
+	 */
258
+	private function validateStartAndEndTimeForBlankDate(array $start_time, array $end_time)
259
+	{
260
+		if (! is_array($start_time)) {
261
+			throw new InvalidDataTypeException('start_time', $start_time, 'array');
262
+		}
263
+		if (! is_array($end_time)) {
264
+			throw new InvalidDataTypeException('end_time', $end_time, 'array');
265
+		}
266
+		if (count($start_time) !== 2) {
267
+			throw new InvalidArgumentException(
268
+				sprintf(
269
+					'The variable %1$s is expected to be an array with two elements.  The first item in the '
270
+					. 'array should be a valid time string, the second item in the array should be a valid time format',
271
+					'$start_time'
272
+				)
273
+			);
274
+		}
275
+		if (count($end_time) !== 2) {
276
+			throw new InvalidArgumentException(
277
+				sprintf(
278
+					'The variable %1$s is expected to be an array with two elements.  The first item in the '
279
+					. 'array should be a valid time string, the second item in the array should be a valid time format',
280
+					'$end_time'
281
+				)
282
+			);
283
+		}
284
+	}
285
+
286
+
287
+	/**
288
+	 * get event start date from db
289
+	 *
290
+	 * @access public
291
+	 * @param int $EVT_ID
292
+	 * @return EE_Datetime[] array on success, FALSE on fail
293
+	 * @throws EE_Error
294
+	 * @throws ReflectionException
295
+	 */
296
+	public function get_all_event_dates($EVT_ID = 0)
297
+	{
298
+		if (! $EVT_ID) { // on add_new_event event_id gets set to 0
299
+			return $this->create_new_blank_datetime();
300
+		}
301
+		$results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
302
+		if (empty($results)) {
303
+			return $this->create_new_blank_datetime();
304
+		}
305
+		return $results;
306
+	}
307
+
308
+
309
+	/**
310
+	 * get all datetimes attached to an event ordered by the DTT_order field
311
+	 *
312
+	 * @public
313
+	 * @param int     $EVT_ID     event id
314
+	 * @param boolean $include_expired
315
+	 * @param boolean $include_deleted
316
+	 * @param int     $limit      If included then limit the count of results by
317
+	 *                            the given number
318
+	 * @return EE_Datetime[]
319
+	 * @throws EE_Error
320
+	 */
321
+	public function get_datetimes_for_event_ordered_by_DTT_order(
322
+		int $EVT_ID,
323
+		bool $include_expired = true,
324
+		bool $include_deleted = true,
325
+		$limit = 0
326
+	) {
327
+		$prev_data_prep_value = $this->prepModelForQuery();
328
+		$where_params         = ['Event.EVT_ID' => absint($EVT_ID)];
329
+		$query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
330
+		$query_params         = $this->addDefaultWhereConditions($query_params);
331
+		$query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
332
+		return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
333
+	}
334
+
335
+
336
+	/**
337
+	 * Gets the datetimes for the event (with the given limit), and orders them by "importance".
338
+	 * By importance, we mean that the primary datetimes are most important (DEPRECATED FOR NOW),
339
+	 * and then the earlier datetimes are the most important.
340
+	 * Maybe we'll want this to take into account datetimes that haven't already passed, but we don't yet.
341
+	 *
342
+	 * @param int $EVT_ID
343
+	 * @param int $limit
344
+	 * @return EE_Datetime[]|EE_Base_Class[]
345
+	 * @throws EE_Error
346
+	 */
347
+	public function get_datetimes_for_event_ordered_by_importance(int $EVT_ID, $limit = 0)
348
+	{
349
+		$query_params[0] = ['Event.EVT_ID' => absint($EVT_ID)];
350
+		$query_params    = $this->addDefaultWhereConditions($query_params);
351
+		$query_params    = $this->addDefaultQueryParams($query_params, $limit);
352
+		return $this->get_all($query_params);
353
+	}
354
+
355
+
356
+	/**
357
+	 * @param int     $EVT_ID
358
+	 * @param boolean $include_expired
359
+	 * @param boolean $include_deleted
360
+	 * @return EE_Datetime
361
+	 * @throws EE_Error
362
+	 */
363
+	public function get_oldest_datetime_for_event(
364
+		int $EVT_ID,
365
+		bool $include_expired = false,
366
+		bool $include_deleted = false
367
+	) {
368
+		$results = $this->get_datetimes_for_event_ordered_by_start_time(
369
+			$EVT_ID,
370
+			$include_expired,
371
+			$include_deleted,
372
+			1
373
+		);
374
+		if ($results) {
375
+			return array_shift($results);
376
+		}
377
+		return null;
378
+	}
379
+
380
+
381
+	/**
382
+	 * Gets the 'primary' datetime for an event.
383
+	 *
384
+	 * @param int  $EVT_ID
385
+	 * @param bool $try_to_exclude_expired
386
+	 * @param bool $try_to_exclude_deleted
387
+	 * @return EE_Datetime
388
+	 * @throws EE_Error
389
+	 */
390
+	public function get_primary_datetime_for_event(
391
+		int $EVT_ID,
392
+		bool $try_to_exclude_expired = true,
393
+		bool $try_to_exclude_deleted = true
394
+	) {
395
+		if ($try_to_exclude_expired) {
396
+			$non_expired = $this->get_oldest_datetime_for_event($EVT_ID, false, false);
397
+			if ($non_expired) {
398
+				return $non_expired;
399
+			}
400
+		}
401
+		if ($try_to_exclude_deleted) {
402
+			$expired_even = $this->get_oldest_datetime_for_event($EVT_ID, true);
403
+			if ($expired_even) {
404
+				return $expired_even;
405
+			}
406
+		}
407
+		return $this->get_oldest_datetime_for_event($EVT_ID, true, true);
408
+	}
409
+
410
+
411
+	/**
412
+	 * Gets ALL the datetimes for an event (including trashed ones, for now), ordered
413
+	 * only by start date
414
+	 *
415
+	 * @param int     $EVT_ID
416
+	 * @param boolean $include_expired
417
+	 * @param boolean $include_deleted
418
+	 * @param int     $limit
419
+	 * @return EE_Datetime[]
420
+	 * @throws EE_Error
421
+	 */
422
+	public function get_datetimes_for_event_ordered_by_start_time(
423
+		int $EVT_ID,
424
+		bool $include_expired = true,
425
+		bool $include_deleted = true,
426
+		$limit = 0
427
+	) {
428
+		$prev_data_prep_value = $this->prepModelForQuery();
429
+		$where_params         = ['Event.EVT_ID' => absint($EVT_ID)];
430
+		$query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
431
+		$query_params         = $this->addDefaultWhereConditions(
432
+			$query_params,
433
+			EE_Default_Where_Conditions::THIS_MODEL_ONLY
434
+		);
435
+		$query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
436
+		return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
437
+	}
438
+
439
+
440
+	/**
441
+	 * Gets ALL the datetimes for an ticket (including trashed ones, for now), ordered
442
+	 * only by start date
443
+	 *
444
+	 * @param int     $TKT_ID
445
+	 * @param boolean $include_expired
446
+	 * @param boolean $include_deleted
447
+	 * @param int     $limit
448
+	 * @return EE_Datetime[]
449
+	 * @throws EE_Error
450
+	 */
451
+	public function get_datetimes_for_ticket_ordered_by_start_time(
452
+		int $TKT_ID,
453
+		bool $include_expired = true,
454
+		bool $include_deleted = true,
455
+		$limit = 0
456
+	) {
457
+		$prev_data_prep_value = $this->prepModelForQuery();
458
+		$where_params         = ['Ticket.TKT_ID' => absint($TKT_ID)];
459
+		$query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
460
+		$query_params         = $this->addDefaultQueryParams($query_params, $limit);
461
+		return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
462
+	}
463
+
464
+
465
+	/**
466
+	 * Gets all the datetimes for a ticket (including trashed ones, for now), ordered by the DTT_order for the
467
+	 * datetimes.
468
+	 *
469
+	 * @param int      $TKT_ID           ID of ticket to retrieve the datetimes for
470
+	 * @param boolean  $include_expired  whether to include expired datetimes or not
471
+	 * @param boolean  $include_deleted  whether to include trashed datetimes or not.
472
+	 * @param int|null $limit            if null, no limit, if int then limit results by
473
+	 *                                   that number
474
+	 * @return EE_Datetime[]
475
+	 * @throws EE_Error
476
+	 */
477
+	public function get_datetimes_for_ticket_ordered_by_DTT_order(
478
+		int $TKT_ID,
479
+		bool $include_expired = true,
480
+		bool $include_deleted = true,
481
+		$limit = 0
482
+	) {
483
+		$prev_data_prep_value = $this->prepModelForQuery();
484
+		$where_params         = ['Ticket.TKT_ID' => absint($TKT_ID)];
485
+		$query_params[0]      = $this->addDefaultWhereParams($where_params, $include_deleted, $include_expired);
486
+		$query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
487
+		return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
488
+	}
489
+
490
+
491
+	/**
492
+	 * Gets the most important datetime for a particular event (ie, the primary event usually. But if for some WACK
493
+	 * reason it doesn't exist, we consider the earliest event the most important)
494
+	 *
495
+	 * @param int $EVT_ID
496
+	 * @return EE_Datetime
497
+	 * @throws EE_Error
498
+	 */
499
+	public function get_most_important_datetime_for_event(int $EVT_ID)
500
+	{
501
+		$results = $this->get_datetimes_for_event_ordered_by_importance($EVT_ID, 1);
502
+		if ($results) {
503
+			return array_shift($results);
504
+		}
505
+		return null;
506
+	}
507
+
508
+
509
+	/**
510
+	 * This returns a wpdb->results        Array of all DTT month and years matching the incoming query params and
511
+	 * grouped by month and year.
512
+	 *
513
+	 * @param array  $where_params       @see
514
+	 *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
515
+	 * @param string $evt_active_status  A string representing the evt active status to filter the months by.
516
+	 *                                   Can be:
517
+	 *                                   - '' = no filter
518
+	 *                                   - upcoming = Published events with at least one upcoming datetime.
519
+	 *                                   - expired = Events with all datetimes expired.
520
+	 *                                   - active = Events that are published and have at least one datetime that
521
+	 *                                   starts before now and ends after now.
522
+	 *                                   - inactive = Events that are either not published.
523
+	 * @return stdClass[]
524
+	 * @throws EE_Error
525
+	 * @throws InvalidArgumentException
526
+	 * @throws InvalidArgumentException
527
+	 */
528
+	public function get_dtt_months_and_years(array $where_params, $evt_active_status = '')
529
+	{
530
+		$current_time_for_DTT_EVT_start = $this->current_time_for_query('DTT_EVT_start');
531
+		$current_time_for_DTT_EVT_end   = $this->current_time_for_query('DTT_EVT_end');
532
+		switch ($evt_active_status) {
533
+			case 'upcoming':
534
+				$where_params['Event.status'] = 'publish';
535
+				// if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
536
+				if (isset($where_params['DTT_EVT_start'])) {
537
+					$where_params['DTT_EVT_start*****'] = $where_params['DTT_EVT_start'];
538
+				}
539
+				$where_params['DTT_EVT_start'] = ['>', $current_time_for_DTT_EVT_start];
540
+				break;
541
+			case 'expired':
542
+				if (isset($where_params['Event.status'])) {
543
+					unset($where_params['Event.status']);
544
+				}
545
+				// get events to exclude
546
+				$exclude_query[0] = array_merge(
547
+					$where_params,
548
+					['DTT_EVT_end' => ['>', $current_time_for_DTT_EVT_end]]
549
+				);
550
+				// first get all events that have datetimes where its not expired.
551
+				$event_ids = $this->_get_all_wpdb_results(
552
+					$exclude_query,
553
+					OBJECT_K,
554
+					'Datetime.EVT_ID'
555
+				);
556
+				$event_ids = array_keys($event_ids);
557
+				if (isset($where_params['DTT_EVT_end'])) {
558
+					$where_params['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
559
+				}
560
+				$where_params['DTT_EVT_end']  = ['<', $current_time_for_DTT_EVT_end];
561
+				$where_params['Event.EVT_ID'] = ['NOT IN', $event_ids];
562
+				break;
563
+			case 'active':
564
+				$where_params['Event.status'] = 'publish';
565
+				if (isset($where_params['DTT_EVT_start'])) {
566
+					$where_params['Datetime.DTT_EVT_start******'] = $where_params['DTT_EVT_start'];
567
+				}
568
+				if (isset($where_params['Datetime.DTT_EVT_end'])) {
569
+					$where_params['Datetime.DTT_EVT_end*****'] = $where_params['DTT_EVT_end'];
570
+				}
571
+				$where_params['DTT_EVT_start'] = ['<', $current_time_for_DTT_EVT_start];
572
+				$where_params['DTT_EVT_end']   = ['>', $current_time_for_DTT_EVT_end];
573
+				break;
574
+			case 'inactive':
575
+				if (isset($where_params['Event.status'])) {
576
+					unset($where_params['Event.status']);
577
+				}
578
+				if (isset($where_params['OR'])) {
579
+					$where_params['AND']['OR'] = $where_params['OR'];
580
+				}
581
+				if (isset($where_params['DTT_EVT_end'])) {
582
+					$where_params['AND']['DTT_EVT_end****'] = $where_params['DTT_EVT_end'];
583
+					unset($where_params['DTT_EVT_end']);
584
+				}
585
+				if (isset($where_params['DTT_EVT_start'])) {
586
+					$where_params['AND']['DTT_EVT_start'] = $where_params['DTT_EVT_start'];
587
+					unset($where_params['DTT_EVT_start']);
588
+				}
589
+				$where_params['AND']['Event.status'] = ['!=', 'publish'];
590
+				break;
591
+		}
592
+		$query_params[0]          = $where_params;
593
+		$query_params['group_by'] = ['dtt_year', 'dtt_month'];
594
+		$query_params             = $this->addOrderByQueryParams($query_params, 'DTT_EVT_start', 'DESC');
595
+
596
+		$query_interval    = EEH_DTT_Helper::get_sql_query_interval_for_offset(
597
+			$this->get_timezone(),
598
+			'DTT_EVT_start'
599
+		);
600
+		$columns_to_select = [
601
+			'dtt_year'      => ['YEAR(' . $query_interval . ')', '%s'],
602
+			'dtt_month'     => ['MONTHNAME(' . $query_interval . ')', '%s'],
603
+			'dtt_month_num' => ['MONTH(' . $query_interval . ')', '%s'],
604
+		];
605
+		return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
606
+	}
607
+
608
+
609
+	/**
610
+	 * Updates the DTT_sold attribute on each datetime (based on the registrations
611
+	 * for the tickets for each datetime)
612
+	 *
613
+	 * @param EE_Base_Class[]|EE_Datetime[] $datetimes
614
+	 * @throws EE_Error
615
+	 * @throws ReflectionException
616
+	 */
617
+	public function update_sold(array $datetimes)
618
+	{
619
+		EE_Error::doing_it_wrong(
620
+			__FUNCTION__,
621
+			esc_html__(
622
+				'Please use \EEM_Ticket::update_tickets_sold() instead which will in turn correctly update both the Ticket AND Datetime counts.',
623
+				'event_espresso'
624
+			),
625
+			'4.9.32.rc.005'
626
+		);
627
+		foreach ($datetimes as $datetime) {
628
+			$datetime->update_sold();
629
+		}
630
+	}
631
+
632
+
633
+	/**
634
+	 *    Gets the total number of tickets available at a particular datetime
635
+	 *    (does NOT take into account the datetime's spaces available)
636
+	 *
637
+	 * @param int   $DTT_ID
638
+	 * @param array $query_params
639
+	 * @return int of tickets available. If sold out, return less than 1. If infinite, returns EE_INF,  IF there are NO
640
+	 *             tickets attached to datetime then FALSE is returned.
641
+	 * @throws EE_Error
642
+	 * @throws ReflectionException
643
+	 */
644
+	public function sum_tickets_currently_available_at_datetime(int $DTT_ID, array $query_params = [])
645
+	{
646
+		$datetime = $this->get_one_by_ID($DTT_ID);
647
+		if ($datetime instanceof EE_Datetime) {
648
+			return $datetime->tickets_remaining($query_params);
649
+		}
650
+		return 0;
651
+	}
652
+
653
+
654
+	/**
655
+	 * This returns an array of counts of datetimes in the database for each Datetime status that can be queried.
656
+	 *
657
+	 * @param array $stati_to_include  If included you can restrict the statuses we return counts for by including the
658
+	 *                                 stati you want counts for as values in the array.  An empty array returns counts
659
+	 *                                 for all valid stati.
660
+	 * @param array $query_params      If included can be used to refine the conditions for returning the count (i.e.
661
+	 *                                 only for Datetimes connected to a specific event, or specific ticket.
662
+	 * @return array  The value returned is an array indexed by Datetime Status and the values are the counts.  The
663
+	 * @throws EE_Error
664
+	 *                                 stati used as index keys are: EE_Datetime::active EE_Datetime::upcoming
665
+	 *                                 EE_Datetime::expired
666
+	 */
667
+	public function get_datetime_counts_by_status(array $stati_to_include = [], array $query_params = [])
668
+	{
669
+		// only accept where conditions for this query.
670
+		$_where            = isset($query_params[0]) ? $query_params[0] : [];
671
+		$status_query_args = [
672
+			EE_Datetime::active   => array_merge(
673
+				$_where,
674
+				['DTT_EVT_start' => ['<', time()], 'DTT_EVT_end' => ['>', time()]]
675
+			),
676
+			EE_Datetime::upcoming => array_merge(
677
+				$_where,
678
+				['DTT_EVT_start' => ['>', time()]]
679
+			),
680
+			EE_Datetime::expired  => array_merge(
681
+				$_where,
682
+				['DTT_EVT_end' => ['<', time()]]
683
+			),
684
+		];
685
+		if (! empty($stati_to_include)) {
686
+			foreach (array_keys($status_query_args) as $status) {
687
+				if (! in_array($status, $stati_to_include, true)) {
688
+					unset($status_query_args[ $status ]);
689
+				}
690
+			}
691
+		}
692
+		// loop through and query counts for each stati.
693
+		$status_query_results = [];
694
+		foreach ($status_query_args as $status => $status_where_conditions) {
695
+			$status_query_results[ $status ] = EEM_Datetime::count(
696
+				[$status_where_conditions],
697
+				'DTT_ID',
698
+				true
699
+			);
700
+		}
701
+		return $status_query_results;
702
+	}
703
+
704
+
705
+	/**
706
+	 * Returns the specific count for a given Datetime status matching any given query_params.
707
+	 *
708
+	 * @param string $status Valid string representation for Datetime status requested. (Defaults to Active).
709
+	 * @param array  $query_params
710
+	 * @return int
711
+	 * @throws EE_Error
712
+	 */
713
+	public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = [])
714
+	{
715
+		$count = $this->get_datetime_counts_by_status([$status], $query_params);
716
+		return ! empty($count[ $status ]) ? $count[ $status ] : 0;
717
+	}
718
+
719
+
720
+	/**
721
+	 * @return bool|int
722
+	 * @since   5.0.0.p
723
+	 */
724
+	private function prepModelForQuery()
725
+	{
726
+		$prev_data_prep_value = $this->get_assumption_concerning_values_already_prepared_by_model_object();
727
+		$this->assume_values_already_prepared_by_model_object(EEM_Base::prepared_for_use_in_db);
728
+		return $prev_data_prep_value;
729
+	}
730
+
731
+
732
+	/**
733
+	 * @param array    $query_params
734
+	 * @param bool|int $prev_data_prep_value
735
+	 * @return EE_Base_Class[]|EE_Datetime[]
736
+	 * @throws EE_Error
737
+	 * @since   5.0.0.p
738
+	 */
739
+	private function getDatetimesAndRestoreModel(array $query_params, $prev_data_prep_value)
740
+	{
741
+		$result = $this->get_all($query_params);
742
+		$this->assume_values_already_prepared_by_model_object($prev_data_prep_value);
743
+		return $result;
744
+	}
745
+
746
+
747
+	/**
748
+	 * @param array  $query_params
749
+	 * @param int    $limit
750
+	 * @param string $order_by
751
+	 * @param string $order
752
+	 * @return array
753
+	 * @since   5.0.0.p
754
+	 */
755
+	private function addDefaultQueryParams(array $query_params, $limit = 0, $order_by = 'DTT_EVT_start', $order = 'ASC')
756
+	{
757
+		$query_params = $this->addOrderByQueryParams($query_params, $order_by, $order);
758
+		$query_params = $this->addLimitQueryParams($query_params, $limit);
759
+		return $query_params;
760
+	}
761
+
762
+
763
+	/**
764
+	 * @param array  $query_params
765
+	 * @param string $default_where_conditions
766
+	 * @return array
767
+	 * @since   5.0.0.p
768
+	 */
769
+	private function addDefaultWhereConditions(
770
+		array $query_params,
771
+		$default_where_conditions = EE_Default_Where_Conditions::NONE
772
+	) {
773
+		$query_params['default_where_conditions'] = $default_where_conditions;
774
+		return $query_params;
775
+	}
776
+
777
+
778
+	/**
779
+	 * @param array $where_params
780
+	 * @param bool  $include_deleted
781
+	 * @param bool  $include_expired
782
+	 * @return array
783
+	 * @since   5.0.0.p
784
+	 */
785
+	private function addDefaultWhereParams(
786
+		array $where_params,
787
+		bool $include_deleted = true,
788
+		bool $include_expired = true
789
+	) {
790
+		$where_params = $this->addExpiredWhereParams($where_params, $include_expired);
791
+		$where_params = $this->addDeletedWhereParams($where_params, $include_deleted);
792
+		return $where_params;
793
+	}
794
+
795
+
796
+	/**
797
+	 * @param array $where_params
798
+	 * @param bool  $include_deleted
799
+	 * @return array
800
+	 * @since   5.0.0.p
801
+	 */
802
+	private function addDeletedWhereParams(array $where_params, bool $include_deleted = true)
803
+	{
804
+		$deleted                     = $include_deleted ? [true, false] : [false];
805
+		$where_params['DTT_deleted'] = ['IN', $deleted];
806
+		return $where_params;
807
+	}
808
+
809
+
810
+	/**
811
+	 * @param array $where_params
812
+	 * @param bool  $include_expired
813
+	 * @return array
814
+	 * @since   5.0.0.p
815
+	 */
816
+	private function addExpiredWhereParams(array $where_params, bool $include_expired = true)
817
+	{
818
+		if (! $include_expired) {
819
+			$where_params['DTT_EVT_end'] = ['>=', current_time('mysql', true)];
820
+		}
821
+		return $where_params;
822
+	}
823
+
824
+
825
+	/**
826
+	 * @param array $query_params
827
+	 * @param int   $limit
828
+	 * @return array
829
+	 * @since   5.0.0.p
830
+	 */
831
+	private function addLimitQueryParams(array $query_params, $limit = 0)
832
+	{
833
+		if ($limit) {
834
+			$query_params['limit'] = $limit;
835
+		}
836
+		return $query_params;
837
+	}
838
+
839
+
840
+	/**
841
+	 * @param array  $query_params
842
+	 * @param string $order_by
843
+	 * @param string $order
844
+	 * @return array
845
+	 * @since   5.0.0.p
846
+	 */
847
+	private function addOrderByQueryParams(array $query_params, $order_by = 'DTT_EVT_start', $order = 'ASC')
848
+	{
849
+		$order                    = $order === 'ASC' ? 'ASC' : 'DESC';
850
+		$valid_order_columns      = ['DTT_ID', 'DTT_EVT_start', 'DTT_EVT_end', 'DTT_order'];
851
+		$order_by                 = in_array($order_by, $valid_order_columns, true) ? $order_by : 'DTT_EVT_start';
852
+		$query_params['order_by'] = [$order_by => $order];
853
+		return $query_params;
854
+	}
855 855
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
                 ),
127 127
             ],
128 128
         ];
129
-        $this->_model_relations        = [
129
+        $this->_model_relations = [
130 130
             'Ticket'          => new EE_HABTM_Relation('Datetime_Ticket'),
131 131
             'Event'           => new EE_Belongs_To_Relation(),
132 132
             'Checkin'         => new EE_Has_Many_Relation(),
@@ -137,19 +137,19 @@  discard block
 block discarded – undo
137 137
         $this->model_chain_to_password = $path_to_event_model;
138 138
         $this->_model_chain_to_wp_user = $path_to_event_model;
139 139
         // this model is generally available for reading
140
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ]       =
140
+        $this->_cap_restriction_generators[EEM_Base::caps_read] =
141 141
             new EE_Restriction_Generator_Event_Related_Public(
142 142
                 $path_to_event_model
143 143
             );
144
-        $this->_cap_restriction_generators[ EEM_Base::caps_read_admin ] =
144
+        $this->_cap_restriction_generators[EEM_Base::caps_read_admin] =
145 145
             new EE_Restriction_Generator_Event_Related_Protected(
146 146
                 $path_to_event_model
147 147
             );
148
-        $this->_cap_restriction_generators[ EEM_Base::caps_edit ]       =
148
+        $this->_cap_restriction_generators[EEM_Base::caps_edit] =
149 149
             new EE_Restriction_Generator_Event_Related_Protected(
150 150
                 $path_to_event_model
151 151
             );
152
-        $this->_cap_restriction_generators[ EEM_Base::caps_delete ]     =
152
+        $this->_cap_restriction_generators[EEM_Base::caps_delete] =
153 153
             new EE_Restriction_Generator_Event_Related_Protected(
154 154
                 $path_to_event_model,
155 155
                 EEM_Base::caps_edit
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
          * @param int $end_data Unix timestamp representing now + 30 days in seconds.
192 192
          * @return int Unix timestamp
193 193
          */
194
-        $end_date       = apply_filters(
194
+        $end_date = apply_filters(
195 195
             'FHEE__EEM_Datetime__create_new_blank_datetime__end_date',
196 196
             $this->current_time_for_query('DTT_EVT_end', true) + MONTH_IN_SECONDS
197 197
         );
@@ -257,10 +257,10 @@  discard block
 block discarded – undo
257 257
      */
258 258
     private function validateStartAndEndTimeForBlankDate(array $start_time, array $end_time)
259 259
     {
260
-        if (! is_array($start_time)) {
260
+        if ( ! is_array($start_time)) {
261 261
             throw new InvalidDataTypeException('start_time', $start_time, 'array');
262 262
         }
263
-        if (! is_array($end_time)) {
263
+        if ( ! is_array($end_time)) {
264 264
             throw new InvalidDataTypeException('end_time', $end_time, 'array');
265 265
         }
266 266
         if (count($start_time) !== 2) {
@@ -295,7 +295,7 @@  discard block
 block discarded – undo
295 295
      */
296 296
     public function get_all_event_dates($EVT_ID = 0)
297 297
     {
298
-        if (! $EVT_ID) { // on add_new_event event_id gets set to 0
298
+        if ( ! $EVT_ID) { // on add_new_event event_id gets set to 0
299 299
             return $this->create_new_blank_datetime();
300 300
         }
301 301
         $results = $this->get_datetimes_for_event_ordered_by_DTT_order($EVT_ID);
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
             $query_params,
433 433
             EE_Default_Where_Conditions::THIS_MODEL_ONLY
434 434
         );
435
-        $query_params         = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
435
+        $query_params = $this->addDefaultQueryParams($query_params, $limit, 'DTT_order');
436 436
         return $this->getDatetimesAndRestoreModel($query_params, $prev_data_prep_value);
437 437
     }
438 438
 
@@ -593,14 +593,14 @@  discard block
 block discarded – undo
593 593
         $query_params['group_by'] = ['dtt_year', 'dtt_month'];
594 594
         $query_params             = $this->addOrderByQueryParams($query_params, 'DTT_EVT_start', 'DESC');
595 595
 
596
-        $query_interval    = EEH_DTT_Helper::get_sql_query_interval_for_offset(
596
+        $query_interval = EEH_DTT_Helper::get_sql_query_interval_for_offset(
597 597
             $this->get_timezone(),
598 598
             'DTT_EVT_start'
599 599
         );
600 600
         $columns_to_select = [
601
-            'dtt_year'      => ['YEAR(' . $query_interval . ')', '%s'],
602
-            'dtt_month'     => ['MONTHNAME(' . $query_interval . ')', '%s'],
603
-            'dtt_month_num' => ['MONTH(' . $query_interval . ')', '%s'],
601
+            'dtt_year'      => ['YEAR('.$query_interval.')', '%s'],
602
+            'dtt_month'     => ['MONTHNAME('.$query_interval.')', '%s'],
603
+            'dtt_month_num' => ['MONTH('.$query_interval.')', '%s'],
604 604
         ];
605 605
         return $this->_get_all_wpdb_results($query_params, OBJECT, $columns_to_select);
606 606
     }
@@ -682,17 +682,17 @@  discard block
 block discarded – undo
682 682
                 ['DTT_EVT_end' => ['<', time()]]
683 683
             ),
684 684
         ];
685
-        if (! empty($stati_to_include)) {
685
+        if ( ! empty($stati_to_include)) {
686 686
             foreach (array_keys($status_query_args) as $status) {
687
-                if (! in_array($status, $stati_to_include, true)) {
688
-                    unset($status_query_args[ $status ]);
687
+                if ( ! in_array($status, $stati_to_include, true)) {
688
+                    unset($status_query_args[$status]);
689 689
                 }
690 690
             }
691 691
         }
692 692
         // loop through and query counts for each stati.
693 693
         $status_query_results = [];
694 694
         foreach ($status_query_args as $status => $status_where_conditions) {
695
-            $status_query_results[ $status ] = EEM_Datetime::count(
695
+            $status_query_results[$status] = EEM_Datetime::count(
696 696
                 [$status_where_conditions],
697 697
                 'DTT_ID',
698 698
                 true
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
     public function get_datetime_count_for_status($status = EE_Datetime::active, array $query_params = [])
714 714
     {
715 715
         $count = $this->get_datetime_counts_by_status([$status], $query_params);
716
-        return ! empty($count[ $status ]) ? $count[ $status ] : 0;
716
+        return ! empty($count[$status]) ? $count[$status] : 0;
717 717
     }
718 718
 
719 719
 
@@ -815,7 +815,7 @@  discard block
 block discarded – undo
815 815
      */
816 816
     private function addExpiredWhereParams(array $where_params, bool $include_expired = true)
817 817
     {
818
-        if (! $include_expired) {
818
+        if ( ! $include_expired) {
819 819
             $where_params['DTT_EVT_end'] = ['>=', current_time('mysql', true)];
820 820
         }
821 821
         return $where_params;
Please login to merge, or discard this patch.
core/db_models/EEM_Event.model.php 1 patch
Indentation   +949 added lines, -949 removed lines patch added patch discarded remove patch
@@ -15,953 +15,953 @@
 block discarded – undo
15 15
  */
16 16
 class EEM_Event extends EEM_CPT_Base
17 17
 {
18
-    /**
19
-     * constant used by status(), indicating that no more tickets can be purchased for any of the datetimes for the
20
-     * event
21
-     */
22
-    const sold_out = 'sold_out';
23
-
24
-    /**
25
-     * constant used by status(), indicating that upcoming event dates have been postponed (may be pushed to a later
26
-     * date)
27
-     */
28
-    const postponed = 'postponed';
29
-
30
-    /**
31
-     * constant used by status(), indicating that the event will no longer occur
32
-     */
33
-    const cancelled = 'cancelled';
34
-
35
-
36
-    protected static string $_default_reg_status;
37
-
38
-    protected static int $_default_additional_limit = 10;
39
-
40
-    protected static ?EEM_Event $_instance = null;
41
-
42
-
43
-    /**
44
-     * Adds a relationship to Term_Taxonomy for each CPT_Base
45
-     *
46
-     * @param string|null $timezone
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    protected function __construct(?string $timezone = '')
51
-    {
52
-        EE_Registry::instance()->load_model('Registration');
53
-        $this->singular_item = esc_html__('Event', 'event_espresso');
54
-        $this->plural_item   = esc_html__('Events', 'event_espresso');
55
-        // to remove Cancelled events from the frontend, copy the following filter to your functions.php file
56
-        // add_filter( 'AFEE__EEM_Event__construct___custom_stati__cancelled__Public', '__return_false' );
57
-        // to remove Postponed events from the frontend, copy the following filter to your functions.php file
58
-        // add_filter( 'AFEE__EEM_Event__construct___custom_stati__postponed__Public', '__return_false' );
59
-        // to remove Sold Out events from the frontend, copy the following filter to your functions.php file
60
-        //  add_filter( 'AFEE__EEM_Event__construct___custom_stati__sold_out__Public', '__return_false' );
61
-        $this->_custom_stati       = apply_filters(
62
-            'AFEE__EEM_Event__construct___custom_stati',
63
-            [
64
-                EEM_Event::cancelled => [
65
-                    'label'  => esc_html__('Cancelled', 'event_espresso'),
66
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__cancelled__Public', true),
67
-                ],
68
-                EEM_Event::postponed => [
69
-                    'label'  => esc_html__('Postponed', 'event_espresso'),
70
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__postponed__Public', true),
71
-                ],
72
-                EEM_Event::sold_out  => [
73
-                    'label'  => esc_html__('Sold Out', 'event_espresso'),
74
-                    'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__sold_out__Public', true),
75
-                ],
76
-            ]
77
-        );
78
-        self::$_default_reg_status = empty(self::$_default_reg_status)
79
-            ? RegStatus::PENDING_PAYMENT
80
-            : self::$_default_reg_status;
81
-        $this->_tables             = [
82
-            'Event_CPT'  => new EE_Primary_Table('posts', 'ID'),
83
-            'Event_Meta' => new EE_Secondary_Table('esp_event_meta', 'EVTM_ID', 'EVT_ID'),
84
-        ];
85
-        $this->_fields             = [
86
-            'Event_CPT'  => [
87
-                'EVT_ID'         => new EE_Primary_Key_Int_Field(
88
-                    'ID',
89
-                    esc_html__('Post ID for Event', 'event_espresso')
90
-                ),
91
-                'EVT_name'       => new EE_Plain_Text_Field(
92
-                    'post_title',
93
-                    esc_html__('Event Name', 'event_espresso'),
94
-                    false,
95
-                    ''
96
-                ),
97
-                'EVT_desc'       => new EE_Post_Content_Field(
98
-                    'post_content',
99
-                    esc_html__('Event Description', 'event_espresso'),
100
-                    false,
101
-                    ''
102
-                ),
103
-                'EVT_slug'       => new EE_Slug_Field(
104
-                    'post_name',
105
-                    esc_html__('Event Slug', 'event_espresso'),
106
-                    false,
107
-                    ''
108
-                ),
109
-                'EVT_created'    => new EE_Datetime_Field(
110
-                    'post_date',
111
-                    esc_html__('Date/Time Event Created', 'event_espresso'),
112
-                    false,
113
-                    EE_Datetime_Field::now
114
-                ),
115
-                'EVT_short_desc' => new EE_Simple_HTML_Field(
116
-                    'post_excerpt',
117
-                    esc_html__('Event Short Description', 'event_espresso'),
118
-                    false,
119
-                    ''
120
-                ),
121
-                'EVT_modified'   => new EE_Datetime_Field(
122
-                    'post_modified',
123
-                    esc_html__('Date/Time Event Modified', 'event_espresso'),
124
-                    false,
125
-                    EE_Datetime_Field::now
126
-                ),
127
-                'EVT_wp_user'    => new EE_WP_User_Field(
128
-                    'post_author',
129
-                    esc_html__('Event Creator ID', 'event_espresso'),
130
-                    false
131
-                ),
132
-                'parent'         => new EE_Integer_Field(
133
-                    'post_parent',
134
-                    esc_html__('Event Parent ID', 'event_espresso'),
135
-                    false,
136
-                    0
137
-                ),
138
-                'EVT_order'      => new EE_Integer_Field(
139
-                    'menu_order',
140
-                    esc_html__('Event Menu Order', 'event_espresso'),
141
-                    false,
142
-                    1
143
-                ),
144
-                'post_type'      => new EE_WP_Post_Type_Field(EspressoPostType::EVENTS),
145
-                // EE_Plain_Text_Field( 'post_type', esc_html__( 'Event Post Type', 'event_espresso' ), FALSE, 'espresso_events' ),
146
-                'status'         => new EE_WP_Post_Status_Field(
147
-                    'post_status',
148
-                    esc_html__('Event Status', 'event_espresso'),
149
-                    false,
150
-                    'draft',
151
-                    $this->_custom_stati
152
-                ),
153
-                'password'       => new EE_Password_Field(
154
-                    'post_password',
155
-                    esc_html__('Password', 'event_espresso'),
156
-                    false,
157
-                    '',
158
-                    [
159
-                        'EVT_desc',
160
-                        'EVT_short_desc',
161
-                        'EVT_display_desc',
162
-                        'EVT_display_ticket_selector',
163
-                        'EVT_visible_on',
164
-                        'EVT_additional_limit',
165
-                        'EVT_default_registration_status',
166
-                        'EVT_member_only',
167
-                        'EVT_phone',
168
-                        'EVT_allow_overflow',
169
-                        'EVT_timezone_string',
170
-                        'EVT_external_URL',
171
-                        'EVT_donations',
172
-                    ]
173
-                ),
174
-            ],
175
-            'Event_Meta' => [
176
-                'EVTM_ID'                         => new EE_DB_Only_Float_Field(
177
-                    'EVTM_ID',
178
-                    esc_html__('Event Meta Row ID', 'event_espresso'),
179
-                    false
180
-                ),
181
-                'EVT_ID_fk'                       => new EE_DB_Only_Int_Field(
182
-                    'EVT_ID',
183
-                    esc_html__('Foreign key to Event ID from Event Meta table', 'event_espresso'),
184
-                    false
185
-                ),
186
-                'VNU_ID'                          => new EE_Foreign_Key_Int_Field(
187
-                    'VNU_ID',
188
-                    __('Venue ID', 'event_espresso'),
189
-                    false,
190
-                    0,
191
-                    'Venue'
192
-                ),
193
-                'EVT_display_desc'                => new EE_Boolean_Field(
194
-                    'EVT_display_desc',
195
-                    esc_html__('Display Description Flag', 'event_espresso'),
196
-                    false,
197
-                    true
198
-                ),
199
-                'EVT_display_ticket_selector'     => new EE_Boolean_Field(
200
-                    'EVT_display_ticket_selector',
201
-                    esc_html__('Display Ticket Selector Flag', 'event_espresso'),
202
-                    false,
203
-                    true
204
-                ),
205
-                'EVT_visible_on'                  => new EE_Datetime_Field(
206
-                    'EVT_visible_on',
207
-                    esc_html__('Event Visible Date', 'event_espresso'),
208
-                    true,
209
-                    EE_Datetime_Field::now
210
-                ),
211
-                'EVT_additional_limit'            => new EE_Integer_Field(
212
-                    'EVT_additional_limit',
213
-                    esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
214
-                    false,
215
-                    self::$_default_additional_limit
216
-                ),
217
-                'EVT_default_registration_status' => new EE_Enum_Text_Field(
218
-                    'EVT_default_registration_status',
219
-                    esc_html__('Default Registration Status on this Event', 'event_espresso'),
220
-                    false,
221
-                    EEM_Event::$_default_reg_status,
222
-                    EEM_Registration::reg_status_array()
223
-                ),
224
-                'EVT_member_only'                 => new EE_Boolean_Field(
225
-                    'EVT_member_only',
226
-                    esc_html__('Member-Only Event Flag', 'event_espresso'),
227
-                    false,
228
-                    false
229
-                ),
230
-                'EVT_phone'                       => new EE_Plain_Text_Field(
231
-                    'EVT_phone',
232
-                    esc_html__('Event Phone Number', 'event_espresso'),
233
-                    false,
234
-                    ''
235
-                ),
236
-                'EVT_allow_overflow'              => new EE_Boolean_Field(
237
-                    'EVT_allow_overflow',
238
-                    esc_html__('Allow Overflow on Event', 'event_espresso'),
239
-                    false,
240
-                    false
241
-                ),
242
-                'EVT_timezone_string'             => new EE_Plain_Text_Field(
243
-                    'EVT_timezone_string',
244
-                    esc_html__('Timezone (name) for Event times', 'event_espresso'),
245
-                    false,
246
-                    ''
247
-                ),
248
-                'EVT_external_URL'                => new EE_Plain_Text_Field(
249
-                    'EVT_external_URL',
250
-                    esc_html__('URL of Event Page if hosted elsewhere', 'event_espresso'),
251
-                    true
252
-                ),
253
-                'EVT_donations'                   => new EE_Boolean_Field(
254
-                    'EVT_donations',
255
-                    esc_html__('Accept Donations?', 'event_espresso'),
256
-                    false,
257
-                    false
258
-                ),
259
-                'FSC_UUID'                        => new EE_Foreign_Key_String_Field(
260
-                    'FSC_UUID',
261
-                    esc_html__('Registration Form UUID (universally unique identifier)', 'event_espresso'),
262
-                    true,
263
-                    null,
264
-                    'Form_Section',
265
-                    false
266
-                ),
267
-            ],
268
-        ];
269
-        $this->_model_relations    = [
270
-            'Attendee'               => new EE_HABTM_Relation('Registration'),
271
-            'Datetime'               => new EE_Has_Many_Relation(),
272
-            'Event_Question_Group'   => new EE_Has_Many_Relation(),
273
-            'Form_Section'           => new EE_Belongs_To_Relation(),
274
-            'Message_Template_Group' => new EE_HABTM_Relation('Event_Message_Template'),
275
-            'Question_Group'         => new EE_HABTM_Relation('Event_Question_Group'),
276
-            'Registration'           => new EE_Has_Many_Relation(),
277
-            'Term_Relationship'      => new EE_Has_Many_Relation(),
278
-            'Term_Taxonomy'          => new EE_HABTM_Relation('Term_Relationship'),
279
-            'Venue'                  => new EE_Belongs_To_Relation(),
280
-            'WP_User'                => new EE_Belongs_To_Relation(),
281
-        ];
282
-        // this model is generally available for reading
283
-        $this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
284
-        $this->model_chain_to_password                            = '';
285
-        parent::__construct($timezone);
286
-    }
287
-
288
-
289
-    /**
290
-     * @param string $default_reg_status
291
-     * @throws EE_Error
292
-     * @throws EE_Error
293
-     */
294
-    public static function set_default_reg_status($default_reg_status)
295
-    {
296
-        self::$_default_reg_status = $default_reg_status;
297
-        // if EEM_Event has already been instantiated,
298
-        // then we need to reset the `EVT_default_reg_status` field to use the new default.
299
-        if (self::$_instance instanceof EEM_Event) {
300
-            $default_reg_status = new EE_Enum_Text_Field(
301
-                'EVT_default_registration_status',
302
-                esc_html__('Default Registration Status on this Event', 'event_espresso'),
303
-                false,
304
-                $default_reg_status,
305
-                EEM_Registration::reg_status_array()
306
-            );
307
-            $default_reg_status->_construct_finalize(
308
-                'Event_Meta',
309
-                'EVT_default_registration_status',
310
-                'EEM_Event'
311
-            );
312
-            self::$_instance->_fields['Event_Meta']['EVT_default_registration_status'] = $default_reg_status;
313
-        }
314
-    }
315
-
316
-
317
-    /**
318
-     * Used to override the default for the additional limit field.
319
-     *
320
-     * @param $additional_limit
321
-     */
322
-    public static function set_default_additional_limit($additional_limit)
323
-    {
324
-        self::$_default_additional_limit = (int) $additional_limit;
325
-        if (self::$_instance instanceof EEM_Event) {
326
-            self::$_instance->_fields['Event_Meta']['EVT_additional_limit'] = new EE_Integer_Field(
327
-                'EVT_additional_limit',
328
-                esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
329
-                false,
330
-                self::$_default_additional_limit
331
-            );
332
-            self::$_instance->_fields['Event_Meta']['EVT_additional_limit']->_construct_finalize(
333
-                'Event_Meta',
334
-                'EVT_additional_limit',
335
-                'EEM_Event'
336
-            );
337
-        }
338
-    }
339
-
340
-
341
-    /**
342
-     * Return what is currently set as the default additional limit for the event.
343
-     *
344
-     * @return int
345
-     */
346
-    public static function get_default_additional_limit()
347
-    {
348
-        return apply_filters('FHEE__EEM_Event__get_default_additional_limit', self::$_default_additional_limit);
349
-    }
350
-
351
-
352
-    /**
353
-     * get_question_groups
354
-     *
355
-     * @return array
356
-     * @throws EE_Error
357
-     * @throws ReflectionException
358
-     */
359
-    public function get_all_question_groups()
360
-    {
361
-        return EE_Registry::instance()->load_model('Question_Group')->get_all(
362
-            [
363
-                ['QSG_deleted' => false],
364
-                'order_by' => ['QSG_order' => 'ASC'],
365
-            ]
366
-        );
367
-    }
368
-
369
-
370
-    /**
371
-     * get_question_groups
372
-     *
373
-     * @param int $EVT_ID
374
-     * @return array|bool
375
-     * @throws EE_Error
376
-     * @throws ReflectionException
377
-     */
378
-    public function get_all_event_question_groups($EVT_ID = 0)
379
-    {
380
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
381
-            EE_Error::add_error(
382
-                esc_html__(
383
-                    'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
384
-                    'event_espresso'
385
-                ),
386
-                __FILE__,
387
-                __FUNCTION__,
388
-                __LINE__
389
-            );
390
-            return false;
391
-        }
392
-        return EE_Registry::instance()->load_model('Event_Question_Group')->get_all(
393
-            [
394
-                ['EVT_ID' => $EVT_ID],
395
-            ]
396
-        );
397
-    }
398
-
399
-
400
-    /**
401
-     * get_question_groups
402
-     *
403
-     * @param int     $EVT_ID
404
-     * @param boolean $for_primary_attendee
405
-     * @return array|bool
406
-     * @throws EE_Error
407
-     * @throws InvalidArgumentException
408
-     * @throws ReflectionException
409
-     * @throws InvalidDataTypeException
410
-     * @throws InvalidInterfaceException
411
-     */
412
-    public function get_event_question_groups($EVT_ID = 0, $for_primary_attendee = true)
413
-    {
414
-        if (! isset($EVT_ID) || ! absint($EVT_ID)) {
415
-            EE_Error::add_error(
416
-                esc_html__(
417
-                // @codingStandardsIgnoreStart
418
-                    'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
419
-                    // @codingStandardsIgnoreEnd
420
-                    'event_espresso'
421
-                ),
422
-                __FILE__,
423
-                __FUNCTION__,
424
-                __LINE__
425
-            );
426
-            return false;
427
-        }
428
-        $query_params = [
429
-            [
430
-                'EVT_ID'                                                                         => $EVT_ID,
431
-                EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary_attendee) => true,
432
-            ],
433
-        ];
434
-        if ($for_primary_attendee) {
435
-            $query_params[0]['EQG_primary'] = true;
436
-        } else {
437
-            $query_params[0]['EQG_additional'] = true;
438
-        }
439
-        return EE_Registry::instance()->load_model('Event_Question_Group')->get_all($query_params);
440
-    }
441
-
442
-
443
-    /**
444
-     * get_question_groups
445
-     *
446
-     * @param int             $EVT_ID
447
-     * @param EE_Registration $registration
448
-     * @return array|bool
449
-     * @throws EE_Error
450
-     * @throws InvalidArgumentException
451
-     * @throws InvalidDataTypeException
452
-     * @throws InvalidInterfaceException
453
-     * @throws ReflectionException
454
-     */
455
-    public function get_question_groups_for_event($EVT_ID, EE_Registration $registration)
456
-    {
457
-        if (! absint($EVT_ID)) {
458
-            EE_Error::add_error(
459
-                esc_html__(
460
-                    'An error occurred. No Question Groups could be retrieved because an Event ID was not received.',
461
-                    'event_espresso'
462
-                ),
463
-                __FILE__,
464
-                __FUNCTION__,
465
-                __LINE__
466
-            );
467
-            return false;
468
-        }
469
-        return EE_Registry::instance()->load_model('Question_Group')->get_all(
470
-            [
471
-                [
472
-                    'Event_Question_Group.EVT_ID' => $EVT_ID,
473
-                    'Event_Question_Group.'
474
-                    . EEM_Event_Question_Group::instance()->fieldNameForContext(
475
-                        $registration->is_primary_registrant()
476
-                    )                             => true,
477
-                ],
478
-                'order_by' => ['QSG_order' => 'ASC'],
479
-            ]
480
-        );
481
-    }
482
-
483
-
484
-    /**
485
-     * get_question_target_db_column
486
-     *
487
-     * @param string $QSG_IDs csv list of $QSG IDs
488
-     * @return array|bool
489
-     * @throws EE_Error
490
-     * @throws ReflectionException
491
-     */
492
-    public function get_questions_in_groups($QSG_IDs = '')
493
-    {
494
-        if (empty($QSG_IDs)) {
495
-            EE_Error::add_error(
496
-                esc_html__('An error occurred. No Question Group IDs were received.', 'event_espresso'),
497
-                __FILE__,
498
-                __FUNCTION__,
499
-                __LINE__
500
-            );
501
-            return false;
502
-        }
503
-        return EE_Registry::instance()->load_model('Question')->get_all(
504
-            [
505
-                [
506
-                    'Question_Group.QSG_ID' => ['IN', $QSG_IDs],
507
-                    'QST_deleted'           => false,
508
-                    'QST_admin_only'        => is_admin(),
509
-                ],
510
-                'order_by' => 'QST_order',
511
-            ]
512
-        );
513
-    }
514
-
515
-
516
-    /**
517
-     * get_options_for_question
518
-     *
519
-     * @param string $QST_IDs csv list of $QST IDs
520
-     * @return array|bool
521
-     * @throws EE_Error
522
-     * @throws ReflectionException
523
-     */
524
-    public function get_options_for_question($QST_IDs)
525
-    {
526
-        if (empty($QST_IDs)) {
527
-            EE_Error::add_error(
528
-                esc_html__('An error occurred. No Question IDs were received.', 'event_espresso'),
529
-                __FILE__,
530
-                __FUNCTION__,
531
-                __LINE__
532
-            );
533
-            return false;
534
-        }
535
-        return EE_Registry::instance()->load_model('Question_Option')->get_all(
536
-            [
537
-                [
538
-                    'Question.QST_ID' => ['IN', $QST_IDs],
539
-                    'QSO_deleted'     => false,
540
-                ],
541
-                'order_by' => 'QSO_ID',
542
-            ]
543
-        );
544
-    }
545
-
546
-
547
-    /**
548
-     * Gets all events that are published
549
-     * and have event start time earlier than now and an event end time later than now
550
-     *
551
-     * @param array $query_params  An array of query params to further filter on
552
-     *                             (note that status and DTT_EVT_start and DTT_EVT_end will be overridden)
553
-     * @param bool  $count         whether to return the count or not (default FALSE)
554
-     * @return EE_Event[]|int
555
-     * @throws EE_Error
556
-     * @throws ReflectionException
557
-     */
558
-    public function get_active_events($query_params, $count = false)
559
-    {
560
-        if (array_key_exists(0, $query_params)) {
561
-            $where_params = $query_params[0];
562
-            unset($query_params[0]);
563
-        } else {
564
-            $where_params = [];
565
-        }
566
-        // if we have count make sure we don't include group by
567
-        if ($count && isset($query_params['group_by'])) {
568
-            unset($query_params['group_by']);
569
-        }
570
-        // add status query
571
-        $where_params = $this->set_where_conditions_for_status($where_params);
572
-        // if already have where params for DTT_EVT_start or DTT_EVT_end then append these conditions
573
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
574
-            $where_params['Datetime.DTT_EVT_start******'] = [
575
-                '<',
576
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
577
-            ];
578
-        } else {
579
-            $where_params['Datetime.DTT_EVT_start'] = [
580
-                '<',
581
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
582
-            ];
583
-        }
584
-        $where_params = $this->set_where_conditions_for_end_datetime($where_params);
585
-        return $this->_get_count_or_all($query_params, $where_params, $count);
586
-    }
587
-
588
-
589
-    /**
590
-     * get all events that are published and have an event start time later than now
591
-     *
592
-     * @param array $query_params  An array of query params to further filter on
593
-     *                             (Note that status and DTT_EVT_start will be overridden)
594
-     * @param bool  $count         whether to return the count or not (default FALSE)
595
-     * @return EE_Event[]|int
596
-     * @throws EE_Error
597
-     * @throws ReflectionException
598
-     */
599
-    public function get_upcoming_events($query_params, $count = false)
600
-    {
601
-        if (array_key_exists(0, $query_params)) {
602
-            $where_params = $query_params[0];
603
-            unset($query_params[0]);
604
-        } else {
605
-            $where_params = [];
606
-        }
607
-        // if we have count make sure we don't include group by
608
-        if ($count && isset($query_params['group_by'])) {
609
-            unset($query_params['group_by']);
610
-        }
611
-        // add status query
612
-        $where_params = $this->set_where_conditions_for_status($where_params);
613
-        // if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
614
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
615
-            $where_params['Datetime.DTT_EVT_start*****'] = [
616
-                '>',
617
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
618
-            ];
619
-        } else {
620
-            $where_params['Datetime.DTT_EVT_start'] = [
621
-                '>',
622
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
623
-            ];
624
-        }
625
-        return $this->_get_count_or_all($query_params, $where_params, $count);
626
-    }
627
-
628
-
629
-    /**
630
-     * Gets all events that are published
631
-     * and have an event end time later than now
632
-     *
633
-     * @param array $query_params  An array of query params to further filter on
634
-     *                             (note that status and DTT_EVT_end will be overridden)
635
-     * @param bool  $count         whether to return the count or not (default FALSE)
636
-     * @return EE_Event[]|int
637
-     * @throws EE_Error
638
-     * @throws ReflectionException
639
-     */
640
-    public function get_active_and_upcoming_events($query_params, $count = false)
641
-    {
642
-        if (array_key_exists(0, $query_params)) {
643
-            $where_params = $query_params[0];
644
-            unset($query_params[0]);
645
-        } else {
646
-            $where_params = [];
647
-        }
648
-        // if we have count make sure we don't include group by
649
-        if ($count && isset($query_params['group_by'])) {
650
-            unset($query_params['group_by']);
651
-        }
652
-        // add status query
653
-        $where_params = $this->set_where_conditions_for_status($where_params);
654
-        // add where params for DTT_EVT_end
655
-        $where_params = $this->set_where_conditions_for_end_datetime($where_params);
656
-        return $this->_get_count_or_all($query_params, $where_params, $count);
657
-    }
658
-
659
-
660
-    /**
661
-     * This only returns events that are expired.
662
-     * They may still be published but all their datetimes have expired.
663
-     *
664
-     * @param array $query_params  An array of query params to further filter on
665
-     *                             (note that status and DTT_EVT_end will be overridden)
666
-     * @param bool  $count         whether to return the count or not (default FALSE)
667
-     * @return EE_Event[]|int
668
-     * @throws EE_Error
669
-     * @throws ReflectionException
670
-     */
671
-    public function get_expired_events($query_params, $count = false)
672
-    {
673
-        $where_params = isset($query_params[0])
674
-            ? $query_params[0]
675
-            : [];
676
-        // if we have count make sure we don't include group by
677
-        if ($count && isset($query_params['group_by'])) {
678
-            unset($query_params['group_by']);
679
-        }
680
-        // let's add specific query_params for active_events
681
-        // keep in mind this will override any sent status in the query AND any date queries.
682
-        if (isset($where_params['status'])) {
683
-            unset($where_params['status']);
684
-        }
685
-        // first get all events that have datetimes where its not expired.
686
-        $event_ids = $this->get_all_not_expired_event_ids($query_params);
687
-        // if we have any additional query_params, let's add them to the 'AND' condition
688
-        $and_condition = [
689
-            'Datetime.DTT_EVT_end' => ['<', EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end')],
690
-            'EVT_ID'               => ['NOT IN', $event_ids],
691
-        ];
692
-        if (isset($where_params['OR'])) {
693
-            $and_condition['OR'] = $where_params['OR'];
694
-            unset($where_params['OR']);
695
-        }
696
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
697
-            $and_condition['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
698
-            unset($where_params['Datetime.DTT_EVT_end']);
699
-        }
700
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
701
-            $and_condition['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
702
-            unset($where_params['Datetime.DTT_EVT_start']);
703
-        }
704
-        // merge remaining $where params with the and conditions.
705
-        $where_params['AND'] = array_merge($and_condition, $where_params);
706
-        return $this->_get_count_or_all($query_params, $where_params, $count);
707
-    }
708
-
709
-
710
-    /**
711
-     * @param array $query_params
712
-     * @return int[]
713
-     * @throws EE_Error
714
-     * @throws ReflectionException
715
-     */
716
-    public function get_all_not_expired_event_ids(array $query_params = []): array
717
-    {
718
-        $query_params[0] = [
719
-            'Datetime.DTT_EVT_end' => [
720
-                '>',
721
-                EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
722
-            ],
723
-        ];
724
-        $event_ids       = $this->_get_all_wpdb_results($query_params, OBJECT_K, 'Event_CPT.ID');
725
-        return array_keys($event_ids);
726
-    }
727
-
728
-
729
-    /**
730
-     * This basically just returns the events that do not have the publish status.
731
-     *
732
-     * @param array   $query_params  An array of query params to further filter on
733
-     *                               (note that status will be overwritten)
734
-     * @param boolean $count         whether to return the count or not (default FALSE)
735
-     * @return EE_Event[]|int
736
-     * @throws EE_Error
737
-     * @throws ReflectionException
738
-     */
739
-    public function get_inactive_events($query_params, $count = false)
740
-    {
741
-        $where_params = isset($query_params[0])
742
-            ? $query_params[0]
743
-            : [];
744
-        // let's add in specific query_params for inactive events.
745
-        if (isset($where_params['status'])) {
746
-            unset($where_params['status']);
747
-        }
748
-        // if we have count make sure we don't include group by
749
-        if ($count && isset($query_params['group_by'])) {
750
-            unset($query_params['group_by']);
751
-        }
752
-        // if we have any additional query_params, let's add them to the 'AND' condition
753
-        $where_params['AND']['status'] = ['!=', 'publish'];
754
-        if (isset($where_params['OR'])) {
755
-            $where_params['AND']['OR'] = $where_params['OR'];
756
-            unset($where_params['OR']);
757
-        }
758
-        if (isset($where_params['Datetime.DTT_EVT_end'])) {
759
-            $where_params['AND']['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
760
-            unset($where_params['Datetime.DTT_EVT_end']);
761
-        }
762
-        if (isset($where_params['Datetime.DTT_EVT_start'])) {
763
-            $where_params['AND']['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
764
-            unset($where_params['Datetime.DTT_EVT_start']);
765
-        }
766
-        return $this->_get_count_or_all($query_params, $where_params, $count);
767
-    }
768
-
769
-
770
-    /**
771
-     * This is just injecting into the parent add_relationship_to so we do special handling on price relationships
772
-     * because we don't want to override any existing global default prices but instead insert NEW prices that get
773
-     * attached to the event. See parent for param descriptions
774
-     *
775
-     * @param        $id_or_obj
776
-     * @param        $other_model_id_or_obj
777
-     * @param string $relationName
778
-     * @param array  $where_query
779
-     * @return EE_Base_Class
780
-     * @throws EE_Error
781
-     * @throws ReflectionException
782
-     */
783
-    public function add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
784
-    {
785
-        if ($relationName === 'Price') {
786
-            // let's get the PRC object for the given ID to make sure that we aren't dealing with a default
787
-            $prc_chk = $this->get_related_model_obj($relationName)->ensure_is_obj($other_model_id_or_obj);
788
-            // if EVT_ID = 0, then this is a default
789
-            if ((int) $prc_chk->get('EVT_ID') === 0) {
790
-                // let's set the prc_id as 0 so we force an insert on the add_relation_to carried out by relation
791
-                $prc_chk->set('PRC_ID', 0);
792
-            }
793
-            // run parent
794
-            return parent::add_relationship_to($id_or_obj, $prc_chk, $relationName, $where_query);
795
-        }
796
-        // otherwise carry on as normal
797
-        return parent::add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query);
798
-    }
799
-
800
-
801
-    /**
802
-     * @param array $where_params
803
-     * @return array
804
-     */
805
-    public function set_where_conditions_for_status(array $where_params): array
806
-    {
807
-        // let's add specific query_params for active_events
808
-        // keep in mind this will override any sent status in the query AND any date queries.
809
-        // we need to pull events with a status of 'publish' and 'sold_out'
810
-        $event_status = ['publish', EEM_Event::sold_out];
811
-        // check if the user can read private events and if so add the 'private status to the where params'
812
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_upcoming_events')) {
813
-            $event_status[] = 'private';
814
-        }
815
-        $where_params['status'] = ['IN', $event_status];
816
-        return $where_params;
817
-    }
818
-
819
-
820
-    /**
821
-     * @param array $where_params
822
-     * @return array
823
-     * @throws EE_Error
824
-     * @throws ReflectionException
825
-     */
826
-    public function set_where_conditions_for_end_datetime(array $where_params): array
827
-    {
828
-        $end_date_field_name = isset($where_params['Datetime.DTT_EVT_end'])
829
-            ? 'Datetime.DTT_EVT_end*****'
830
-            // prevents overwrite of existing where condition
831
-            : 'Datetime.DTT_EVT_end';
832
-
833
-        $where_params[ $end_date_field_name ] = [
834
-            '>',
835
-            EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
836
-        ];
837
-
838
-        return $where_params;
839
-    }
840
-
841
-
842
-    /**
843
-     * @param array $query_params
844
-     * @param array $where_params
845
-     * @param bool  $count
846
-     * @return EE_Soft_Delete_Base_Class[]|int
847
-     * @throws EE_Error
848
-     * @throws ReflectionException
849
-     */
850
-    protected function _get_count_or_all(array $query_params, array $where_params, bool $count = false)
851
-    {
852
-        $query_params[0] = $where_params;
853
-        // don't use $query_params with count()
854
-        // because we don't want to include additional query clauses like "GROUP BY"
855
-        return $count
856
-            ? $this->count([$where_params], 'EVT_ID', true)
857
-            : $this->get_all($query_params);
858
-    }
859
-
860
-
861
-    /******************** DEPRECATED METHODS ********************/
862
-
863
-
864
-    /**
865
-     * _get_question_target_db_column
866
-     *
867
-     * @param EE_Registration $registration    (so existing answers for registration are included)
868
-     * @param int             $EVT_ID          so all question groups are included for event (not just answers from
869
-     *                                         registration).
870
-     * @return    array
871
-     * @throws ReflectionException
872
-     * @throws EE_Error
873
-     * @deprecated as of 4.8.32.rc.001. Instead consider using
874
-     *                                         EE_Registration_Custom_Questions_Form located in
875
-     *                                         admin_pages/registrations/form_sections/EE_Registration_Custom_Questions_Form.form.php
876
-     * @access     public
877
-     */
878
-    public function assemble_array_of_groups_questions_and_options(EE_Registration $registration, $EVT_ID = 0)
879
-    {
880
-        if (empty($EVT_ID)) {
881
-            throw new EE_Error(
882
-                esc_html__(
883
-                    'An error occurred. No EVT_ID is included.  Needed to know which question groups to retrieve.',
884
-                    'event_espresso'
885
-                )
886
-            );
887
-        }
888
-        $questions = [];
889
-        // get all question groups for event
890
-        $qgs = $this->get_question_groups_for_event($EVT_ID, $registration);
891
-        if (! empty($qgs)) {
892
-            foreach ($qgs as $qg) {
893
-                $qsts                                    = $qg->questions();
894
-                $questions[ $qg->ID() ]                  = $qg->model_field_array();
895
-                $questions[ $qg->ID() ]['QSG_questions'] = [];
896
-                foreach ($qsts as $qst) {
897
-                    if ($qst->is_system_question()) {
898
-                        continue;
899
-                    }
900
-                    $answer                                                                   =
901
-                        EEM_Answer::instance()->get_one(
902
-                            [
903
-                                [
904
-                                    'QST_ID' => $qst->ID(),
905
-                                    'REG_ID' => $registration->ID(),
906
-                                ],
907
-                            ]
908
-                        );
909
-                    $answer                                                                   =
910
-                        $answer instanceof EE_Answer
911
-                            ? $answer
912
-                            : EEM_Answer::instance()->create_default_object();
913
-                    $qst_name                                                                 = $qstn_id = $qst->ID();
914
-                    $ans_id                                                                   = $answer->ID();
915
-                    $qst_name                                                                 = ! empty($ans_id)
916
-                        ? '[' . $qst_name . '][' . $ans_id . ']'
917
-                        : '[' . $qst_name . ']';
918
-                    $input_name                                                               = '';
919
-                    $input_id                                                                 =
920
-                        sanitize_key($qst->display_text());
921
-                    $input_class                                                              = '';
922
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]                    =
923
-                        $qst->model_field_array();
924
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_name']  = 'qstn'
925
-                                                                                                . $input_name
926
-                                                                                                . $qst_name;
927
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_id']    =
928
-                        $input_id . '-' . $qstn_id;
929
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_class'] = $input_class;
930
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options']     = [];
931
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['qst_obj']         = $qst;
932
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['ans_obj']         = $answer;
933
-                    // leave responses as-is, don't convert stuff into html entities please!
934
-                    $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['htmlentities'] = false;
935
-                    if ($qst->type() == 'RADIO_BTN' || $qst->type() == 'CHECKBOX' || $qst->type() == 'DROPDOWN') {
936
-                        $QSOs = $qst->options(true, $answer->value());
937
-                        if (is_array($QSOs)) {
938
-                            foreach ($QSOs as $QSO_ID => $QSO) {
939
-                                $questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options'][ $QSO_ID ] =
940
-                                    $QSO->model_field_array();
941
-                            }
942
-                        }
943
-                    }
944
-                }
945
-            }
946
-        }
947
-        return $questions;
948
-    }
949
-
950
-
951
-    /**
952
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
953
-     *                             or an stdClass where each property is the name of a column,
954
-     * @return EE_Base_Class
955
-     * @throws EE_Error
956
-     * @throws ReflectionException
957
-     */
958
-    public function instantiate_class_from_array_or_object($cols_n_values)
959
-    {
960
-        $classInstance = parent::instantiate_class_from_array_or_object($cols_n_values);
961
-        if ($classInstance instanceof EE_Event) {
962
-            // events have their timezone defined in the DB, so use it immediately
963
-            $this->set_timezone($classInstance->get_timezone());
964
-        }
965
-        return $classInstance;
966
-    }
18
+	/**
19
+	 * constant used by status(), indicating that no more tickets can be purchased for any of the datetimes for the
20
+	 * event
21
+	 */
22
+	const sold_out = 'sold_out';
23
+
24
+	/**
25
+	 * constant used by status(), indicating that upcoming event dates have been postponed (may be pushed to a later
26
+	 * date)
27
+	 */
28
+	const postponed = 'postponed';
29
+
30
+	/**
31
+	 * constant used by status(), indicating that the event will no longer occur
32
+	 */
33
+	const cancelled = 'cancelled';
34
+
35
+
36
+	protected static string $_default_reg_status;
37
+
38
+	protected static int $_default_additional_limit = 10;
39
+
40
+	protected static ?EEM_Event $_instance = null;
41
+
42
+
43
+	/**
44
+	 * Adds a relationship to Term_Taxonomy for each CPT_Base
45
+	 *
46
+	 * @param string|null $timezone
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	protected function __construct(?string $timezone = '')
51
+	{
52
+		EE_Registry::instance()->load_model('Registration');
53
+		$this->singular_item = esc_html__('Event', 'event_espresso');
54
+		$this->plural_item   = esc_html__('Events', 'event_espresso');
55
+		// to remove Cancelled events from the frontend, copy the following filter to your functions.php file
56
+		// add_filter( 'AFEE__EEM_Event__construct___custom_stati__cancelled__Public', '__return_false' );
57
+		// to remove Postponed events from the frontend, copy the following filter to your functions.php file
58
+		// add_filter( 'AFEE__EEM_Event__construct___custom_stati__postponed__Public', '__return_false' );
59
+		// to remove Sold Out events from the frontend, copy the following filter to your functions.php file
60
+		//  add_filter( 'AFEE__EEM_Event__construct___custom_stati__sold_out__Public', '__return_false' );
61
+		$this->_custom_stati       = apply_filters(
62
+			'AFEE__EEM_Event__construct___custom_stati',
63
+			[
64
+				EEM_Event::cancelled => [
65
+					'label'  => esc_html__('Cancelled', 'event_espresso'),
66
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__cancelled__Public', true),
67
+				],
68
+				EEM_Event::postponed => [
69
+					'label'  => esc_html__('Postponed', 'event_espresso'),
70
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__postponed__Public', true),
71
+				],
72
+				EEM_Event::sold_out  => [
73
+					'label'  => esc_html__('Sold Out', 'event_espresso'),
74
+					'public' => apply_filters('AFEE__EEM_Event__construct___custom_stati__sold_out__Public', true),
75
+				],
76
+			]
77
+		);
78
+		self::$_default_reg_status = empty(self::$_default_reg_status)
79
+			? RegStatus::PENDING_PAYMENT
80
+			: self::$_default_reg_status;
81
+		$this->_tables             = [
82
+			'Event_CPT'  => new EE_Primary_Table('posts', 'ID'),
83
+			'Event_Meta' => new EE_Secondary_Table('esp_event_meta', 'EVTM_ID', 'EVT_ID'),
84
+		];
85
+		$this->_fields             = [
86
+			'Event_CPT'  => [
87
+				'EVT_ID'         => new EE_Primary_Key_Int_Field(
88
+					'ID',
89
+					esc_html__('Post ID for Event', 'event_espresso')
90
+				),
91
+				'EVT_name'       => new EE_Plain_Text_Field(
92
+					'post_title',
93
+					esc_html__('Event Name', 'event_espresso'),
94
+					false,
95
+					''
96
+				),
97
+				'EVT_desc'       => new EE_Post_Content_Field(
98
+					'post_content',
99
+					esc_html__('Event Description', 'event_espresso'),
100
+					false,
101
+					''
102
+				),
103
+				'EVT_slug'       => new EE_Slug_Field(
104
+					'post_name',
105
+					esc_html__('Event Slug', 'event_espresso'),
106
+					false,
107
+					''
108
+				),
109
+				'EVT_created'    => new EE_Datetime_Field(
110
+					'post_date',
111
+					esc_html__('Date/Time Event Created', 'event_espresso'),
112
+					false,
113
+					EE_Datetime_Field::now
114
+				),
115
+				'EVT_short_desc' => new EE_Simple_HTML_Field(
116
+					'post_excerpt',
117
+					esc_html__('Event Short Description', 'event_espresso'),
118
+					false,
119
+					''
120
+				),
121
+				'EVT_modified'   => new EE_Datetime_Field(
122
+					'post_modified',
123
+					esc_html__('Date/Time Event Modified', 'event_espresso'),
124
+					false,
125
+					EE_Datetime_Field::now
126
+				),
127
+				'EVT_wp_user'    => new EE_WP_User_Field(
128
+					'post_author',
129
+					esc_html__('Event Creator ID', 'event_espresso'),
130
+					false
131
+				),
132
+				'parent'         => new EE_Integer_Field(
133
+					'post_parent',
134
+					esc_html__('Event Parent ID', 'event_espresso'),
135
+					false,
136
+					0
137
+				),
138
+				'EVT_order'      => new EE_Integer_Field(
139
+					'menu_order',
140
+					esc_html__('Event Menu Order', 'event_espresso'),
141
+					false,
142
+					1
143
+				),
144
+				'post_type'      => new EE_WP_Post_Type_Field(EspressoPostType::EVENTS),
145
+				// EE_Plain_Text_Field( 'post_type', esc_html__( 'Event Post Type', 'event_espresso' ), FALSE, 'espresso_events' ),
146
+				'status'         => new EE_WP_Post_Status_Field(
147
+					'post_status',
148
+					esc_html__('Event Status', 'event_espresso'),
149
+					false,
150
+					'draft',
151
+					$this->_custom_stati
152
+				),
153
+				'password'       => new EE_Password_Field(
154
+					'post_password',
155
+					esc_html__('Password', 'event_espresso'),
156
+					false,
157
+					'',
158
+					[
159
+						'EVT_desc',
160
+						'EVT_short_desc',
161
+						'EVT_display_desc',
162
+						'EVT_display_ticket_selector',
163
+						'EVT_visible_on',
164
+						'EVT_additional_limit',
165
+						'EVT_default_registration_status',
166
+						'EVT_member_only',
167
+						'EVT_phone',
168
+						'EVT_allow_overflow',
169
+						'EVT_timezone_string',
170
+						'EVT_external_URL',
171
+						'EVT_donations',
172
+					]
173
+				),
174
+			],
175
+			'Event_Meta' => [
176
+				'EVTM_ID'                         => new EE_DB_Only_Float_Field(
177
+					'EVTM_ID',
178
+					esc_html__('Event Meta Row ID', 'event_espresso'),
179
+					false
180
+				),
181
+				'EVT_ID_fk'                       => new EE_DB_Only_Int_Field(
182
+					'EVT_ID',
183
+					esc_html__('Foreign key to Event ID from Event Meta table', 'event_espresso'),
184
+					false
185
+				),
186
+				'VNU_ID'                          => new EE_Foreign_Key_Int_Field(
187
+					'VNU_ID',
188
+					__('Venue ID', 'event_espresso'),
189
+					false,
190
+					0,
191
+					'Venue'
192
+				),
193
+				'EVT_display_desc'                => new EE_Boolean_Field(
194
+					'EVT_display_desc',
195
+					esc_html__('Display Description Flag', 'event_espresso'),
196
+					false,
197
+					true
198
+				),
199
+				'EVT_display_ticket_selector'     => new EE_Boolean_Field(
200
+					'EVT_display_ticket_selector',
201
+					esc_html__('Display Ticket Selector Flag', 'event_espresso'),
202
+					false,
203
+					true
204
+				),
205
+				'EVT_visible_on'                  => new EE_Datetime_Field(
206
+					'EVT_visible_on',
207
+					esc_html__('Event Visible Date', 'event_espresso'),
208
+					true,
209
+					EE_Datetime_Field::now
210
+				),
211
+				'EVT_additional_limit'            => new EE_Integer_Field(
212
+					'EVT_additional_limit',
213
+					esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
214
+					false,
215
+					self::$_default_additional_limit
216
+				),
217
+				'EVT_default_registration_status' => new EE_Enum_Text_Field(
218
+					'EVT_default_registration_status',
219
+					esc_html__('Default Registration Status on this Event', 'event_espresso'),
220
+					false,
221
+					EEM_Event::$_default_reg_status,
222
+					EEM_Registration::reg_status_array()
223
+				),
224
+				'EVT_member_only'                 => new EE_Boolean_Field(
225
+					'EVT_member_only',
226
+					esc_html__('Member-Only Event Flag', 'event_espresso'),
227
+					false,
228
+					false
229
+				),
230
+				'EVT_phone'                       => new EE_Plain_Text_Field(
231
+					'EVT_phone',
232
+					esc_html__('Event Phone Number', 'event_espresso'),
233
+					false,
234
+					''
235
+				),
236
+				'EVT_allow_overflow'              => new EE_Boolean_Field(
237
+					'EVT_allow_overflow',
238
+					esc_html__('Allow Overflow on Event', 'event_espresso'),
239
+					false,
240
+					false
241
+				),
242
+				'EVT_timezone_string'             => new EE_Plain_Text_Field(
243
+					'EVT_timezone_string',
244
+					esc_html__('Timezone (name) for Event times', 'event_espresso'),
245
+					false,
246
+					''
247
+				),
248
+				'EVT_external_URL'                => new EE_Plain_Text_Field(
249
+					'EVT_external_URL',
250
+					esc_html__('URL of Event Page if hosted elsewhere', 'event_espresso'),
251
+					true
252
+				),
253
+				'EVT_donations'                   => new EE_Boolean_Field(
254
+					'EVT_donations',
255
+					esc_html__('Accept Donations?', 'event_espresso'),
256
+					false,
257
+					false
258
+				),
259
+				'FSC_UUID'                        => new EE_Foreign_Key_String_Field(
260
+					'FSC_UUID',
261
+					esc_html__('Registration Form UUID (universally unique identifier)', 'event_espresso'),
262
+					true,
263
+					null,
264
+					'Form_Section',
265
+					false
266
+				),
267
+			],
268
+		];
269
+		$this->_model_relations    = [
270
+			'Attendee'               => new EE_HABTM_Relation('Registration'),
271
+			'Datetime'               => new EE_Has_Many_Relation(),
272
+			'Event_Question_Group'   => new EE_Has_Many_Relation(),
273
+			'Form_Section'           => new EE_Belongs_To_Relation(),
274
+			'Message_Template_Group' => new EE_HABTM_Relation('Event_Message_Template'),
275
+			'Question_Group'         => new EE_HABTM_Relation('Event_Question_Group'),
276
+			'Registration'           => new EE_Has_Many_Relation(),
277
+			'Term_Relationship'      => new EE_Has_Many_Relation(),
278
+			'Term_Taxonomy'          => new EE_HABTM_Relation('Term_Relationship'),
279
+			'Venue'                  => new EE_Belongs_To_Relation(),
280
+			'WP_User'                => new EE_Belongs_To_Relation(),
281
+		];
282
+		// this model is generally available for reading
283
+		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
284
+		$this->model_chain_to_password                            = '';
285
+		parent::__construct($timezone);
286
+	}
287
+
288
+
289
+	/**
290
+	 * @param string $default_reg_status
291
+	 * @throws EE_Error
292
+	 * @throws EE_Error
293
+	 */
294
+	public static function set_default_reg_status($default_reg_status)
295
+	{
296
+		self::$_default_reg_status = $default_reg_status;
297
+		// if EEM_Event has already been instantiated,
298
+		// then we need to reset the `EVT_default_reg_status` field to use the new default.
299
+		if (self::$_instance instanceof EEM_Event) {
300
+			$default_reg_status = new EE_Enum_Text_Field(
301
+				'EVT_default_registration_status',
302
+				esc_html__('Default Registration Status on this Event', 'event_espresso'),
303
+				false,
304
+				$default_reg_status,
305
+				EEM_Registration::reg_status_array()
306
+			);
307
+			$default_reg_status->_construct_finalize(
308
+				'Event_Meta',
309
+				'EVT_default_registration_status',
310
+				'EEM_Event'
311
+			);
312
+			self::$_instance->_fields['Event_Meta']['EVT_default_registration_status'] = $default_reg_status;
313
+		}
314
+	}
315
+
316
+
317
+	/**
318
+	 * Used to override the default for the additional limit field.
319
+	 *
320
+	 * @param $additional_limit
321
+	 */
322
+	public static function set_default_additional_limit($additional_limit)
323
+	{
324
+		self::$_default_additional_limit = (int) $additional_limit;
325
+		if (self::$_instance instanceof EEM_Event) {
326
+			self::$_instance->_fields['Event_Meta']['EVT_additional_limit'] = new EE_Integer_Field(
327
+				'EVT_additional_limit',
328
+				esc_html__('Limit of Additional Registrations on Same Transaction', 'event_espresso'),
329
+				false,
330
+				self::$_default_additional_limit
331
+			);
332
+			self::$_instance->_fields['Event_Meta']['EVT_additional_limit']->_construct_finalize(
333
+				'Event_Meta',
334
+				'EVT_additional_limit',
335
+				'EEM_Event'
336
+			);
337
+		}
338
+	}
339
+
340
+
341
+	/**
342
+	 * Return what is currently set as the default additional limit for the event.
343
+	 *
344
+	 * @return int
345
+	 */
346
+	public static function get_default_additional_limit()
347
+	{
348
+		return apply_filters('FHEE__EEM_Event__get_default_additional_limit', self::$_default_additional_limit);
349
+	}
350
+
351
+
352
+	/**
353
+	 * get_question_groups
354
+	 *
355
+	 * @return array
356
+	 * @throws EE_Error
357
+	 * @throws ReflectionException
358
+	 */
359
+	public function get_all_question_groups()
360
+	{
361
+		return EE_Registry::instance()->load_model('Question_Group')->get_all(
362
+			[
363
+				['QSG_deleted' => false],
364
+				'order_by' => ['QSG_order' => 'ASC'],
365
+			]
366
+		);
367
+	}
368
+
369
+
370
+	/**
371
+	 * get_question_groups
372
+	 *
373
+	 * @param int $EVT_ID
374
+	 * @return array|bool
375
+	 * @throws EE_Error
376
+	 * @throws ReflectionException
377
+	 */
378
+	public function get_all_event_question_groups($EVT_ID = 0)
379
+	{
380
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
381
+			EE_Error::add_error(
382
+				esc_html__(
383
+					'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
384
+					'event_espresso'
385
+				),
386
+				__FILE__,
387
+				__FUNCTION__,
388
+				__LINE__
389
+			);
390
+			return false;
391
+		}
392
+		return EE_Registry::instance()->load_model('Event_Question_Group')->get_all(
393
+			[
394
+				['EVT_ID' => $EVT_ID],
395
+			]
396
+		);
397
+	}
398
+
399
+
400
+	/**
401
+	 * get_question_groups
402
+	 *
403
+	 * @param int     $EVT_ID
404
+	 * @param boolean $for_primary_attendee
405
+	 * @return array|bool
406
+	 * @throws EE_Error
407
+	 * @throws InvalidArgumentException
408
+	 * @throws ReflectionException
409
+	 * @throws InvalidDataTypeException
410
+	 * @throws InvalidInterfaceException
411
+	 */
412
+	public function get_event_question_groups($EVT_ID = 0, $for_primary_attendee = true)
413
+	{
414
+		if (! isset($EVT_ID) || ! absint($EVT_ID)) {
415
+			EE_Error::add_error(
416
+				esc_html__(
417
+				// @codingStandardsIgnoreStart
418
+					'An error occurred. No Event Question Groups could be retrieved because an Event ID was not received.',
419
+					// @codingStandardsIgnoreEnd
420
+					'event_espresso'
421
+				),
422
+				__FILE__,
423
+				__FUNCTION__,
424
+				__LINE__
425
+			);
426
+			return false;
427
+		}
428
+		$query_params = [
429
+			[
430
+				'EVT_ID'                                                                         => $EVT_ID,
431
+				EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary_attendee) => true,
432
+			],
433
+		];
434
+		if ($for_primary_attendee) {
435
+			$query_params[0]['EQG_primary'] = true;
436
+		} else {
437
+			$query_params[0]['EQG_additional'] = true;
438
+		}
439
+		return EE_Registry::instance()->load_model('Event_Question_Group')->get_all($query_params);
440
+	}
441
+
442
+
443
+	/**
444
+	 * get_question_groups
445
+	 *
446
+	 * @param int             $EVT_ID
447
+	 * @param EE_Registration $registration
448
+	 * @return array|bool
449
+	 * @throws EE_Error
450
+	 * @throws InvalidArgumentException
451
+	 * @throws InvalidDataTypeException
452
+	 * @throws InvalidInterfaceException
453
+	 * @throws ReflectionException
454
+	 */
455
+	public function get_question_groups_for_event($EVT_ID, EE_Registration $registration)
456
+	{
457
+		if (! absint($EVT_ID)) {
458
+			EE_Error::add_error(
459
+				esc_html__(
460
+					'An error occurred. No Question Groups could be retrieved because an Event ID was not received.',
461
+					'event_espresso'
462
+				),
463
+				__FILE__,
464
+				__FUNCTION__,
465
+				__LINE__
466
+			);
467
+			return false;
468
+		}
469
+		return EE_Registry::instance()->load_model('Question_Group')->get_all(
470
+			[
471
+				[
472
+					'Event_Question_Group.EVT_ID' => $EVT_ID,
473
+					'Event_Question_Group.'
474
+					. EEM_Event_Question_Group::instance()->fieldNameForContext(
475
+						$registration->is_primary_registrant()
476
+					)                             => true,
477
+				],
478
+				'order_by' => ['QSG_order' => 'ASC'],
479
+			]
480
+		);
481
+	}
482
+
483
+
484
+	/**
485
+	 * get_question_target_db_column
486
+	 *
487
+	 * @param string $QSG_IDs csv list of $QSG IDs
488
+	 * @return array|bool
489
+	 * @throws EE_Error
490
+	 * @throws ReflectionException
491
+	 */
492
+	public function get_questions_in_groups($QSG_IDs = '')
493
+	{
494
+		if (empty($QSG_IDs)) {
495
+			EE_Error::add_error(
496
+				esc_html__('An error occurred. No Question Group IDs were received.', 'event_espresso'),
497
+				__FILE__,
498
+				__FUNCTION__,
499
+				__LINE__
500
+			);
501
+			return false;
502
+		}
503
+		return EE_Registry::instance()->load_model('Question')->get_all(
504
+			[
505
+				[
506
+					'Question_Group.QSG_ID' => ['IN', $QSG_IDs],
507
+					'QST_deleted'           => false,
508
+					'QST_admin_only'        => is_admin(),
509
+				],
510
+				'order_by' => 'QST_order',
511
+			]
512
+		);
513
+	}
514
+
515
+
516
+	/**
517
+	 * get_options_for_question
518
+	 *
519
+	 * @param string $QST_IDs csv list of $QST IDs
520
+	 * @return array|bool
521
+	 * @throws EE_Error
522
+	 * @throws ReflectionException
523
+	 */
524
+	public function get_options_for_question($QST_IDs)
525
+	{
526
+		if (empty($QST_IDs)) {
527
+			EE_Error::add_error(
528
+				esc_html__('An error occurred. No Question IDs were received.', 'event_espresso'),
529
+				__FILE__,
530
+				__FUNCTION__,
531
+				__LINE__
532
+			);
533
+			return false;
534
+		}
535
+		return EE_Registry::instance()->load_model('Question_Option')->get_all(
536
+			[
537
+				[
538
+					'Question.QST_ID' => ['IN', $QST_IDs],
539
+					'QSO_deleted'     => false,
540
+				],
541
+				'order_by' => 'QSO_ID',
542
+			]
543
+		);
544
+	}
545
+
546
+
547
+	/**
548
+	 * Gets all events that are published
549
+	 * and have event start time earlier than now and an event end time later than now
550
+	 *
551
+	 * @param array $query_params  An array of query params to further filter on
552
+	 *                             (note that status and DTT_EVT_start and DTT_EVT_end will be overridden)
553
+	 * @param bool  $count         whether to return the count or not (default FALSE)
554
+	 * @return EE_Event[]|int
555
+	 * @throws EE_Error
556
+	 * @throws ReflectionException
557
+	 */
558
+	public function get_active_events($query_params, $count = false)
559
+	{
560
+		if (array_key_exists(0, $query_params)) {
561
+			$where_params = $query_params[0];
562
+			unset($query_params[0]);
563
+		} else {
564
+			$where_params = [];
565
+		}
566
+		// if we have count make sure we don't include group by
567
+		if ($count && isset($query_params['group_by'])) {
568
+			unset($query_params['group_by']);
569
+		}
570
+		// add status query
571
+		$where_params = $this->set_where_conditions_for_status($where_params);
572
+		// if already have where params for DTT_EVT_start or DTT_EVT_end then append these conditions
573
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
574
+			$where_params['Datetime.DTT_EVT_start******'] = [
575
+				'<',
576
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
577
+			];
578
+		} else {
579
+			$where_params['Datetime.DTT_EVT_start'] = [
580
+				'<',
581
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
582
+			];
583
+		}
584
+		$where_params = $this->set_where_conditions_for_end_datetime($where_params);
585
+		return $this->_get_count_or_all($query_params, $where_params, $count);
586
+	}
587
+
588
+
589
+	/**
590
+	 * get all events that are published and have an event start time later than now
591
+	 *
592
+	 * @param array $query_params  An array of query params to further filter on
593
+	 *                             (Note that status and DTT_EVT_start will be overridden)
594
+	 * @param bool  $count         whether to return the count or not (default FALSE)
595
+	 * @return EE_Event[]|int
596
+	 * @throws EE_Error
597
+	 * @throws ReflectionException
598
+	 */
599
+	public function get_upcoming_events($query_params, $count = false)
600
+	{
601
+		if (array_key_exists(0, $query_params)) {
602
+			$where_params = $query_params[0];
603
+			unset($query_params[0]);
604
+		} else {
605
+			$where_params = [];
606
+		}
607
+		// if we have count make sure we don't include group by
608
+		if ($count && isset($query_params['group_by'])) {
609
+			unset($query_params['group_by']);
610
+		}
611
+		// add status query
612
+		$where_params = $this->set_where_conditions_for_status($where_params);
613
+		// if there are already query_params matching DTT_EVT_start then we need to modify that to add them.
614
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
615
+			$where_params['Datetime.DTT_EVT_start*****'] = [
616
+				'>',
617
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
618
+			];
619
+		} else {
620
+			$where_params['Datetime.DTT_EVT_start'] = [
621
+				'>',
622
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_start'),
623
+			];
624
+		}
625
+		return $this->_get_count_or_all($query_params, $where_params, $count);
626
+	}
627
+
628
+
629
+	/**
630
+	 * Gets all events that are published
631
+	 * and have an event end time later than now
632
+	 *
633
+	 * @param array $query_params  An array of query params to further filter on
634
+	 *                             (note that status and DTT_EVT_end will be overridden)
635
+	 * @param bool  $count         whether to return the count or not (default FALSE)
636
+	 * @return EE_Event[]|int
637
+	 * @throws EE_Error
638
+	 * @throws ReflectionException
639
+	 */
640
+	public function get_active_and_upcoming_events($query_params, $count = false)
641
+	{
642
+		if (array_key_exists(0, $query_params)) {
643
+			$where_params = $query_params[0];
644
+			unset($query_params[0]);
645
+		} else {
646
+			$where_params = [];
647
+		}
648
+		// if we have count make sure we don't include group by
649
+		if ($count && isset($query_params['group_by'])) {
650
+			unset($query_params['group_by']);
651
+		}
652
+		// add status query
653
+		$where_params = $this->set_where_conditions_for_status($where_params);
654
+		// add where params for DTT_EVT_end
655
+		$where_params = $this->set_where_conditions_for_end_datetime($where_params);
656
+		return $this->_get_count_or_all($query_params, $where_params, $count);
657
+	}
658
+
659
+
660
+	/**
661
+	 * This only returns events that are expired.
662
+	 * They may still be published but all their datetimes have expired.
663
+	 *
664
+	 * @param array $query_params  An array of query params to further filter on
665
+	 *                             (note that status and DTT_EVT_end will be overridden)
666
+	 * @param bool  $count         whether to return the count or not (default FALSE)
667
+	 * @return EE_Event[]|int
668
+	 * @throws EE_Error
669
+	 * @throws ReflectionException
670
+	 */
671
+	public function get_expired_events($query_params, $count = false)
672
+	{
673
+		$where_params = isset($query_params[0])
674
+			? $query_params[0]
675
+			: [];
676
+		// if we have count make sure we don't include group by
677
+		if ($count && isset($query_params['group_by'])) {
678
+			unset($query_params['group_by']);
679
+		}
680
+		// let's add specific query_params for active_events
681
+		// keep in mind this will override any sent status in the query AND any date queries.
682
+		if (isset($where_params['status'])) {
683
+			unset($where_params['status']);
684
+		}
685
+		// first get all events that have datetimes where its not expired.
686
+		$event_ids = $this->get_all_not_expired_event_ids($query_params);
687
+		// if we have any additional query_params, let's add them to the 'AND' condition
688
+		$and_condition = [
689
+			'Datetime.DTT_EVT_end' => ['<', EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end')],
690
+			'EVT_ID'               => ['NOT IN', $event_ids],
691
+		];
692
+		if (isset($where_params['OR'])) {
693
+			$and_condition['OR'] = $where_params['OR'];
694
+			unset($where_params['OR']);
695
+		}
696
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
697
+			$and_condition['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
698
+			unset($where_params['Datetime.DTT_EVT_end']);
699
+		}
700
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
701
+			$and_condition['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
702
+			unset($where_params['Datetime.DTT_EVT_start']);
703
+		}
704
+		// merge remaining $where params with the and conditions.
705
+		$where_params['AND'] = array_merge($and_condition, $where_params);
706
+		return $this->_get_count_or_all($query_params, $where_params, $count);
707
+	}
708
+
709
+
710
+	/**
711
+	 * @param array $query_params
712
+	 * @return int[]
713
+	 * @throws EE_Error
714
+	 * @throws ReflectionException
715
+	 */
716
+	public function get_all_not_expired_event_ids(array $query_params = []): array
717
+	{
718
+		$query_params[0] = [
719
+			'Datetime.DTT_EVT_end' => [
720
+				'>',
721
+				EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
722
+			],
723
+		];
724
+		$event_ids       = $this->_get_all_wpdb_results($query_params, OBJECT_K, 'Event_CPT.ID');
725
+		return array_keys($event_ids);
726
+	}
727
+
728
+
729
+	/**
730
+	 * This basically just returns the events that do not have the publish status.
731
+	 *
732
+	 * @param array   $query_params  An array of query params to further filter on
733
+	 *                               (note that status will be overwritten)
734
+	 * @param boolean $count         whether to return the count or not (default FALSE)
735
+	 * @return EE_Event[]|int
736
+	 * @throws EE_Error
737
+	 * @throws ReflectionException
738
+	 */
739
+	public function get_inactive_events($query_params, $count = false)
740
+	{
741
+		$where_params = isset($query_params[0])
742
+			? $query_params[0]
743
+			: [];
744
+		// let's add in specific query_params for inactive events.
745
+		if (isset($where_params['status'])) {
746
+			unset($where_params['status']);
747
+		}
748
+		// if we have count make sure we don't include group by
749
+		if ($count && isset($query_params['group_by'])) {
750
+			unset($query_params['group_by']);
751
+		}
752
+		// if we have any additional query_params, let's add them to the 'AND' condition
753
+		$where_params['AND']['status'] = ['!=', 'publish'];
754
+		if (isset($where_params['OR'])) {
755
+			$where_params['AND']['OR'] = $where_params['OR'];
756
+			unset($where_params['OR']);
757
+		}
758
+		if (isset($where_params['Datetime.DTT_EVT_end'])) {
759
+			$where_params['AND']['Datetime.DTT_EVT_end****'] = $where_params['Datetime.DTT_EVT_end'];
760
+			unset($where_params['Datetime.DTT_EVT_end']);
761
+		}
762
+		if (isset($where_params['Datetime.DTT_EVT_start'])) {
763
+			$where_params['AND']['Datetime.DTT_EVT_start'] = $where_params['Datetime.DTT_EVT_start'];
764
+			unset($where_params['Datetime.DTT_EVT_start']);
765
+		}
766
+		return $this->_get_count_or_all($query_params, $where_params, $count);
767
+	}
768
+
769
+
770
+	/**
771
+	 * This is just injecting into the parent add_relationship_to so we do special handling on price relationships
772
+	 * because we don't want to override any existing global default prices but instead insert NEW prices that get
773
+	 * attached to the event. See parent for param descriptions
774
+	 *
775
+	 * @param        $id_or_obj
776
+	 * @param        $other_model_id_or_obj
777
+	 * @param string $relationName
778
+	 * @param array  $where_query
779
+	 * @return EE_Base_Class
780
+	 * @throws EE_Error
781
+	 * @throws ReflectionException
782
+	 */
783
+	public function add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
784
+	{
785
+		if ($relationName === 'Price') {
786
+			// let's get the PRC object for the given ID to make sure that we aren't dealing with a default
787
+			$prc_chk = $this->get_related_model_obj($relationName)->ensure_is_obj($other_model_id_or_obj);
788
+			// if EVT_ID = 0, then this is a default
789
+			if ((int) $prc_chk->get('EVT_ID') === 0) {
790
+				// let's set the prc_id as 0 so we force an insert on the add_relation_to carried out by relation
791
+				$prc_chk->set('PRC_ID', 0);
792
+			}
793
+			// run parent
794
+			return parent::add_relationship_to($id_or_obj, $prc_chk, $relationName, $where_query);
795
+		}
796
+		// otherwise carry on as normal
797
+		return parent::add_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query);
798
+	}
799
+
800
+
801
+	/**
802
+	 * @param array $where_params
803
+	 * @return array
804
+	 */
805
+	public function set_where_conditions_for_status(array $where_params): array
806
+	{
807
+		// let's add specific query_params for active_events
808
+		// keep in mind this will override any sent status in the query AND any date queries.
809
+		// we need to pull events with a status of 'publish' and 'sold_out'
810
+		$event_status = ['publish', EEM_Event::sold_out];
811
+		// check if the user can read private events and if so add the 'private status to the where params'
812
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_private_events', 'get_upcoming_events')) {
813
+			$event_status[] = 'private';
814
+		}
815
+		$where_params['status'] = ['IN', $event_status];
816
+		return $where_params;
817
+	}
818
+
819
+
820
+	/**
821
+	 * @param array $where_params
822
+	 * @return array
823
+	 * @throws EE_Error
824
+	 * @throws ReflectionException
825
+	 */
826
+	public function set_where_conditions_for_end_datetime(array $where_params): array
827
+	{
828
+		$end_date_field_name = isset($where_params['Datetime.DTT_EVT_end'])
829
+			? 'Datetime.DTT_EVT_end*****'
830
+			// prevents overwrite of existing where condition
831
+			: 'Datetime.DTT_EVT_end';
832
+
833
+		$where_params[ $end_date_field_name ] = [
834
+			'>',
835
+			EEM_Datetime::instance()->current_time_for_query('DTT_EVT_end'),
836
+		];
837
+
838
+		return $where_params;
839
+	}
840
+
841
+
842
+	/**
843
+	 * @param array $query_params
844
+	 * @param array $where_params
845
+	 * @param bool  $count
846
+	 * @return EE_Soft_Delete_Base_Class[]|int
847
+	 * @throws EE_Error
848
+	 * @throws ReflectionException
849
+	 */
850
+	protected function _get_count_or_all(array $query_params, array $where_params, bool $count = false)
851
+	{
852
+		$query_params[0] = $where_params;
853
+		// don't use $query_params with count()
854
+		// because we don't want to include additional query clauses like "GROUP BY"
855
+		return $count
856
+			? $this->count([$where_params], 'EVT_ID', true)
857
+			: $this->get_all($query_params);
858
+	}
859
+
860
+
861
+	/******************** DEPRECATED METHODS ********************/
862
+
863
+
864
+	/**
865
+	 * _get_question_target_db_column
866
+	 *
867
+	 * @param EE_Registration $registration    (so existing answers for registration are included)
868
+	 * @param int             $EVT_ID          so all question groups are included for event (not just answers from
869
+	 *                                         registration).
870
+	 * @return    array
871
+	 * @throws ReflectionException
872
+	 * @throws EE_Error
873
+	 * @deprecated as of 4.8.32.rc.001. Instead consider using
874
+	 *                                         EE_Registration_Custom_Questions_Form located in
875
+	 *                                         admin_pages/registrations/form_sections/EE_Registration_Custom_Questions_Form.form.php
876
+	 * @access     public
877
+	 */
878
+	public function assemble_array_of_groups_questions_and_options(EE_Registration $registration, $EVT_ID = 0)
879
+	{
880
+		if (empty($EVT_ID)) {
881
+			throw new EE_Error(
882
+				esc_html__(
883
+					'An error occurred. No EVT_ID is included.  Needed to know which question groups to retrieve.',
884
+					'event_espresso'
885
+				)
886
+			);
887
+		}
888
+		$questions = [];
889
+		// get all question groups for event
890
+		$qgs = $this->get_question_groups_for_event($EVT_ID, $registration);
891
+		if (! empty($qgs)) {
892
+			foreach ($qgs as $qg) {
893
+				$qsts                                    = $qg->questions();
894
+				$questions[ $qg->ID() ]                  = $qg->model_field_array();
895
+				$questions[ $qg->ID() ]['QSG_questions'] = [];
896
+				foreach ($qsts as $qst) {
897
+					if ($qst->is_system_question()) {
898
+						continue;
899
+					}
900
+					$answer                                                                   =
901
+						EEM_Answer::instance()->get_one(
902
+							[
903
+								[
904
+									'QST_ID' => $qst->ID(),
905
+									'REG_ID' => $registration->ID(),
906
+								],
907
+							]
908
+						);
909
+					$answer                                                                   =
910
+						$answer instanceof EE_Answer
911
+							? $answer
912
+							: EEM_Answer::instance()->create_default_object();
913
+					$qst_name                                                                 = $qstn_id = $qst->ID();
914
+					$ans_id                                                                   = $answer->ID();
915
+					$qst_name                                                                 = ! empty($ans_id)
916
+						? '[' . $qst_name . '][' . $ans_id . ']'
917
+						: '[' . $qst_name . ']';
918
+					$input_name                                                               = '';
919
+					$input_id                                                                 =
920
+						sanitize_key($qst->display_text());
921
+					$input_class                                                              = '';
922
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]                    =
923
+						$qst->model_field_array();
924
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_name']  = 'qstn'
925
+																								. $input_name
926
+																								. $qst_name;
927
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_id']    =
928
+						$input_id . '-' . $qstn_id;
929
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_input_class'] = $input_class;
930
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options']     = [];
931
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['qst_obj']         = $qst;
932
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['ans_obj']         = $answer;
933
+					// leave responses as-is, don't convert stuff into html entities please!
934
+					$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['htmlentities'] = false;
935
+					if ($qst->type() == 'RADIO_BTN' || $qst->type() == 'CHECKBOX' || $qst->type() == 'DROPDOWN') {
936
+						$QSOs = $qst->options(true, $answer->value());
937
+						if (is_array($QSOs)) {
938
+							foreach ($QSOs as $QSO_ID => $QSO) {
939
+								$questions[ $qg->ID() ]['QSG_questions'][ $qst->ID() ]['QST_options'][ $QSO_ID ] =
940
+									$QSO->model_field_array();
941
+							}
942
+						}
943
+					}
944
+				}
945
+			}
946
+		}
947
+		return $questions;
948
+	}
949
+
950
+
951
+	/**
952
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
953
+	 *                             or an stdClass where each property is the name of a column,
954
+	 * @return EE_Base_Class
955
+	 * @throws EE_Error
956
+	 * @throws ReflectionException
957
+	 */
958
+	public function instantiate_class_from_array_or_object($cols_n_values)
959
+	{
960
+		$classInstance = parent::instantiate_class_from_array_or_object($cols_n_values);
961
+		if ($classInstance instanceof EE_Event) {
962
+			// events have their timezone defined in the DB, so use it immediately
963
+			$this->set_timezone($classInstance->get_timezone());
964
+		}
965
+		return $classInstance;
966
+	}
967 967
 }
Please login to merge, or discard this patch.
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6667 added lines, -6667 removed lines patch added patch discarded remove patch
@@ -39,6676 +39,6676 @@
 block discarded – undo
39 39
  */
40 40
 abstract class EEM_Base extends EE_Base implements ResettableInterface
41 41
 {
42
-    /**
43
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
44
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
45
-     * They almost always WILL NOT, but it's not necessarily a requirement.
46
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
47
-     *
48
-     * @var boolean
49
-     */
50
-    private $_values_already_prepared_by_model_object = 0;
51
-
52
-    /**
53
-     * when $_values_already_prepared_by_model_object equals this, we assume
54
-     * the data is just like form input that needs to have the model fields'
55
-     * prepare_for_set and prepare_for_use_in_db called on it
56
-     */
57
-    const not_prepared_by_model_object = 0;
58
-
59
-    /**
60
-     * when $_values_already_prepared_by_model_object equals this, we
61
-     * assume this value is coming from a model object and doesn't need to have
62
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
63
-     */
64
-    const prepared_by_model_object = 1;
65
-
66
-    /**
67
-     * when $_values_already_prepared_by_model_object equals this, we assume
68
-     * the values are already to be used in the database (ie no processing is done
69
-     * on them by the model's fields)
70
-     */
71
-    const prepared_for_use_in_db = 2;
72
-
73
-
74
-    protected $singular_item = 'Item';
75
-
76
-    protected $plural_item   = 'Items';
77
-
78
-    /**
79
-     * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
80
-     */
81
-    protected $_tables;
82
-
83
-    /**
84
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
85
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
86
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
87
-     *
88
-     * @var EE_Model_Field_Base[][] $_fields
89
-     */
90
-    protected $_fields;
91
-
92
-    /**
93
-     * array of different kinds of relations
94
-     *
95
-     * @var EE_Model_Relation_Base[] $_model_relations
96
-     */
97
-    protected $_model_relations = [];
98
-
99
-    /**
100
-     * @var EE_Index[] $_indexes
101
-     */
102
-    protected $_indexes = [];
103
-
104
-    /**
105
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
106
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
107
-     * by setting the same columns as used in these queries in the query yourself.
108
-     *
109
-     * @var EE_Default_Where_Conditions
110
-     */
111
-    protected $_default_where_conditions_strategy;
112
-
113
-    /**
114
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
115
-     * This is particularly useful when you want something between 'none' and 'default'
116
-     *
117
-     * @var EE_Default_Where_Conditions
118
-     */
119
-    protected $_minimum_where_conditions_strategy;
120
-
121
-    /**
122
-     * String describing how to find the "owner" of this model's objects.
123
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
124
-     * But when there isn't, this indicates which related model, or transiently-related model,
125
-     * has the foreign key to the wp_users table.
126
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
127
-     * related to events, and events have a foreign key to wp_users.
128
-     * On EEM_Transaction, this would be 'Transaction.Event'
129
-     *
130
-     * @var string
131
-     */
132
-    protected $_model_chain_to_wp_user = '';
133
-
134
-    /**
135
-     * String describing how to find the model with a password controlling access to this model. This property has the
136
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
137
-     * This value is the path of models to follow to arrive at the model with the password field.
138
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
139
-     * model with a password that should affect reading this on the front-end.
140
-     * Eg this is an empty string for the Event model because it has a password.
141
-     * This is null for the Registration model, because its event's password has no bearing on whether
142
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
143
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
144
-     * should hide tickets for datetimes for events that have a password set.
145
-     *
146
-     * @var string |null
147
-     */
148
-    protected $model_chain_to_password = null;
149
-
150
-    /**
151
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
-     * don't need it (particularly CPT models)
153
-     *
154
-     * @var bool
155
-     */
156
-    protected $_ignore_where_strategy = false;
157
-
158
-    /**
159
-     * String used in caps relating to this model. Eg, if the caps relating to this
160
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
-     *
162
-     * @var string. If null it hasn't been initialized yet. If false then we
163
-     * have indicated capabilities don't apply to this
164
-     */
165
-    protected $_caps_slug = null;
166
-
167
-    /**
168
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
-     * and next-level keys are capability names, and each's value is a
170
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
-     * they specify which context to use (ie, frontend, backend, edit or delete)
172
-     * and then each capability in the corresponding sub-array that they're missing
173
-     * adds the where conditions onto the query.
174
-     *
175
-     * @var array
176
-     */
177
-    protected $_cap_restrictions = [
178
-        self::caps_read       => [],
179
-        self::caps_read_admin => [],
180
-        self::caps_edit       => [],
181
-        self::caps_delete     => [],
182
-    ];
183
-
184
-    /**
185
-     * Array defining which cap restriction generators to use to create default
186
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
187
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
-     * automatically set this to false (not just null).
190
-     *
191
-     * @var EE_Restriction_Generator_Base[]
192
-     */
193
-    protected $_cap_restriction_generators = [];
194
-
195
-    /**
196
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
-     */
198
-    const caps_read       = 'read';
199
-
200
-    const caps_read_admin = 'read_admin';
201
-
202
-    const caps_edit       = 'edit';
203
-
204
-    const caps_delete     = 'delete';
205
-
206
-    /**
207
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
-     * maps to 'read' because when looking for relevant permissions we're going to use
210
-     * 'read' in the capabilities names like 'ee_read_events' etc.
211
-     *
212
-     * @var array
213
-     */
214
-    protected $_cap_contexts_to_cap_action_map = [
215
-        self::caps_read       => 'read',
216
-        self::caps_read_admin => 'read',
217
-        self::caps_edit       => 'edit',
218
-        self::caps_delete     => 'delete',
219
-    ];
220
-
221
-    /**
222
-     * Timezone
223
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
-     * EE_Datetime_Field data type will have access to it.
227
-     *
228
-     * @var string
229
-     */
230
-    protected $_timezone;
231
-
232
-
233
-    /**
234
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
-     * multisite.
236
-     *
237
-     * @var int
238
-     */
239
-    protected static $_model_query_blog_id;
240
-
241
-    /**
242
-     * A copy of _fields, except the array keys are the model names pointed to by
243
-     * the field
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cache_foreign_key_to_fields = [];
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, indexed by their name
251
-     *
252
-     * @var EE_Model_Field_Base[]
253
-     */
254
-    private $_cached_fields = null;
255
-
256
-    /**
257
-     * Cached list of all the fields on the model, except those that are
258
-     * marked as only pertinent to the database
259
-     *
260
-     * @var EE_Model_Field_Base[]
261
-     */
262
-    private $_cached_fields_non_db_only = null;
263
-
264
-    /**
265
-     * A cached reference to the primary key for quick lookup
266
-     *
267
-     * @var EE_Model_Field_Base
268
-     */
269
-    private $_primary_key_field = null;
270
-
271
-    /**
272
-     * Flag indicating whether this model has a primary key or not
273
-     *
274
-     * @var boolean
275
-     */
276
-    protected $_has_primary_key_field = null;
277
-
278
-    /**
279
-     * array in the format:  [ FK alias => full PK ]
280
-     * where keys are local column name aliases for foreign keys
281
-     * and values are the fully qualified column name for the primary key they represent
282
-     *  ex:
283
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
-     *
285
-     * @var array $foreign_key_aliases
286
-     */
287
-    protected $foreign_key_aliases = [];
288
-
289
-    /**
290
-     * Whether or not this model is based off a table in WP core only (CPTs should set
291
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
-     * This should be true for models that deal with data that should exist independent of EE.
293
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
295
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
297
-     *
298
-     * @var boolean
299
-     */
300
-    protected $_wp_core_model = false;
301
-
302
-    /**
303
-     * @var bool stores whether this model has a password field or not.
304
-     * null until initialized by hasPasswordField()
305
-     */
306
-    protected $has_password_field;
307
-
308
-    /**
309
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
310
-     */
311
-    protected $password_field;
312
-
313
-    /**
314
-     *    List of valid operators that can be used for querying.
315
-     * The keys are all operators we'll accept, the values are the real SQL
316
-     * operators used
317
-     *
318
-     * @var array
319
-     */
320
-    protected $_valid_operators = [
321
-        '='           => '=',
322
-        '<='          => '<=',
323
-        '<'           => '<',
324
-        '>='          => '>=',
325
-        '>'           => '>',
326
-        '!='          => '!=',
327
-        'LIKE'        => 'LIKE',
328
-        'like'        => 'LIKE',
329
-        'NOT_LIKE'    => 'NOT LIKE',
330
-        'not_like'    => 'NOT LIKE',
331
-        'NOT LIKE'    => 'NOT LIKE',
332
-        'not like'    => 'NOT LIKE',
333
-        'IN'          => 'IN',
334
-        'in'          => 'IN',
335
-        'NOT_IN'      => 'NOT IN',
336
-        'not_in'      => 'NOT IN',
337
-        'NOT IN'      => 'NOT IN',
338
-        'not in'      => 'NOT IN',
339
-        'between'     => 'BETWEEN',
340
-        'BETWEEN'     => 'BETWEEN',
341
-        'IS_NOT_NULL' => 'IS NOT NULL',
342
-        'is_not_null' => 'IS NOT NULL',
343
-        'IS NOT NULL' => 'IS NOT NULL',
344
-        'is not null' => 'IS NOT NULL',
345
-        'IS_NULL'     => 'IS NULL',
346
-        'is_null'     => 'IS NULL',
347
-        'IS NULL'     => 'IS NULL',
348
-        'is null'     => 'IS NULL',
349
-        'REGEXP'      => 'REGEXP',
350
-        'regexp'      => 'REGEXP',
351
-        'NOT_REGEXP'  => 'NOT REGEXP',
352
-        'not_regexp'  => 'NOT REGEXP',
353
-        'NOT REGEXP'  => 'NOT REGEXP',
354
-        'not regexp'  => 'NOT REGEXP',
355
-    ];
356
-
357
-    /**
358
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
359
-     *
360
-     * @var array
361
-     */
362
-    protected $_in_style_operators = ['IN', 'NOT IN'];
363
-
364
-    /**
365
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
366
-     * '12-31-2012'"
367
-     *
368
-     * @var array
369
-     */
370
-    protected $_between_style_operators = ['BETWEEN'];
371
-
372
-    /**
373
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
378
-
379
-    /**
380
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
381
-     * on a join table.
382
-     *
383
-     * @var array
384
-     */
385
-    protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
386
-
387
-    /**
388
-     * Allowed values for $query_params['order'] for ordering in queries
389
-     *
390
-     * @var array
391
-     */
392
-    protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
393
-
394
-    /**
395
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
396
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
397
-     *
398
-     * @var array
399
-     */
400
-    private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
401
-
402
-    /**
403
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
404
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
405
-     *
406
-     * @var array
407
-     */
408
-    private $_allowed_query_params = [
409
-        0,
410
-        'limit',
411
-        'order_by',
412
-        'group_by',
413
-        'having',
414
-        'force_join',
415
-        'order',
416
-        'on_join_limit',
417
-        'default_where_conditions',
418
-        'caps',
419
-        'extra_selects',
420
-        'exclude_protected',
421
-    ];
422
-
423
-    /**
424
-     * All the data types that can be used in $wpdb->prepare statements.
425
-     *
426
-     * @var array
427
-     */
428
-    private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
429
-
430
-    /**
431
-     * @var EE_Registry $EE
432
-     */
433
-    protected $EE = null;
434
-
435
-
436
-    /**
437
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
438
-     *
439
-     * @var int
440
-     */
441
-    protected $_show_next_x_db_queries = 0;
442
-
443
-    /**
444
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
445
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
446
-     * WHERE, GROUP_BY, etc.
447
-     *
448
-     * @var CustomSelects
449
-     */
450
-    protected $_custom_selections = [];
451
-
452
-    /**
453
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
454
-     * caches every model object we've fetched from the DB on this request
455
-     *
456
-     * @var array
457
-     */
458
-    protected $_entity_map;
459
-
460
-    /**
461
-     * @var LoaderInterface
462
-     */
463
-    protected static $loader;
464
-
465
-    /**
466
-     * @var Mirror
467
-     */
468
-    private static $mirror;
469
-
470
-
471
-    /**
472
-     * constant used to show EEM_Base has not yet verified the db on this http request
473
-     */
474
-    const db_verified_none = 0;
475
-
476
-    /**
477
-     * constant used to show EEM_Base has verified the EE core db on this http request,
478
-     * but not the addons' dbs
479
-     */
480
-    const db_verified_core = 1;
481
-
482
-    /**
483
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
484
-     * the EE core db too)
485
-     */
486
-    const db_verified_addons = 2;
487
-
488
-    /**
489
-     * indicates whether an EEM_Base child has already re-verified the DB
490
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
491
-     * looking like EEM_Base::db_verified_*
492
-     *
493
-     * @var int - 0 = none, 1 = core, 2 = addons
494
-     */
495
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
496
-
497
-    /**
498
-     * @deprecatd 5.0.40.p
499
-     */
500
-    const default_where_conditions_all = EE_Default_Where_Conditions::ALL;
501
-
502
-    /**
503
-     * @deprecatd 5.0.40.p
504
-     */
505
-    const default_where_conditions_this_only = EE_Default_Where_Conditions::THIS_MODEL_ONLY;
506
-
507
-    /**
508
-     * @deprecatd 5.0.40.p
509
-     */
510
-    const default_where_conditions_others_only = EE_Default_Where_Conditions::OTHER_MODELS_ONLY;
511
-
512
-    /**
513
-     * @deprecatd 5.0.40.p
514
-     */
515
-    const default_where_conditions_minimum_all = EE_Default_Where_Conditions::MINIMUM_ALL;
516
-
517
-    /**
518
-     * @deprecatd 5.0.40.p
519
-     */
520
-    const default_where_conditions_minimum_others = EE_Default_Where_Conditions::MINIMUM_OTHERS;
521
-
522
-    /**
523
-     * @deprecatd 5.0.40.p
524
-     */
525
-    const default_where_conditions_none = EE_Default_Where_Conditions::NONE;
526
-
527
-
528
-    /**
529
-     * About all child constructors:
530
-     * they should define the _tables, _fields and _model_relations arrays.
531
-     * Should ALWAYS be called after child constructor.
532
-     * In order to make the child constructors to be as simple as possible, this parent constructor
533
-     * finalizes constructing all the object's attributes.
534
-     * Generally, rather than requiring a child to code
535
-     * $this->_tables = array(
536
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
537
-     *        ...);
538
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
539
-     * each EE_Table has a function to set the table's alias after the constructor, using
540
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
541
-     * do something similar.
542
-     *
543
-     * @param string|null $timezone
544
-     * @throws EE_Error
545
-     * @throws Exception
546
-     */
547
-    protected function __construct($timezone = '')
548
-    {
549
-        // check that the model has not been loaded too soon
550
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
551
-            throw new EE_Error(
552
-                sprintf(
553
-                    esc_html__(
554
-                        'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
555
-                        'event_espresso'
556
-                    ),
557
-                    get_class($this)
558
-                )
559
-            );
560
-        }
561
-        /**
562
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
563
-         */
564
-        if (empty(EEM_Base::$_model_query_blog_id)) {
565
-            EEM_Base::set_model_query_blog_id();
566
-        }
567
-        /**
568
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
569
-         * just use EE_Register_Model_Extension
570
-         *
571
-         * @var EE_Table_Base[] $_tables
572
-         */
573
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
574
-        foreach ($this->_tables as $table_alias => $table_obj) {
575
-            /** @var $table_obj EE_Table_Base */
576
-            $table_obj->_construct_finalize_with_alias($table_alias);
577
-            if ($table_obj instanceof EE_Secondary_Table) {
578
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
579
-            }
580
-        }
581
-        /**
582
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
583
-         * EE_Register_Model_Extension
584
-         *
585
-         * @param EE_Model_Field_Base[] $_fields
586
-         */
587
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
588
-        $this->_invalidate_field_caches();
589
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
590
-            if (! array_key_exists($table_alias, $this->_tables)) {
591
-                throw new EE_Error(
592
-                    sprintf(
593
-                        esc_html__(
594
-                            "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
595
-                            'event_espresso'
596
-                        ),
597
-                        $table_alias,
598
-                        implode(",", $this->_fields)
599
-                    )
600
-                );
601
-            }
602
-            foreach ($fields_for_table as $field_name => $field_obj) {
603
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
604
-                // primary key field base has a slightly different _construct_finalize
605
-                /** @var $field_obj EE_Model_Field_Base */
606
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
607
-            }
608
-        }
609
-        // everything is related to Extra_Meta
610
-        if (get_class($this) !== 'EEM_Extra_Meta') {
611
-            // make extra meta related to everything, but don't block deleting things just
612
-            // because they have related extra meta info. For now just orphan those extra meta
613
-            // in the future we should automatically delete them
614
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
615
-        }
616
-        // and change logs
617
-        if (get_class($this) !== 'EEM_Change_Log') {
618
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
619
-        }
620
-        /**
621
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
622
-         * EE_Register_Model_Extension
623
-         *
624
-         * @param EE_Model_Relation_Base[] $_model_relations
625
-         */
626
-        $this->_model_relations = (array) apply_filters(
627
-            'FHEE__' . get_class($this) . '__construct__model_relations',
628
-            $this->_model_relations
629
-        );
630
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
631
-            /** @var $relation_obj EE_Model_Relation_Base */
632
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
633
-        }
634
-        foreach ($this->_indexes as $index_name => $index_obj) {
635
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
636
-        }
637
-        $this->set_timezone($timezone);
638
-        // finalize default where condition strategy, or set default
639
-        if (! $this->_default_where_conditions_strategy) {
640
-            // nothing was set during child constructor, so set default
641
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
642
-        }
643
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
644
-        if (! $this->_minimum_where_conditions_strategy) {
645
-            // nothing was set during child constructor, so set default
646
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
647
-        }
648
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
649
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
650
-        // to indicate to NOT set it, set it to the logical default
651
-        if ($this->_caps_slug === null) {
652
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
653
-        }
654
-        // initialize the standard cap restriction generators if none were specified by the child constructor
655
-        if (is_array($this->_cap_restriction_generators)) {
656
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
657
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
658
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
659
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
660
-                        new EE_Restriction_Generator_Protected(),
661
-                        $cap_context,
662
-                        $this
663
-                    );
664
-                }
665
-            }
666
-        }
667
-        // if there are cap restriction generators, use them to make the default cap restrictions
668
-        if (is_array($this->_cap_restriction_generators)) {
669
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
670
-                if (! $generator_object) {
671
-                    continue;
672
-                }
673
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
674
-                    throw new EE_Error(
675
-                        sprintf(
676
-                            esc_html__(
677
-                                'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
678
-                                'event_espresso'
679
-                            ),
680
-                            $context,
681
-                            $this->get_this_model_name()
682
-                        )
683
-                    );
684
-                }
685
-                $action = $this->cap_action_for_context($context);
686
-                if (! $generator_object->construction_finalized()) {
687
-                    $generator_object->_construct_finalize($this, $action);
688
-                }
689
-            }
690
-        }
691
-        do_action('AHEE__' . get_class($this) . '__construct__end');
692
-    }
693
-
694
-
695
-    /**
696
-     * @return LoaderInterface
697
-     * @throws InvalidArgumentException
698
-     * @throws InvalidDataTypeException
699
-     * @throws InvalidInterfaceException
700
-     */
701
-    protected static function getLoader(): LoaderInterface
702
-    {
703
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
704
-            EEM_Base::$loader = LoaderFactory::getLoader();
705
-        }
706
-        return EEM_Base::$loader;
707
-    }
708
-
709
-
710
-    /**
711
-     * @return Mirror
712
-     * @since   5.0.0.p
713
-     */
714
-    private static function getMirror(): Mirror
715
-    {
716
-        if (! EEM_Base::$mirror instanceof Mirror) {
717
-            EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
718
-        }
719
-        return EEM_Base::$mirror;
720
-    }
721
-
722
-
723
-    /**
724
-     * @param string $model_class_Name
725
-     * @param string $timezone
726
-     * @return array
727
-     * @throws ReflectionException
728
-     * @since   5.0.0.p
729
-     */
730
-    private static function getModelArguments(string $model_class_Name, string $timezone): array
731
-    {
732
-        $arguments = [$timezone];
733
-        $params    = EEM_Base::getMirror()->getParameters($model_class_Name);
734
-        if (count($params) > 1) {
735
-            if ($params[1]->getName() === 'model_field_factory') {
736
-                $arguments = [
737
-                    $timezone,
738
-                    EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
739
-                ];
740
-            } elseif ($model_class_Name === 'EEM_Form_Section') {
741
-                $arguments = [
742
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
743
-                    $timezone,
744
-                ];
745
-            } elseif ($model_class_Name === 'EEM_Form_Element') {
746
-                $arguments = [
747
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
748
-                    EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
749
-                    $timezone,
750
-                ];
751
-            }
752
-        }
753
-        return $arguments;
754
-    }
755
-
756
-
757
-    /**
758
-     * This function is a singleton method used to instantiate the Espresso_model object
759
-     *
760
-     * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
761
-     *                                (and any incoming timezone data that gets saved).
762
-     *                                Note this just sends the timezone info to the date time model field objects.
763
-     *                                Default is NULL
764
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
765
-     * @return static (as in the concrete child class)
766
-     * @throws EE_Error
767
-     * @throws ReflectionException
768
-     */
769
-    public static function instance($timezone = '')
770
-    {
771
-        // check if instance of Espresso_model already exists
772
-        if (! static::$_instance instanceof static) {
773
-            $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
774
-            $model     = new static(...$arguments);
775
-            EEM_Base::getLoader()->share(static::class, $model, $arguments);
776
-            static::$_instance = $model;
777
-        }
778
-        // we might have a timezone set, let set_timezone decide what to do with it
779
-        if ($timezone) {
780
-            static::$_instance->set_timezone($timezone);
781
-        }
782
-        // Espresso_model object
783
-        return static::$_instance;
784
-    }
785
-
786
-
787
-    /**
788
-     * resets the model and returns it
789
-     *
790
-     * @param string|null $timezone
791
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
792
-     * all its properties reset; if it wasn't instantiated, returns null)
793
-     * @throws EE_Error
794
-     * @throws ReflectionException
795
-     * @throws InvalidArgumentException
796
-     * @throws InvalidDataTypeException
797
-     * @throws InvalidInterfaceException
798
-     */
799
-    public static function reset($timezone = '')
800
-    {
801
-        if (! static::$_instance instanceof EEM_Base) {
802
-            return null;
803
-        }
804
-        // Let's NOT swap out the current instance for a new one
805
-        // because if someone has a reference to it, we can't remove their reference.
806
-        // It's best to keep using the same reference but change the original object instead,
807
-        // so reset all its properties to their original values as defined in the class.
808
-        $static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
809
-        foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
810
-            // don't set instance to null like it was originally,
811
-            // but it's static anyways, and we're ignoring static properties (for now at least)
812
-            if (! isset($static_properties[ $property ])) {
813
-                static::$_instance->{$property} = $value;
814
-            }
815
-        }
816
-        // and then directly call its constructor again, like we would if we were creating a new one
817
-        $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
818
-        static::$_instance->__construct(...$arguments);
819
-        return self::instance();
820
-    }
821
-
822
-
823
-    /**
824
-     * Used to set the $_model_query_blog_id static property.
825
-     *
826
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
827
-     *                      value for get_current_blog_id() will be used.
828
-     */
829
-    public static function set_model_query_blog_id($blog_id = 0)
830
-    {
831
-        EEM_Base::$_model_query_blog_id = $blog_id > 0
832
-            ? (int) $blog_id
833
-            : get_current_blog_id();
834
-    }
835
-
836
-
837
-    /**
838
-     * Returns whatever is set as the internal $model_query_blog_id.
839
-     *
840
-     * @return int
841
-     */
842
-    public static function get_model_query_blog_id()
843
-    {
844
-        return EEM_Base::$_model_query_blog_id;
845
-    }
846
-
847
-
848
-    /**
849
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
850
-     *
851
-     * @param boolean $translated return localized strings or JUST the array.
852
-     * @return array
853
-     * @throws EE_Error
854
-     * @throws InvalidArgumentException
855
-     * @throws InvalidDataTypeException
856
-     * @throws InvalidInterfaceException
857
-     * @throws ReflectionException
858
-     */
859
-    public function status_array($translated = false)
860
-    {
861
-        if (! array_key_exists('Status', $this->_model_relations)) {
862
-            return [];
863
-        }
864
-        $model_name   = $this->get_this_model_name();
865
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
866
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
867
-        $status_array = [];
868
-        foreach ($stati as $status) {
869
-            $status_array[ $status->ID() ] = $status->get('STS_code');
870
-        }
871
-        return $translated
872
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
873
-            : $status_array;
874
-    }
875
-
876
-
877
-    /**
878
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
879
-     *
880
-     * @param array $query_params             @see
881
-     *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
882
-     *                                        or if you have the development copy of EE you can view this at the path:
883
-     *                                        /docs/G--Model-System/model-query-params.md
884
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
885
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
886
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
887
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
888
-     *                                        EEM_Transaction::instance()->get_all( array( array(
889
-     *                                        'OR'=>array(
890
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
891
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
892
-     *                                        )
893
-     *                                        ),
894
-     *                                        'limit'=>10,
895
-     *                                        'group_by'=>'TXN_ID'
896
-     *                                        ));
897
-     *                                        get all the answers to the question titled "shirt size" for event with id
898
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
899
-     *                                        'Question.QST_display_text'=>'shirt size',
900
-     *                                        'Registration.Event.EVT_ID'=>12
901
-     *                                        ),
902
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
903
-     *                                        ));
904
-     * @throws EE_Error
905
-     * @throws ReflectionException
906
-     */
907
-    public function get_all($query_params = [])
908
-    {
909
-        if (
910
-            isset($query_params['limit'])
911
-            && ! isset($query_params['group_by'])
912
-        ) {
913
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
914
-        }
915
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
916
-    }
917
-
918
-
919
-    /**
920
-     * Modifies the query parameters so we only get back model objects
921
-     * that "belong" to the current user
922
-     *
923
-     * @param array $query_params @see
924
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
925
-     * @return array @see
926
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
927
-     * @throws ReflectionException
928
-     * @throws ReflectionException
929
-     */
930
-    public function alter_query_params_to_only_include_mine($query_params = [])
931
-    {
932
-        $wp_user_field_name = $this->wp_user_field_name();
933
-        if ($wp_user_field_name) {
934
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
935
-        }
936
-        return $query_params;
937
-    }
938
-
939
-
940
-    /**
941
-     * Returns the name of the field's name that points to the WP_User table
942
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
943
-     * foreign key to the WP_User table)
944
-     *
945
-     * @return string|boolean string on success, boolean false when there is no
946
-     * foreign key to the WP_User table
947
-     * @throws ReflectionException
948
-     * @throws ReflectionException
949
-     */
950
-    public function wp_user_field_name()
951
-    {
952
-        try {
953
-            if (! empty($this->_model_chain_to_wp_user)) {
954
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
955
-                $last_model_name              = end($models_to_follow_to_wp_users);
956
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
957
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
958
-            } else {
959
-                $model_with_fk_to_wp_users = $this;
960
-                $model_chain_to_wp_user    = '';
961
-            }
962
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
963
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
964
-        } catch (EE_Error $e) {
965
-            return false;
966
-        }
967
-    }
968
-
969
-
970
-    /**
971
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
972
-     * (or transiently-related model) has a foreign key to the wp_users table;
973
-     * useful for finding if model objects of this type are 'owned' by the current user.
974
-     * This is an empty string when the foreign key is on this model and when it isn't,
975
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
976
-     * (or transiently-related model)
977
-     *
978
-     * @return string
979
-     */
980
-    public function model_chain_to_wp_user()
981
-    {
982
-        return $this->_model_chain_to_wp_user;
983
-    }
984
-
985
-
986
-    /**
987
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
988
-     * like how registrations don't have a foreign key to wp_users, but the
989
-     * events they are for are), or is unrelated to wp users.
990
-     * generally available
991
-     *
992
-     * @return boolean
993
-     */
994
-    public function is_owned()
995
-    {
996
-        if ($this->model_chain_to_wp_user()) {
997
-            return true;
998
-        }
999
-        try {
1000
-            $this->get_foreign_key_to('WP_User');
1001
-            return true;
1002
-        } catch (EE_Error $e) {
1003
-            return false;
1004
-        }
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1010
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1011
-     * the model)
1012
-     *
1013
-     * @param array  $query_params      @see
1014
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1015
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1016
-     * @param mixed  $columns_to_select What columns to select. By default, we select all columns specified by the
1017
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1018
-     *                                  override this and set the select to "*", or a specific column name, like
1019
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1020
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1021
-     *                                  the aliases used to refer to this selection, and values are to be
1022
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1023
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1024
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1025
-     * @throws EE_Error
1026
-     * @throws InvalidArgumentException
1027
-     * @throws ReflectionException
1028
-     */
1029
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1030
-    {
1031
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1032
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1033
-        $select_expressions       = $columns_to_select === null
1034
-            ? $this->_construct_default_select_sql($model_query_info)
1035
-            : '';
1036
-        if ($this->_custom_selections instanceof CustomSelects) {
1037
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1038
-            $select_expressions .= $select_expressions
1039
-                ? ', ' . $custom_expressions
1040
-                : $custom_expressions;
1041
-        }
1042
-
1043
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1044
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1045
-    }
1046
-
1047
-
1048
-    /**
1049
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1050
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1051
-     * method of including extra select information.
1052
-     *
1053
-     * @param array             $query_params
1054
-     * @param null|array|string $columns_to_select
1055
-     * @return null|CustomSelects
1056
-     * @throws InvalidArgumentException
1057
-     */
1058
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1059
-    {
1060
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1061
-            return null;
1062
-        }
1063
-        $selects = $query_params['extra_selects'] ?? $columns_to_select;
1064
-        $selects = is_string($selects)
1065
-            ? explode(',', $selects)
1066
-            : $selects;
1067
-        return new CustomSelects($selects);
1068
-    }
1069
-
1070
-
1071
-    /**
1072
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1073
-     * but you can use the model query params to more easily
1074
-     * take care of joins, field preparation etc.
1075
-     *
1076
-     * @param array  $query_params      @see
1077
-     *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1078
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1079
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1080
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1081
-     *                                  override this and set the select to "*", or a specific column name, like
1082
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1083
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1084
-     *                                  the aliases used to refer to this selection, and values are to be
1085
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1086
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1087
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1088
-     * @throws EE_Error
1089
-     * @throws ReflectionException
1090
-     */
1091
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1092
-    {
1093
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1094
-    }
1095
-
1096
-
1097
-    /**
1098
-     * For creating a custom select statement
1099
-     *
1100
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1101
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1102
-     *                                 SQL, and 1=>is the datatype
1103
-     * @return string
1104
-     * @throws EE_Error
1105
-     */
1106
-    private function _construct_select_from_input($columns_to_select)
1107
-    {
1108
-        if (is_array($columns_to_select)) {
1109
-            $select_sql_array = [];
1110
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1111
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1112
-                    throw new EE_Error(
1113
-                        sprintf(
1114
-                            esc_html__(
1115
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1116
-                                'event_espresso'
1117
-                            ),
1118
-                            $selection_and_datatype,
1119
-                            $alias
1120
-                        )
1121
-                    );
1122
-                }
1123
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1124
-                    throw new EE_Error(
1125
-                        sprintf(
1126
-                            esc_html__(
1127
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1128
-                                'event_espresso'
1129
-                            ),
1130
-                            $selection_and_datatype[1],
1131
-                            $selection_and_datatype[0],
1132
-                            $alias,
1133
-                            implode(', ', $this->_valid_wpdb_data_types)
1134
-                        )
1135
-                    );
1136
-                }
1137
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1138
-            }
1139
-            $columns_to_select_string = implode(', ', $select_sql_array);
1140
-        } else {
1141
-            $columns_to_select_string = $columns_to_select;
1142
-        }
1143
-        return $columns_to_select_string;
1144
-    }
1145
-
1146
-
1147
-    /**
1148
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1149
-     *
1150
-     * @return string
1151
-     * @throws EE_Error
1152
-     */
1153
-    public function primary_key_name()
1154
-    {
1155
-        return $this->get_primary_key_field()->get_name();
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1161
-     * If there is no primary key on this model, $id is treated as primary key string
1162
-     *
1163
-     * @param mixed $id int or string, depending on the type of the model's primary key
1164
-     * @return EE_Base_Class|mixed|null
1165
-     * @throws EE_Error
1166
-     * @throws ReflectionException
1167
-     */
1168
-    public function get_one_by_ID($id)
1169
-    {
1170
-        // since entities with no ID can still have properties, we need to check the cache for them
1171
-        $cached_value = $this->get_from_entity_map($id);
1172
-        if ($cached_value) {
1173
-            return $cached_value;
1174
-        }
1175
-        // but if no cached property AND no id is passed, just return null
1176
-        if (empty($id)) {
1177
-            return null;
1178
-        }
1179
-        $model_object = $this->get_one(
1180
-            $this->alter_query_params_to_restrict_by_ID(
1181
-                $id,
1182
-                ['default_where_conditions' => EE_Default_Where_Conditions::MINIMUM_ALL]
1183
-            )
1184
-        );
1185
-        $className    = $this->_get_class_name();
1186
-        if ($model_object instanceof $className) {
1187
-            // make sure valid objects get added to the entity map
1188
-            // so that the next call to this method doesn't trigger another trip to the db
1189
-            $this->add_to_entity_map($model_object);
1190
-        }
1191
-        return $model_object;
1192
-    }
1193
-
1194
-
1195
-    /**
1196
-     * Alters query parameters to only get items with this ID are returned.
1197
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1198
-     * or could just be a simple primary key ID
1199
-     *
1200
-     * @param int   $id
1201
-     * @param array $query_params
1202
-     * @return array of normal query params, @see
1203
-     *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1204
-     * @throws EE_Error
1205
-     */
1206
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1207
-    {
1208
-        if (! isset($query_params[0])) {
1209
-            $query_params[0] = [];
1210
-        }
1211
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1212
-        if ($conditions_from_id === null) {
1213
-            $query_params[0][ $this->primary_key_name() ] = $id;
1214
-        } else {
1215
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1216
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1217
-        }
1218
-        return $query_params;
1219
-    }
1220
-
1221
-
1222
-    /**
1223
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1224
-     * array. If no item is found, null is returned.
1225
-     *
1226
-     * @param array $query_params like EEM_Base's $query_params variable.
1227
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1228
-     * @throws EE_Error
1229
-     * @throws ReflectionException
1230
-     */
1231
-    public function get_one($query_params = [])
1232
-    {
1233
-        if (! is_array($query_params)) {
1234
-            EE_Error::doing_it_wrong(
1235
-                'EEM_Base::get_one',
1236
-                sprintf(
1237
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1238
-                    gettype($query_params)
1239
-                ),
1240
-                '4.6.0'
1241
-            );
1242
-            $query_params = [];
1243
-        }
1244
-        $query_params['limit'] = 1;
1245
-        $items                 = $this->get_all($query_params);
1246
-        if (empty($items)) {
1247
-            return null;
1248
-        }
1249
-        return array_shift($items);
1250
-    }
1251
-
1252
-
1253
-    /**
1254
-     * Returns the next x number of items in sequence from the given value as
1255
-     * found in the database matching the given query conditions.
1256
-     *
1257
-     * @param mixed $current_field_value    Value used for the reference point.
1258
-     * @param null  $field_to_order_by      What field is used for the
1259
-     *                                      reference point.
1260
-     * @param int   $limit                  How many to return.
1261
-     * @param array $query_params           Extra conditions on the query.
1262
-     * @param null  $columns_to_select      If left null, then an array of
1263
-     *                                      EE_Base_Class objects is returned,
1264
-     *                                      otherwise you can indicate just the
1265
-     *                                      columns you want returned.
1266
-     * @return EE_Base_Class[]|array
1267
-     * @throws EE_Error
1268
-     * @throws ReflectionException
1269
-     */
1270
-    public function next_x(
1271
-        $current_field_value,
1272
-        $field_to_order_by = null,
1273
-        $limit = 1,
1274
-        $query_params = [],
1275
-        $columns_to_select = null
1276
-    ) {
1277
-        return $this->_get_consecutive(
1278
-            $current_field_value,
1279
-            '>',
1280
-            $field_to_order_by,
1281
-            $limit,
1282
-            $query_params,
1283
-            $columns_to_select
1284
-        );
1285
-    }
1286
-
1287
-
1288
-    /**
1289
-     * Returns the previous x number of items in sequence from the given value
1290
-     * as found in the database matching the given query conditions.
1291
-     *
1292
-     * @param mixed $current_field_value    Value used for the reference point.
1293
-     * @param null  $field_to_order_by      What field is used for the
1294
-     *                                      reference point.
1295
-     * @param int   $limit                  How many to return.
1296
-     * @param array $query_params           Extra conditions on the query.
1297
-     * @param null  $columns_to_select      If left null, then an array of
1298
-     *                                      EE_Base_Class objects is returned,
1299
-     *                                      otherwise you can indicate just the
1300
-     *                                      columns you want returned.
1301
-     * @return EE_Base_Class[]|array
1302
-     * @throws EE_Error
1303
-     * @throws ReflectionException
1304
-     */
1305
-    public function previous_x(
1306
-        $current_field_value,
1307
-        $field_to_order_by = null,
1308
-        $limit = 1,
1309
-        $query_params = [],
1310
-        $columns_to_select = null
1311
-    ) {
1312
-        return $this->_get_consecutive(
1313
-            $current_field_value,
1314
-            '<',
1315
-            $field_to_order_by,
1316
-            $limit,
1317
-            $query_params,
1318
-            $columns_to_select
1319
-        );
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * Returns the next item in sequence from the given value as found in the
1325
-     * database matching the given query conditions.
1326
-     *
1327
-     * @param mixed $current_field_value    Value used for the reference point.
1328
-     * @param null  $field_to_order_by      What field is used for the
1329
-     *                                      reference point.
1330
-     * @param array $query_params           Extra conditions on the query.
1331
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1332
-     *                                      object is returned, otherwise you
1333
-     *                                      can indicate just the columns you
1334
-     *                                      want and a single array indexed by
1335
-     *                                      the columns will be returned.
1336
-     * @return EE_Base_Class|null|array()
1337
-     * @throws EE_Error
1338
-     * @throws ReflectionException
1339
-     */
1340
-    public function next(
1341
-        $current_field_value,
1342
-        $field_to_order_by = null,
1343
-        $query_params = [],
1344
-        $columns_to_select = null
1345
-    ) {
1346
-        $results = $this->_get_consecutive(
1347
-            $current_field_value,
1348
-            '>',
1349
-            $field_to_order_by,
1350
-            1,
1351
-            $query_params,
1352
-            $columns_to_select
1353
-        );
1354
-        return empty($results)
1355
-            ? null
1356
-            : reset($results);
1357
-    }
1358
-
1359
-
1360
-    /**
1361
-     * Returns the previous item in sequence from the given value as found in
1362
-     * the database matching the given query conditions.
1363
-     *
1364
-     * @param mixed $current_field_value    Value used for the reference point.
1365
-     * @param null  $field_to_order_by      What field is used for the
1366
-     *                                      reference point.
1367
-     * @param array $query_params           Extra conditions on the query.
1368
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1369
-     *                                      object is returned, otherwise you
1370
-     *                                      can indicate just the columns you
1371
-     *                                      want and a single array indexed by
1372
-     *                                      the columns will be returned.
1373
-     * @return EE_Base_Class|null|array()
1374
-     * @throws EE_Error
1375
-     * @throws ReflectionException
1376
-     */
1377
-    public function previous(
1378
-        $current_field_value,
1379
-        $field_to_order_by = null,
1380
-        $query_params = [],
1381
-        $columns_to_select = null
1382
-    ) {
1383
-        $results = $this->_get_consecutive(
1384
-            $current_field_value,
1385
-            '<',
1386
-            $field_to_order_by,
1387
-            1,
1388
-            $query_params,
1389
-            $columns_to_select
1390
-        );
1391
-        return empty($results)
1392
-            ? null
1393
-            : reset($results);
1394
-    }
1395
-
1396
-
1397
-    /**
1398
-     * Returns the a consecutive number of items in sequence from the given
1399
-     * value as found in the database matching the given query conditions.
1400
-     *
1401
-     * @param mixed  $current_field_value   Value used for the reference point.
1402
-     * @param string $operand               What operand is used for the sequence.
1403
-     * @param string $field_to_order_by     What field is used for the reference point.
1404
-     * @param int    $limit                 How many to return.
1405
-     * @param array  $query_params          Extra conditions on the query.
1406
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1407
-     *                                      otherwise you can indicate just the columns you want returned.
1408
-     * @return EE_Base_Class[]|array
1409
-     * @throws EE_Error
1410
-     * @throws ReflectionException
1411
-     */
1412
-    protected function _get_consecutive(
1413
-        $current_field_value,
1414
-        $operand = '>',
1415
-        $field_to_order_by = null,
1416
-        $limit = 1,
1417
-        $query_params = [],
1418
-        $columns_to_select = null
1419
-    ) {
1420
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1421
-        if (empty($field_to_order_by)) {
1422
-            if ($this->has_primary_key_field()) {
1423
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1424
-            } else {
1425
-                if (defined('WP_DEBUG') && WP_DEBUG) {
1426
-                    throw new EE_Error(
1427
-                        esc_html__(
1428
-                            'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1429
-                            'event_espresso'
1430
-                        )
1431
-                    );
1432
-                }
1433
-                EE_Error::add_error(
1434
-                    esc_html__('There was an error with the query.', 'event_espresso'),
1435
-                    __FILE__,
1436
-                    __FUNCTION__,
1437
-                    __LINE__
1438
-                );
1439
-                return [];
1440
-            }
1441
-        }
1442
-        if (! is_array($query_params)) {
1443
-            EE_Error::doing_it_wrong(
1444
-                'EEM_Base::_get_consecutive',
1445
-                sprintf(
1446
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1447
-                    gettype($query_params)
1448
-                ),
1449
-                '4.6.0'
1450
-            );
1451
-            $query_params = [];
1452
-        }
1453
-        // let's add the where query param for consecutive look up.
1454
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1455
-        $query_params['limit']                 = $limit;
1456
-        // set direction
1457
-        $incoming_orderby         = isset($query_params['order_by'])
1458
-            ? (array) $query_params['order_by']
1459
-            : [];
1460
-        $query_params['order_by'] = $operand === '>'
1461
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1462
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1463
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1464
-        if (empty($columns_to_select)) {
1465
-            return $this->get_all($query_params);
1466
-        }
1467
-        // getting just the fields
1468
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1469
-    }
1470
-
1471
-
1472
-    /**
1473
-     * This sets the _timezone property after model object has been instantiated.
1474
-     *
1475
-     * @param string|null $timezone valid PHP DateTimeZone timezone string
1476
-     * @throws Exception
1477
-     */
1478
-    public function set_timezone(?string $timezone = '')
1479
-    {
1480
-        if (! $timezone) {
1481
-            return;
1482
-        }
1483
-        $this->_timezone = $timezone;
1484
-        // note we need to loop through relations and set the timezone on those objects as well.
1485
-        foreach ($this->_model_relations as $relation) {
1486
-            $relation->set_timezone($timezone);
1487
-        }
1488
-        // and finally we do the same for any datetime fields
1489
-        foreach ($this->_fields as $field) {
1490
-            if ($field instanceof EE_Datetime_Field) {
1491
-                $field->set_timezone($timezone);
1492
-            }
1493
-        }
1494
-    }
1495
-
1496
-
1497
-    /**
1498
-     * This just returns whatever is set for the current timezone.
1499
-     *
1500
-     * @access public
1501
-     * @return string
1502
-     * @throws Exception
1503
-     */
1504
-    public function get_timezone()
1505
-    {
1506
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1507
-        if (empty($this->_timezone)) {
1508
-            foreach ($this->_fields as $field) {
1509
-                if ($field instanceof EE_Datetime_Field) {
1510
-                    $this->set_timezone($field->get_timezone());
1511
-                    break;
1512
-                }
1513
-            }
1514
-        }
1515
-        // if timezone STILL empty then return the default timezone for the site.
1516
-        if (empty($this->_timezone)) {
1517
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1518
-        }
1519
-        return $this->_timezone;
1520
-    }
1521
-
1522
-
1523
-    /**
1524
-     * This returns the date formats set for the given field name and also ensures that
1525
-     * $this->_timezone property is set correctly.
1526
-     *
1527
-     * @param string $field_name The name of the field the formats are being retrieved for.
1528
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1529
-     * @return array formats in an array with the date format first, and the time format last.
1530
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1531
-     * @since 4.6.x
1532
-     */
1533
-    public function get_formats_for($field_name, $pretty = false)
1534
-    {
1535
-        $field_settings = $this->field_settings_for($field_name);
1536
-        // if not a valid EE_Datetime_Field then throw error
1537
-        if (! $field_settings instanceof EE_Datetime_Field) {
1538
-            throw new EE_Error(
1539
-                sprintf(
1540
-                    esc_html__(
1541
-                        'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1542
-                        'event_espresso'
1543
-                    ),
1544
-                    $field_name
1545
-                )
1546
-            );
1547
-        }
1548
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1549
-        // the field.
1550
-        $this->_timezone = $field_settings->get_timezone();
1551
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1552
-    }
1553
-
1554
-
1555
-    /**
1556
-     * This returns the current time in a format setup for a query on this model.
1557
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1558
-     * it will return:
1559
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1560
-     *  NOW
1561
-     *  - or a unix timestamp (equivalent to time())
1562
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1563
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1564
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1565
-     *
1566
-     * @param string $field_name       The field the current time is needed for.
1567
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1568
-     *                                 formatted string matching the set format for the field in the set timezone will
1569
-     *                                 be returned.
1570
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1571
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1572
-     *                                 exception is triggered.
1573
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1574
-     * @throws Exception
1575
-     * @since 4.6.x
1576
-     */
1577
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1578
-    {
1579
-        $formats  = $this->get_formats_for($field_name);
1580
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1581
-        if ($timestamp) {
1582
-            return $DateTime->format('U');
1583
-        }
1584
-        // not returning timestamp, so return formatted string in timezone.
1585
-        switch ($what) {
1586
-            case 'time':
1587
-                return $DateTime->format($formats[1]);
1588
-            case 'date':
1589
-                return $DateTime->format($formats[0]);
1590
-            default:
1591
-                return $DateTime->format(implode(' ', $formats));
1592
-        }
1593
-    }
1594
-
1595
-
1596
-    /**
1597
-     * This receives a time string for a given field and ensures
1598
-     * that it is set up to match what the internal settings for the model are.
1599
-     * Returns a DateTime object.
1600
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1601
-     * (functionally the equivalent of UTC+0).
1602
-     * So when you send it in, whatever timezone string you include is ignored.
1603
-     *
1604
-     * @param string      $field_name      The field being setup.
1605
-     * @param string      $timestring      The date time string being used.
1606
-     * @param string      $incoming_format The format for the time string.
1607
-     * @param string|null $timezone_string By default, it is assumed the incoming time string is in timezone for
1608
-     *                                     the blog.  If this is not the case, then it can be specified here.  If
1609
-     *                                     incoming format is
1610
-     *                                     'U', this is ignored.
1611
-     * @return DbSafeDateTime
1612
-     * @throws EE_Error
1613
-     * @throws Exception
1614
-     */
1615
-    public function convert_datetime_for_query(
1616
-        string $field_name,
1617
-        string $timestring,
1618
-        string $incoming_format,
1619
-        ?string $timezone_string = ''
1620
-    ): DbSafeDateTime {
1621
-        // just using this to ensure the timezone is set correctly internally
1622
-        $this->get_formats_for($field_name);
1623
-        // load EEH_DTT_Helper
1624
-        $timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1625
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1626
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1627
-        return DbSafeDateTime::createFromDateTime($incomingDateTime);
1628
-    }
1629
-
1630
-
1631
-    /**
1632
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1633
-     *
1634
-     * @return EE_Table_Base[]
1635
-     */
1636
-    public function get_tables()
1637
-    {
1638
-        return $this->_tables;
1639
-    }
1640
-
1641
-
1642
-    /**
1643
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1644
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1645
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1646
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1647
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1648
-     * model object with EVT_ID = 1
1649
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1650
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1651
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1652
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1653
-     * are not specified)
1654
-     *
1655
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1656
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1657
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1658
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1659
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1660
-     *                                         ID=34, we'd use this method as follows:
1661
-     *                                         EEM_Transaction::instance()->update(
1662
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1663
-     *                                         array(array('TXN_ID'=>34)));
1664
-     * @param array   $query_params            @see
1665
-     *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1666
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1667
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1668
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1669
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1670
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1671
-     *                                         TRUE, it is assumed that you've already called
1672
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1673
-     *                                         malicious javascript. However, if
1674
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1675
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1676
-     *                                         and every other field, before insertion. We provide this parameter
1677
-     *                                         because model objects perform their prepare_for_set function on all
1678
-     *                                         their values, and so don't need to be called again (and in many cases,
1679
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1680
-     *                                         prepare_for_set method...)
1681
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1682
-     *                                         in this model's entity map according to $fields_n_values that match
1683
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1684
-     *                                         by setting this to FALSE, but be aware that model objects being used
1685
-     *                                         could get out-of-sync with the database
1686
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1687
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1688
-     *                                         bad)
1689
-     * @throws EE_Error
1690
-     * @throws ReflectionException
1691
-     */
1692
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1693
-    {
1694
-        if (! is_array($query_params)) {
1695
-            EE_Error::doing_it_wrong(
1696
-                'EEM_Base::update',
1697
-                sprintf(
1698
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1699
-                    gettype($query_params)
1700
-                ),
1701
-                '4.6.0'
1702
-            );
1703
-            $query_params = [];
1704
-        }
1705
-        /**
1706
-         * Action called before a model update call has been made.
1707
-         *
1708
-         * @param EEM_Base $model
1709
-         * @param array    $fields_n_values the updated fields and their new values
1710
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1711
-         */
1712
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1713
-        /**
1714
-         * Filters the fields about to be updated given the query parameters. You can provide the
1715
-         * $query_params to $this->get_all() to find exactly which records will be updated
1716
-         *
1717
-         * @param array    $fields_n_values fields and their new values
1718
-         * @param EEM_Base $model           the model being queried
1719
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1720
-         */
1721
-        $fields_n_values = (array) apply_filters(
1722
-            'FHEE__EEM_Base__update__fields_n_values',
1723
-            $fields_n_values,
1724
-            $this,
1725
-            $query_params
1726
-        );
1727
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1728
-        // to do that, for each table, verify that it's PK isn't null.
1729
-        $tables = $this->get_tables();
1730
-        // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1731
-        // NOTE: we should make this code more efficient by NOT querying twice
1732
-        // before the real update, but that needs to first go through ALPHA testing
1733
-        // as it's dangerous. says Mike August 8 2014
1734
-        // we want to make sure the default_where strategy is ignored
1735
-        $this->_ignore_where_strategy = true;
1736
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1737
-        foreach ($wpdb_select_results as $wpdb_result) {
1738
-            // type cast stdClass as array
1739
-            $wpdb_result = (array) $wpdb_result;
1740
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1741
-            if ($this->has_primary_key_field()) {
1742
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1743
-            } else {
1744
-                // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1745
-                $main_table_pk_value = null;
1746
-            }
1747
-            // if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1748
-            // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1749
-            if (count($tables) > 1) {
1750
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1751
-                // in that table, and so we'll want to insert one
1752
-                foreach ($tables as $table_obj) {
1753
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1754
-                    // if there is no private key for this table on the results, it means there's no entry
1755
-                    // in this table, right? so insert a row in the current table, using any fields available
1756
-                    if (
1757
-                        ! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
-                           && $wpdb_result[ $this_table_pk_column ])
1759
-                    ) {
1760
-                        $success = $this->_insert_into_specific_table(
1761
-                            $table_obj,
1762
-                            $fields_n_values,
1763
-                            $main_table_pk_value
1764
-                        );
1765
-                        // if we died here, report the error
1766
-                        if (! $success) {
1767
-                            return false;
1768
-                        }
1769
-                    }
1770
-                }
1771
-            }
1772
-            //              //and now check that if we have cached any models by that ID on the model, that
1773
-            //              //they also get updated properly
1774
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1775
-            //              if( $model_object ){
1776
-            //                  foreach( $fields_n_values as $field => $value ){
1777
-            //                      $model_object->set($field, $value);
1778
-            // let's make sure default_where strategy is followed now
1779
-            $this->_ignore_where_strategy = false;
1780
-        }
1781
-        // if we want to keep model objects in sync, AND
1782
-        // if this wasn't called from a model object (to update itself)
1783
-        // then we want to make sure we keep all the existing
1784
-        // model objects in sync with the db
1785
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1786
-            if ($this->has_primary_key_field()) {
1787
-                $model_objs_affected_ids = $this->get_col($query_params);
1788
-            } else {
1789
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1790
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1791
-                $model_objs_affected_ids     = [];
1792
-                foreach ($models_affected_key_columns as $row) {
1793
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1794
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1795
-                }
1796
-            }
1797
-            if (! $model_objs_affected_ids) {
1798
-                // wait wait wait- if nothing was affected let's stop here
1799
-                return 0;
1800
-            }
1801
-            foreach ($model_objs_affected_ids as $id) {
1802
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1803
-                if ($model_obj_in_entity_map) {
1804
-                    foreach ($fields_n_values as $field => $new_value) {
1805
-                        $model_obj_in_entity_map->set($field, $new_value);
1806
-                    }
1807
-                }
1808
-            }
1809
-            // if there is a primary key on this model, we can now do a slight optimization
1810
-            if ($this->has_primary_key_field()) {
1811
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1812
-                $query_params = [
1813
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1814
-                    'limit'                    => count($model_objs_affected_ids),
1815
-                    'default_where_conditions' => EE_Default_Where_Conditions::NONE,
1816
-                ];
1817
-            }
1818
-        }
1819
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1820
-
1821
-        // note: the following query doesn't use _construct_2nd_half_of_select_query()
1822
-        // because it doesn't accept LIMIT, ORDER BY, etc.
1823
-        $rows_affected = $this->_do_wpdb_query(
1824
-            'query',
1825
-            [
1826
-                "UPDATE " . $model_query_info->get_full_join_sql()
1827
-                . " SET " . $this->_construct_update_sql($fields_n_values)
1828
-                . $model_query_info->get_where_sql(),
1829
-            ]
1830
-        );
1831
-
1832
-        /**
1833
-         * Action called after a model update call has been made.
1834
-         *
1835
-         * @param EEM_Base $model
1836
-         * @param array    $fields_n_values the updated fields and their new values
1837
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1838
-         * @param int      $rows_affected
1839
-         */
1840
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1841
-        return $rows_affected;// how many supposedly got updated
1842
-    }
1843
-
1844
-
1845
-    /**
1846
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where the values
1847
-     * are the values of the field specified (or by default the primary key field)
1848
-     * that matched the query params. Note that you should pass the name of the
1849
-     * model FIELD, not the database table's column name.
1850
-     *
1851
-     * @param array  $query_params
1852
-     * @param string $field_to_select
1853
-     * @return array just like $wpdb->get_col()
1854
-     * @throws EE_Error
1855
-     * @throws ReflectionException
1856
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md for $query_params values
1857
-     */
1858
-    public function get_col($query_params = [], $field_to_select = null)
1859
-    {
1860
-        if ($field_to_select) {
1861
-            $field = $this->field_settings_for($field_to_select);
1862
-        } elseif ($this->has_primary_key_field()) {
1863
-            $field = $this->get_primary_key_field();
1864
-        } else {
1865
-            $field_settings = $this->field_settings();
1866
-            // no primary key, just grab the first column
1867
-            $field = reset($field_settings);
1868
-            // don't need this array now
1869
-            unset($field_settings);
1870
-        }
1871
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1872
-        $select_expressions = $field->get_qualified_column();
1873
-        $SQL                =
1874
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1875
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1876
-    }
1877
-
1878
-
1879
-    /**
1880
-     * Returns a single column value for a single row from the database
1881
-     *
1882
-     * @param array  $query_params    @see
1883
-     *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1884
-     * @param string $field_to_select @see EEM_Base::get_col()
1885
-     * @return string
1886
-     * @throws EE_Error
1887
-     * @throws ReflectionException
1888
-     */
1889
-    public function get_var($query_params = [], $field_to_select = null)
1890
-    {
1891
-        $query_params['limit'] = 1;
1892
-        $col                   = $this->get_col($query_params, $field_to_select);
1893
-        if (! empty($col)) {
1894
-            return reset($col);
1895
-        }
1896
-        return null;
1897
-    }
1898
-
1899
-
1900
-    /**
1901
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1902
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1903
-     * injection, but currently no further filtering is done
1904
-     *
1905
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1906
-     *                               be updated to in the DB
1907
-     * @return string of SQL
1908
-     * @throws EE_Error
1909
-     * @global      $wpdb
1910
-     */
1911
-    public function _construct_update_sql($fields_n_values)
1912
-    {
1913
-        /** @type WPDB $wpdb */
1914
-        global $wpdb;
1915
-        $cols_n_values = [];
1916
-        foreach ($fields_n_values as $field_name => $value) {
1917
-            $field_obj = $this->field_settings_for($field_name);
1918
-            // if the value is NULL, we want to assign the value to that.
1919
-            // wpdb->prepare doesn't really handle that properly
1920
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1921
-            $value_sql       = $prepared_value === null
1922
-                ? 'NULL'
1923
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1924
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1925
-        }
1926
-        return implode(",", $cols_n_values);
1927
-    }
1928
-
1929
-
1930
-    /**
1931
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1932
-     * Performs a HARD delete, meaning the database row should always be removed,
1933
-     * not just have a flag field on it switched
1934
-     * Wrapper for EEM_Base::delete_permanently()
1935
-     *
1936
-     * @param mixed $id
1937
-     * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
1938
-     *                             ie: enforce referential integrity
1939
-     *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
1940
-     * @return int the number of rows deleted
1941
-     * @throws EE_Error
1942
-     * @throws ReflectionException
1943
-     */
1944
-    public function delete_permanently_by_ID($id, $block_deletes = true): int
1945
-    {
1946
-        return $this->delete_permanently(
1947
-            [
1948
-                [$this->get_primary_key_field()->get_name() => $id],
1949
-                'limit' => 1,
1950
-            ],
1951
-            $block_deletes
1952
-        );
1953
-    }
1954
-
1955
-
1956
-    /**
1957
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1958
-     * Wrapper for EEM_Base::delete()
1959
-     *
1960
-     * @param mixed $id
1961
-     * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
1962
-     *                             ie: enforce referential integrity
1963
-     *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
1964
-     * @return int the number of rows deleted
1965
-     * @throws EE_Error
1966
-     * @throws ReflectionException
1967
-     */
1968
-    public function delete_by_ID($id, $block_deletes = true)
1969
-    {
1970
-        return $this->delete(
1971
-            [
1972
-                [$this->get_primary_key_field()->get_name() => $id],
1973
-                'limit' => 1,
1974
-            ],
1975
-            $block_deletes
1976
-        );
1977
-    }
1978
-
1979
-
1980
-    /**
1981
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1982
-     * meaning if the model has a field that indicates its been "trashed" or
1983
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1984
-     *
1985
-     * @param array   $query_params
1986
-     * @param boolean $block_deletes whether to allow related model objects to block (prevent) this deletion
1987
-     *                               ie: enforce referential integrity
1988
-     *                               It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
1989
-     * @return int how many rows got deleted
1990
-     * @throws EE_Error
1991
-     * @throws ReflectionException
1992
-     * @see EEM_Base::delete_permanently
1993
-     */
1994
-    public function delete($query_params, $block_deletes = true)
1995
-    {
1996
-        return $this->delete_permanently($query_params, $block_deletes);
1997
-    }
1998
-
1999
-
2000
-    /**
2001
-     * Deletes the model objects that meet the query params. Note: this method is overridden
2002
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
2003
-     * as archived, not actually deleted
2004
-     *
2005
-     * @param array   $query_params
2006
-     * @param boolean $block_deletes  whether to allow related model objects to block (prevent) this deletion
2007
-     *                                ie: enforce referential integrity
2008
-     *                                It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
2009
-     * @return int how many rows got deleted
2010
-     * @throws EE_Error
2011
-     * @throws ReflectionException
2012
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2013
-     */
2014
-    public function delete_permanently($query_params, $block_deletes = true): int
2015
-    {
2016
-        /**
2017
-         * Action called just before performing a real deletion query. You can use the
2018
-         * model and its $query_params to find exactly which items will be deleted
2019
-         *
2020
-         * @param EEM_Base $model
2021
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2022
-         * @param bool     $block_deletes @see param description in method phpdoc block.
2023
-         */
2024
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $block_deletes);
2025
-        // some MySQL databases may be running safe mode, which may restrict
2026
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
2027
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
2028
-        // to delete them
2029
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2030
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $block_deletes);
2031
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2032
-            $columns_and_ids_for_deleting
2033
-        );
2034
-        /**
2035
-         * Allows client code to act on the items being deleted before the query is actually executed.
2036
-         * see php doc blocks for more details
2037
-         *
2038
-         * @param EEM_Base $this                         The model instance being acted on.
2039
-         * @param array    $query_params                 The incoming array of query parameters influencing what gets deleted.
2040
-         * @param bool     $block_deletes                @see param description in method phpdoc block.
2041
-         * @param array    $columns_and_ids_for_deleting An array indicating what entities will get removed as
2042
-         *                                               derived from the incoming query parameters.
2043
-         * @see details on the structure of this array in the phpdocs for the `_get_ids_for_delete_method`
2044
-         */
2045
-        do_action(
2046
-            'AHEE__EEM_Base__delete__before_query',
2047
-            $this,
2048
-            $query_params,
2049
-            $block_deletes,
2050
-            $columns_and_ids_for_deleting
2051
-        );
2052
-        $rows_deleted = 0;
2053
-        if ($deletion_where_query_part) {
2054
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2055
-            $table_aliases    = array_keys($this->_tables);
2056
-            $SQL              = "DELETE "
2057
-                                . implode(", ", $table_aliases)
2058
-                                . " FROM "
2059
-                                . $model_query_info->get_full_join_sql()
2060
-                                . " WHERE "
2061
-                                . $deletion_where_query_part;
2062
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2063
-        }
2064
-
2065
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2066
-        // there was no error with the delete query.
2067
-        if (
2068
-            $this->has_primary_key_field()
2069
-            && $rows_deleted !== false
2070
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2071
-        ) {
2072
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2073
-            foreach ($ids_for_removal as $id) {
2074
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2075
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2076
-                }
2077
-            }
2078
-
2079
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2080
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2081
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2082
-            // (although it is possible).
2083
-            // Note this can be skipped by using the provided filter and returning false.
2084
-            if (
2085
-                apply_filters(
2086
-                    'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2087
-                    ! $this instanceof EEM_Extra_Meta,
2088
-                    $this
2089
-                )
2090
-            ) {
2091
-                EEM_Extra_Meta::instance()->delete_permanently(
2092
-                    [
2093
-                        0 => [
2094
-                            'EXM_type' => $this->get_this_model_name(),
2095
-                            'OBJ_ID'   => [
2096
-                                'IN',
2097
-                                $ids_for_removal,
2098
-                            ],
2099
-                        ],
2100
-                    ]
2101
-                );
2102
-            }
2103
-        }
2104
-
2105
-        /**
2106
-         * Action called just after performing a real deletion query. Although at this point the
2107
-         * items should have been deleted
2108
-         *
2109
-         * @param EEM_Base $model
2110
-         * @param array $query_params
2111
-         * @param int   $rows_deleted
2112
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2113
-         */
2114
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2115
-        return (int) $rows_deleted;// how many supposedly got deleted
2116
-    }
2117
-
2118
-
2119
-    /**
2120
-     * Checks all the relations that throw error messages when there are blocking related objects
2121
-     * for related model objects. If there are any related model objects on those relations,
2122
-     * adds an EE_Error, and return true
2123
-     *
2124
-     * @param EE_Base_Class|int $this_model_obj_or_id
2125
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2126
-     *                                                 should be ignored when determining whether there are related
2127
-     *                                                 model objects which block this model object's deletion. Useful
2128
-     *                                                 if you know A is related to B and are considering deleting A,
2129
-     *                                                 but want to see if A has any other objects blocking its deletion
2130
-     *                                                 before removing the relation between A and B
2131
-     * @return boolean
2132
-     * @throws EE_Error
2133
-     * @throws ReflectionException
2134
-     */
2135
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2136
-    {
2137
-        // first, if $ignore_this_model_obj was supplied, get its model
2138
-        $ignored_model = $ignore_this_model_obj instanceof EE_Base_Class
2139
-            ? $ignore_this_model_obj->get_model()
2140
-            : null;
2141
-        // now check all the relations of $this_model_obj_or_id and see if there
2142
-        // are any related model objects blocking it?
2143
-        $is_blocked = false;
2144
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2145
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2146
-                // if $ignore_this_model_obj was supplied, then for the query
2147
-                // on that model needs to be told to ignore $ignore_this_model_obj
2148
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2149
-                    $related_model_objects = $relation_obj->get_all_related(
2150
-                        $this_model_obj_or_id,
2151
-                        [
2152
-                            [
2153
-                                $ignored_model->get_primary_key_field()->get_name() => [
2154
-                                    '!=',
2155
-                                    $ignore_this_model_obj->ID(),
2156
-                                ],
2157
-                            ],
2158
-                        ]
2159
-                    );
2160
-                } else {
2161
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2162
-                }
2163
-                if ($related_model_objects) {
2164
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2165
-                    $is_blocked = true;
2166
-                }
2167
-            }
2168
-        }
2169
-        return $is_blocked;
2170
-    }
2171
-
2172
-
2173
-    /**
2174
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2175
-     *
2176
-     * @param array $row_results_for_deleting
2177
-     * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
2178
-     *                             ie: enforce referential integrity
2179
-     *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
2180
-     * @return array               The shape of this array depends on whether the model `has_primary_key_field` or not.
2181
-     *                             If the model DOES have a primary_key_field, then the array will be a simple single
2182
-     *                             dimension array where the key is the fully qualified primary key column and
2183
-     *                             the value is an array of ids that will be deleted.
2184
-     *                             Example:
2185
-     *                              [ 'Event.EVT_ID' => [ 1,2,3 ]]
2186
-     *                             If the model DOES NOT have a primary_key_field, then the array will be a
2187
-     *                             two-dimensional array where each element is a group of columns and values that get deleted.
2188
-     *                             Example:
2189
-     *                              [
2190
-     *                                  0 => [
2191
-     *                                      'Term_Relationship.object_id' => 1
2192
-     *                                      'Term_Relationship.term_taxonomy_id' => 5
2193
-     *                                  ],
2194
-     *                                  1 => [
2195
-     *                                      'Term_Relationship.object_id' => 1
2196
-     *                                      'Term_Relationship.term_taxonomy_id' => 6
2197
-     *                                  ]
2198
-     *                              ]
2199
-     * @throws EE_Error
2200
-     * @throws ReflectionException
2201
-     */
2202
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $block_deletes = true)
2203
-    {
2204
-        $ids_to_delete_indexed_by_column = [];
2205
-        if ($this->has_primary_key_field()) {
2206
-            $primary_table = $this->_get_main_table();
2207
-            // following lines are commented out because the variables were not being used
2208
-            // not deleting because unsure if calls were intentionally causing side effects
2209
-            // $primary_table_pk_field          =
2210
-            //     $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2211
-            // $other_tables                    = $this->_get_other_tables();
2212
-            $ids_to_delete_indexed_by_column = $query = [];
2213
-            foreach ($row_results_for_deleting as $item_to_delete) {
2214
-                // before we mark this item for deletion,
2215
-                // make sure there's no related entities blocking its deletion (if we're checking)
2216
-                if (
2217
-                    $block_deletes
2218
-                    && $this->delete_is_blocked_by_related_models(
2219
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2220
-                    )
2221
-                ) {
2222
-                    continue;
2223
-                }
2224
-                // primary table deletes
2225
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2226
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2227
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2228
-                }
2229
-            }
2230
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2231
-            $fields = $this->get_combined_primary_key_fields();
2232
-            foreach ($row_results_for_deleting as $item_to_delete) {
2233
-                $ids_to_delete_indexed_by_column_for_row = [];
2234
-                foreach ($fields as $cpk_field) {
2235
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2236
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2237
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2238
-                    }
2239
-                }
2240
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2241
-            }
2242
-        } else {
2243
-            // so there's no primary key and no combined key...
2244
-            // sorry, can't help you
2245
-            throw new EE_Error(
2246
-                sprintf(
2247
-                    esc_html__(
2248
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2249
-                        "event_espresso"
2250
-                    ),
2251
-                    get_class($this)
2252
-                )
2253
-            );
2254
-        }
2255
-        return $ids_to_delete_indexed_by_column;
2256
-    }
2257
-
2258
-
2259
-    /**
2260
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2261
-     * the corresponding query_part for the query performing the deletion.
2262
-     *
2263
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2264
-     * @return string
2265
-     * @throws EE_Error
2266
-     */
2267
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2268
-    {
2269
-        $query_part = '';
2270
-        if (empty($ids_to_delete_indexed_by_column)) {
2271
-            return $query_part;
2272
-        } elseif ($this->has_primary_key_field()) {
2273
-            $query = [];
2274
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2275
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2276
-            }
2277
-            $query_part = ! empty($query)
2278
-                ? implode(' AND ', $query)
2279
-                : $query_part;
2280
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2281
-            $ways_to_identify_a_row = [];
2282
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2283
-                $values_for_each_combined_primary_key_for_a_row = [];
2284
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2285
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2286
-                }
2287
-                $ways_to_identify_a_row[] = '('
2288
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2289
-                                            . ')';
2290
-            }
2291
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2292
-        }
2293
-        return $query_part;
2294
-    }
2295
-
2296
-
2297
-    /**
2298
-     * Gets the model field by the fully qualified name
2299
-     *
2300
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2301
-     * @return EE_Model_Field_Base
2302
-     * @throws EE_Error
2303
-     * @throws EE_Error
2304
-     */
2305
-    public function get_field_by_column($qualified_column_name)
2306
-    {
2307
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2308
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2309
-                return $field_obj;
2310
-            }
2311
-        }
2312
-        throw new EE_Error(
2313
-            sprintf(
2314
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2315
-                $this->get_this_model_name(),
2316
-                $qualified_column_name
2317
-            )
2318
-        );
2319
-    }
2320
-
2321
-
2322
-    /**
2323
-     * Count all the rows that match criteria the model query params.
2324
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2325
-     * column
2326
-     *
2327
-     * @param array  $query_params   @see
2328
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2329
-     * @param string $field_to_count field on model to count by (not column name)
2330
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2331
-     *                               that by the setting $distinct to TRUE;
2332
-     * @return int
2333
-     * @throws EE_Error
2334
-     * @throws ReflectionException
2335
-     */
2336
-    public function count($query_params = [], $field_to_count = '', $distinct = false)
2337
-    {
2338
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2339
-        if ($field_to_count) {
2340
-            $field_obj       = $this->field_settings_for($field_to_count);
2341
-            $column_to_count = $field_obj->get_qualified_column();
2342
-        } elseif ($this->has_primary_key_field()) {
2343
-            $pk_field_obj    = $this->get_primary_key_field();
2344
-            $column_to_count = $pk_field_obj->get_qualified_column();
2345
-        } else {
2346
-            // there's no primary key
2347
-            // if we're counting distinct items, and there's no primary key,
2348
-            // we need to list out the columns for distinction;
2349
-            // otherwise we can just use star
2350
-            if ($distinct) {
2351
-                $columns_to_use = [];
2352
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2353
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2354
-                }
2355
-                $column_to_count = implode(',', $columns_to_use);
2356
-            } else {
2357
-                $column_to_count = '*';
2358
-            }
2359
-        }
2360
-        $column_to_count = $distinct
2361
-            ? "DISTINCT " . $column_to_count
2362
-            : $column_to_count;
2363
-        $SQL             =
2364
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2365
-        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2366
-    }
2367
-
2368
-
2369
-    /**
2370
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2371
-     *
2372
-     * @param array  $query_params @see
2373
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2374
-     * @param string $field_to_sum name of field (array key in $_fields array)
2375
-     * @return float
2376
-     * @throws EE_Error
2377
-     * @throws ReflectionException
2378
-     */
2379
-    public function sum($query_params, $field_to_sum = null)
2380
-    {
2381
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2382
-        if ($field_to_sum) {
2383
-            $field_obj = $this->field_settings_for($field_to_sum);
2384
-        } else {
2385
-            $field_obj = $this->get_primary_key_field();
2386
-        }
2387
-        $column_to_count = $field_obj->get_qualified_column();
2388
-        $SQL             =
2389
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2390
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2391
-        $data_type       = $field_obj->get_wpdb_data_type();
2392
-        if ($data_type === '%d' || $data_type === '%s') {
2393
-            return (float) $return_value;
2394
-        }
2395
-        // must be %f
2396
-        return (float) $return_value;
2397
-    }
2398
-
2399
-
2400
-    /**
2401
-     * Just calls the specified method on $wpdb with the given arguments
2402
-     * Consolidates a little extra error handling code
2403
-     *
2404
-     * @param string $wpdb_method
2405
-     * @param array  $arguments_to_provide
2406
-     * @return mixed
2407
-     * @throws EE_Error
2408
-     * @global wpdb  $wpdb
2409
-     */
2410
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2411
-    {
2412
-        // if we're in maintenance mode level 2, DON'T run any queries
2413
-        // because level 2 indicates the database needs updating and
2414
-        // is probably out of sync with the code
2415
-        if (DbStatus::isOffline()) {
2416
-            throw new RuntimeException(
2417
-                esc_html__(
2418
-                    "Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2419
-                    "event_espresso"
2420
-                )
2421
-            );
2422
-        }
2423
-        /** @type WPDB $wpdb */
2424
-        global $wpdb;
2425
-        if (! method_exists($wpdb, $wpdb_method)) {
2426
-            throw new DomainException(
2427
-                sprintf(
2428
-                    esc_html__(
2429
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2430
-                        'event_espresso'
2431
-                    ),
2432
-                    $wpdb_method
2433
-                )
2434
-            );
2435
-        }
2436
-        $old_show_errors_value = $wpdb->show_errors;
2437
-        if (defined('WP_DEBUG') && WP_DEBUG) {
2438
-            $wpdb->show_errors(false);
2439
-        }
2440
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2441
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2442
-        if (defined('WP_DEBUG') && WP_DEBUG) {
2443
-            $wpdb->show_errors($old_show_errors_value);
2444
-            if (! empty($wpdb->last_error)) {
2445
-                throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2446
-            }
2447
-            if ($result === false) {
2448
-                throw new EE_Error(
2449
-                    sprintf(
2450
-                        esc_html__(
2451
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2452
-                            'event_espresso'
2453
-                        ),
2454
-                        $wpdb_method,
2455
-                        var_export($arguments_to_provide, true)
2456
-                    )
2457
-                );
2458
-            }
2459
-        } elseif ($result === false) {
2460
-            EE_Error::add_error(
2461
-                sprintf(
2462
-                    esc_html__(
2463
-                        'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2464
-                        'event_espresso'
2465
-                    ),
2466
-                    $wpdb_method,
2467
-                    var_export($arguments_to_provide, true),
2468
-                    $wpdb->last_error
2469
-                ),
2470
-                __FILE__,
2471
-                __FUNCTION__,
2472
-                __LINE__
2473
-            );
2474
-        }
2475
-        return $result;
2476
-    }
2477
-
2478
-
2479
-    /**
2480
-     * Attempts to run the indicated WPDB method with the provided arguments,
2481
-     * and if there's an error tries to verify the DB is correct. Uses
2482
-     * the static property EEM_Base::$_db_verification_level to determine whether
2483
-     * we should try to fix the EE core db, the addons, or just give up
2484
-     *
2485
-     * @param string $wpdb_method
2486
-     * @param array  $arguments_to_provide
2487
-     * @return mixed
2488
-     */
2489
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2490
-    {
2491
-        /** @type WPDB $wpdb */
2492
-        global $wpdb;
2493
-        $wpdb->last_error = null;
2494
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2495
-        // was there an error running the query? but we don't care on new activations
2496
-        // (we're going to setup the DB anyway on new activations)
2497
-        if (
2498
-            ($result === false || ! empty($wpdb->last_error))
2499
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2500
-        ) {
2501
-            switch (EEM_Base::$_db_verification_level) {
2502
-                case EEM_Base::db_verified_none:
2503
-                    // let's double-check core's DB
2504
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2505
-                    break;
2506
-                case EEM_Base::db_verified_core:
2507
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2508
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2509
-                    break;
2510
-                case EEM_Base::db_verified_addons:
2511
-                    // ummmm... you in trouble
2512
-                    return $result;
2513
-            }
2514
-            if (! empty($error_message)) {
2515
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2516
-                trigger_error($error_message);
2517
-            }
2518
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2519
-        }
2520
-        return $result;
2521
-    }
2522
-
2523
-
2524
-    /**
2525
-     * Verifies the EE core database is up-to-date and records that we've done it on
2526
-     * EEM_Base::$_db_verification_level
2527
-     *
2528
-     * @param string $wpdb_method
2529
-     * @param array  $arguments_to_provide
2530
-     * @return string
2531
-     * @throws EE_Error
2532
-     * @throws ReflectionException
2533
-     */
2534
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2535
-    {
2536
-        /** @type WPDB $wpdb */
2537
-        global $wpdb;
2538
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2539
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2540
-        $error_message                    = sprintf(
2541
-            esc_html__(
2542
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2543
-                'event_espresso'
2544
-            ),
2545
-            $wpdb->last_error,
2546
-            $wpdb_method,
2547
-            wp_json_encode($arguments_to_provide)
2548
-        );
2549
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2550
-        return $error_message;
2551
-    }
2552
-
2553
-
2554
-    /**
2555
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2556
-     * EEM_Base::$_db_verification_level
2557
-     *
2558
-     * @param $wpdb_method
2559
-     * @param $arguments_to_provide
2560
-     * @return string
2561
-     * @throws EE_Error
2562
-     * @throws ReflectionException
2563
-     */
2564
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2565
-    {
2566
-        /** @type WPDB $wpdb */
2567
-        global $wpdb;
2568
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2569
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2570
-        $error_message                    = sprintf(
2571
-            esc_html__(
2572
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2573
-                'event_espresso'
2574
-            ),
2575
-            $wpdb->last_error,
2576
-            $wpdb_method,
2577
-            wp_json_encode($arguments_to_provide)
2578
-        );
2579
-        EE_System::instance()->initialize_addons();
2580
-        return $error_message;
2581
-    }
2582
-
2583
-
2584
-    /**
2585
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2586
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2587
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2588
-     * ..."
2589
-     *
2590
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2591
-     * @return string
2592
-     */
2593
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2594
-    {
2595
-        return " FROM " . $model_query_info->get_full_join_sql() .
2596
-               $model_query_info->get_where_sql() .
2597
-               $model_query_info->get_group_by_sql() .
2598
-               $model_query_info->get_having_sql() .
2599
-               $model_query_info->get_order_by_sql() .
2600
-               $model_query_info->get_limit_sql();
2601
-    }
2602
-
2603
-
2604
-    /**
2605
-     * Set to easily debug the next X queries ran from this model.
2606
-     *
2607
-     * @param int $count
2608
-     */
2609
-    public function show_next_x_db_queries($count = 1)
2610
-    {
2611
-        $this->_show_next_x_db_queries = $count;
2612
-    }
2613
-
2614
-
2615
-    /**
2616
-     * @param $sql_query
2617
-     */
2618
-    public function show_db_query_if_previously_requested($sql_query)
2619
-    {
2620
-        if ($this->_show_next_x_db_queries > 0) {
2621
-            $left = is_admin() ? '12rem' : '2rem';
2622
-            echo "
42
+	/**
43
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
44
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
45
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
46
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
47
+	 *
48
+	 * @var boolean
49
+	 */
50
+	private $_values_already_prepared_by_model_object = 0;
51
+
52
+	/**
53
+	 * when $_values_already_prepared_by_model_object equals this, we assume
54
+	 * the data is just like form input that needs to have the model fields'
55
+	 * prepare_for_set and prepare_for_use_in_db called on it
56
+	 */
57
+	const not_prepared_by_model_object = 0;
58
+
59
+	/**
60
+	 * when $_values_already_prepared_by_model_object equals this, we
61
+	 * assume this value is coming from a model object and doesn't need to have
62
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
63
+	 */
64
+	const prepared_by_model_object = 1;
65
+
66
+	/**
67
+	 * when $_values_already_prepared_by_model_object equals this, we assume
68
+	 * the values are already to be used in the database (ie no processing is done
69
+	 * on them by the model's fields)
70
+	 */
71
+	const prepared_for_use_in_db = 2;
72
+
73
+
74
+	protected $singular_item = 'Item';
75
+
76
+	protected $plural_item   = 'Items';
77
+
78
+	/**
79
+	 * @type EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
80
+	 */
81
+	protected $_tables;
82
+
83
+	/**
84
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
85
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
86
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
87
+	 *
88
+	 * @var EE_Model_Field_Base[][] $_fields
89
+	 */
90
+	protected $_fields;
91
+
92
+	/**
93
+	 * array of different kinds of relations
94
+	 *
95
+	 * @var EE_Model_Relation_Base[] $_model_relations
96
+	 */
97
+	protected $_model_relations = [];
98
+
99
+	/**
100
+	 * @var EE_Index[] $_indexes
101
+	 */
102
+	protected $_indexes = [];
103
+
104
+	/**
105
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
106
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
107
+	 * by setting the same columns as used in these queries in the query yourself.
108
+	 *
109
+	 * @var EE_Default_Where_Conditions
110
+	 */
111
+	protected $_default_where_conditions_strategy;
112
+
113
+	/**
114
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
115
+	 * This is particularly useful when you want something between 'none' and 'default'
116
+	 *
117
+	 * @var EE_Default_Where_Conditions
118
+	 */
119
+	protected $_minimum_where_conditions_strategy;
120
+
121
+	/**
122
+	 * String describing how to find the "owner" of this model's objects.
123
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
124
+	 * But when there isn't, this indicates which related model, or transiently-related model,
125
+	 * has the foreign key to the wp_users table.
126
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
127
+	 * related to events, and events have a foreign key to wp_users.
128
+	 * On EEM_Transaction, this would be 'Transaction.Event'
129
+	 *
130
+	 * @var string
131
+	 */
132
+	protected $_model_chain_to_wp_user = '';
133
+
134
+	/**
135
+	 * String describing how to find the model with a password controlling access to this model. This property has the
136
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
137
+	 * This value is the path of models to follow to arrive at the model with the password field.
138
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
139
+	 * model with a password that should affect reading this on the front-end.
140
+	 * Eg this is an empty string for the Event model because it has a password.
141
+	 * This is null for the Registration model, because its event's password has no bearing on whether
142
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
143
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
144
+	 * should hide tickets for datetimes for events that have a password set.
145
+	 *
146
+	 * @var string |null
147
+	 */
148
+	protected $model_chain_to_password = null;
149
+
150
+	/**
151
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
152
+	 * don't need it (particularly CPT models)
153
+	 *
154
+	 * @var bool
155
+	 */
156
+	protected $_ignore_where_strategy = false;
157
+
158
+	/**
159
+	 * String used in caps relating to this model. Eg, if the caps relating to this
160
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
161
+	 *
162
+	 * @var string. If null it hasn't been initialized yet. If false then we
163
+	 * have indicated capabilities don't apply to this
164
+	 */
165
+	protected $_caps_slug = null;
166
+
167
+	/**
168
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
169
+	 * and next-level keys are capability names, and each's value is a
170
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
171
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
172
+	 * and then each capability in the corresponding sub-array that they're missing
173
+	 * adds the where conditions onto the query.
174
+	 *
175
+	 * @var array
176
+	 */
177
+	protected $_cap_restrictions = [
178
+		self::caps_read       => [],
179
+		self::caps_read_admin => [],
180
+		self::caps_edit       => [],
181
+		self::caps_delete     => [],
182
+	];
183
+
184
+	/**
185
+	 * Array defining which cap restriction generators to use to create default
186
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
187
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
188
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
189
+	 * automatically set this to false (not just null).
190
+	 *
191
+	 * @var EE_Restriction_Generator_Base[]
192
+	 */
193
+	protected $_cap_restriction_generators = [];
194
+
195
+	/**
196
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
197
+	 */
198
+	const caps_read       = 'read';
199
+
200
+	const caps_read_admin = 'read_admin';
201
+
202
+	const caps_edit       = 'edit';
203
+
204
+	const caps_delete     = 'delete';
205
+
206
+	/**
207
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
208
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
209
+	 * maps to 'read' because when looking for relevant permissions we're going to use
210
+	 * 'read' in the capabilities names like 'ee_read_events' etc.
211
+	 *
212
+	 * @var array
213
+	 */
214
+	protected $_cap_contexts_to_cap_action_map = [
215
+		self::caps_read       => 'read',
216
+		self::caps_read_admin => 'read',
217
+		self::caps_edit       => 'edit',
218
+		self::caps_delete     => 'delete',
219
+	];
220
+
221
+	/**
222
+	 * Timezone
223
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
224
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
225
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
226
+	 * EE_Datetime_Field data type will have access to it.
227
+	 *
228
+	 * @var string
229
+	 */
230
+	protected $_timezone;
231
+
232
+
233
+	/**
234
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
235
+	 * multisite.
236
+	 *
237
+	 * @var int
238
+	 */
239
+	protected static $_model_query_blog_id;
240
+
241
+	/**
242
+	 * A copy of _fields, except the array keys are the model names pointed to by
243
+	 * the field
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cache_foreign_key_to_fields = [];
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, indexed by their name
251
+	 *
252
+	 * @var EE_Model_Field_Base[]
253
+	 */
254
+	private $_cached_fields = null;
255
+
256
+	/**
257
+	 * Cached list of all the fields on the model, except those that are
258
+	 * marked as only pertinent to the database
259
+	 *
260
+	 * @var EE_Model_Field_Base[]
261
+	 */
262
+	private $_cached_fields_non_db_only = null;
263
+
264
+	/**
265
+	 * A cached reference to the primary key for quick lookup
266
+	 *
267
+	 * @var EE_Model_Field_Base
268
+	 */
269
+	private $_primary_key_field = null;
270
+
271
+	/**
272
+	 * Flag indicating whether this model has a primary key or not
273
+	 *
274
+	 * @var boolean
275
+	 */
276
+	protected $_has_primary_key_field = null;
277
+
278
+	/**
279
+	 * array in the format:  [ FK alias => full PK ]
280
+	 * where keys are local column name aliases for foreign keys
281
+	 * and values are the fully qualified column name for the primary key they represent
282
+	 *  ex:
283
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
284
+	 *
285
+	 * @var array $foreign_key_aliases
286
+	 */
287
+	protected $foreign_key_aliases = [];
288
+
289
+	/**
290
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
291
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
292
+	 * This should be true for models that deal with data that should exist independent of EE.
293
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
294
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
295
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
296
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
297
+	 *
298
+	 * @var boolean
299
+	 */
300
+	protected $_wp_core_model = false;
301
+
302
+	/**
303
+	 * @var bool stores whether this model has a password field or not.
304
+	 * null until initialized by hasPasswordField()
305
+	 */
306
+	protected $has_password_field;
307
+
308
+	/**
309
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
310
+	 */
311
+	protected $password_field;
312
+
313
+	/**
314
+	 *    List of valid operators that can be used for querying.
315
+	 * The keys are all operators we'll accept, the values are the real SQL
316
+	 * operators used
317
+	 *
318
+	 * @var array
319
+	 */
320
+	protected $_valid_operators = [
321
+		'='           => '=',
322
+		'<='          => '<=',
323
+		'<'           => '<',
324
+		'>='          => '>=',
325
+		'>'           => '>',
326
+		'!='          => '!=',
327
+		'LIKE'        => 'LIKE',
328
+		'like'        => 'LIKE',
329
+		'NOT_LIKE'    => 'NOT LIKE',
330
+		'not_like'    => 'NOT LIKE',
331
+		'NOT LIKE'    => 'NOT LIKE',
332
+		'not like'    => 'NOT LIKE',
333
+		'IN'          => 'IN',
334
+		'in'          => 'IN',
335
+		'NOT_IN'      => 'NOT IN',
336
+		'not_in'      => 'NOT IN',
337
+		'NOT IN'      => 'NOT IN',
338
+		'not in'      => 'NOT IN',
339
+		'between'     => 'BETWEEN',
340
+		'BETWEEN'     => 'BETWEEN',
341
+		'IS_NOT_NULL' => 'IS NOT NULL',
342
+		'is_not_null' => 'IS NOT NULL',
343
+		'IS NOT NULL' => 'IS NOT NULL',
344
+		'is not null' => 'IS NOT NULL',
345
+		'IS_NULL'     => 'IS NULL',
346
+		'is_null'     => 'IS NULL',
347
+		'IS NULL'     => 'IS NULL',
348
+		'is null'     => 'IS NULL',
349
+		'REGEXP'      => 'REGEXP',
350
+		'regexp'      => 'REGEXP',
351
+		'NOT_REGEXP'  => 'NOT REGEXP',
352
+		'not_regexp'  => 'NOT REGEXP',
353
+		'NOT REGEXP'  => 'NOT REGEXP',
354
+		'not regexp'  => 'NOT REGEXP',
355
+	];
356
+
357
+	/**
358
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
359
+	 *
360
+	 * @var array
361
+	 */
362
+	protected $_in_style_operators = ['IN', 'NOT IN'];
363
+
364
+	/**
365
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
366
+	 * '12-31-2012'"
367
+	 *
368
+	 * @var array
369
+	 */
370
+	protected $_between_style_operators = ['BETWEEN'];
371
+
372
+	/**
373
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_like_style_operators = ['LIKE', 'NOT LIKE'];
378
+
379
+	/**
380
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
381
+	 * on a join table.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	protected $_null_style_operators = ['IS NOT NULL', 'IS NULL'];
386
+
387
+	/**
388
+	 * Allowed values for $query_params['order'] for ordering in queries
389
+	 *
390
+	 * @var array
391
+	 */
392
+	protected $_allowed_order_values = ['asc', 'desc', 'ASC', 'DESC'];
393
+
394
+	/**
395
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
396
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_logic_query_param_keys = ['not', 'and', 'or', 'NOT', 'AND', 'OR'];
401
+
402
+	/**
403
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
404
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
405
+	 *
406
+	 * @var array
407
+	 */
408
+	private $_allowed_query_params = [
409
+		0,
410
+		'limit',
411
+		'order_by',
412
+		'group_by',
413
+		'having',
414
+		'force_join',
415
+		'order',
416
+		'on_join_limit',
417
+		'default_where_conditions',
418
+		'caps',
419
+		'extra_selects',
420
+		'exclude_protected',
421
+	];
422
+
423
+	/**
424
+	 * All the data types that can be used in $wpdb->prepare statements.
425
+	 *
426
+	 * @var array
427
+	 */
428
+	private $_valid_wpdb_data_types = ['%d', '%s', '%f'];
429
+
430
+	/**
431
+	 * @var EE_Registry $EE
432
+	 */
433
+	protected $EE = null;
434
+
435
+
436
+	/**
437
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
438
+	 *
439
+	 * @var int
440
+	 */
441
+	protected $_show_next_x_db_queries = 0;
442
+
443
+	/**
444
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
445
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
446
+	 * WHERE, GROUP_BY, etc.
447
+	 *
448
+	 * @var CustomSelects
449
+	 */
450
+	protected $_custom_selections = [];
451
+
452
+	/**
453
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
454
+	 * caches every model object we've fetched from the DB on this request
455
+	 *
456
+	 * @var array
457
+	 */
458
+	protected $_entity_map;
459
+
460
+	/**
461
+	 * @var LoaderInterface
462
+	 */
463
+	protected static $loader;
464
+
465
+	/**
466
+	 * @var Mirror
467
+	 */
468
+	private static $mirror;
469
+
470
+
471
+	/**
472
+	 * constant used to show EEM_Base has not yet verified the db on this http request
473
+	 */
474
+	const db_verified_none = 0;
475
+
476
+	/**
477
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
478
+	 * but not the addons' dbs
479
+	 */
480
+	const db_verified_core = 1;
481
+
482
+	/**
483
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
484
+	 * the EE core db too)
485
+	 */
486
+	const db_verified_addons = 2;
487
+
488
+	/**
489
+	 * indicates whether an EEM_Base child has already re-verified the DB
490
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
491
+	 * looking like EEM_Base::db_verified_*
492
+	 *
493
+	 * @var int - 0 = none, 1 = core, 2 = addons
494
+	 */
495
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
496
+
497
+	/**
498
+	 * @deprecatd 5.0.40.p
499
+	 */
500
+	const default_where_conditions_all = EE_Default_Where_Conditions::ALL;
501
+
502
+	/**
503
+	 * @deprecatd 5.0.40.p
504
+	 */
505
+	const default_where_conditions_this_only = EE_Default_Where_Conditions::THIS_MODEL_ONLY;
506
+
507
+	/**
508
+	 * @deprecatd 5.0.40.p
509
+	 */
510
+	const default_where_conditions_others_only = EE_Default_Where_Conditions::OTHER_MODELS_ONLY;
511
+
512
+	/**
513
+	 * @deprecatd 5.0.40.p
514
+	 */
515
+	const default_where_conditions_minimum_all = EE_Default_Where_Conditions::MINIMUM_ALL;
516
+
517
+	/**
518
+	 * @deprecatd 5.0.40.p
519
+	 */
520
+	const default_where_conditions_minimum_others = EE_Default_Where_Conditions::MINIMUM_OTHERS;
521
+
522
+	/**
523
+	 * @deprecatd 5.0.40.p
524
+	 */
525
+	const default_where_conditions_none = EE_Default_Where_Conditions::NONE;
526
+
527
+
528
+	/**
529
+	 * About all child constructors:
530
+	 * they should define the _tables, _fields and _model_relations arrays.
531
+	 * Should ALWAYS be called after child constructor.
532
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
533
+	 * finalizes constructing all the object's attributes.
534
+	 * Generally, rather than requiring a child to code
535
+	 * $this->_tables = array(
536
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
537
+	 *        ...);
538
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
539
+	 * each EE_Table has a function to set the table's alias after the constructor, using
540
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
541
+	 * do something similar.
542
+	 *
543
+	 * @param string|null $timezone
544
+	 * @throws EE_Error
545
+	 * @throws Exception
546
+	 */
547
+	protected function __construct($timezone = '')
548
+	{
549
+		// check that the model has not been loaded too soon
550
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
551
+			throw new EE_Error(
552
+				sprintf(
553
+					esc_html__(
554
+						'The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
555
+						'event_espresso'
556
+					),
557
+					get_class($this)
558
+				)
559
+			);
560
+		}
561
+		/**
562
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
563
+		 */
564
+		if (empty(EEM_Base::$_model_query_blog_id)) {
565
+			EEM_Base::set_model_query_blog_id();
566
+		}
567
+		/**
568
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
569
+		 * just use EE_Register_Model_Extension
570
+		 *
571
+		 * @var EE_Table_Base[] $_tables
572
+		 */
573
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
574
+		foreach ($this->_tables as $table_alias => $table_obj) {
575
+			/** @var $table_obj EE_Table_Base */
576
+			$table_obj->_construct_finalize_with_alias($table_alias);
577
+			if ($table_obj instanceof EE_Secondary_Table) {
578
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
579
+			}
580
+		}
581
+		/**
582
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
583
+		 * EE_Register_Model_Extension
584
+		 *
585
+		 * @param EE_Model_Field_Base[] $_fields
586
+		 */
587
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
588
+		$this->_invalidate_field_caches();
589
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
590
+			if (! array_key_exists($table_alias, $this->_tables)) {
591
+				throw new EE_Error(
592
+					sprintf(
593
+						esc_html__(
594
+							"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
595
+							'event_espresso'
596
+						),
597
+						$table_alias,
598
+						implode(",", $this->_fields)
599
+					)
600
+				);
601
+			}
602
+			foreach ($fields_for_table as $field_name => $field_obj) {
603
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
604
+				// primary key field base has a slightly different _construct_finalize
605
+				/** @var $field_obj EE_Model_Field_Base */
606
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
607
+			}
608
+		}
609
+		// everything is related to Extra_Meta
610
+		if (get_class($this) !== 'EEM_Extra_Meta') {
611
+			// make extra meta related to everything, but don't block deleting things just
612
+			// because they have related extra meta info. For now just orphan those extra meta
613
+			// in the future we should automatically delete them
614
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
615
+		}
616
+		// and change logs
617
+		if (get_class($this) !== 'EEM_Change_Log') {
618
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
619
+		}
620
+		/**
621
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
622
+		 * EE_Register_Model_Extension
623
+		 *
624
+		 * @param EE_Model_Relation_Base[] $_model_relations
625
+		 */
626
+		$this->_model_relations = (array) apply_filters(
627
+			'FHEE__' . get_class($this) . '__construct__model_relations',
628
+			$this->_model_relations
629
+		);
630
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
631
+			/** @var $relation_obj EE_Model_Relation_Base */
632
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
633
+		}
634
+		foreach ($this->_indexes as $index_name => $index_obj) {
635
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
636
+		}
637
+		$this->set_timezone($timezone);
638
+		// finalize default where condition strategy, or set default
639
+		if (! $this->_default_where_conditions_strategy) {
640
+			// nothing was set during child constructor, so set default
641
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
642
+		}
643
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
644
+		if (! $this->_minimum_where_conditions_strategy) {
645
+			// nothing was set during child constructor, so set default
646
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
647
+		}
648
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
649
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
650
+		// to indicate to NOT set it, set it to the logical default
651
+		if ($this->_caps_slug === null) {
652
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
653
+		}
654
+		// initialize the standard cap restriction generators if none were specified by the child constructor
655
+		if (is_array($this->_cap_restriction_generators)) {
656
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
657
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
658
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
659
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
660
+						new EE_Restriction_Generator_Protected(),
661
+						$cap_context,
662
+						$this
663
+					);
664
+				}
665
+			}
666
+		}
667
+		// if there are cap restriction generators, use them to make the default cap restrictions
668
+		if (is_array($this->_cap_restriction_generators)) {
669
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
670
+				if (! $generator_object) {
671
+					continue;
672
+				}
673
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
674
+					throw new EE_Error(
675
+						sprintf(
676
+							esc_html__(
677
+								'Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
678
+								'event_espresso'
679
+							),
680
+							$context,
681
+							$this->get_this_model_name()
682
+						)
683
+					);
684
+				}
685
+				$action = $this->cap_action_for_context($context);
686
+				if (! $generator_object->construction_finalized()) {
687
+					$generator_object->_construct_finalize($this, $action);
688
+				}
689
+			}
690
+		}
691
+		do_action('AHEE__' . get_class($this) . '__construct__end');
692
+	}
693
+
694
+
695
+	/**
696
+	 * @return LoaderInterface
697
+	 * @throws InvalidArgumentException
698
+	 * @throws InvalidDataTypeException
699
+	 * @throws InvalidInterfaceException
700
+	 */
701
+	protected static function getLoader(): LoaderInterface
702
+	{
703
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
704
+			EEM_Base::$loader = LoaderFactory::getLoader();
705
+		}
706
+		return EEM_Base::$loader;
707
+	}
708
+
709
+
710
+	/**
711
+	 * @return Mirror
712
+	 * @since   5.0.0.p
713
+	 */
714
+	private static function getMirror(): Mirror
715
+	{
716
+		if (! EEM_Base::$mirror instanceof Mirror) {
717
+			EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
718
+		}
719
+		return EEM_Base::$mirror;
720
+	}
721
+
722
+
723
+	/**
724
+	 * @param string $model_class_Name
725
+	 * @param string $timezone
726
+	 * @return array
727
+	 * @throws ReflectionException
728
+	 * @since   5.0.0.p
729
+	 */
730
+	private static function getModelArguments(string $model_class_Name, string $timezone): array
731
+	{
732
+		$arguments = [$timezone];
733
+		$params    = EEM_Base::getMirror()->getParameters($model_class_Name);
734
+		if (count($params) > 1) {
735
+			if ($params[1]->getName() === 'model_field_factory') {
736
+				$arguments = [
737
+					$timezone,
738
+					EEM_Base::getLoader()->getShared(ModelFieldFactory::class),
739
+				];
740
+			} elseif ($model_class_Name === 'EEM_Form_Section') {
741
+				$arguments = [
742
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
743
+					$timezone,
744
+				];
745
+			} elseif ($model_class_Name === 'EEM_Form_Element') {
746
+				$arguments = [
747
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\FormStatus'),
748
+					EEM_Base::getLoader()->getShared('EventEspresso\core\services\form\meta\InputTypes'),
749
+					$timezone,
750
+				];
751
+			}
752
+		}
753
+		return $arguments;
754
+	}
755
+
756
+
757
+	/**
758
+	 * This function is a singleton method used to instantiate the Espresso_model object
759
+	 *
760
+	 * @param string|null $timezone   string representing the timezone we want to set for returned Date Time Strings
761
+	 *                                (and any incoming timezone data that gets saved).
762
+	 *                                Note this just sends the timezone info to the date time model field objects.
763
+	 *                                Default is NULL
764
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
765
+	 * @return static (as in the concrete child class)
766
+	 * @throws EE_Error
767
+	 * @throws ReflectionException
768
+	 */
769
+	public static function instance($timezone = '')
770
+	{
771
+		// check if instance of Espresso_model already exists
772
+		if (! static::$_instance instanceof static) {
773
+			$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
774
+			$model     = new static(...$arguments);
775
+			EEM_Base::getLoader()->share(static::class, $model, $arguments);
776
+			static::$_instance = $model;
777
+		}
778
+		// we might have a timezone set, let set_timezone decide what to do with it
779
+		if ($timezone) {
780
+			static::$_instance->set_timezone($timezone);
781
+		}
782
+		// Espresso_model object
783
+		return static::$_instance;
784
+	}
785
+
786
+
787
+	/**
788
+	 * resets the model and returns it
789
+	 *
790
+	 * @param string|null $timezone
791
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
792
+	 * all its properties reset; if it wasn't instantiated, returns null)
793
+	 * @throws EE_Error
794
+	 * @throws ReflectionException
795
+	 * @throws InvalidArgumentException
796
+	 * @throws InvalidDataTypeException
797
+	 * @throws InvalidInterfaceException
798
+	 */
799
+	public static function reset($timezone = '')
800
+	{
801
+		if (! static::$_instance instanceof EEM_Base) {
802
+			return null;
803
+		}
804
+		// Let's NOT swap out the current instance for a new one
805
+		// because if someone has a reference to it, we can't remove their reference.
806
+		// It's best to keep using the same reference but change the original object instead,
807
+		// so reset all its properties to their original values as defined in the class.
808
+		$static_properties = EEM_Base::getMirror()->getStaticProperties(static::class);
809
+		foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
810
+			// don't set instance to null like it was originally,
811
+			// but it's static anyways, and we're ignoring static properties (for now at least)
812
+			if (! isset($static_properties[ $property ])) {
813
+				static::$_instance->{$property} = $value;
814
+			}
815
+		}
816
+		// and then directly call its constructor again, like we would if we were creating a new one
817
+		$arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
818
+		static::$_instance->__construct(...$arguments);
819
+		return self::instance();
820
+	}
821
+
822
+
823
+	/**
824
+	 * Used to set the $_model_query_blog_id static property.
825
+	 *
826
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
827
+	 *                      value for get_current_blog_id() will be used.
828
+	 */
829
+	public static function set_model_query_blog_id($blog_id = 0)
830
+	{
831
+		EEM_Base::$_model_query_blog_id = $blog_id > 0
832
+			? (int) $blog_id
833
+			: get_current_blog_id();
834
+	}
835
+
836
+
837
+	/**
838
+	 * Returns whatever is set as the internal $model_query_blog_id.
839
+	 *
840
+	 * @return int
841
+	 */
842
+	public static function get_model_query_blog_id()
843
+	{
844
+		return EEM_Base::$_model_query_blog_id;
845
+	}
846
+
847
+
848
+	/**
849
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
850
+	 *
851
+	 * @param boolean $translated return localized strings or JUST the array.
852
+	 * @return array
853
+	 * @throws EE_Error
854
+	 * @throws InvalidArgumentException
855
+	 * @throws InvalidDataTypeException
856
+	 * @throws InvalidInterfaceException
857
+	 * @throws ReflectionException
858
+	 */
859
+	public function status_array($translated = false)
860
+	{
861
+		if (! array_key_exists('Status', $this->_model_relations)) {
862
+			return [];
863
+		}
864
+		$model_name   = $this->get_this_model_name();
865
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
866
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
867
+		$status_array = [];
868
+		foreach ($stati as $status) {
869
+			$status_array[ $status->ID() ] = $status->get('STS_code');
870
+		}
871
+		return $translated
872
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
873
+			: $status_array;
874
+	}
875
+
876
+
877
+	/**
878
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
879
+	 *
880
+	 * @param array $query_params             @see
881
+	 *                                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
882
+	 *                                        or if you have the development copy of EE you can view this at the path:
883
+	 *                                        /docs/G--Model-System/model-query-params.md
884
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
885
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
886
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
887
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
888
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
889
+	 *                                        'OR'=>array(
890
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
891
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
892
+	 *                                        )
893
+	 *                                        ),
894
+	 *                                        'limit'=>10,
895
+	 *                                        'group_by'=>'TXN_ID'
896
+	 *                                        ));
897
+	 *                                        get all the answers to the question titled "shirt size" for event with id
898
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
899
+	 *                                        'Question.QST_display_text'=>'shirt size',
900
+	 *                                        'Registration.Event.EVT_ID'=>12
901
+	 *                                        ),
902
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
903
+	 *                                        ));
904
+	 * @throws EE_Error
905
+	 * @throws ReflectionException
906
+	 */
907
+	public function get_all($query_params = [])
908
+	{
909
+		if (
910
+			isset($query_params['limit'])
911
+			&& ! isset($query_params['group_by'])
912
+		) {
913
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
914
+		}
915
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
916
+	}
917
+
918
+
919
+	/**
920
+	 * Modifies the query parameters so we only get back model objects
921
+	 * that "belong" to the current user
922
+	 *
923
+	 * @param array $query_params @see
924
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
925
+	 * @return array @see
926
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
927
+	 * @throws ReflectionException
928
+	 * @throws ReflectionException
929
+	 */
930
+	public function alter_query_params_to_only_include_mine($query_params = [])
931
+	{
932
+		$wp_user_field_name = $this->wp_user_field_name();
933
+		if ($wp_user_field_name) {
934
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
935
+		}
936
+		return $query_params;
937
+	}
938
+
939
+
940
+	/**
941
+	 * Returns the name of the field's name that points to the WP_User table
942
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
943
+	 * foreign key to the WP_User table)
944
+	 *
945
+	 * @return string|boolean string on success, boolean false when there is no
946
+	 * foreign key to the WP_User table
947
+	 * @throws ReflectionException
948
+	 * @throws ReflectionException
949
+	 */
950
+	public function wp_user_field_name()
951
+	{
952
+		try {
953
+			if (! empty($this->_model_chain_to_wp_user)) {
954
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
955
+				$last_model_name              = end($models_to_follow_to_wp_users);
956
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
957
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
958
+			} else {
959
+				$model_with_fk_to_wp_users = $this;
960
+				$model_chain_to_wp_user    = '';
961
+			}
962
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
963
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
964
+		} catch (EE_Error $e) {
965
+			return false;
966
+		}
967
+	}
968
+
969
+
970
+	/**
971
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
972
+	 * (or transiently-related model) has a foreign key to the wp_users table;
973
+	 * useful for finding if model objects of this type are 'owned' by the current user.
974
+	 * This is an empty string when the foreign key is on this model and when it isn't,
975
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
976
+	 * (or transiently-related model)
977
+	 *
978
+	 * @return string
979
+	 */
980
+	public function model_chain_to_wp_user()
981
+	{
982
+		return $this->_model_chain_to_wp_user;
983
+	}
984
+
985
+
986
+	/**
987
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
988
+	 * like how registrations don't have a foreign key to wp_users, but the
989
+	 * events they are for are), or is unrelated to wp users.
990
+	 * generally available
991
+	 *
992
+	 * @return boolean
993
+	 */
994
+	public function is_owned()
995
+	{
996
+		if ($this->model_chain_to_wp_user()) {
997
+			return true;
998
+		}
999
+		try {
1000
+			$this->get_foreign_key_to('WP_User');
1001
+			return true;
1002
+		} catch (EE_Error $e) {
1003
+			return false;
1004
+		}
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1010
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1011
+	 * the model)
1012
+	 *
1013
+	 * @param array  $query_params      @see
1014
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1015
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1016
+	 * @param mixed  $columns_to_select What columns to select. By default, we select all columns specified by the
1017
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1018
+	 *                                  override this and set the select to "*", or a specific column name, like
1019
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1020
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1021
+	 *                                  the aliases used to refer to this selection, and values are to be
1022
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1023
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1024
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1025
+	 * @throws EE_Error
1026
+	 * @throws InvalidArgumentException
1027
+	 * @throws ReflectionException
1028
+	 */
1029
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1030
+	{
1031
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1032
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1033
+		$select_expressions       = $columns_to_select === null
1034
+			? $this->_construct_default_select_sql($model_query_info)
1035
+			: '';
1036
+		if ($this->_custom_selections instanceof CustomSelects) {
1037
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1038
+			$select_expressions .= $select_expressions
1039
+				? ', ' . $custom_expressions
1040
+				: $custom_expressions;
1041
+		}
1042
+
1043
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1044
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1045
+	}
1046
+
1047
+
1048
+	/**
1049
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1050
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1051
+	 * method of including extra select information.
1052
+	 *
1053
+	 * @param array             $query_params
1054
+	 * @param null|array|string $columns_to_select
1055
+	 * @return null|CustomSelects
1056
+	 * @throws InvalidArgumentException
1057
+	 */
1058
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1059
+	{
1060
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1061
+			return null;
1062
+		}
1063
+		$selects = $query_params['extra_selects'] ?? $columns_to_select;
1064
+		$selects = is_string($selects)
1065
+			? explode(',', $selects)
1066
+			: $selects;
1067
+		return new CustomSelects($selects);
1068
+	}
1069
+
1070
+
1071
+	/**
1072
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1073
+	 * but you can use the model query params to more easily
1074
+	 * take care of joins, field preparation etc.
1075
+	 *
1076
+	 * @param array  $query_params      @see
1077
+	 *                                  https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1078
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1079
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1080
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1081
+	 *                                  override this and set the select to "*", or a specific column name, like
1082
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1083
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1084
+	 *                                  the aliases used to refer to this selection, and values are to be
1085
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1086
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1087
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1088
+	 * @throws EE_Error
1089
+	 * @throws ReflectionException
1090
+	 */
1091
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1092
+	{
1093
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1094
+	}
1095
+
1096
+
1097
+	/**
1098
+	 * For creating a custom select statement
1099
+	 *
1100
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1101
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1102
+	 *                                 SQL, and 1=>is the datatype
1103
+	 * @return string
1104
+	 * @throws EE_Error
1105
+	 */
1106
+	private function _construct_select_from_input($columns_to_select)
1107
+	{
1108
+		if (is_array($columns_to_select)) {
1109
+			$select_sql_array = [];
1110
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1111
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1112
+					throw new EE_Error(
1113
+						sprintf(
1114
+							esc_html__(
1115
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1116
+								'event_espresso'
1117
+							),
1118
+							$selection_and_datatype,
1119
+							$alias
1120
+						)
1121
+					);
1122
+				}
1123
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1124
+					throw new EE_Error(
1125
+						sprintf(
1126
+							esc_html__(
1127
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1128
+								'event_espresso'
1129
+							),
1130
+							$selection_and_datatype[1],
1131
+							$selection_and_datatype[0],
1132
+							$alias,
1133
+							implode(', ', $this->_valid_wpdb_data_types)
1134
+						)
1135
+					);
1136
+				}
1137
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1138
+			}
1139
+			$columns_to_select_string = implode(', ', $select_sql_array);
1140
+		} else {
1141
+			$columns_to_select_string = $columns_to_select;
1142
+		}
1143
+		return $columns_to_select_string;
1144
+	}
1145
+
1146
+
1147
+	/**
1148
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1149
+	 *
1150
+	 * @return string
1151
+	 * @throws EE_Error
1152
+	 */
1153
+	public function primary_key_name()
1154
+	{
1155
+		return $this->get_primary_key_field()->get_name();
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1161
+	 * If there is no primary key on this model, $id is treated as primary key string
1162
+	 *
1163
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1164
+	 * @return EE_Base_Class|mixed|null
1165
+	 * @throws EE_Error
1166
+	 * @throws ReflectionException
1167
+	 */
1168
+	public function get_one_by_ID($id)
1169
+	{
1170
+		// since entities with no ID can still have properties, we need to check the cache for them
1171
+		$cached_value = $this->get_from_entity_map($id);
1172
+		if ($cached_value) {
1173
+			return $cached_value;
1174
+		}
1175
+		// but if no cached property AND no id is passed, just return null
1176
+		if (empty($id)) {
1177
+			return null;
1178
+		}
1179
+		$model_object = $this->get_one(
1180
+			$this->alter_query_params_to_restrict_by_ID(
1181
+				$id,
1182
+				['default_where_conditions' => EE_Default_Where_Conditions::MINIMUM_ALL]
1183
+			)
1184
+		);
1185
+		$className    = $this->_get_class_name();
1186
+		if ($model_object instanceof $className) {
1187
+			// make sure valid objects get added to the entity map
1188
+			// so that the next call to this method doesn't trigger another trip to the db
1189
+			$this->add_to_entity_map($model_object);
1190
+		}
1191
+		return $model_object;
1192
+	}
1193
+
1194
+
1195
+	/**
1196
+	 * Alters query parameters to only get items with this ID are returned.
1197
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1198
+	 * or could just be a simple primary key ID
1199
+	 *
1200
+	 * @param int   $id
1201
+	 * @param array $query_params
1202
+	 * @return array of normal query params, @see
1203
+	 *               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1204
+	 * @throws EE_Error
1205
+	 */
1206
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1207
+	{
1208
+		if (! isset($query_params[0])) {
1209
+			$query_params[0] = [];
1210
+		}
1211
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1212
+		if ($conditions_from_id === null) {
1213
+			$query_params[0][ $this->primary_key_name() ] = $id;
1214
+		} else {
1215
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1216
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1217
+		}
1218
+		return $query_params;
1219
+	}
1220
+
1221
+
1222
+	/**
1223
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1224
+	 * array. If no item is found, null is returned.
1225
+	 *
1226
+	 * @param array $query_params like EEM_Base's $query_params variable.
1227
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1228
+	 * @throws EE_Error
1229
+	 * @throws ReflectionException
1230
+	 */
1231
+	public function get_one($query_params = [])
1232
+	{
1233
+		if (! is_array($query_params)) {
1234
+			EE_Error::doing_it_wrong(
1235
+				'EEM_Base::get_one',
1236
+				sprintf(
1237
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1238
+					gettype($query_params)
1239
+				),
1240
+				'4.6.0'
1241
+			);
1242
+			$query_params = [];
1243
+		}
1244
+		$query_params['limit'] = 1;
1245
+		$items                 = $this->get_all($query_params);
1246
+		if (empty($items)) {
1247
+			return null;
1248
+		}
1249
+		return array_shift($items);
1250
+	}
1251
+
1252
+
1253
+	/**
1254
+	 * Returns the next x number of items in sequence from the given value as
1255
+	 * found in the database matching the given query conditions.
1256
+	 *
1257
+	 * @param mixed $current_field_value    Value used for the reference point.
1258
+	 * @param null  $field_to_order_by      What field is used for the
1259
+	 *                                      reference point.
1260
+	 * @param int   $limit                  How many to return.
1261
+	 * @param array $query_params           Extra conditions on the query.
1262
+	 * @param null  $columns_to_select      If left null, then an array of
1263
+	 *                                      EE_Base_Class objects is returned,
1264
+	 *                                      otherwise you can indicate just the
1265
+	 *                                      columns you want returned.
1266
+	 * @return EE_Base_Class[]|array
1267
+	 * @throws EE_Error
1268
+	 * @throws ReflectionException
1269
+	 */
1270
+	public function next_x(
1271
+		$current_field_value,
1272
+		$field_to_order_by = null,
1273
+		$limit = 1,
1274
+		$query_params = [],
1275
+		$columns_to_select = null
1276
+	) {
1277
+		return $this->_get_consecutive(
1278
+			$current_field_value,
1279
+			'>',
1280
+			$field_to_order_by,
1281
+			$limit,
1282
+			$query_params,
1283
+			$columns_to_select
1284
+		);
1285
+	}
1286
+
1287
+
1288
+	/**
1289
+	 * Returns the previous x number of items in sequence from the given value
1290
+	 * as found in the database matching the given query conditions.
1291
+	 *
1292
+	 * @param mixed $current_field_value    Value used for the reference point.
1293
+	 * @param null  $field_to_order_by      What field is used for the
1294
+	 *                                      reference point.
1295
+	 * @param int   $limit                  How many to return.
1296
+	 * @param array $query_params           Extra conditions on the query.
1297
+	 * @param null  $columns_to_select      If left null, then an array of
1298
+	 *                                      EE_Base_Class objects is returned,
1299
+	 *                                      otherwise you can indicate just the
1300
+	 *                                      columns you want returned.
1301
+	 * @return EE_Base_Class[]|array
1302
+	 * @throws EE_Error
1303
+	 * @throws ReflectionException
1304
+	 */
1305
+	public function previous_x(
1306
+		$current_field_value,
1307
+		$field_to_order_by = null,
1308
+		$limit = 1,
1309
+		$query_params = [],
1310
+		$columns_to_select = null
1311
+	) {
1312
+		return $this->_get_consecutive(
1313
+			$current_field_value,
1314
+			'<',
1315
+			$field_to_order_by,
1316
+			$limit,
1317
+			$query_params,
1318
+			$columns_to_select
1319
+		);
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * Returns the next item in sequence from the given value as found in the
1325
+	 * database matching the given query conditions.
1326
+	 *
1327
+	 * @param mixed $current_field_value    Value used for the reference point.
1328
+	 * @param null  $field_to_order_by      What field is used for the
1329
+	 *                                      reference point.
1330
+	 * @param array $query_params           Extra conditions on the query.
1331
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1332
+	 *                                      object is returned, otherwise you
1333
+	 *                                      can indicate just the columns you
1334
+	 *                                      want and a single array indexed by
1335
+	 *                                      the columns will be returned.
1336
+	 * @return EE_Base_Class|null|array()
1337
+	 * @throws EE_Error
1338
+	 * @throws ReflectionException
1339
+	 */
1340
+	public function next(
1341
+		$current_field_value,
1342
+		$field_to_order_by = null,
1343
+		$query_params = [],
1344
+		$columns_to_select = null
1345
+	) {
1346
+		$results = $this->_get_consecutive(
1347
+			$current_field_value,
1348
+			'>',
1349
+			$field_to_order_by,
1350
+			1,
1351
+			$query_params,
1352
+			$columns_to_select
1353
+		);
1354
+		return empty($results)
1355
+			? null
1356
+			: reset($results);
1357
+	}
1358
+
1359
+
1360
+	/**
1361
+	 * Returns the previous item in sequence from the given value as found in
1362
+	 * the database matching the given query conditions.
1363
+	 *
1364
+	 * @param mixed $current_field_value    Value used for the reference point.
1365
+	 * @param null  $field_to_order_by      What field is used for the
1366
+	 *                                      reference point.
1367
+	 * @param array $query_params           Extra conditions on the query.
1368
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1369
+	 *                                      object is returned, otherwise you
1370
+	 *                                      can indicate just the columns you
1371
+	 *                                      want and a single array indexed by
1372
+	 *                                      the columns will be returned.
1373
+	 * @return EE_Base_Class|null|array()
1374
+	 * @throws EE_Error
1375
+	 * @throws ReflectionException
1376
+	 */
1377
+	public function previous(
1378
+		$current_field_value,
1379
+		$field_to_order_by = null,
1380
+		$query_params = [],
1381
+		$columns_to_select = null
1382
+	) {
1383
+		$results = $this->_get_consecutive(
1384
+			$current_field_value,
1385
+			'<',
1386
+			$field_to_order_by,
1387
+			1,
1388
+			$query_params,
1389
+			$columns_to_select
1390
+		);
1391
+		return empty($results)
1392
+			? null
1393
+			: reset($results);
1394
+	}
1395
+
1396
+
1397
+	/**
1398
+	 * Returns the a consecutive number of items in sequence from the given
1399
+	 * value as found in the database matching the given query conditions.
1400
+	 *
1401
+	 * @param mixed  $current_field_value   Value used for the reference point.
1402
+	 * @param string $operand               What operand is used for the sequence.
1403
+	 * @param string $field_to_order_by     What field is used for the reference point.
1404
+	 * @param int    $limit                 How many to return.
1405
+	 * @param array  $query_params          Extra conditions on the query.
1406
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1407
+	 *                                      otherwise you can indicate just the columns you want returned.
1408
+	 * @return EE_Base_Class[]|array
1409
+	 * @throws EE_Error
1410
+	 * @throws ReflectionException
1411
+	 */
1412
+	protected function _get_consecutive(
1413
+		$current_field_value,
1414
+		$operand = '>',
1415
+		$field_to_order_by = null,
1416
+		$limit = 1,
1417
+		$query_params = [],
1418
+		$columns_to_select = null
1419
+	) {
1420
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1421
+		if (empty($field_to_order_by)) {
1422
+			if ($this->has_primary_key_field()) {
1423
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1424
+			} else {
1425
+				if (defined('WP_DEBUG') && WP_DEBUG) {
1426
+					throw new EE_Error(
1427
+						esc_html__(
1428
+							'EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1429
+							'event_espresso'
1430
+						)
1431
+					);
1432
+				}
1433
+				EE_Error::add_error(
1434
+					esc_html__('There was an error with the query.', 'event_espresso'),
1435
+					__FILE__,
1436
+					__FUNCTION__,
1437
+					__LINE__
1438
+				);
1439
+				return [];
1440
+			}
1441
+		}
1442
+		if (! is_array($query_params)) {
1443
+			EE_Error::doing_it_wrong(
1444
+				'EEM_Base::_get_consecutive',
1445
+				sprintf(
1446
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1447
+					gettype($query_params)
1448
+				),
1449
+				'4.6.0'
1450
+			);
1451
+			$query_params = [];
1452
+		}
1453
+		// let's add the where query param for consecutive look up.
1454
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1455
+		$query_params['limit']                 = $limit;
1456
+		// set direction
1457
+		$incoming_orderby         = isset($query_params['order_by'])
1458
+			? (array) $query_params['order_by']
1459
+			: [];
1460
+		$query_params['order_by'] = $operand === '>'
1461
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1462
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1463
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1464
+		if (empty($columns_to_select)) {
1465
+			return $this->get_all($query_params);
1466
+		}
1467
+		// getting just the fields
1468
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1469
+	}
1470
+
1471
+
1472
+	/**
1473
+	 * This sets the _timezone property after model object has been instantiated.
1474
+	 *
1475
+	 * @param string|null $timezone valid PHP DateTimeZone timezone string
1476
+	 * @throws Exception
1477
+	 */
1478
+	public function set_timezone(?string $timezone = '')
1479
+	{
1480
+		if (! $timezone) {
1481
+			return;
1482
+		}
1483
+		$this->_timezone = $timezone;
1484
+		// note we need to loop through relations and set the timezone on those objects as well.
1485
+		foreach ($this->_model_relations as $relation) {
1486
+			$relation->set_timezone($timezone);
1487
+		}
1488
+		// and finally we do the same for any datetime fields
1489
+		foreach ($this->_fields as $field) {
1490
+			if ($field instanceof EE_Datetime_Field) {
1491
+				$field->set_timezone($timezone);
1492
+			}
1493
+		}
1494
+	}
1495
+
1496
+
1497
+	/**
1498
+	 * This just returns whatever is set for the current timezone.
1499
+	 *
1500
+	 * @access public
1501
+	 * @return string
1502
+	 * @throws Exception
1503
+	 */
1504
+	public function get_timezone()
1505
+	{
1506
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1507
+		if (empty($this->_timezone)) {
1508
+			foreach ($this->_fields as $field) {
1509
+				if ($field instanceof EE_Datetime_Field) {
1510
+					$this->set_timezone($field->get_timezone());
1511
+					break;
1512
+				}
1513
+			}
1514
+		}
1515
+		// if timezone STILL empty then return the default timezone for the site.
1516
+		if (empty($this->_timezone)) {
1517
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1518
+		}
1519
+		return $this->_timezone;
1520
+	}
1521
+
1522
+
1523
+	/**
1524
+	 * This returns the date formats set for the given field name and also ensures that
1525
+	 * $this->_timezone property is set correctly.
1526
+	 *
1527
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1528
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1529
+	 * @return array formats in an array with the date format first, and the time format last.
1530
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1531
+	 * @since 4.6.x
1532
+	 */
1533
+	public function get_formats_for($field_name, $pretty = false)
1534
+	{
1535
+		$field_settings = $this->field_settings_for($field_name);
1536
+		// if not a valid EE_Datetime_Field then throw error
1537
+		if (! $field_settings instanceof EE_Datetime_Field) {
1538
+			throw new EE_Error(
1539
+				sprintf(
1540
+					esc_html__(
1541
+						'The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1542
+						'event_espresso'
1543
+					),
1544
+					$field_name
1545
+				)
1546
+			);
1547
+		}
1548
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1549
+		// the field.
1550
+		$this->_timezone = $field_settings->get_timezone();
1551
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1552
+	}
1553
+
1554
+
1555
+	/**
1556
+	 * This returns the current time in a format setup for a query on this model.
1557
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1558
+	 * it will return:
1559
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1560
+	 *  NOW
1561
+	 *  - or a unix timestamp (equivalent to time())
1562
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1563
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1564
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1565
+	 *
1566
+	 * @param string $field_name       The field the current time is needed for.
1567
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1568
+	 *                                 formatted string matching the set format for the field in the set timezone will
1569
+	 *                                 be returned.
1570
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1571
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1572
+	 *                                 exception is triggered.
1573
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1574
+	 * @throws Exception
1575
+	 * @since 4.6.x
1576
+	 */
1577
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1578
+	{
1579
+		$formats  = $this->get_formats_for($field_name);
1580
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1581
+		if ($timestamp) {
1582
+			return $DateTime->format('U');
1583
+		}
1584
+		// not returning timestamp, so return formatted string in timezone.
1585
+		switch ($what) {
1586
+			case 'time':
1587
+				return $DateTime->format($formats[1]);
1588
+			case 'date':
1589
+				return $DateTime->format($formats[0]);
1590
+			default:
1591
+				return $DateTime->format(implode(' ', $formats));
1592
+		}
1593
+	}
1594
+
1595
+
1596
+	/**
1597
+	 * This receives a time string for a given field and ensures
1598
+	 * that it is set up to match what the internal settings for the model are.
1599
+	 * Returns a DateTime object.
1600
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1601
+	 * (functionally the equivalent of UTC+0).
1602
+	 * So when you send it in, whatever timezone string you include is ignored.
1603
+	 *
1604
+	 * @param string      $field_name      The field being setup.
1605
+	 * @param string      $timestring      The date time string being used.
1606
+	 * @param string      $incoming_format The format for the time string.
1607
+	 * @param string|null $timezone_string By default, it is assumed the incoming time string is in timezone for
1608
+	 *                                     the blog.  If this is not the case, then it can be specified here.  If
1609
+	 *                                     incoming format is
1610
+	 *                                     'U', this is ignored.
1611
+	 * @return DbSafeDateTime
1612
+	 * @throws EE_Error
1613
+	 * @throws Exception
1614
+	 */
1615
+	public function convert_datetime_for_query(
1616
+		string $field_name,
1617
+		string $timestring,
1618
+		string $incoming_format,
1619
+		?string $timezone_string = ''
1620
+	): DbSafeDateTime {
1621
+		// just using this to ensure the timezone is set correctly internally
1622
+		$this->get_formats_for($field_name);
1623
+		// load EEH_DTT_Helper
1624
+		$timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1625
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1626
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1627
+		return DbSafeDateTime::createFromDateTime($incomingDateTime);
1628
+	}
1629
+
1630
+
1631
+	/**
1632
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1633
+	 *
1634
+	 * @return EE_Table_Base[]
1635
+	 */
1636
+	public function get_tables()
1637
+	{
1638
+		return $this->_tables;
1639
+	}
1640
+
1641
+
1642
+	/**
1643
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1644
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1645
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1646
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1647
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1648
+	 * model object with EVT_ID = 1
1649
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1650
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1651
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1652
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1653
+	 * are not specified)
1654
+	 *
1655
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1656
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1657
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1658
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1659
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1660
+	 *                                         ID=34, we'd use this method as follows:
1661
+	 *                                         EEM_Transaction::instance()->update(
1662
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1663
+	 *                                         array(array('TXN_ID'=>34)));
1664
+	 * @param array   $query_params            @see
1665
+	 *                                         https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1666
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1667
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1668
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1669
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1670
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1671
+	 *                                         TRUE, it is assumed that you've already called
1672
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1673
+	 *                                         malicious javascript. However, if
1674
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1675
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1676
+	 *                                         and every other field, before insertion. We provide this parameter
1677
+	 *                                         because model objects perform their prepare_for_set function on all
1678
+	 *                                         their values, and so don't need to be called again (and in many cases,
1679
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1680
+	 *                                         prepare_for_set method...)
1681
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1682
+	 *                                         in this model's entity map according to $fields_n_values that match
1683
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1684
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1685
+	 *                                         could get out-of-sync with the database
1686
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1687
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1688
+	 *                                         bad)
1689
+	 * @throws EE_Error
1690
+	 * @throws ReflectionException
1691
+	 */
1692
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1693
+	{
1694
+		if (! is_array($query_params)) {
1695
+			EE_Error::doing_it_wrong(
1696
+				'EEM_Base::update',
1697
+				sprintf(
1698
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1699
+					gettype($query_params)
1700
+				),
1701
+				'4.6.0'
1702
+			);
1703
+			$query_params = [];
1704
+		}
1705
+		/**
1706
+		 * Action called before a model update call has been made.
1707
+		 *
1708
+		 * @param EEM_Base $model
1709
+		 * @param array    $fields_n_values the updated fields and their new values
1710
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1711
+		 */
1712
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1713
+		/**
1714
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1715
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1716
+		 *
1717
+		 * @param array    $fields_n_values fields and their new values
1718
+		 * @param EEM_Base $model           the model being queried
1719
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1720
+		 */
1721
+		$fields_n_values = (array) apply_filters(
1722
+			'FHEE__EEM_Base__update__fields_n_values',
1723
+			$fields_n_values,
1724
+			$this,
1725
+			$query_params
1726
+		);
1727
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1728
+		// to do that, for each table, verify that it's PK isn't null.
1729
+		$tables = $this->get_tables();
1730
+		// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1731
+		// NOTE: we should make this code more efficient by NOT querying twice
1732
+		// before the real update, but that needs to first go through ALPHA testing
1733
+		// as it's dangerous. says Mike August 8 2014
1734
+		// we want to make sure the default_where strategy is ignored
1735
+		$this->_ignore_where_strategy = true;
1736
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1737
+		foreach ($wpdb_select_results as $wpdb_result) {
1738
+			// type cast stdClass as array
1739
+			$wpdb_result = (array) $wpdb_result;
1740
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1741
+			if ($this->has_primary_key_field()) {
1742
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1743
+			} else {
1744
+				// if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1745
+				$main_table_pk_value = null;
1746
+			}
1747
+			// if there are more than 1 tables, we'll want to verify that each table for this model has an entry in the other tables
1748
+			// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1749
+			if (count($tables) > 1) {
1750
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1751
+				// in that table, and so we'll want to insert one
1752
+				foreach ($tables as $table_obj) {
1753
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1754
+					// if there is no private key for this table on the results, it means there's no entry
1755
+					// in this table, right? so insert a row in the current table, using any fields available
1756
+					if (
1757
+						! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
+						   && $wpdb_result[ $this_table_pk_column ])
1759
+					) {
1760
+						$success = $this->_insert_into_specific_table(
1761
+							$table_obj,
1762
+							$fields_n_values,
1763
+							$main_table_pk_value
1764
+						);
1765
+						// if we died here, report the error
1766
+						if (! $success) {
1767
+							return false;
1768
+						}
1769
+					}
1770
+				}
1771
+			}
1772
+			//              //and now check that if we have cached any models by that ID on the model, that
1773
+			//              //they also get updated properly
1774
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1775
+			//              if( $model_object ){
1776
+			//                  foreach( $fields_n_values as $field => $value ){
1777
+			//                      $model_object->set($field, $value);
1778
+			// let's make sure default_where strategy is followed now
1779
+			$this->_ignore_where_strategy = false;
1780
+		}
1781
+		// if we want to keep model objects in sync, AND
1782
+		// if this wasn't called from a model object (to update itself)
1783
+		// then we want to make sure we keep all the existing
1784
+		// model objects in sync with the db
1785
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1786
+			if ($this->has_primary_key_field()) {
1787
+				$model_objs_affected_ids = $this->get_col($query_params);
1788
+			} else {
1789
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1790
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1791
+				$model_objs_affected_ids     = [];
1792
+				foreach ($models_affected_key_columns as $row) {
1793
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1794
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1795
+				}
1796
+			}
1797
+			if (! $model_objs_affected_ids) {
1798
+				// wait wait wait- if nothing was affected let's stop here
1799
+				return 0;
1800
+			}
1801
+			foreach ($model_objs_affected_ids as $id) {
1802
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1803
+				if ($model_obj_in_entity_map) {
1804
+					foreach ($fields_n_values as $field => $new_value) {
1805
+						$model_obj_in_entity_map->set($field, $new_value);
1806
+					}
1807
+				}
1808
+			}
1809
+			// if there is a primary key on this model, we can now do a slight optimization
1810
+			if ($this->has_primary_key_field()) {
1811
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1812
+				$query_params = [
1813
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1814
+					'limit'                    => count($model_objs_affected_ids),
1815
+					'default_where_conditions' => EE_Default_Where_Conditions::NONE,
1816
+				];
1817
+			}
1818
+		}
1819
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1820
+
1821
+		// note: the following query doesn't use _construct_2nd_half_of_select_query()
1822
+		// because it doesn't accept LIMIT, ORDER BY, etc.
1823
+		$rows_affected = $this->_do_wpdb_query(
1824
+			'query',
1825
+			[
1826
+				"UPDATE " . $model_query_info->get_full_join_sql()
1827
+				. " SET " . $this->_construct_update_sql($fields_n_values)
1828
+				. $model_query_info->get_where_sql(),
1829
+			]
1830
+		);
1831
+
1832
+		/**
1833
+		 * Action called after a model update call has been made.
1834
+		 *
1835
+		 * @param EEM_Base $model
1836
+		 * @param array    $fields_n_values the updated fields and their new values
1837
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1838
+		 * @param int      $rows_affected
1839
+		 */
1840
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1841
+		return $rows_affected;// how many supposedly got updated
1842
+	}
1843
+
1844
+
1845
+	/**
1846
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where the values
1847
+	 * are the values of the field specified (or by default the primary key field)
1848
+	 * that matched the query params. Note that you should pass the name of the
1849
+	 * model FIELD, not the database table's column name.
1850
+	 *
1851
+	 * @param array  $query_params
1852
+	 * @param string $field_to_select
1853
+	 * @return array just like $wpdb->get_col()
1854
+	 * @throws EE_Error
1855
+	 * @throws ReflectionException
1856
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md for $query_params values
1857
+	 */
1858
+	public function get_col($query_params = [], $field_to_select = null)
1859
+	{
1860
+		if ($field_to_select) {
1861
+			$field = $this->field_settings_for($field_to_select);
1862
+		} elseif ($this->has_primary_key_field()) {
1863
+			$field = $this->get_primary_key_field();
1864
+		} else {
1865
+			$field_settings = $this->field_settings();
1866
+			// no primary key, just grab the first column
1867
+			$field = reset($field_settings);
1868
+			// don't need this array now
1869
+			unset($field_settings);
1870
+		}
1871
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1872
+		$select_expressions = $field->get_qualified_column();
1873
+		$SQL                =
1874
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1875
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1876
+	}
1877
+
1878
+
1879
+	/**
1880
+	 * Returns a single column value for a single row from the database
1881
+	 *
1882
+	 * @param array  $query_params    @see
1883
+	 *                                https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1884
+	 * @param string $field_to_select @see EEM_Base::get_col()
1885
+	 * @return string
1886
+	 * @throws EE_Error
1887
+	 * @throws ReflectionException
1888
+	 */
1889
+	public function get_var($query_params = [], $field_to_select = null)
1890
+	{
1891
+		$query_params['limit'] = 1;
1892
+		$col                   = $this->get_col($query_params, $field_to_select);
1893
+		if (! empty($col)) {
1894
+			return reset($col);
1895
+		}
1896
+		return null;
1897
+	}
1898
+
1899
+
1900
+	/**
1901
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1902
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1903
+	 * injection, but currently no further filtering is done
1904
+	 *
1905
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1906
+	 *                               be updated to in the DB
1907
+	 * @return string of SQL
1908
+	 * @throws EE_Error
1909
+	 * @global      $wpdb
1910
+	 */
1911
+	public function _construct_update_sql($fields_n_values)
1912
+	{
1913
+		/** @type WPDB $wpdb */
1914
+		global $wpdb;
1915
+		$cols_n_values = [];
1916
+		foreach ($fields_n_values as $field_name => $value) {
1917
+			$field_obj = $this->field_settings_for($field_name);
1918
+			// if the value is NULL, we want to assign the value to that.
1919
+			// wpdb->prepare doesn't really handle that properly
1920
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1921
+			$value_sql       = $prepared_value === null
1922
+				? 'NULL'
1923
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1924
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1925
+		}
1926
+		return implode(",", $cols_n_values);
1927
+	}
1928
+
1929
+
1930
+	/**
1931
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1932
+	 * Performs a HARD delete, meaning the database row should always be removed,
1933
+	 * not just have a flag field on it switched
1934
+	 * Wrapper for EEM_Base::delete_permanently()
1935
+	 *
1936
+	 * @param mixed $id
1937
+	 * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
1938
+	 *                             ie: enforce referential integrity
1939
+	 *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
1940
+	 * @return int the number of rows deleted
1941
+	 * @throws EE_Error
1942
+	 * @throws ReflectionException
1943
+	 */
1944
+	public function delete_permanently_by_ID($id, $block_deletes = true): int
1945
+	{
1946
+		return $this->delete_permanently(
1947
+			[
1948
+				[$this->get_primary_key_field()->get_name() => $id],
1949
+				'limit' => 1,
1950
+			],
1951
+			$block_deletes
1952
+		);
1953
+	}
1954
+
1955
+
1956
+	/**
1957
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1958
+	 * Wrapper for EEM_Base::delete()
1959
+	 *
1960
+	 * @param mixed $id
1961
+	 * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
1962
+	 *                             ie: enforce referential integrity
1963
+	 *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
1964
+	 * @return int the number of rows deleted
1965
+	 * @throws EE_Error
1966
+	 * @throws ReflectionException
1967
+	 */
1968
+	public function delete_by_ID($id, $block_deletes = true)
1969
+	{
1970
+		return $this->delete(
1971
+			[
1972
+				[$this->get_primary_key_field()->get_name() => $id],
1973
+				'limit' => 1,
1974
+			],
1975
+			$block_deletes
1976
+		);
1977
+	}
1978
+
1979
+
1980
+	/**
1981
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1982
+	 * meaning if the model has a field that indicates its been "trashed" or
1983
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1984
+	 *
1985
+	 * @param array   $query_params
1986
+	 * @param boolean $block_deletes whether to allow related model objects to block (prevent) this deletion
1987
+	 *                               ie: enforce referential integrity
1988
+	 *                               It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
1989
+	 * @return int how many rows got deleted
1990
+	 * @throws EE_Error
1991
+	 * @throws ReflectionException
1992
+	 * @see EEM_Base::delete_permanently
1993
+	 */
1994
+	public function delete($query_params, $block_deletes = true)
1995
+	{
1996
+		return $this->delete_permanently($query_params, $block_deletes);
1997
+	}
1998
+
1999
+
2000
+	/**
2001
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
2002
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
2003
+	 * as archived, not actually deleted
2004
+	 *
2005
+	 * @param array   $query_params
2006
+	 * @param boolean $block_deletes  whether to allow related model objects to block (prevent) this deletion
2007
+	 *                                ie: enforce referential integrity
2008
+	 *                                It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
2009
+	 * @return int how many rows got deleted
2010
+	 * @throws EE_Error
2011
+	 * @throws ReflectionException
2012
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2013
+	 */
2014
+	public function delete_permanently($query_params, $block_deletes = true): int
2015
+	{
2016
+		/**
2017
+		 * Action called just before performing a real deletion query. You can use the
2018
+		 * model and its $query_params to find exactly which items will be deleted
2019
+		 *
2020
+		 * @param EEM_Base $model
2021
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
2022
+		 * @param bool     $block_deletes @see param description in method phpdoc block.
2023
+		 */
2024
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $block_deletes);
2025
+		// some MySQL databases may be running safe mode, which may restrict
2026
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
2027
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
2028
+		// to delete them
2029
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
2030
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $block_deletes);
2031
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
2032
+			$columns_and_ids_for_deleting
2033
+		);
2034
+		/**
2035
+		 * Allows client code to act on the items being deleted before the query is actually executed.
2036
+		 * see php doc blocks for more details
2037
+		 *
2038
+		 * @param EEM_Base $this                         The model instance being acted on.
2039
+		 * @param array    $query_params                 The incoming array of query parameters influencing what gets deleted.
2040
+		 * @param bool     $block_deletes                @see param description in method phpdoc block.
2041
+		 * @param array    $columns_and_ids_for_deleting An array indicating what entities will get removed as
2042
+		 *                                               derived from the incoming query parameters.
2043
+		 * @see details on the structure of this array in the phpdocs for the `_get_ids_for_delete_method`
2044
+		 */
2045
+		do_action(
2046
+			'AHEE__EEM_Base__delete__before_query',
2047
+			$this,
2048
+			$query_params,
2049
+			$block_deletes,
2050
+			$columns_and_ids_for_deleting
2051
+		);
2052
+		$rows_deleted = 0;
2053
+		if ($deletion_where_query_part) {
2054
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2055
+			$table_aliases    = array_keys($this->_tables);
2056
+			$SQL              = "DELETE "
2057
+								. implode(", ", $table_aliases)
2058
+								. " FROM "
2059
+								. $model_query_info->get_full_join_sql()
2060
+								. " WHERE "
2061
+								. $deletion_where_query_part;
2062
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2063
+		}
2064
+
2065
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2066
+		// there was no error with the delete query.
2067
+		if (
2068
+			$this->has_primary_key_field()
2069
+			&& $rows_deleted !== false
2070
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2071
+		) {
2072
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2073
+			foreach ($ids_for_removal as $id) {
2074
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2075
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2076
+				}
2077
+			}
2078
+
2079
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2080
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2081
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2082
+			// (although it is possible).
2083
+			// Note this can be skipped by using the provided filter and returning false.
2084
+			if (
2085
+				apply_filters(
2086
+					'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2087
+					! $this instanceof EEM_Extra_Meta,
2088
+					$this
2089
+				)
2090
+			) {
2091
+				EEM_Extra_Meta::instance()->delete_permanently(
2092
+					[
2093
+						0 => [
2094
+							'EXM_type' => $this->get_this_model_name(),
2095
+							'OBJ_ID'   => [
2096
+								'IN',
2097
+								$ids_for_removal,
2098
+							],
2099
+						],
2100
+					]
2101
+				);
2102
+			}
2103
+		}
2104
+
2105
+		/**
2106
+		 * Action called just after performing a real deletion query. Although at this point the
2107
+		 * items should have been deleted
2108
+		 *
2109
+		 * @param EEM_Base $model
2110
+		 * @param array $query_params
2111
+		 * @param int   $rows_deleted
2112
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2113
+		 */
2114
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2115
+		return (int) $rows_deleted;// how many supposedly got deleted
2116
+	}
2117
+
2118
+
2119
+	/**
2120
+	 * Checks all the relations that throw error messages when there are blocking related objects
2121
+	 * for related model objects. If there are any related model objects on those relations,
2122
+	 * adds an EE_Error, and return true
2123
+	 *
2124
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2125
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2126
+	 *                                                 should be ignored when determining whether there are related
2127
+	 *                                                 model objects which block this model object's deletion. Useful
2128
+	 *                                                 if you know A is related to B and are considering deleting A,
2129
+	 *                                                 but want to see if A has any other objects blocking its deletion
2130
+	 *                                                 before removing the relation between A and B
2131
+	 * @return boolean
2132
+	 * @throws EE_Error
2133
+	 * @throws ReflectionException
2134
+	 */
2135
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2136
+	{
2137
+		// first, if $ignore_this_model_obj was supplied, get its model
2138
+		$ignored_model = $ignore_this_model_obj instanceof EE_Base_Class
2139
+			? $ignore_this_model_obj->get_model()
2140
+			: null;
2141
+		// now check all the relations of $this_model_obj_or_id and see if there
2142
+		// are any related model objects blocking it?
2143
+		$is_blocked = false;
2144
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2145
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2146
+				// if $ignore_this_model_obj was supplied, then for the query
2147
+				// on that model needs to be told to ignore $ignore_this_model_obj
2148
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2149
+					$related_model_objects = $relation_obj->get_all_related(
2150
+						$this_model_obj_or_id,
2151
+						[
2152
+							[
2153
+								$ignored_model->get_primary_key_field()->get_name() => [
2154
+									'!=',
2155
+									$ignore_this_model_obj->ID(),
2156
+								],
2157
+							],
2158
+						]
2159
+					);
2160
+				} else {
2161
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2162
+				}
2163
+				if ($related_model_objects) {
2164
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2165
+					$is_blocked = true;
2166
+				}
2167
+			}
2168
+		}
2169
+		return $is_blocked;
2170
+	}
2171
+
2172
+
2173
+	/**
2174
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2175
+	 *
2176
+	 * @param array $row_results_for_deleting
2177
+	 * @param bool  $block_deletes whether to allow related model objects to block (prevent) this deletion
2178
+	 *                             ie: enforce referential integrity
2179
+	 *                             It's advisable to always leave this as TRUE, otherwise you could corrupt your DB
2180
+	 * @return array               The shape of this array depends on whether the model `has_primary_key_field` or not.
2181
+	 *                             If the model DOES have a primary_key_field, then the array will be a simple single
2182
+	 *                             dimension array where the key is the fully qualified primary key column and
2183
+	 *                             the value is an array of ids that will be deleted.
2184
+	 *                             Example:
2185
+	 *                              [ 'Event.EVT_ID' => [ 1,2,3 ]]
2186
+	 *                             If the model DOES NOT have a primary_key_field, then the array will be a
2187
+	 *                             two-dimensional array where each element is a group of columns and values that get deleted.
2188
+	 *                             Example:
2189
+	 *                              [
2190
+	 *                                  0 => [
2191
+	 *                                      'Term_Relationship.object_id' => 1
2192
+	 *                                      'Term_Relationship.term_taxonomy_id' => 5
2193
+	 *                                  ],
2194
+	 *                                  1 => [
2195
+	 *                                      'Term_Relationship.object_id' => 1
2196
+	 *                                      'Term_Relationship.term_taxonomy_id' => 6
2197
+	 *                                  ]
2198
+	 *                              ]
2199
+	 * @throws EE_Error
2200
+	 * @throws ReflectionException
2201
+	 */
2202
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $block_deletes = true)
2203
+	{
2204
+		$ids_to_delete_indexed_by_column = [];
2205
+		if ($this->has_primary_key_field()) {
2206
+			$primary_table = $this->_get_main_table();
2207
+			// following lines are commented out because the variables were not being used
2208
+			// not deleting because unsure if calls were intentionally causing side effects
2209
+			// $primary_table_pk_field          =
2210
+			//     $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2211
+			// $other_tables                    = $this->_get_other_tables();
2212
+			$ids_to_delete_indexed_by_column = $query = [];
2213
+			foreach ($row_results_for_deleting as $item_to_delete) {
2214
+				// before we mark this item for deletion,
2215
+				// make sure there's no related entities blocking its deletion (if we're checking)
2216
+				if (
2217
+					$block_deletes
2218
+					&& $this->delete_is_blocked_by_related_models(
2219
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2220
+					)
2221
+				) {
2222
+					continue;
2223
+				}
2224
+				// primary table deletes
2225
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2226
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2227
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2228
+				}
2229
+			}
2230
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2231
+			$fields = $this->get_combined_primary_key_fields();
2232
+			foreach ($row_results_for_deleting as $item_to_delete) {
2233
+				$ids_to_delete_indexed_by_column_for_row = [];
2234
+				foreach ($fields as $cpk_field) {
2235
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2236
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2237
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2238
+					}
2239
+				}
2240
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2241
+			}
2242
+		} else {
2243
+			// so there's no primary key and no combined key...
2244
+			// sorry, can't help you
2245
+			throw new EE_Error(
2246
+				sprintf(
2247
+					esc_html__(
2248
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2249
+						"event_espresso"
2250
+					),
2251
+					get_class($this)
2252
+				)
2253
+			);
2254
+		}
2255
+		return $ids_to_delete_indexed_by_column;
2256
+	}
2257
+
2258
+
2259
+	/**
2260
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2261
+	 * the corresponding query_part for the query performing the deletion.
2262
+	 *
2263
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2264
+	 * @return string
2265
+	 * @throws EE_Error
2266
+	 */
2267
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2268
+	{
2269
+		$query_part = '';
2270
+		if (empty($ids_to_delete_indexed_by_column)) {
2271
+			return $query_part;
2272
+		} elseif ($this->has_primary_key_field()) {
2273
+			$query = [];
2274
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2275
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2276
+			}
2277
+			$query_part = ! empty($query)
2278
+				? implode(' AND ', $query)
2279
+				: $query_part;
2280
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2281
+			$ways_to_identify_a_row = [];
2282
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2283
+				$values_for_each_combined_primary_key_for_a_row = [];
2284
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2285
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2286
+				}
2287
+				$ways_to_identify_a_row[] = '('
2288
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2289
+											. ')';
2290
+			}
2291
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2292
+		}
2293
+		return $query_part;
2294
+	}
2295
+
2296
+
2297
+	/**
2298
+	 * Gets the model field by the fully qualified name
2299
+	 *
2300
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2301
+	 * @return EE_Model_Field_Base
2302
+	 * @throws EE_Error
2303
+	 * @throws EE_Error
2304
+	 */
2305
+	public function get_field_by_column($qualified_column_name)
2306
+	{
2307
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2308
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2309
+				return $field_obj;
2310
+			}
2311
+		}
2312
+		throw new EE_Error(
2313
+			sprintf(
2314
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2315
+				$this->get_this_model_name(),
2316
+				$qualified_column_name
2317
+			)
2318
+		);
2319
+	}
2320
+
2321
+
2322
+	/**
2323
+	 * Count all the rows that match criteria the model query params.
2324
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2325
+	 * column
2326
+	 *
2327
+	 * @param array  $query_params   @see
2328
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2329
+	 * @param string $field_to_count field on model to count by (not column name)
2330
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2331
+	 *                               that by the setting $distinct to TRUE;
2332
+	 * @return int
2333
+	 * @throws EE_Error
2334
+	 * @throws ReflectionException
2335
+	 */
2336
+	public function count($query_params = [], $field_to_count = '', $distinct = false)
2337
+	{
2338
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2339
+		if ($field_to_count) {
2340
+			$field_obj       = $this->field_settings_for($field_to_count);
2341
+			$column_to_count = $field_obj->get_qualified_column();
2342
+		} elseif ($this->has_primary_key_field()) {
2343
+			$pk_field_obj    = $this->get_primary_key_field();
2344
+			$column_to_count = $pk_field_obj->get_qualified_column();
2345
+		} else {
2346
+			// there's no primary key
2347
+			// if we're counting distinct items, and there's no primary key,
2348
+			// we need to list out the columns for distinction;
2349
+			// otherwise we can just use star
2350
+			if ($distinct) {
2351
+				$columns_to_use = [];
2352
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2353
+					$columns_to_use[] = $field_obj->get_qualified_column();
2354
+				}
2355
+				$column_to_count = implode(',', $columns_to_use);
2356
+			} else {
2357
+				$column_to_count = '*';
2358
+			}
2359
+		}
2360
+		$column_to_count = $distinct
2361
+			? "DISTINCT " . $column_to_count
2362
+			: $column_to_count;
2363
+		$SQL             =
2364
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2365
+		return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2366
+	}
2367
+
2368
+
2369
+	/**
2370
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2371
+	 *
2372
+	 * @param array  $query_params @see
2373
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2374
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2375
+	 * @return float
2376
+	 * @throws EE_Error
2377
+	 * @throws ReflectionException
2378
+	 */
2379
+	public function sum($query_params, $field_to_sum = null)
2380
+	{
2381
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2382
+		if ($field_to_sum) {
2383
+			$field_obj = $this->field_settings_for($field_to_sum);
2384
+		} else {
2385
+			$field_obj = $this->get_primary_key_field();
2386
+		}
2387
+		$column_to_count = $field_obj->get_qualified_column();
2388
+		$SQL             =
2389
+			"SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2390
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2391
+		$data_type       = $field_obj->get_wpdb_data_type();
2392
+		if ($data_type === '%d' || $data_type === '%s') {
2393
+			return (float) $return_value;
2394
+		}
2395
+		// must be %f
2396
+		return (float) $return_value;
2397
+	}
2398
+
2399
+
2400
+	/**
2401
+	 * Just calls the specified method on $wpdb with the given arguments
2402
+	 * Consolidates a little extra error handling code
2403
+	 *
2404
+	 * @param string $wpdb_method
2405
+	 * @param array  $arguments_to_provide
2406
+	 * @return mixed
2407
+	 * @throws EE_Error
2408
+	 * @global wpdb  $wpdb
2409
+	 */
2410
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2411
+	{
2412
+		// if we're in maintenance mode level 2, DON'T run any queries
2413
+		// because level 2 indicates the database needs updating and
2414
+		// is probably out of sync with the code
2415
+		if (DbStatus::isOffline()) {
2416
+			throw new RuntimeException(
2417
+				esc_html__(
2418
+					"Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2419
+					"event_espresso"
2420
+				)
2421
+			);
2422
+		}
2423
+		/** @type WPDB $wpdb */
2424
+		global $wpdb;
2425
+		if (! method_exists($wpdb, $wpdb_method)) {
2426
+			throw new DomainException(
2427
+				sprintf(
2428
+					esc_html__(
2429
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2430
+						'event_espresso'
2431
+					),
2432
+					$wpdb_method
2433
+				)
2434
+			);
2435
+		}
2436
+		$old_show_errors_value = $wpdb->show_errors;
2437
+		if (defined('WP_DEBUG') && WP_DEBUG) {
2438
+			$wpdb->show_errors(false);
2439
+		}
2440
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2441
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2442
+		if (defined('WP_DEBUG') && WP_DEBUG) {
2443
+			$wpdb->show_errors($old_show_errors_value);
2444
+			if (! empty($wpdb->last_error)) {
2445
+				throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2446
+			}
2447
+			if ($result === false) {
2448
+				throw new EE_Error(
2449
+					sprintf(
2450
+						esc_html__(
2451
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2452
+							'event_espresso'
2453
+						),
2454
+						$wpdb_method,
2455
+						var_export($arguments_to_provide, true)
2456
+					)
2457
+				);
2458
+			}
2459
+		} elseif ($result === false) {
2460
+			EE_Error::add_error(
2461
+				sprintf(
2462
+					esc_html__(
2463
+						'A database error has occurred. Turn on WP_DEBUG for more information.||A database error occurred doing wpdb method "%1$s", with arguments "%2$s". The error was "%3$s"',
2464
+						'event_espresso'
2465
+					),
2466
+					$wpdb_method,
2467
+					var_export($arguments_to_provide, true),
2468
+					$wpdb->last_error
2469
+				),
2470
+				__FILE__,
2471
+				__FUNCTION__,
2472
+				__LINE__
2473
+			);
2474
+		}
2475
+		return $result;
2476
+	}
2477
+
2478
+
2479
+	/**
2480
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2481
+	 * and if there's an error tries to verify the DB is correct. Uses
2482
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2483
+	 * we should try to fix the EE core db, the addons, or just give up
2484
+	 *
2485
+	 * @param string $wpdb_method
2486
+	 * @param array  $arguments_to_provide
2487
+	 * @return mixed
2488
+	 */
2489
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2490
+	{
2491
+		/** @type WPDB $wpdb */
2492
+		global $wpdb;
2493
+		$wpdb->last_error = null;
2494
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2495
+		// was there an error running the query? but we don't care on new activations
2496
+		// (we're going to setup the DB anyway on new activations)
2497
+		if (
2498
+			($result === false || ! empty($wpdb->last_error))
2499
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2500
+		) {
2501
+			switch (EEM_Base::$_db_verification_level) {
2502
+				case EEM_Base::db_verified_none:
2503
+					// let's double-check core's DB
2504
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2505
+					break;
2506
+				case EEM_Base::db_verified_core:
2507
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2508
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2509
+					break;
2510
+				case EEM_Base::db_verified_addons:
2511
+					// ummmm... you in trouble
2512
+					return $result;
2513
+			}
2514
+			if (! empty($error_message)) {
2515
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2516
+				trigger_error($error_message);
2517
+			}
2518
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2519
+		}
2520
+		return $result;
2521
+	}
2522
+
2523
+
2524
+	/**
2525
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2526
+	 * EEM_Base::$_db_verification_level
2527
+	 *
2528
+	 * @param string $wpdb_method
2529
+	 * @param array  $arguments_to_provide
2530
+	 * @return string
2531
+	 * @throws EE_Error
2532
+	 * @throws ReflectionException
2533
+	 */
2534
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2535
+	{
2536
+		/** @type WPDB $wpdb */
2537
+		global $wpdb;
2538
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2539
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2540
+		$error_message                    = sprintf(
2541
+			esc_html__(
2542
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2543
+				'event_espresso'
2544
+			),
2545
+			$wpdb->last_error,
2546
+			$wpdb_method,
2547
+			wp_json_encode($arguments_to_provide)
2548
+		);
2549
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2550
+		return $error_message;
2551
+	}
2552
+
2553
+
2554
+	/**
2555
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2556
+	 * EEM_Base::$_db_verification_level
2557
+	 *
2558
+	 * @param $wpdb_method
2559
+	 * @param $arguments_to_provide
2560
+	 * @return string
2561
+	 * @throws EE_Error
2562
+	 * @throws ReflectionException
2563
+	 */
2564
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2565
+	{
2566
+		/** @type WPDB $wpdb */
2567
+		global $wpdb;
2568
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2569
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2570
+		$error_message                    = sprintf(
2571
+			esc_html__(
2572
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2573
+				'event_espresso'
2574
+			),
2575
+			$wpdb->last_error,
2576
+			$wpdb_method,
2577
+			wp_json_encode($arguments_to_provide)
2578
+		);
2579
+		EE_System::instance()->initialize_addons();
2580
+		return $error_message;
2581
+	}
2582
+
2583
+
2584
+	/**
2585
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2586
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2587
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2588
+	 * ..."
2589
+	 *
2590
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2591
+	 * @return string
2592
+	 */
2593
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2594
+	{
2595
+		return " FROM " . $model_query_info->get_full_join_sql() .
2596
+			   $model_query_info->get_where_sql() .
2597
+			   $model_query_info->get_group_by_sql() .
2598
+			   $model_query_info->get_having_sql() .
2599
+			   $model_query_info->get_order_by_sql() .
2600
+			   $model_query_info->get_limit_sql();
2601
+	}
2602
+
2603
+
2604
+	/**
2605
+	 * Set to easily debug the next X queries ran from this model.
2606
+	 *
2607
+	 * @param int $count
2608
+	 */
2609
+	public function show_next_x_db_queries($count = 1)
2610
+	{
2611
+		$this->_show_next_x_db_queries = $count;
2612
+	}
2613
+
2614
+
2615
+	/**
2616
+	 * @param $sql_query
2617
+	 */
2618
+	public function show_db_query_if_previously_requested($sql_query)
2619
+	{
2620
+		if ($this->_show_next_x_db_queries > 0) {
2621
+			$left = is_admin() ? '12rem' : '2rem';
2622
+			echo "
2623 2623
             <div class='ee-status-outline ee-status-bg--attention' style='margin: 2rem 2rem 2rem $left;'>
2624 2624
                 " . esc_html($sql_query) . "
2625 2625
             </div>";
2626
-            $this->_show_next_x_db_queries--;
2627
-        }
2628
-    }
2629
-
2630
-
2631
-    /**
2632
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2633
-     * There are the 3 cases:
2634
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2635
-     * $otherModelObject has no ID, it is first saved.
2636
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2637
-     * has no ID, it is first saved.
2638
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2639
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2640
-     * join table
2641
-     *
2642
-     * @param EE_Base_Class|int $id_or_obj                        EE_base_Class or ID of $thisModelObject
2643
-     * @param EE_Base_Class|int $other_model_id_or_obj            EE_base_Class or ID of other Model Object
2644
-     * @param string            $relationName                     , key in EEM_Base::_relations
2645
-     *                                                            an attendee to a group, you also want to specify
2646
-     *                                                            which role they will have in that group. So you would
2647
-     *                                                            use this parameter to specify
2648
-     *                                                            array('role-column-name'=>'role-id')
2649
-     * @param array|null        $extra_join_model_fields_n_values This allows you to enter further query params for the
2650
-     *                                                            relation to for relation to methods that allow you to
2651
-     *                                                            further specify extra columns to join by (such as
2652
-     *                                                            HABTM).  Keep in mind that the only acceptable
2653
-     *                                                            query_params is strict "col" => "value" pairs because
2654
-     *                                                            these will be inserted in any new rows created as
2655
-     *                                                            well.
2656
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2657
-     * @throws EE_Error
2658
-     */
2659
-    public function add_relationship_to(
2660
-        $id_or_obj,
2661
-        $other_model_id_or_obj,
2662
-        $relationName,
2663
-        $extra_join_model_fields_n_values = []
2664
-    ) {
2665
-        $relation_obj = $this->related_settings_for($relationName);
2666
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2667
-    }
2668
-
2669
-
2670
-    /**
2671
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2672
-     * There are the 3 cases:
2673
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2674
-     * error
2675
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2676
-     * an error
2677
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2678
-     *
2679
-     * @param EE_Base_Class|int $id_or_obj             EE_base_Class or ID of $thisModelObject
2680
-     * @param EE_Base_Class|int $other_model_id_or_obj EE_base_Class or ID of other Model Object
2681
-     * @param string            $relationName          key in EEM_Base::_relations
2682
-     * @param array|null        $where_query           This allows you to enter further query params for the relation
2683
-     *                                                 to for relation to methods that allow you to further specify
2684
-     *                                                 extra columns to join by (such as HABTM). Keep in mind that the
2685
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2686
-     *                                                 because these will be inserted in any new rows created as well.
2687
-     * @return EE_Base_Class
2688
-     * @throws EE_Error
2689
-     */
2690
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2691
-    {
2692
-        $relation_obj = $this->related_settings_for($relationName);
2693
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2694
-    }
2695
-
2696
-
2697
-    /**
2698
-     * @param mixed       $id_or_obj
2699
-     * @param string      $relationName
2700
-     * @param array|null  $where_query_params
2701
-     * @return EE_Base_Class[]
2702
-     * @throws EE_Error
2703
-     * @throws ReflectionException
2704
-     */
2705
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2706
-    {
2707
-        $relation_obj = $this->related_settings_for($relationName);
2708
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2709
-    }
2710
-
2711
-
2712
-    /**
2713
-     * Gets all the related items of the specified $model_name, using $query_params.
2714
-     * Note: by default, we remove the "default query params"
2715
-     * because we want to get even deleted items etc.
2716
-     *
2717
-     * @param mixed       $id_or_obj    EE_Base_Class child or its ID
2718
-     * @param string      $model_name   like 'Event', 'Registration', etc. always singular
2719
-     * @param array|null  $query_params @see
2720
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2721
-     * @return EE_Base_Class[]
2722
-     * @throws EE_Error
2723
-     * @throws ReflectionException
2724
-     */
2725
-    public function get_all_related($id_or_obj, $model_name, ?array $query_params = [])
2726
-    {
2727
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2728
-        $relation_settings = $this->related_settings_for($model_name);
2729
-        return $relation_settings->get_all_related($model_obj, $query_params);
2730
-    }
2731
-
2732
-
2733
-    /**
2734
-     * Deletes all the model objects across the relation indicated by $model_name
2735
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2736
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2737
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2738
-     *
2739
-     * @param EE_Base_Class|int|string $id_or_obj
2740
-     * @param string                   $model_name
2741
-     * @param array|null               $query_params
2742
-     * @return int how many deleted
2743
-     * @throws EE_Error
2744
-     * @throws ReflectionException
2745
-     */
2746
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2747
-    {
2748
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2749
-        $relation_settings = $this->related_settings_for($model_name);
2750
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2751
-    }
2752
-
2753
-
2754
-    /**
2755
-     * Hard deletes all the model objects across the relation indicated by $model_name
2756
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2757
-     * the model objects can't be hard deleted because of blocking related model objects,
2758
-     * just does a soft-delete on them instead.
2759
-     *
2760
-     * @param EE_Base_Class|int|string $id_or_obj
2761
-     * @param string                   $model_name
2762
-     * @param array|null               $query_params
2763
-     * @return int how many deleted
2764
-     * @throws EE_Error
2765
-     * @throws ReflectionException
2766
-     */
2767
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2768
-    {
2769
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2770
-        $relation_settings = $this->related_settings_for($model_name);
2771
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2772
-    }
2773
-
2774
-
2775
-    /**
2776
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2777
-     * unless otherwise specified in the $query_params
2778
-     *
2779
-     * @param EE_Base_Class|int|string $id_or_obj
2780
-     * @param string                   $model_name     like 'Event', or 'Registration'
2781
-     * @param array|null               $query_params   @see
2782
-     *                                                 https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2783
-     * @param string                   $field_to_count name of field to count by. By default, uses primary key
2784
-     * @param bool                     $distinct       if we want to only count the distinct values for the column then
2785
-     *                                                 you can trigger that by the setting $distinct to TRUE;
2786
-     * @return int
2787
-     * @throws EE_Error
2788
-     * @throws ReflectionException
2789
-     */
2790
-    public function count_related(
2791
-        $id_or_obj,
2792
-        $model_name,
2793
-        $query_params = [],
2794
-        $field_to_count = null,
2795
-        $distinct = false
2796
-    ) {
2797
-        $related_model = $this->get_related_model_obj($model_name);
2798
-        // we're just going to use the query params on the related model's normal get_all query,
2799
-        // except add a condition to say to match the current mod
2800
-        if (! isset($query_params['default_where_conditions'])) {
2801
-            $query_params['default_where_conditions'] = EE_Default_Where_Conditions::NONE;
2802
-        }
2803
-        $this_model_name                                                 = $this->get_this_model_name();
2804
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2805
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2806
-        return $related_model->count($query_params, $field_to_count, $distinct);
2807
-    }
2808
-
2809
-
2810
-    /**
2811
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2812
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2813
-     *
2814
-     * @param EE_Base_Class|int|string $id_or_obj
2815
-     * @param string                   $model_name   like 'Event', or 'Registration'
2816
-     * @param array|null               $query_params @see
2817
-     *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2818
-     * @param string                   $field_to_sum name of field to count by. By default, uses primary key
2819
-     * @return float
2820
-     * @throws EE_Error
2821
-     * @throws ReflectionException
2822
-     */
2823
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2824
-    {
2825
-        $related_model = $this->get_related_model_obj($model_name);
2826
-        if (! is_array($query_params)) {
2827
-            EE_Error::doing_it_wrong(
2828
-                'EEM_Base::sum_related',
2829
-                sprintf(
2830
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2831
-                    gettype($query_params)
2832
-                ),
2833
-                '4.6.0'
2834
-            );
2835
-            $query_params = [];
2836
-        }
2837
-        // we're just going to use the query params on the related model's normal get_all query,
2838
-        // except add a condition to say to match the current mod
2839
-        if (! isset($query_params['default_where_conditions'])) {
2840
-            $query_params['default_where_conditions'] = EE_Default_Where_Conditions::NONE;
2841
-        }
2842
-        $this_model_name                                                 = $this->get_this_model_name();
2843
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2844
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2845
-        return $related_model->sum($query_params, $field_to_sum);
2846
-    }
2847
-
2848
-
2849
-    /**
2850
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2851
-     * $modelObject
2852
-     *
2853
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2854
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2855
-     * @param array|null          $query_params     @see
2856
-     *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2857
-     * @return EE_Base_Class
2858
-     * @throws EE_Error
2859
-     * @throws ReflectionException
2860
-     */
2861
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2862
-    {
2863
-        $query_params['limit'] = 1;
2864
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2865
-        if ($results) {
2866
-            return array_shift($results);
2867
-        }
2868
-        return null;
2869
-    }
2870
-
2871
-
2872
-    /**
2873
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2874
-     *
2875
-     * @return string
2876
-     */
2877
-    public function get_this_model_name()
2878
-    {
2879
-        return str_replace("EEM_", "", get_class($this));
2880
-    }
2881
-
2882
-
2883
-    /**
2884
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2885
-     *
2886
-     * @return EE_Any_Foreign_Model_Name_Field
2887
-     * @throws EE_Error
2888
-     */
2889
-    public function get_field_containing_related_model_name()
2890
-    {
2891
-        foreach ($this->field_settings(true) as $field) {
2892
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2893
-                $field_with_model_name = $field;
2894
-            }
2895
-        }
2896
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2897
-            throw new EE_Error(
2898
-                sprintf(
2899
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2900
-                    $this->get_this_model_name()
2901
-                )
2902
-            );
2903
-        }
2904
-        return $field_with_model_name;
2905
-    }
2906
-
2907
-
2908
-    /**
2909
-     * Inserts a new entry into the database, for each table.
2910
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2911
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2912
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2913
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2914
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2915
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2916
-     *
2917
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2918
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2919
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2920
-     *                              of EEM_Base)
2921
-     * @return int|string new primary key on main table that got inserted
2922
-     * @throws EE_Error
2923
-     * @throws ReflectionException
2924
-     */
2925
-    public function insert($field_n_values)
2926
-    {
2927
-        /**
2928
-         * Filters the fields and their values before inserting an item using the models
2929
-         *
2930
-         * @param array    $fields_n_values keys are the fields and values are their new values
2931
-         * @param EEM_Base $model           the model used
2932
-         */
2933
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2934
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2935
-            $main_table = $this->_get_main_table();
2936
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2937
-            if ($new_id !== false) {
2938
-                foreach ($this->_get_other_tables() as $other_table) {
2939
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2940
-                }
2941
-            }
2942
-            /**
2943
-             * Done just after attempting to insert a new model object
2944
-             *
2945
-             * @param EEM_Base $model           used
2946
-             * @param array    $fields_n_values fields and their values
2947
-             * @param int|string the              ID of the newly-inserted model object
2948
-             */
2949
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2950
-            return $new_id;
2951
-        }
2952
-        return false;
2953
-    }
2954
-
2955
-
2956
-    /**
2957
-     * Checks that the result would satisfy the unique indexes on this model
2958
-     *
2959
-     * @param array  $field_n_values
2960
-     * @param string $action
2961
-     * @return boolean
2962
-     * @throws EE_Error
2963
-     * @throws ReflectionException
2964
-     */
2965
-    protected function _satisfies_unique_indexes(array $field_n_values, $action = 'insert')
2966
-    {
2967
-        foreach ($this->unique_indexes() as $index_name => $index) {
2968
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2969
-            if ($this->exists([$uniqueness_where_params])) {
2970
-                EE_Error::add_error(
2971
-                    sprintf(
2972
-                        esc_html__(
2973
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2974
-                            "event_espresso"
2975
-                        ),
2976
-                        $action,
2977
-                        $this->_get_class_name(),
2978
-                        $index_name,
2979
-                        implode(",", $index->field_names()),
2980
-                        http_build_query($uniqueness_where_params)
2981
-                    ),
2982
-                    __FILE__,
2983
-                    __FUNCTION__,
2984
-                    __LINE__
2985
-                );
2986
-                return false;
2987
-            }
2988
-        }
2989
-        return true;
2990
-    }
2991
-
2992
-
2993
-    /**
2994
-     * Checks the database for an item that conflicts (ie, if this item were
2995
-     * saved to the DB would break some uniqueness requirement, like a primary key
2996
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2997
-     * can be either an EE_Base_Class or an array of fields n values
2998
-     *
2999
-     * @param EE_Base_Class|array $obj_or_fields_array
3000
-     * @param boolean             $include_primary_key whether to use the model object's primary key
3001
-     *                                                 when looking for conflicts
3002
-     *                                                 (ie, if false, we ignore the model object's primary key
3003
-     *                                                 when finding "conflicts". If true, it's also considered).
3004
-     *                                                 Only works for INT primary key,
3005
-     *                                                 STRING primary keys cannot be ignored
3006
-     * @return EE_Base_Class|array
3007
-     * @throws EE_Error
3008
-     * @throws ReflectionException
3009
-     */
3010
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
3011
-    {
3012
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
3013
-            $fields_n_values = $obj_or_fields_array->model_field_array();
3014
-        } elseif (is_array($obj_or_fields_array)) {
3015
-            $fields_n_values = $obj_or_fields_array;
3016
-        } else {
3017
-            throw new EE_Error(
3018
-                sprintf(
3019
-                    esc_html__(
3020
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
3021
-                        "event_espresso"
3022
-                    ),
3023
-                    get_class($this),
3024
-                    $obj_or_fields_array
3025
-                )
3026
-            );
3027
-        }
3028
-        $query_params = [];
3029
-        if (
3030
-            $this->has_primary_key_field()
3031
-            && ($include_primary_key
3032
-                || $this->get_primary_key_field()
3033
-                   instanceof
3034
-                   EE_Primary_Key_String_Field)
3035
-            && isset($fields_n_values[ $this->primary_key_name() ])
3036
-        ) {
3037
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3038
-        }
3039
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3040
-            $uniqueness_where_params                              =
3041
-                array_intersect_key($fields_n_values, $unique_index->fields());
3042
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3043
-        }
3044
-        // if there is nothing to base this search on, then we shouldn't find anything
3045
-        if (empty($query_params)) {
3046
-            return [];
3047
-        }
3048
-        return $this->get_one($query_params);
3049
-    }
3050
-
3051
-
3052
-    /**
3053
-     * Like count, but is optimized and returns a boolean instead of an int
3054
-     *
3055
-     * @param array $query_params
3056
-     * @return boolean
3057
-     * @throws EE_Error
3058
-     * @throws ReflectionException
3059
-     */
3060
-    public function exists($query_params)
3061
-    {
3062
-        $query_params['limit'] = 1;
3063
-        return $this->count($query_params) > 0;
3064
-    }
3065
-
3066
-
3067
-    /**
3068
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
3069
-     *
3070
-     * @param int|string $id
3071
-     * @return boolean
3072
-     * @throws EE_Error
3073
-     * @throws ReflectionException
3074
-     */
3075
-    public function exists_by_ID($id)
3076
-    {
3077
-        return $this->exists(
3078
-            [
3079
-                'default_where_conditions' => EE_Default_Where_Conditions::NONE,
3080
-                [
3081
-                    $this->primary_key_name() => $id,
3082
-                ],
3083
-            ]
3084
-        );
3085
-    }
3086
-
3087
-
3088
-    /**
3089
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3090
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3091
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3092
-     * on the main table)
3093
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3094
-     * cases where we want to call it directly rather than via insert().
3095
-     *
3096
-     * @access   protected
3097
-     * @param EE_Table_Base $table
3098
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3099
-     *                                       float
3100
-     * @param int           $new_id          for now we assume only int keys
3101
-     * @return int ID of new row inserted, or FALSE on failure
3102
-     * @throws EE_Error
3103
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3104
-     */
3105
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3106
-    {
3107
-        global $wpdb;
3108
-        $insertion_col_n_values = [];
3109
-        $format_for_insertion   = [];
3110
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3111
-        foreach ($fields_on_table as $field_obj) {
3112
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3113
-            if ($field_obj->is_auto_increment()) {
3114
-                continue;
3115
-            }
3116
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3117
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3118
-            if ($prepared_value !== null) {
3119
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3120
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3121
-            }
3122
-        }
3123
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3124
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3125
-            // so add the fk to the main table as a column
3126
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3127
-            $format_for_insertion[]                              =
3128
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3129
-        }
3130
-
3131
-        // insert the new entry
3132
-        $result = $this->_do_wpdb_query(
3133
-            'insert',
3134
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3135
-        );
3136
-        if ($result === false) {
3137
-            return false;
3138
-        }
3139
-        // ok, now what do we return for the ID of the newly-inserted thing?
3140
-        if ($this->has_primary_key_field()) {
3141
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3142
-                return $wpdb->insert_id;
3143
-            }
3144
-            // it's not an auto-increment primary key, so
3145
-            // it must have been supplied
3146
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3147
-        }
3148
-        // we can't return a  primary key because there is none. instead return
3149
-        // a unique string indicating this model
3150
-        return $this->get_index_primary_key_string($fields_n_values);
3151
-    }
3152
-
3153
-
3154
-    /**
3155
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3156
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3157
-     * and there is no default, we pass it along. WPDB will take care of it)
3158
-     *
3159
-     * @param EE_Model_Field_Base $field_obj
3160
-     * @param array               $fields_n_values
3161
-     * @return mixed string|int|float depending on what the table column will be expecting
3162
-     * @throws EE_Error
3163
-     */
3164
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3165
-    {
3166
-        $field_name = $field_obj->get_name();
3167
-        // if this field doesn't allow nullable, don't allow it
3168
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3169
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3170
-        }
3171
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3172
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3173
-    }
3174
-
3175
-
3176
-    /**
3177
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3178
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3179
-     * the field's prepare_for_set() method.
3180
-     *
3181
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3182
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3183
-     *                                   top of file)
3184
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3185
-     *                                   $value is a custom selection
3186
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3187
-     */
3188
-    private function _prepare_value_for_use_in_db($value, $field)
3189
-    {
3190
-        if ($field instanceof EE_Model_Field_Base) {
3191
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3192
-            switch ($this->_values_already_prepared_by_model_object) {
3193
-                /** @noinspection PhpMissingBreakStatementInspection */
3194
-                case self::not_prepared_by_model_object:
3195
-                    $value = $field->prepare_for_set($value);
3196
-                // purposefully left out "return"
3197
-                // no break
3198
-                case self::prepared_by_model_object:
3199
-                    /** @noinspection SuspiciousAssignmentsInspection */
3200
-                    $value = $field->prepare_for_use_in_db($value);
3201
-                // no break
3202
-                case self::prepared_for_use_in_db:
3203
-                    // leave the value alone
3204
-            }
3205
-            // phpcs:enable
3206
-        }
3207
-        return $value;
3208
-    }
3209
-
3210
-
3211
-    /**
3212
-     * Returns the main table on this model
3213
-     *
3214
-     * @return EE_Primary_Table
3215
-     * @throws EE_Error
3216
-     */
3217
-    protected function _get_main_table()
3218
-    {
3219
-        foreach ($this->_tables as $table) {
3220
-            if ($table instanceof EE_Primary_Table) {
3221
-                return $table;
3222
-            }
3223
-        }
3224
-        throw new EE_Error(
3225
-            sprintf(
3226
-                esc_html__(
3227
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3228
-                    'event_espresso'
3229
-                ),
3230
-                get_class($this)
3231
-            )
3232
-        );
3233
-    }
3234
-
3235
-
3236
-    /**
3237
-     * table
3238
-     * returns EE_Primary_Table table name
3239
-     *
3240
-     * @return string
3241
-     * @throws EE_Error
3242
-     */
3243
-    public function table()
3244
-    {
3245
-        return $this->_get_main_table()->get_table_name();
3246
-    }
3247
-
3248
-
3249
-    /**
3250
-     * table
3251
-     * returns first EE_Secondary_Table table name
3252
-     *
3253
-     * @return string
3254
-     */
3255
-    public function second_table()
3256
-    {
3257
-        // grab second table from tables array
3258
-        $second_table = end($this->_tables);
3259
-        return $second_table instanceof EE_Secondary_Table
3260
-            ? $second_table->get_table_name()
3261
-            : null;
3262
-    }
3263
-
3264
-
3265
-    /**
3266
-     * get_table_obj_by_alias
3267
-     * returns table name given it's alias
3268
-     *
3269
-     * @param string $table_alias
3270
-     * @return EE_Primary_Table | EE_Secondary_Table
3271
-     */
3272
-    public function get_table_obj_by_alias($table_alias = '')
3273
-    {
3274
-        return $this->_tables[ $table_alias ] ?? null;
3275
-    }
3276
-
3277
-
3278
-    /**
3279
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3280
-     *
3281
-     * @return EE_Secondary_Table[]
3282
-     */
3283
-    protected function _get_other_tables()
3284
-    {
3285
-        $other_tables = [];
3286
-        foreach ($this->_tables as $table_alias => $table) {
3287
-            if ($table instanceof EE_Secondary_Table) {
3288
-                $other_tables[ $table_alias ] = $table;
3289
-            }
3290
-        }
3291
-        return $other_tables;
3292
-    }
3293
-
3294
-
3295
-    /**
3296
-     * Finds all the fields that correspond to the given table
3297
-     *
3298
-     * @param string $table_alias , array key in EEM_Base::_tables
3299
-     * @return EE_Model_Field_Base[]
3300
-     */
3301
-    public function _get_fields_for_table($table_alias)
3302
-    {
3303
-        return $this->_fields[ $table_alias ];
3304
-    }
3305
-
3306
-
3307
-    /**
3308
-     * Recurses through all the where parameters, and finds all the related models we'll need
3309
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3310
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3311
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3312
-     * related Registration, Transaction, and Payment models.
3313
-     *
3314
-     * @param array $query_params @see
3315
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3316
-     * @return EE_Model_Query_Info_Carrier
3317
-     * @throws EE_Error
3318
-     */
3319
-    public function _extract_related_models_from_query($query_params)
3320
-    {
3321
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3322
-        if (array_key_exists(0, $query_params)) {
3323
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3324
-        }
3325
-        if (array_key_exists('group_by', $query_params)) {
3326
-            if (is_array($query_params['group_by'])) {
3327
-                $this->_extract_related_models_from_sub_params_array_values(
3328
-                    $query_params['group_by'],
3329
-                    $query_info_carrier,
3330
-                    'group_by'
3331
-                );
3332
-            } elseif (! empty($query_params['group_by'])) {
3333
-                $this->_extract_related_model_info_from_query_param(
3334
-                    $query_params['group_by'],
3335
-                    $query_info_carrier,
3336
-                    'group_by'
3337
-                );
3338
-            }
3339
-        }
3340
-        if (array_key_exists('having', $query_params)) {
3341
-            $this->_extract_related_models_from_sub_params_array_keys(
3342
-                $query_params[0],
3343
-                $query_info_carrier,
3344
-                'having'
3345
-            );
3346
-        }
3347
-        if (array_key_exists('order_by', $query_params)) {
3348
-            if (is_array($query_params['order_by'])) {
3349
-                $this->_extract_related_models_from_sub_params_array_keys(
3350
-                    $query_params['order_by'],
3351
-                    $query_info_carrier,
3352
-                    'order_by'
3353
-                );
3354
-            } elseif (! empty($query_params['order_by'])) {
3355
-                $this->_extract_related_model_info_from_query_param(
3356
-                    $query_params['order_by'],
3357
-                    $query_info_carrier,
3358
-                    'order_by'
3359
-                );
3360
-            }
3361
-        }
3362
-        if (array_key_exists('force_join', $query_params)) {
3363
-            $this->_extract_related_models_from_sub_params_array_values(
3364
-                $query_params['force_join'],
3365
-                $query_info_carrier,
3366
-                'force_join'
3367
-            );
3368
-        }
3369
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3370
-        return $query_info_carrier;
3371
-    }
3372
-
3373
-
3374
-    /**
3375
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3376
-     *
3377
-     * @param array                       $sub_query_params
3378
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3379
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3380
-     * @return EE_Model_Query_Info_Carrier
3381
-     * @throws EE_Error
3382
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3383
-     */
3384
-    private function _extract_related_models_from_sub_params_array_keys(
3385
-        $sub_query_params,
3386
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3387
-        $query_param_type
3388
-    ) {
3389
-        if (! empty($sub_query_params)) {
3390
-            $sub_query_params = (array) $sub_query_params;
3391
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3392
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3393
-                $this->_extract_related_model_info_from_query_param(
3394
-                    $param,
3395
-                    $model_query_info_carrier,
3396
-                    $query_param_type
3397
-                );
3398
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3399
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3400
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3401
-                // of array('Registration.TXN_ID'=>23)
3402
-                $query_param_sans_stars =
3403
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3404
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3405
-                    if (! is_array($possibly_array_of_params)) {
3406
-                        throw new EE_Error(
3407
-                            sprintf(
3408
-                                esc_html__(
3409
-                                    "You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3410
-                                    "event_espresso"
3411
-                                ),
3412
-                                $param,
3413
-                                $possibly_array_of_params
3414
-                            )
3415
-                        );
3416
-                    }
3417
-                    $this->_extract_related_models_from_sub_params_array_keys(
3418
-                        $possibly_array_of_params,
3419
-                        $model_query_info_carrier,
3420
-                        $query_param_type
3421
-                    );
3422
-                } elseif (
3423
-                    $query_param_type === 0 // ie WHERE
3424
-                    && is_array($possibly_array_of_params) // need is_array() check so we don't try to explode a string
3425
-                    && isset($possibly_array_of_params[2])
3426
-                    && $possibly_array_of_params[2]
3427
-                ) {
3428
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3429
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3430
-                    // from which we should extract query parameters!
3431
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3432
-                        throw new EE_Error(
3433
-                            sprintf(
3434
-                                esc_html__(
3435
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3436
-                                    "event_espresso"
3437
-                                ),
3438
-                                $query_param_type,
3439
-                                implode(",", $possibly_array_of_params)
3440
-                            )
3441
-                        );
3442
-                    }
3443
-                    $this->_extract_related_model_info_from_query_param(
3444
-                        $possibly_array_of_params[1],
3445
-                        $model_query_info_carrier,
3446
-                        $query_param_type
3447
-                    );
3448
-                }
3449
-            }
3450
-        }
3451
-        return $model_query_info_carrier;
3452
-    }
3453
-
3454
-
3455
-    /**
3456
-     * For extracting related models from forced_joins, where the array values contain the info about what
3457
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3458
-     *
3459
-     * @param array                       $sub_query_params @see
3460
-     *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3461
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3462
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3463
-     * @return EE_Model_Query_Info_Carrier
3464
-     * @throws EE_Error
3465
-     */
3466
-    private function _extract_related_models_from_sub_params_array_values(
3467
-        $sub_query_params,
3468
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3469
-        $query_param_type
3470
-    ) {
3471
-        if (! empty($sub_query_params)) {
3472
-            if (! is_array($sub_query_params)) {
3473
-                throw new EE_Error(
3474
-                    sprintf(
3475
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3476
-                        $sub_query_params
3477
-                    )
3478
-                );
3479
-            }
3480
-            foreach ($sub_query_params as $param) {
3481
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3482
-                $this->_extract_related_model_info_from_query_param(
3483
-                    $param,
3484
-                    $model_query_info_carrier,
3485
-                    $query_param_type
3486
-                );
3487
-            }
3488
-        }
3489
-        return $model_query_info_carrier;
3490
-    }
3491
-
3492
-
3493
-    /**
3494
-     * Extract all the query parts from  model query params
3495
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3496
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3497
-     * but use them in a different order. Eg, we need to know what models we are querying
3498
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3499
-     * other models before we can finalize the where clause SQL.
3500
-     *
3501
-     * @param array $query_params
3502
-     * @return EE_Model_Query_Info_Carrier
3503
-     * @throws EE_Error
3504
-     * @throws ModelConfigurationException
3505
-     * @throws ReflectionException
3506
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3507
-     */
3508
-    public function _create_model_query_info_carrier($query_params)
3509
-    {
3510
-        if (! is_array($query_params)) {
3511
-            EE_Error::doing_it_wrong(
3512
-                'EEM_Base::_create_model_query_info_carrier',
3513
-                sprintf(
3514
-                    esc_html__(
3515
-                        '$query_params should be an array, you passed a variable of type %s',
3516
-                        'event_espresso'
3517
-                    ),
3518
-                    gettype($query_params)
3519
-                ),
3520
-                '4.6.0'
3521
-            );
3522
-            $query_params = [];
3523
-        }
3524
-        $query_params[0] = $query_params[0] ?? [];
3525
-        // first check if we should alter the query to account for caps or not
3526
-        // because the caps might require us to do extra joins
3527
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3528
-            $query_params[0] = array_replace_recursive(
3529
-                $query_params[0],
3530
-                $this->caps_where_conditions($query_params['caps'])
3531
-            );
3532
-        }
3533
-
3534
-        // check if we should alter the query to remove data related to protected
3535
-        // custom post types
3536
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3537
-            $where_param_key_for_password = $this->modelChainAndPassword();
3538
-            // only include if related to a cpt where no password has been set
3539
-            $query_params[0]['OR*nopassword'] = [
3540
-                $where_param_key_for_password       => '',
3541
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3542
-            ];
3543
-        }
3544
-        $query_object = $this->_extract_related_models_from_query($query_params);
3545
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3546
-        foreach ($query_params[0] as $key => $value) {
3547
-            if (is_int($key)) {
3548
-                throw new EE_Error(
3549
-                    sprintf(
3550
-                        esc_html__(
3551
-                            "WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3552
-                            "event_espresso"
3553
-                        ),
3554
-                        $key,
3555
-                        var_export($value, true),
3556
-                        var_export($query_params, true),
3557
-                        get_class($this)
3558
-                    )
3559
-                );
3560
-            }
3561
-        }
3562
-        if (
3563
-            array_key_exists('default_where_conditions', $query_params)
3564
-            && ! empty($query_params['default_where_conditions'])
3565
-        ) {
3566
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3567
-        } else {
3568
-            $use_default_where_conditions = EE_Default_Where_Conditions::ALL;
3569
-        }
3570
-        $query_params[0] = array_merge(
3571
-            $this->_get_default_where_conditions_for_models_in_query(
3572
-                $query_object,
3573
-                $use_default_where_conditions,
3574
-                $query_params[0]
3575
-            ),
3576
-            $query_params[0]
3577
-        );
3578
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3579
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3580
-        // So we need to setup a subquery and use that for the main join.
3581
-        // Note for now this only works on the primary table for the model.
3582
-        // So for instance, you could set the limit array like this:
3583
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3584
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3585
-            $query_object->set_main_model_join_sql(
3586
-                $this->_construct_limit_join_select(
3587
-                    $query_params['on_join_limit'][0],
3588
-                    $query_params['on_join_limit'][1]
3589
-                )
3590
-            );
3591
-        }
3592
-        // set limit
3593
-        if (array_key_exists('limit', $query_params)) {
3594
-            if (is_array($query_params['limit'])) {
3595
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3596
-                    $e = sprintf(
3597
-                        esc_html__(
3598
-                            "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3599
-                            "event_espresso"
3600
-                        ),
3601
-                        http_build_query($query_params['limit'])
3602
-                    );
3603
-                    throw new EE_Error($e . "|" . $e);
3604
-                }
3605
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3606
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3607
-            } elseif (! empty($query_params['limit'])) {
3608
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3609
-            }
3610
-        }
3611
-        // set order by
3612
-        if (array_key_exists('order_by', $query_params)) {
3613
-            if (is_array($query_params['order_by'])) {
3614
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3615
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3616
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3617
-                if (array_key_exists('order', $query_params)) {
3618
-                    throw new EE_Error(
3619
-                        sprintf(
3620
-                            esc_html__(
3621
-                                "In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3622
-                                "event_espresso"
3623
-                            ),
3624
-                            get_class($this),
3625
-                            implode(", ", array_keys($query_params['order_by'])),
3626
-                            implode(", ", $query_params['order_by']),
3627
-                            $query_params['order']
3628
-                        )
3629
-                    );
3630
-                }
3631
-                $this->_extract_related_models_from_sub_params_array_keys(
3632
-                    $query_params['order_by'],
3633
-                    $query_object,
3634
-                    'order_by'
3635
-                );
3636
-                // assume it's an array of fields to order by
3637
-                $order_array = [];
3638
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3639
-                    $order         = $this->_extract_order($order);
3640
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3641
-                }
3642
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3643
-            } elseif (! empty($query_params['order_by'])) {
3644
-                $this->_extract_related_model_info_from_query_param(
3645
-                    $query_params['order_by'],
3646
-                    $query_object,
3647
-                    'order',
3648
-                    $query_params['order_by']
3649
-                );
3650
-                $order = isset($query_params['order'])
3651
-                    ? $this->_extract_order($query_params['order'])
3652
-                    : 'DESC';
3653
-                $query_object->set_order_by_sql(
3654
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3655
-                );
3656
-            }
3657
-        }
3658
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3659
-        if (
3660
-            ! array_key_exists('order_by', $query_params)
3661
-            && array_key_exists('order', $query_params)
3662
-            && ! empty($query_params['order'])
3663
-        ) {
3664
-            $pk_field = $this->get_primary_key_field();
3665
-            $order    = $this->_extract_order($query_params['order']);
3666
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3667
-        }
3668
-        // set group by
3669
-        if (array_key_exists('group_by', $query_params)) {
3670
-            if (is_array($query_params['group_by'])) {
3671
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3672
-                $group_by_array = [];
3673
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3674
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3675
-                }
3676
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3677
-            } elseif (! empty($query_params['group_by'])) {
3678
-                $query_object->set_group_by_sql(
3679
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3680
-                );
3681
-            }
3682
-        }
3683
-        // set having
3684
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3685
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3686
-        }
3687
-        // now, just verify they didn't pass anything wack
3688
-        foreach ($query_params as $query_key => $query_value) {
3689
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3690
-                throw new EE_Error(
3691
-                    sprintf(
3692
-                        esc_html__(
3693
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3694
-                            'event_espresso'
3695
-                        ),
3696
-                        $query_key,
3697
-                        get_class($this),
3698
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3699
-                        implode(',', $this->_allowed_query_params)
3700
-                    )
3701
-                );
3702
-            }
3703
-        }
3704
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3705
-        if (empty($main_model_join_sql)) {
3706
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3707
-        }
3708
-        return $query_object;
3709
-    }
3710
-
3711
-
3712
-    /**
3713
-     * Gets the where conditions that should be imposed on the query based on the
3714
-     * context (eg reading frontend, backend, edit or delete).
3715
-     *
3716
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3717
-     * @return array @see
3718
-     *                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3719
-     * @throws EE_Error
3720
-     */
3721
-    public function caps_where_conditions($context = self::caps_read)
3722
-    {
3723
-        EEM_Base::verify_is_valid_cap_context($context);
3724
-        $cap_where_conditions = [];
3725
-        $cap_restrictions     = $this->caps_missing($context);
3726
-        foreach ($cap_restrictions as $restriction_if_no_cap) {
3727
-            $cap_where_conditions = array_replace_recursive(
3728
-                $cap_where_conditions,
3729
-                $restriction_if_no_cap->get_default_where_conditions()
3730
-            );
3731
-        }
3732
-        return apply_filters(
3733
-            'FHEE__EEM_Base__caps_where_conditions__return',
3734
-            $cap_where_conditions,
3735
-            $this,
3736
-            $context,
3737
-            $cap_restrictions
3738
-        );
3739
-    }
3740
-
3741
-
3742
-    /**
3743
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3744
-     * otherwise throws an exception
3745
-     *
3746
-     * @param string $should_be_order_string
3747
-     * @return string either ASC, asc, DESC or desc
3748
-     * @throws EE_Error
3749
-     */
3750
-    private function _extract_order($should_be_order_string)
3751
-    {
3752
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3753
-            return $should_be_order_string;
3754
-        }
3755
-        throw new EE_Error(
3756
-            sprintf(
3757
-                esc_html__(
3758
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3759
-                    "event_espresso"
3760
-                ),
3761
-                get_class($this),
3762
-                $should_be_order_string
3763
-            )
3764
-        );
3765
-    }
3766
-
3767
-
3768
-    /**
3769
-     * Looks at all the models which are included in this query, and asks each
3770
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3771
-     * so they can be merged
3772
-     *
3773
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3774
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3775
-     *                                                                  'none' means NO default where conditions will
3776
-     *                                                                  be used AT ALL during this query.
3777
-     *                                                                  'other_models_only' means default where
3778
-     *                                                                  conditions from other models will be used, but
3779
-     *                                                                  not for this primary model. 'all', the default,
3780
-     *                                                                  means default where conditions will apply as
3781
-     *                                                                  normal
3782
-     * @param array                       $where_query_params
3783
-     * @return array
3784
-     * @throws EE_Error
3785
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params
3786
-     *                                                                  .md#0-where-conditions
3787
-     */
3788
-    private function _get_default_where_conditions_for_models_in_query(
3789
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3790
-        $use_default_where_conditions = EE_Default_Where_Conditions::ALL,
3791
-        $where_query_params = []
3792
-    ) {
3793
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3794
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3795
-            throw new EE_Error(
3796
-                sprintf(
3797
-                    esc_html__(
3798
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3799
-                        "event_espresso"
3800
-                    ),
3801
-                    $use_default_where_conditions,
3802
-                    implode(", ", $allowed_used_default_where_conditions_values)
3803
-                )
3804
-            );
3805
-        }
3806
-        $universal_query_params = [];
3807
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3808
-            $universal_query_params = $this->_get_default_where_conditions();
3809
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3810
-            $universal_query_params = $this->_get_minimum_where_conditions();
3811
-        }
3812
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3813
-            $related_model = $this->get_related_model_obj($model_name);
3814
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3815
-                $related_model_universal_where_params =
3816
-                    $related_model->_get_default_where_conditions($model_relation_path);
3817
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3818
-                $related_model_universal_where_params =
3819
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3820
-            } else {
3821
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3822
-                continue;
3823
-            }
3824
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3825
-                $related_model_universal_where_params,
3826
-                $where_query_params,
3827
-                $related_model,
3828
-                $model_relation_path
3829
-            );
3830
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3831
-                $universal_query_params,
3832
-                $overrides
3833
-            );
3834
-        }
3835
-        return $universal_query_params;
3836
-    }
3837
-
3838
-
3839
-    /**
3840
-     * Determines whether or not we should use default where conditions for the model in question
3841
-     * (this model, or other related models).
3842
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3843
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3844
-     * We should use default where conditions on related models when they requested to use default where conditions
3845
-     * on all models, or specifically just on other related models
3846
-     *
3847
-     * @param      $default_where_conditions_value
3848
-     * @param bool $for_this_model false means this is for OTHER related models
3849
-     * @return bool
3850
-     */
3851
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3852
-    {
3853
-        return (
3854
-                   $for_this_model
3855
-                   && in_array(
3856
-                       $default_where_conditions_value,
3857
-                       [
3858
-                           EE_Default_Where_Conditions::ALL,
3859
-                           EE_Default_Where_Conditions::THIS_MODEL_ONLY,
3860
-                           EE_Default_Where_Conditions::MINIMUM_OTHERS,
3861
-                       ],
3862
-                       true
3863
-                   )
3864
-               )
3865
-               || (
3866
-                   ! $for_this_model
3867
-                   && in_array(
3868
-                       $default_where_conditions_value,
3869
-                       [
3870
-                           EE_Default_Where_Conditions::ALL,
3871
-                           EE_Default_Where_Conditions::OTHER_MODELS_ONLY,
3872
-                       ],
3873
-                       true
3874
-                   )
3875
-               );
3876
-    }
3877
-
3878
-
3879
-    /**
3880
-     * Determines whether or not we should use default minimum conditions for the model in question
3881
-     * (this model, or other related models).
3882
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3883
-     * where conditions.
3884
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3885
-     * on this model or others
3886
-     *
3887
-     * @param      $default_where_conditions_value
3888
-     * @param bool $for_this_model false means this is for OTHER related models
3889
-     * @return bool
3890
-     */
3891
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3892
-    {
3893
-        return (
3894
-                   $for_this_model
3895
-                   && $default_where_conditions_value === EE_Default_Where_Conditions::MINIMUM_ALL
3896
-               )
3897
-               || (
3898
-                   ! $for_this_model
3899
-                   && in_array(
3900
-                       $default_where_conditions_value,
3901
-                       [
3902
-                           EE_Default_Where_Conditions::MINIMUM_OTHERS,
3903
-                           EE_Default_Where_Conditions::MINIMUM_ALL,
3904
-                       ],
3905
-                       true
3906
-                   )
3907
-               );
3908
-    }
3909
-
3910
-
3911
-    /**
3912
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3913
-     * then we also add a special where condition which allows for that model's primary key
3914
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3915
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3916
-     *
3917
-     * @param array    $default_where_conditions
3918
-     * @param array    $provided_where_conditions
3919
-     * @param EEM_Base $model
3920
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3921
-     * @return array @see
3922
-     *                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3923
-     * @throws EE_Error
3924
-     */
3925
-    private function _override_defaults_or_make_null_friendly(
3926
-        $default_where_conditions,
3927
-        $provided_where_conditions,
3928
-        $model,
3929
-        $model_relation_path
3930
-    ) {
3931
-        $null_friendly_where_conditions = [];
3932
-        $none_overridden                = true;
3933
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3934
-        foreach ($default_where_conditions as $key => $val) {
3935
-            if (isset($provided_where_conditions[ $key ])) {
3936
-                $none_overridden = false;
3937
-            } else {
3938
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3939
-            }
3940
-        }
3941
-        if ($none_overridden && $default_where_conditions) {
3942
-            if ($model->has_primary_key_field()) {
3943
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3944
-                                                                                   . "."
3945
-                                                                                   . $model->primary_key_name() ] =
3946
-                    ['IS NULL'];
3947
-            }/*else{
2626
+			$this->_show_next_x_db_queries--;
2627
+		}
2628
+	}
2629
+
2630
+
2631
+	/**
2632
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2633
+	 * There are the 3 cases:
2634
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2635
+	 * $otherModelObject has no ID, it is first saved.
2636
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2637
+	 * has no ID, it is first saved.
2638
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2639
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2640
+	 * join table
2641
+	 *
2642
+	 * @param EE_Base_Class|int $id_or_obj                        EE_base_Class or ID of $thisModelObject
2643
+	 * @param EE_Base_Class|int $other_model_id_or_obj            EE_base_Class or ID of other Model Object
2644
+	 * @param string            $relationName                     , key in EEM_Base::_relations
2645
+	 *                                                            an attendee to a group, you also want to specify
2646
+	 *                                                            which role they will have in that group. So you would
2647
+	 *                                                            use this parameter to specify
2648
+	 *                                                            array('role-column-name'=>'role-id')
2649
+	 * @param array|null        $extra_join_model_fields_n_values This allows you to enter further query params for the
2650
+	 *                                                            relation to for relation to methods that allow you to
2651
+	 *                                                            further specify extra columns to join by (such as
2652
+	 *                                                            HABTM).  Keep in mind that the only acceptable
2653
+	 *                                                            query_params is strict "col" => "value" pairs because
2654
+	 *                                                            these will be inserted in any new rows created as
2655
+	 *                                                            well.
2656
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2657
+	 * @throws EE_Error
2658
+	 */
2659
+	public function add_relationship_to(
2660
+		$id_or_obj,
2661
+		$other_model_id_or_obj,
2662
+		$relationName,
2663
+		$extra_join_model_fields_n_values = []
2664
+	) {
2665
+		$relation_obj = $this->related_settings_for($relationName);
2666
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2667
+	}
2668
+
2669
+
2670
+	/**
2671
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2672
+	 * There are the 3 cases:
2673
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2674
+	 * error
2675
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2676
+	 * an error
2677
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2678
+	 *
2679
+	 * @param EE_Base_Class|int $id_or_obj             EE_base_Class or ID of $thisModelObject
2680
+	 * @param EE_Base_Class|int $other_model_id_or_obj EE_base_Class or ID of other Model Object
2681
+	 * @param string            $relationName          key in EEM_Base::_relations
2682
+	 * @param array|null        $where_query           This allows you to enter further query params for the relation
2683
+	 *                                                 to for relation to methods that allow you to further specify
2684
+	 *                                                 extra columns to join by (such as HABTM). Keep in mind that the
2685
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2686
+	 *                                                 because these will be inserted in any new rows created as well.
2687
+	 * @return EE_Base_Class
2688
+	 * @throws EE_Error
2689
+	 */
2690
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2691
+	{
2692
+		$relation_obj = $this->related_settings_for($relationName);
2693
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2694
+	}
2695
+
2696
+
2697
+	/**
2698
+	 * @param mixed       $id_or_obj
2699
+	 * @param string      $relationName
2700
+	 * @param array|null  $where_query_params
2701
+	 * @return EE_Base_Class[]
2702
+	 * @throws EE_Error
2703
+	 * @throws ReflectionException
2704
+	 */
2705
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2706
+	{
2707
+		$relation_obj = $this->related_settings_for($relationName);
2708
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2709
+	}
2710
+
2711
+
2712
+	/**
2713
+	 * Gets all the related items of the specified $model_name, using $query_params.
2714
+	 * Note: by default, we remove the "default query params"
2715
+	 * because we want to get even deleted items etc.
2716
+	 *
2717
+	 * @param mixed       $id_or_obj    EE_Base_Class child or its ID
2718
+	 * @param string      $model_name   like 'Event', 'Registration', etc. always singular
2719
+	 * @param array|null  $query_params @see
2720
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2721
+	 * @return EE_Base_Class[]
2722
+	 * @throws EE_Error
2723
+	 * @throws ReflectionException
2724
+	 */
2725
+	public function get_all_related($id_or_obj, $model_name, ?array $query_params = [])
2726
+	{
2727
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2728
+		$relation_settings = $this->related_settings_for($model_name);
2729
+		return $relation_settings->get_all_related($model_obj, $query_params);
2730
+	}
2731
+
2732
+
2733
+	/**
2734
+	 * Deletes all the model objects across the relation indicated by $model_name
2735
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2736
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2737
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2738
+	 *
2739
+	 * @param EE_Base_Class|int|string $id_or_obj
2740
+	 * @param string                   $model_name
2741
+	 * @param array|null               $query_params
2742
+	 * @return int how many deleted
2743
+	 * @throws EE_Error
2744
+	 * @throws ReflectionException
2745
+	 */
2746
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2747
+	{
2748
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2749
+		$relation_settings = $this->related_settings_for($model_name);
2750
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2751
+	}
2752
+
2753
+
2754
+	/**
2755
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2756
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2757
+	 * the model objects can't be hard deleted because of blocking related model objects,
2758
+	 * just does a soft-delete on them instead.
2759
+	 *
2760
+	 * @param EE_Base_Class|int|string $id_or_obj
2761
+	 * @param string                   $model_name
2762
+	 * @param array|null               $query_params
2763
+	 * @return int how many deleted
2764
+	 * @throws EE_Error
2765
+	 * @throws ReflectionException
2766
+	 */
2767
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2768
+	{
2769
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2770
+		$relation_settings = $this->related_settings_for($model_name);
2771
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2772
+	}
2773
+
2774
+
2775
+	/**
2776
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2777
+	 * unless otherwise specified in the $query_params
2778
+	 *
2779
+	 * @param EE_Base_Class|int|string $id_or_obj
2780
+	 * @param string                   $model_name     like 'Event', or 'Registration'
2781
+	 * @param array|null               $query_params   @see
2782
+	 *                                                 https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2783
+	 * @param string                   $field_to_count name of field to count by. By default, uses primary key
2784
+	 * @param bool                     $distinct       if we want to only count the distinct values for the column then
2785
+	 *                                                 you can trigger that by the setting $distinct to TRUE;
2786
+	 * @return int
2787
+	 * @throws EE_Error
2788
+	 * @throws ReflectionException
2789
+	 */
2790
+	public function count_related(
2791
+		$id_or_obj,
2792
+		$model_name,
2793
+		$query_params = [],
2794
+		$field_to_count = null,
2795
+		$distinct = false
2796
+	) {
2797
+		$related_model = $this->get_related_model_obj($model_name);
2798
+		// we're just going to use the query params on the related model's normal get_all query,
2799
+		// except add a condition to say to match the current mod
2800
+		if (! isset($query_params['default_where_conditions'])) {
2801
+			$query_params['default_where_conditions'] = EE_Default_Where_Conditions::NONE;
2802
+		}
2803
+		$this_model_name                                                 = $this->get_this_model_name();
2804
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2805
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2806
+		return $related_model->count($query_params, $field_to_count, $distinct);
2807
+	}
2808
+
2809
+
2810
+	/**
2811
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2812
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2813
+	 *
2814
+	 * @param EE_Base_Class|int|string $id_or_obj
2815
+	 * @param string                   $model_name   like 'Event', or 'Registration'
2816
+	 * @param array|null               $query_params @see
2817
+	 *                                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2818
+	 * @param string                   $field_to_sum name of field to count by. By default, uses primary key
2819
+	 * @return float
2820
+	 * @throws EE_Error
2821
+	 * @throws ReflectionException
2822
+	 */
2823
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2824
+	{
2825
+		$related_model = $this->get_related_model_obj($model_name);
2826
+		if (! is_array($query_params)) {
2827
+			EE_Error::doing_it_wrong(
2828
+				'EEM_Base::sum_related',
2829
+				sprintf(
2830
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2831
+					gettype($query_params)
2832
+				),
2833
+				'4.6.0'
2834
+			);
2835
+			$query_params = [];
2836
+		}
2837
+		// we're just going to use the query params on the related model's normal get_all query,
2838
+		// except add a condition to say to match the current mod
2839
+		if (! isset($query_params['default_where_conditions'])) {
2840
+			$query_params['default_where_conditions'] = EE_Default_Where_Conditions::NONE;
2841
+		}
2842
+		$this_model_name                                                 = $this->get_this_model_name();
2843
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2844
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2845
+		return $related_model->sum($query_params, $field_to_sum);
2846
+	}
2847
+
2848
+
2849
+	/**
2850
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2851
+	 * $modelObject
2852
+	 *
2853
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2854
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2855
+	 * @param array|null          $query_params     @see
2856
+	 *                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2857
+	 * @return EE_Base_Class
2858
+	 * @throws EE_Error
2859
+	 * @throws ReflectionException
2860
+	 */
2861
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2862
+	{
2863
+		$query_params['limit'] = 1;
2864
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2865
+		if ($results) {
2866
+			return array_shift($results);
2867
+		}
2868
+		return null;
2869
+	}
2870
+
2871
+
2872
+	/**
2873
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2874
+	 *
2875
+	 * @return string
2876
+	 */
2877
+	public function get_this_model_name()
2878
+	{
2879
+		return str_replace("EEM_", "", get_class($this));
2880
+	}
2881
+
2882
+
2883
+	/**
2884
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2885
+	 *
2886
+	 * @return EE_Any_Foreign_Model_Name_Field
2887
+	 * @throws EE_Error
2888
+	 */
2889
+	public function get_field_containing_related_model_name()
2890
+	{
2891
+		foreach ($this->field_settings(true) as $field) {
2892
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2893
+				$field_with_model_name = $field;
2894
+			}
2895
+		}
2896
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2897
+			throw new EE_Error(
2898
+				sprintf(
2899
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2900
+					$this->get_this_model_name()
2901
+				)
2902
+			);
2903
+		}
2904
+		return $field_with_model_name;
2905
+	}
2906
+
2907
+
2908
+	/**
2909
+	 * Inserts a new entry into the database, for each table.
2910
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2911
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2912
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2913
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2914
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2915
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2916
+	 *
2917
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2918
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2919
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2920
+	 *                              of EEM_Base)
2921
+	 * @return int|string new primary key on main table that got inserted
2922
+	 * @throws EE_Error
2923
+	 * @throws ReflectionException
2924
+	 */
2925
+	public function insert($field_n_values)
2926
+	{
2927
+		/**
2928
+		 * Filters the fields and their values before inserting an item using the models
2929
+		 *
2930
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2931
+		 * @param EEM_Base $model           the model used
2932
+		 */
2933
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2934
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2935
+			$main_table = $this->_get_main_table();
2936
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2937
+			if ($new_id !== false) {
2938
+				foreach ($this->_get_other_tables() as $other_table) {
2939
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2940
+				}
2941
+			}
2942
+			/**
2943
+			 * Done just after attempting to insert a new model object
2944
+			 *
2945
+			 * @param EEM_Base $model           used
2946
+			 * @param array    $fields_n_values fields and their values
2947
+			 * @param int|string the              ID of the newly-inserted model object
2948
+			 */
2949
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2950
+			return $new_id;
2951
+		}
2952
+		return false;
2953
+	}
2954
+
2955
+
2956
+	/**
2957
+	 * Checks that the result would satisfy the unique indexes on this model
2958
+	 *
2959
+	 * @param array  $field_n_values
2960
+	 * @param string $action
2961
+	 * @return boolean
2962
+	 * @throws EE_Error
2963
+	 * @throws ReflectionException
2964
+	 */
2965
+	protected function _satisfies_unique_indexes(array $field_n_values, $action = 'insert')
2966
+	{
2967
+		foreach ($this->unique_indexes() as $index_name => $index) {
2968
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2969
+			if ($this->exists([$uniqueness_where_params])) {
2970
+				EE_Error::add_error(
2971
+					sprintf(
2972
+						esc_html__(
2973
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2974
+							"event_espresso"
2975
+						),
2976
+						$action,
2977
+						$this->_get_class_name(),
2978
+						$index_name,
2979
+						implode(",", $index->field_names()),
2980
+						http_build_query($uniqueness_where_params)
2981
+					),
2982
+					__FILE__,
2983
+					__FUNCTION__,
2984
+					__LINE__
2985
+				);
2986
+				return false;
2987
+			}
2988
+		}
2989
+		return true;
2990
+	}
2991
+
2992
+
2993
+	/**
2994
+	 * Checks the database for an item that conflicts (ie, if this item were
2995
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2996
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2997
+	 * can be either an EE_Base_Class or an array of fields n values
2998
+	 *
2999
+	 * @param EE_Base_Class|array $obj_or_fields_array
3000
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
3001
+	 *                                                 when looking for conflicts
3002
+	 *                                                 (ie, if false, we ignore the model object's primary key
3003
+	 *                                                 when finding "conflicts". If true, it's also considered).
3004
+	 *                                                 Only works for INT primary key,
3005
+	 *                                                 STRING primary keys cannot be ignored
3006
+	 * @return EE_Base_Class|array
3007
+	 * @throws EE_Error
3008
+	 * @throws ReflectionException
3009
+	 */
3010
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
3011
+	{
3012
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
3013
+			$fields_n_values = $obj_or_fields_array->model_field_array();
3014
+		} elseif (is_array($obj_or_fields_array)) {
3015
+			$fields_n_values = $obj_or_fields_array;
3016
+		} else {
3017
+			throw new EE_Error(
3018
+				sprintf(
3019
+					esc_html__(
3020
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
3021
+						"event_espresso"
3022
+					),
3023
+					get_class($this),
3024
+					$obj_or_fields_array
3025
+				)
3026
+			);
3027
+		}
3028
+		$query_params = [];
3029
+		if (
3030
+			$this->has_primary_key_field()
3031
+			&& ($include_primary_key
3032
+				|| $this->get_primary_key_field()
3033
+				   instanceof
3034
+				   EE_Primary_Key_String_Field)
3035
+			&& isset($fields_n_values[ $this->primary_key_name() ])
3036
+		) {
3037
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3038
+		}
3039
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3040
+			$uniqueness_where_params                              =
3041
+				array_intersect_key($fields_n_values, $unique_index->fields());
3042
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3043
+		}
3044
+		// if there is nothing to base this search on, then we shouldn't find anything
3045
+		if (empty($query_params)) {
3046
+			return [];
3047
+		}
3048
+		return $this->get_one($query_params);
3049
+	}
3050
+
3051
+
3052
+	/**
3053
+	 * Like count, but is optimized and returns a boolean instead of an int
3054
+	 *
3055
+	 * @param array $query_params
3056
+	 * @return boolean
3057
+	 * @throws EE_Error
3058
+	 * @throws ReflectionException
3059
+	 */
3060
+	public function exists($query_params)
3061
+	{
3062
+		$query_params['limit'] = 1;
3063
+		return $this->count($query_params) > 0;
3064
+	}
3065
+
3066
+
3067
+	/**
3068
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
3069
+	 *
3070
+	 * @param int|string $id
3071
+	 * @return boolean
3072
+	 * @throws EE_Error
3073
+	 * @throws ReflectionException
3074
+	 */
3075
+	public function exists_by_ID($id)
3076
+	{
3077
+		return $this->exists(
3078
+			[
3079
+				'default_where_conditions' => EE_Default_Where_Conditions::NONE,
3080
+				[
3081
+					$this->primary_key_name() => $id,
3082
+				],
3083
+			]
3084
+		);
3085
+	}
3086
+
3087
+
3088
+	/**
3089
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3090
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3091
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3092
+	 * on the main table)
3093
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3094
+	 * cases where we want to call it directly rather than via insert().
3095
+	 *
3096
+	 * @access   protected
3097
+	 * @param EE_Table_Base $table
3098
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3099
+	 *                                       float
3100
+	 * @param int           $new_id          for now we assume only int keys
3101
+	 * @return int ID of new row inserted, or FALSE on failure
3102
+	 * @throws EE_Error
3103
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3104
+	 */
3105
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3106
+	{
3107
+		global $wpdb;
3108
+		$insertion_col_n_values = [];
3109
+		$format_for_insertion   = [];
3110
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3111
+		foreach ($fields_on_table as $field_obj) {
3112
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3113
+			if ($field_obj->is_auto_increment()) {
3114
+				continue;
3115
+			}
3116
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3117
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3118
+			if ($prepared_value !== null) {
3119
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3120
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3121
+			}
3122
+		}
3123
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3124
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3125
+			// so add the fk to the main table as a column
3126
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3127
+			$format_for_insertion[]                              =
3128
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3129
+		}
3130
+
3131
+		// insert the new entry
3132
+		$result = $this->_do_wpdb_query(
3133
+			'insert',
3134
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3135
+		);
3136
+		if ($result === false) {
3137
+			return false;
3138
+		}
3139
+		// ok, now what do we return for the ID of the newly-inserted thing?
3140
+		if ($this->has_primary_key_field()) {
3141
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3142
+				return $wpdb->insert_id;
3143
+			}
3144
+			// it's not an auto-increment primary key, so
3145
+			// it must have been supplied
3146
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3147
+		}
3148
+		// we can't return a  primary key because there is none. instead return
3149
+		// a unique string indicating this model
3150
+		return $this->get_index_primary_key_string($fields_n_values);
3151
+	}
3152
+
3153
+
3154
+	/**
3155
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3156
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3157
+	 * and there is no default, we pass it along. WPDB will take care of it)
3158
+	 *
3159
+	 * @param EE_Model_Field_Base $field_obj
3160
+	 * @param array               $fields_n_values
3161
+	 * @return mixed string|int|float depending on what the table column will be expecting
3162
+	 * @throws EE_Error
3163
+	 */
3164
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3165
+	{
3166
+		$field_name = $field_obj->get_name();
3167
+		// if this field doesn't allow nullable, don't allow it
3168
+		if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3169
+			$fields_n_values[ $field_name ] = $field_obj->get_default_value();
3170
+		}
3171
+		$unprepared_value = $fields_n_values[ $field_name ] ?? null;
3172
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3173
+	}
3174
+
3175
+
3176
+	/**
3177
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3178
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3179
+	 * the field's prepare_for_set() method.
3180
+	 *
3181
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3182
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3183
+	 *                                   top of file)
3184
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3185
+	 *                                   $value is a custom selection
3186
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3187
+	 */
3188
+	private function _prepare_value_for_use_in_db($value, $field)
3189
+	{
3190
+		if ($field instanceof EE_Model_Field_Base) {
3191
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3192
+			switch ($this->_values_already_prepared_by_model_object) {
3193
+				/** @noinspection PhpMissingBreakStatementInspection */
3194
+				case self::not_prepared_by_model_object:
3195
+					$value = $field->prepare_for_set($value);
3196
+				// purposefully left out "return"
3197
+				// no break
3198
+				case self::prepared_by_model_object:
3199
+					/** @noinspection SuspiciousAssignmentsInspection */
3200
+					$value = $field->prepare_for_use_in_db($value);
3201
+				// no break
3202
+				case self::prepared_for_use_in_db:
3203
+					// leave the value alone
3204
+			}
3205
+			// phpcs:enable
3206
+		}
3207
+		return $value;
3208
+	}
3209
+
3210
+
3211
+	/**
3212
+	 * Returns the main table on this model
3213
+	 *
3214
+	 * @return EE_Primary_Table
3215
+	 * @throws EE_Error
3216
+	 */
3217
+	protected function _get_main_table()
3218
+	{
3219
+		foreach ($this->_tables as $table) {
3220
+			if ($table instanceof EE_Primary_Table) {
3221
+				return $table;
3222
+			}
3223
+		}
3224
+		throw new EE_Error(
3225
+			sprintf(
3226
+				esc_html__(
3227
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3228
+					'event_espresso'
3229
+				),
3230
+				get_class($this)
3231
+			)
3232
+		);
3233
+	}
3234
+
3235
+
3236
+	/**
3237
+	 * table
3238
+	 * returns EE_Primary_Table table name
3239
+	 *
3240
+	 * @return string
3241
+	 * @throws EE_Error
3242
+	 */
3243
+	public function table()
3244
+	{
3245
+		return $this->_get_main_table()->get_table_name();
3246
+	}
3247
+
3248
+
3249
+	/**
3250
+	 * table
3251
+	 * returns first EE_Secondary_Table table name
3252
+	 *
3253
+	 * @return string
3254
+	 */
3255
+	public function second_table()
3256
+	{
3257
+		// grab second table from tables array
3258
+		$second_table = end($this->_tables);
3259
+		return $second_table instanceof EE_Secondary_Table
3260
+			? $second_table->get_table_name()
3261
+			: null;
3262
+	}
3263
+
3264
+
3265
+	/**
3266
+	 * get_table_obj_by_alias
3267
+	 * returns table name given it's alias
3268
+	 *
3269
+	 * @param string $table_alias
3270
+	 * @return EE_Primary_Table | EE_Secondary_Table
3271
+	 */
3272
+	public function get_table_obj_by_alias($table_alias = '')
3273
+	{
3274
+		return $this->_tables[ $table_alias ] ?? null;
3275
+	}
3276
+
3277
+
3278
+	/**
3279
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3280
+	 *
3281
+	 * @return EE_Secondary_Table[]
3282
+	 */
3283
+	protected function _get_other_tables()
3284
+	{
3285
+		$other_tables = [];
3286
+		foreach ($this->_tables as $table_alias => $table) {
3287
+			if ($table instanceof EE_Secondary_Table) {
3288
+				$other_tables[ $table_alias ] = $table;
3289
+			}
3290
+		}
3291
+		return $other_tables;
3292
+	}
3293
+
3294
+
3295
+	/**
3296
+	 * Finds all the fields that correspond to the given table
3297
+	 *
3298
+	 * @param string $table_alias , array key in EEM_Base::_tables
3299
+	 * @return EE_Model_Field_Base[]
3300
+	 */
3301
+	public function _get_fields_for_table($table_alias)
3302
+	{
3303
+		return $this->_fields[ $table_alias ];
3304
+	}
3305
+
3306
+
3307
+	/**
3308
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3309
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3310
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3311
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3312
+	 * related Registration, Transaction, and Payment models.
3313
+	 *
3314
+	 * @param array $query_params @see
3315
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3316
+	 * @return EE_Model_Query_Info_Carrier
3317
+	 * @throws EE_Error
3318
+	 */
3319
+	public function _extract_related_models_from_query($query_params)
3320
+	{
3321
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3322
+		if (array_key_exists(0, $query_params)) {
3323
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3324
+		}
3325
+		if (array_key_exists('group_by', $query_params)) {
3326
+			if (is_array($query_params['group_by'])) {
3327
+				$this->_extract_related_models_from_sub_params_array_values(
3328
+					$query_params['group_by'],
3329
+					$query_info_carrier,
3330
+					'group_by'
3331
+				);
3332
+			} elseif (! empty($query_params['group_by'])) {
3333
+				$this->_extract_related_model_info_from_query_param(
3334
+					$query_params['group_by'],
3335
+					$query_info_carrier,
3336
+					'group_by'
3337
+				);
3338
+			}
3339
+		}
3340
+		if (array_key_exists('having', $query_params)) {
3341
+			$this->_extract_related_models_from_sub_params_array_keys(
3342
+				$query_params[0],
3343
+				$query_info_carrier,
3344
+				'having'
3345
+			);
3346
+		}
3347
+		if (array_key_exists('order_by', $query_params)) {
3348
+			if (is_array($query_params['order_by'])) {
3349
+				$this->_extract_related_models_from_sub_params_array_keys(
3350
+					$query_params['order_by'],
3351
+					$query_info_carrier,
3352
+					'order_by'
3353
+				);
3354
+			} elseif (! empty($query_params['order_by'])) {
3355
+				$this->_extract_related_model_info_from_query_param(
3356
+					$query_params['order_by'],
3357
+					$query_info_carrier,
3358
+					'order_by'
3359
+				);
3360
+			}
3361
+		}
3362
+		if (array_key_exists('force_join', $query_params)) {
3363
+			$this->_extract_related_models_from_sub_params_array_values(
3364
+				$query_params['force_join'],
3365
+				$query_info_carrier,
3366
+				'force_join'
3367
+			);
3368
+		}
3369
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3370
+		return $query_info_carrier;
3371
+	}
3372
+
3373
+
3374
+	/**
3375
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3376
+	 *
3377
+	 * @param array                       $sub_query_params
3378
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3379
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3380
+	 * @return EE_Model_Query_Info_Carrier
3381
+	 * @throws EE_Error
3382
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3383
+	 */
3384
+	private function _extract_related_models_from_sub_params_array_keys(
3385
+		$sub_query_params,
3386
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3387
+		$query_param_type
3388
+	) {
3389
+		if (! empty($sub_query_params)) {
3390
+			$sub_query_params = (array) $sub_query_params;
3391
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3392
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3393
+				$this->_extract_related_model_info_from_query_param(
3394
+					$param,
3395
+					$model_query_info_carrier,
3396
+					$query_param_type
3397
+				);
3398
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3399
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3400
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3401
+				// of array('Registration.TXN_ID'=>23)
3402
+				$query_param_sans_stars =
3403
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3404
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3405
+					if (! is_array($possibly_array_of_params)) {
3406
+						throw new EE_Error(
3407
+							sprintf(
3408
+								esc_html__(
3409
+									"You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3410
+									"event_espresso"
3411
+								),
3412
+								$param,
3413
+								$possibly_array_of_params
3414
+							)
3415
+						);
3416
+					}
3417
+					$this->_extract_related_models_from_sub_params_array_keys(
3418
+						$possibly_array_of_params,
3419
+						$model_query_info_carrier,
3420
+						$query_param_type
3421
+					);
3422
+				} elseif (
3423
+					$query_param_type === 0 // ie WHERE
3424
+					&& is_array($possibly_array_of_params) // need is_array() check so we don't try to explode a string
3425
+					&& isset($possibly_array_of_params[2])
3426
+					&& $possibly_array_of_params[2]
3427
+				) {
3428
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3429
+					// indicating that $possible_array_of_params[1] is actually a field name,
3430
+					// from which we should extract query parameters!
3431
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3432
+						throw new EE_Error(
3433
+							sprintf(
3434
+								esc_html__(
3435
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3436
+									"event_espresso"
3437
+								),
3438
+								$query_param_type,
3439
+								implode(",", $possibly_array_of_params)
3440
+							)
3441
+						);
3442
+					}
3443
+					$this->_extract_related_model_info_from_query_param(
3444
+						$possibly_array_of_params[1],
3445
+						$model_query_info_carrier,
3446
+						$query_param_type
3447
+					);
3448
+				}
3449
+			}
3450
+		}
3451
+		return $model_query_info_carrier;
3452
+	}
3453
+
3454
+
3455
+	/**
3456
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3457
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3458
+	 *
3459
+	 * @param array                       $sub_query_params @see
3460
+	 *                                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3461
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3462
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3463
+	 * @return EE_Model_Query_Info_Carrier
3464
+	 * @throws EE_Error
3465
+	 */
3466
+	private function _extract_related_models_from_sub_params_array_values(
3467
+		$sub_query_params,
3468
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3469
+		$query_param_type
3470
+	) {
3471
+		if (! empty($sub_query_params)) {
3472
+			if (! is_array($sub_query_params)) {
3473
+				throw new EE_Error(
3474
+					sprintf(
3475
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3476
+						$sub_query_params
3477
+					)
3478
+				);
3479
+			}
3480
+			foreach ($sub_query_params as $param) {
3481
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3482
+				$this->_extract_related_model_info_from_query_param(
3483
+					$param,
3484
+					$model_query_info_carrier,
3485
+					$query_param_type
3486
+				);
3487
+			}
3488
+		}
3489
+		return $model_query_info_carrier;
3490
+	}
3491
+
3492
+
3493
+	/**
3494
+	 * Extract all the query parts from  model query params
3495
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3496
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3497
+	 * but use them in a different order. Eg, we need to know what models we are querying
3498
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3499
+	 * other models before we can finalize the where clause SQL.
3500
+	 *
3501
+	 * @param array $query_params
3502
+	 * @return EE_Model_Query_Info_Carrier
3503
+	 * @throws EE_Error
3504
+	 * @throws ModelConfigurationException
3505
+	 * @throws ReflectionException
3506
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3507
+	 */
3508
+	public function _create_model_query_info_carrier($query_params)
3509
+	{
3510
+		if (! is_array($query_params)) {
3511
+			EE_Error::doing_it_wrong(
3512
+				'EEM_Base::_create_model_query_info_carrier',
3513
+				sprintf(
3514
+					esc_html__(
3515
+						'$query_params should be an array, you passed a variable of type %s',
3516
+						'event_espresso'
3517
+					),
3518
+					gettype($query_params)
3519
+				),
3520
+				'4.6.0'
3521
+			);
3522
+			$query_params = [];
3523
+		}
3524
+		$query_params[0] = $query_params[0] ?? [];
3525
+		// first check if we should alter the query to account for caps or not
3526
+		// because the caps might require us to do extra joins
3527
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3528
+			$query_params[0] = array_replace_recursive(
3529
+				$query_params[0],
3530
+				$this->caps_where_conditions($query_params['caps'])
3531
+			);
3532
+		}
3533
+
3534
+		// check if we should alter the query to remove data related to protected
3535
+		// custom post types
3536
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3537
+			$where_param_key_for_password = $this->modelChainAndPassword();
3538
+			// only include if related to a cpt where no password has been set
3539
+			$query_params[0]['OR*nopassword'] = [
3540
+				$where_param_key_for_password       => '',
3541
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3542
+			];
3543
+		}
3544
+		$query_object = $this->_extract_related_models_from_query($query_params);
3545
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3546
+		foreach ($query_params[0] as $key => $value) {
3547
+			if (is_int($key)) {
3548
+				throw new EE_Error(
3549
+					sprintf(
3550
+						esc_html__(
3551
+							"WHERE query params must NOT be numerically-indexed. You provided the array key '%s' for value '%s' while querying model %s. All the query params provided were '%s' Please read documentation on EEM_Base::get_all.",
3552
+							"event_espresso"
3553
+						),
3554
+						$key,
3555
+						var_export($value, true),
3556
+						var_export($query_params, true),
3557
+						get_class($this)
3558
+					)
3559
+				);
3560
+			}
3561
+		}
3562
+		if (
3563
+			array_key_exists('default_where_conditions', $query_params)
3564
+			&& ! empty($query_params['default_where_conditions'])
3565
+		) {
3566
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3567
+		} else {
3568
+			$use_default_where_conditions = EE_Default_Where_Conditions::ALL;
3569
+		}
3570
+		$query_params[0] = array_merge(
3571
+			$this->_get_default_where_conditions_for_models_in_query(
3572
+				$query_object,
3573
+				$use_default_where_conditions,
3574
+				$query_params[0]
3575
+			),
3576
+			$query_params[0]
3577
+		);
3578
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3579
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3580
+		// So we need to setup a subquery and use that for the main join.
3581
+		// Note for now this only works on the primary table for the model.
3582
+		// So for instance, you could set the limit array like this:
3583
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3584
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3585
+			$query_object->set_main_model_join_sql(
3586
+				$this->_construct_limit_join_select(
3587
+					$query_params['on_join_limit'][0],
3588
+					$query_params['on_join_limit'][1]
3589
+				)
3590
+			);
3591
+		}
3592
+		// set limit
3593
+		if (array_key_exists('limit', $query_params)) {
3594
+			if (is_array($query_params['limit'])) {
3595
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3596
+					$e = sprintf(
3597
+						esc_html__(
3598
+							"Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
3599
+							"event_espresso"
3600
+						),
3601
+						http_build_query($query_params['limit'])
3602
+					);
3603
+					throw new EE_Error($e . "|" . $e);
3604
+				}
3605
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3606
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3607
+			} elseif (! empty($query_params['limit'])) {
3608
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3609
+			}
3610
+		}
3611
+		// set order by
3612
+		if (array_key_exists('order_by', $query_params)) {
3613
+			if (is_array($query_params['order_by'])) {
3614
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3615
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3616
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3617
+				if (array_key_exists('order', $query_params)) {
3618
+					throw new EE_Error(
3619
+						sprintf(
3620
+							esc_html__(
3621
+								"In querying %s, we are using query parameter 'order_by' as an array (keys:%s,values:%s), and so we can't use query parameter 'order' (value %s). You should just use the 'order_by' parameter ",
3622
+								"event_espresso"
3623
+							),
3624
+							get_class($this),
3625
+							implode(", ", array_keys($query_params['order_by'])),
3626
+							implode(", ", $query_params['order_by']),
3627
+							$query_params['order']
3628
+						)
3629
+					);
3630
+				}
3631
+				$this->_extract_related_models_from_sub_params_array_keys(
3632
+					$query_params['order_by'],
3633
+					$query_object,
3634
+					'order_by'
3635
+				);
3636
+				// assume it's an array of fields to order by
3637
+				$order_array = [];
3638
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3639
+					$order         = $this->_extract_order($order);
3640
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3641
+				}
3642
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3643
+			} elseif (! empty($query_params['order_by'])) {
3644
+				$this->_extract_related_model_info_from_query_param(
3645
+					$query_params['order_by'],
3646
+					$query_object,
3647
+					'order',
3648
+					$query_params['order_by']
3649
+				);
3650
+				$order = isset($query_params['order'])
3651
+					? $this->_extract_order($query_params['order'])
3652
+					: 'DESC';
3653
+				$query_object->set_order_by_sql(
3654
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3655
+				);
3656
+			}
3657
+		}
3658
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3659
+		if (
3660
+			! array_key_exists('order_by', $query_params)
3661
+			&& array_key_exists('order', $query_params)
3662
+			&& ! empty($query_params['order'])
3663
+		) {
3664
+			$pk_field = $this->get_primary_key_field();
3665
+			$order    = $this->_extract_order($query_params['order']);
3666
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3667
+		}
3668
+		// set group by
3669
+		if (array_key_exists('group_by', $query_params)) {
3670
+			if (is_array($query_params['group_by'])) {
3671
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3672
+				$group_by_array = [];
3673
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3674
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3675
+				}
3676
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3677
+			} elseif (! empty($query_params['group_by'])) {
3678
+				$query_object->set_group_by_sql(
3679
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3680
+				);
3681
+			}
3682
+		}
3683
+		// set having
3684
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3685
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3686
+		}
3687
+		// now, just verify they didn't pass anything wack
3688
+		foreach ($query_params as $query_key => $query_value) {
3689
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3690
+				throw new EE_Error(
3691
+					sprintf(
3692
+						esc_html__(
3693
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3694
+							'event_espresso'
3695
+						),
3696
+						$query_key,
3697
+						get_class($this),
3698
+						//                      print_r( $this->_allowed_query_params, TRUE )
3699
+						implode(',', $this->_allowed_query_params)
3700
+					)
3701
+				);
3702
+			}
3703
+		}
3704
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3705
+		if (empty($main_model_join_sql)) {
3706
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3707
+		}
3708
+		return $query_object;
3709
+	}
3710
+
3711
+
3712
+	/**
3713
+	 * Gets the where conditions that should be imposed on the query based on the
3714
+	 * context (eg reading frontend, backend, edit or delete).
3715
+	 *
3716
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3717
+	 * @return array @see
3718
+	 *                        https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3719
+	 * @throws EE_Error
3720
+	 */
3721
+	public function caps_where_conditions($context = self::caps_read)
3722
+	{
3723
+		EEM_Base::verify_is_valid_cap_context($context);
3724
+		$cap_where_conditions = [];
3725
+		$cap_restrictions     = $this->caps_missing($context);
3726
+		foreach ($cap_restrictions as $restriction_if_no_cap) {
3727
+			$cap_where_conditions = array_replace_recursive(
3728
+				$cap_where_conditions,
3729
+				$restriction_if_no_cap->get_default_where_conditions()
3730
+			);
3731
+		}
3732
+		return apply_filters(
3733
+			'FHEE__EEM_Base__caps_where_conditions__return',
3734
+			$cap_where_conditions,
3735
+			$this,
3736
+			$context,
3737
+			$cap_restrictions
3738
+		);
3739
+	}
3740
+
3741
+
3742
+	/**
3743
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3744
+	 * otherwise throws an exception
3745
+	 *
3746
+	 * @param string $should_be_order_string
3747
+	 * @return string either ASC, asc, DESC or desc
3748
+	 * @throws EE_Error
3749
+	 */
3750
+	private function _extract_order($should_be_order_string)
3751
+	{
3752
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3753
+			return $should_be_order_string;
3754
+		}
3755
+		throw new EE_Error(
3756
+			sprintf(
3757
+				esc_html__(
3758
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3759
+					"event_espresso"
3760
+				),
3761
+				get_class($this),
3762
+				$should_be_order_string
3763
+			)
3764
+		);
3765
+	}
3766
+
3767
+
3768
+	/**
3769
+	 * Looks at all the models which are included in this query, and asks each
3770
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3771
+	 * so they can be merged
3772
+	 *
3773
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3774
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3775
+	 *                                                                  'none' means NO default where conditions will
3776
+	 *                                                                  be used AT ALL during this query.
3777
+	 *                                                                  'other_models_only' means default where
3778
+	 *                                                                  conditions from other models will be used, but
3779
+	 *                                                                  not for this primary model. 'all', the default,
3780
+	 *                                                                  means default where conditions will apply as
3781
+	 *                                                                  normal
3782
+	 * @param array                       $where_query_params
3783
+	 * @return array
3784
+	 * @throws EE_Error
3785
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params
3786
+	 *                                                                  .md#0-where-conditions
3787
+	 */
3788
+	private function _get_default_where_conditions_for_models_in_query(
3789
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3790
+		$use_default_where_conditions = EE_Default_Where_Conditions::ALL,
3791
+		$where_query_params = []
3792
+	) {
3793
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3794
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3795
+			throw new EE_Error(
3796
+				sprintf(
3797
+					esc_html__(
3798
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3799
+						"event_espresso"
3800
+					),
3801
+					$use_default_where_conditions,
3802
+					implode(", ", $allowed_used_default_where_conditions_values)
3803
+				)
3804
+			);
3805
+		}
3806
+		$universal_query_params = [];
3807
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3808
+			$universal_query_params = $this->_get_default_where_conditions();
3809
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3810
+			$universal_query_params = $this->_get_minimum_where_conditions();
3811
+		}
3812
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3813
+			$related_model = $this->get_related_model_obj($model_name);
3814
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3815
+				$related_model_universal_where_params =
3816
+					$related_model->_get_default_where_conditions($model_relation_path);
3817
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3818
+				$related_model_universal_where_params =
3819
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3820
+			} else {
3821
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3822
+				continue;
3823
+			}
3824
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3825
+				$related_model_universal_where_params,
3826
+				$where_query_params,
3827
+				$related_model,
3828
+				$model_relation_path
3829
+			);
3830
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3831
+				$universal_query_params,
3832
+				$overrides
3833
+			);
3834
+		}
3835
+		return $universal_query_params;
3836
+	}
3837
+
3838
+
3839
+	/**
3840
+	 * Determines whether or not we should use default where conditions for the model in question
3841
+	 * (this model, or other related models).
3842
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3843
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3844
+	 * We should use default where conditions on related models when they requested to use default where conditions
3845
+	 * on all models, or specifically just on other related models
3846
+	 *
3847
+	 * @param      $default_where_conditions_value
3848
+	 * @param bool $for_this_model false means this is for OTHER related models
3849
+	 * @return bool
3850
+	 */
3851
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3852
+	{
3853
+		return (
3854
+				   $for_this_model
3855
+				   && in_array(
3856
+					   $default_where_conditions_value,
3857
+					   [
3858
+						   EE_Default_Where_Conditions::ALL,
3859
+						   EE_Default_Where_Conditions::THIS_MODEL_ONLY,
3860
+						   EE_Default_Where_Conditions::MINIMUM_OTHERS,
3861
+					   ],
3862
+					   true
3863
+				   )
3864
+			   )
3865
+			   || (
3866
+				   ! $for_this_model
3867
+				   && in_array(
3868
+					   $default_where_conditions_value,
3869
+					   [
3870
+						   EE_Default_Where_Conditions::ALL,
3871
+						   EE_Default_Where_Conditions::OTHER_MODELS_ONLY,
3872
+					   ],
3873
+					   true
3874
+				   )
3875
+			   );
3876
+	}
3877
+
3878
+
3879
+	/**
3880
+	 * Determines whether or not we should use default minimum conditions for the model in question
3881
+	 * (this model, or other related models).
3882
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3883
+	 * where conditions.
3884
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3885
+	 * on this model or others
3886
+	 *
3887
+	 * @param      $default_where_conditions_value
3888
+	 * @param bool $for_this_model false means this is for OTHER related models
3889
+	 * @return bool
3890
+	 */
3891
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3892
+	{
3893
+		return (
3894
+				   $for_this_model
3895
+				   && $default_where_conditions_value === EE_Default_Where_Conditions::MINIMUM_ALL
3896
+			   )
3897
+			   || (
3898
+				   ! $for_this_model
3899
+				   && in_array(
3900
+					   $default_where_conditions_value,
3901
+					   [
3902
+						   EE_Default_Where_Conditions::MINIMUM_OTHERS,
3903
+						   EE_Default_Where_Conditions::MINIMUM_ALL,
3904
+					   ],
3905
+					   true
3906
+				   )
3907
+			   );
3908
+	}
3909
+
3910
+
3911
+	/**
3912
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3913
+	 * then we also add a special where condition which allows for that model's primary key
3914
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3915
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3916
+	 *
3917
+	 * @param array    $default_where_conditions
3918
+	 * @param array    $provided_where_conditions
3919
+	 * @param EEM_Base $model
3920
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3921
+	 * @return array @see
3922
+	 *                                      https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3923
+	 * @throws EE_Error
3924
+	 */
3925
+	private function _override_defaults_or_make_null_friendly(
3926
+		$default_where_conditions,
3927
+		$provided_where_conditions,
3928
+		$model,
3929
+		$model_relation_path
3930
+	) {
3931
+		$null_friendly_where_conditions = [];
3932
+		$none_overridden                = true;
3933
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3934
+		foreach ($default_where_conditions as $key => $val) {
3935
+			if (isset($provided_where_conditions[ $key ])) {
3936
+				$none_overridden = false;
3937
+			} else {
3938
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3939
+			}
3940
+		}
3941
+		if ($none_overridden && $default_where_conditions) {
3942
+			if ($model->has_primary_key_field()) {
3943
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3944
+																				   . "."
3945
+																				   . $model->primary_key_name() ] =
3946
+					['IS NULL'];
3947
+			}/*else{
3948 3948
                 //@todo NO PK, use other defaults
3949 3949
             }*/
3950
-        }
3951
-        return $null_friendly_where_conditions;
3952
-    }
3953
-
3954
-
3955
-    /**
3956
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3957
-     * default where conditions on all get_all, update, and delete queries done by this model.
3958
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3959
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3960
-     *
3961
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3962
-     * @return array @see
3963
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3964
-     * @throws EE_Error
3965
-     * @throws EE_Error
3966
-     */
3967
-    private function _get_default_where_conditions($model_relation_path = '')
3968
-    {
3969
-        if ($this->_ignore_where_strategy) {
3970
-            return [];
3971
-        }
3972
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3973
-    }
3974
-
3975
-
3976
-    /**
3977
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3978
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3979
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3980
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3981
-     * Similar to _get_default_where_conditions
3982
-     *
3983
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3984
-     * @return array @see
3985
-     *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3986
-     * @throws EE_Error
3987
-     * @throws EE_Error
3988
-     */
3989
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3990
-    {
3991
-        if ($this->_ignore_where_strategy) {
3992
-            return [];
3993
-        }
3994
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3995
-    }
3996
-
3997
-
3998
-    /**
3999
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
4000
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
4001
-     *
4002
-     * @param EE_Model_Query_Info_Carrier $model_query_info
4003
-     * @return string
4004
-     * @throws EE_Error
4005
-     */
4006
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
4007
-    {
4008
-        $selects = $this->_get_columns_to_select_for_this_model();
4009
-        foreach (
4010
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
4011
-        ) {
4012
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
4013
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
4014
-            foreach ($other_model_selects as $key => $value) {
4015
-                $selects[] = $value;
4016
-            }
4017
-        }
4018
-        return implode(", ", $selects);
4019
-    }
4020
-
4021
-
4022
-    /**
4023
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
4024
-     * So that's going to be the columns for all the fields on the model
4025
-     *
4026
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
4027
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
4028
-     */
4029
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
4030
-    {
4031
-        $fields                                       = $this->field_settings();
4032
-        $selects                                      = [];
4033
-        $table_alias_with_model_relation_chain_prefix =
4034
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
4035
-                $model_relation_chain,
4036
-                $this->get_this_model_name()
4037
-            );
4038
-        foreach ($fields as $field_obj) {
4039
-            $selects[] = $table_alias_with_model_relation_chain_prefix
4040
-                         . $field_obj->get_table_alias()
4041
-                         . "."
4042
-                         . $field_obj->get_table_column()
4043
-                         . " AS '"
4044
-                         . $table_alias_with_model_relation_chain_prefix
4045
-                         . $field_obj->get_table_alias()
4046
-                         . "."
4047
-                         . $field_obj->get_table_column()
4048
-                         . "'";
4049
-        }
4050
-        // make sure we are also getting the PKs of each table
4051
-        $tables = $this->get_tables();
4052
-        if (count($tables) > 1) {
4053
-            foreach ($tables as $table_obj) {
4054
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4055
-                                       . $table_obj->get_fully_qualified_pk_column();
4056
-                if (! in_array($qualified_pk_column, $selects)) {
4057
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4058
-                }
4059
-            }
4060
-        }
4061
-        return $selects;
4062
-    }
4063
-
4064
-
4065
-    /**
4066
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4067
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4068
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4069
-     * SQL for joining, and the data types
4070
-     *
4071
-     * @param null|string                 $original_query_param
4072
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
4073
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4074
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4075
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4076
-     *                                                          column name. We only want model names, eg 'Event.Venue'
4077
-     *                                                          or 'Registration's
4078
-     * @param string                      $original_query_param what it originally was (eg
4079
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4080
-     *                                                          matches $query_param
4081
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4082
-     * @throws EE_Error
4083
-     */
4084
-    private function _extract_related_model_info_from_query_param(
4085
-        $query_param,
4086
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4087
-        $query_param_type,
4088
-        $original_query_param = null
4089
-    ) {
4090
-        if ($original_query_param === null) {
4091
-            $original_query_param = $query_param;
4092
-        }
4093
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4094
-        // check to see if we have a field on this model
4095
-        $this_model_fields = $this->field_settings(true);
4096
-        if (array_key_exists($query_param, $this_model_fields)) {
4097
-            $field_is_allowed = in_array(
4098
-                $query_param_type,
4099
-                [0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4100
-                true
4101
-            );
4102
-            if ($field_is_allowed) {
4103
-                return;
4104
-            }
4105
-            throw new EE_Error(
4106
-                sprintf(
4107
-                    esc_html__(
4108
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4109
-                        "event_espresso"
4110
-                    ),
4111
-                    $query_param,
4112
-                    get_class($this),
4113
-                    $query_param_type,
4114
-                    $original_query_param
4115
-                )
4116
-            );
4117
-        }
4118
-        // check if this is a special logic query param
4119
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4120
-            $operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4121
-            if ($operator_is_allowed) {
4122
-                return;
4123
-            }
4124
-            throw new EE_Error(
4125
-                sprintf(
4126
-                    esc_html__(
4127
-                        'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4128
-                        'event_espresso'
4129
-                    ),
4130
-                    implode('", "', $this->_logic_query_param_keys),
4131
-                    $query_param,
4132
-                    get_class($this),
4133
-                    '<br />',
4134
-                    "\t"
4135
-                    . ' $passed_in_query_info = <pre>'
4136
-                    . print_r($passed_in_query_info, true)
4137
-                    . '</pre>'
4138
-                    . "\n\t"
4139
-                    . ' $query_param_type = '
4140
-                    . $query_param_type
4141
-                    . "\n\t"
4142
-                    . ' $original_query_param = '
4143
-                    . $original_query_param
4144
-                )
4145
-            );
4146
-        }
4147
-        // check if it's a custom selection
4148
-        if (
4149
-            $this->_custom_selections instanceof CustomSelects
4150
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4151
-        ) {
4152
-            return;
4153
-        }
4154
-        // check if has a model name at the beginning
4155
-        // and
4156
-        // check if it's a field on a related model
4157
-        if (
4158
-            $this->extractJoinModelFromQueryParams(
4159
-                $passed_in_query_info,
4160
-                $query_param,
4161
-                $original_query_param,
4162
-                $query_param_type
4163
-            )
4164
-        ) {
4165
-            return;
4166
-        }
4167
-
4168
-        // ok so $query_param didn't start with a model name
4169
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4170
-        // it's wack, that's what it is
4171
-        throw new EE_Error(
4172
-            sprintf(
4173
-                esc_html__(
4174
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4175
-                    "event_espresso"
4176
-                ),
4177
-                $query_param,
4178
-                get_class($this),
4179
-                $query_param_type,
4180
-                $original_query_param
4181
-            )
4182
-        );
4183
-    }
4184
-
4185
-
4186
-    /**
4187
-     * Extracts any possible join model information from the provided possible_join_string.
4188
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4189
-     * join
4190
-     * parts that should be added to the query.
4191
-     *
4192
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4193
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4194
-     * @param null|string                 $original_query_param
4195
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4196
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4197
-     *                                                           etc.)
4198
-     * @return bool  returns true if a join was added and false if not.
4199
-     * @throws EE_Error
4200
-     */
4201
-    private function extractJoinModelFromQueryParams(
4202
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4203
-        $possible_join_string,
4204
-        $original_query_param,
4205
-        $query_parameter_type
4206
-    ) {
4207
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4208
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4209
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4210
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4211
-                if ($possible_join_string === '') {
4212
-                    // nothing left to $query_param
4213
-                    // we should actually end in a field name, not a model like this!
4214
-                    throw new EE_Error(
4215
-                        sprintf(
4216
-                            esc_html__(
4217
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4218
-                                "event_espresso"
4219
-                            ),
4220
-                            $possible_join_string,
4221
-                            $query_parameter_type,
4222
-                            get_class($this),
4223
-                            $valid_related_model_name
4224
-                        )
4225
-                    );
4226
-                }
4227
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4228
-                $related_model_obj->_extract_related_model_info_from_query_param(
4229
-                    $possible_join_string,
4230
-                    $query_info_carrier,
4231
-                    $query_parameter_type,
4232
-                    $original_query_param
4233
-                );
4234
-                return true;
4235
-            }
4236
-            if ($possible_join_string === $valid_related_model_name) {
4237
-                $this->_add_join_to_model(
4238
-                    $valid_related_model_name,
4239
-                    $query_info_carrier,
4240
-                    $original_query_param
4241
-                );
4242
-                return true;
4243
-            }
4244
-        }
4245
-        return false;
4246
-    }
4247
-
4248
-
4249
-    /**
4250
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4251
-     *
4252
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4253
-     * @throws EE_Error
4254
-     */
4255
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4256
-    {
4257
-        if (
4258
-            $this->_custom_selections instanceof CustomSelects
4259
-            && (
4260
-                $this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4261
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4262
-            )
4263
-        ) {
4264
-            $original_selects = $this->_custom_selections->originalSelects();
4265
-            foreach ($original_selects as $alias => $select_configuration) {
4266
-                $this->extractJoinModelFromQueryParams(
4267
-                    $query_info_carrier,
4268
-                    $select_configuration[0],
4269
-                    $select_configuration[0],
4270
-                    'custom_selects'
4271
-                );
4272
-            }
4273
-        }
4274
-    }
4275
-
4276
-
4277
-    /**
4278
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4279
-     * and store it on $passed_in_query_info
4280
-     *
4281
-     * @param string                      $model_name
4282
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4283
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4284
-     *                                                          model and $model_name. Eg, if we are querying Event,
4285
-     *                                                          and are adding a join to 'Payment' with the original
4286
-     *                                                          query param key
4287
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4288
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4289
-     *                                                          Payment wants to add default query params so that it
4290
-     *                                                          will know what models to prepend onto its default query
4291
-     *                                                          params or in case it wants to rename tables (in case
4292
-     *                                                          there are multiple joins to the same table)
4293
-     * @return void
4294
-     * @throws EE_Error
4295
-     */
4296
-    private function _add_join_to_model(
4297
-        $model_name,
4298
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4299
-        $original_query_param
4300
-    ) {
4301
-        $relation_obj         = $this->related_settings_for($model_name);
4302
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4303
-        // check if the relation is HABTM, because then we're essentially doing two joins
4304
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4305
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4306
-            $join_model_obj = $relation_obj->get_join_model();
4307
-            // replace the model specified with the join model for this relation chain, whi
4308
-            $relation_chain_to_join_model =
4309
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4310
-                    $model_name,
4311
-                    $join_model_obj->get_this_model_name(),
4312
-                    $model_relation_chain
4313
-                );
4314
-            $passed_in_query_info->merge(
4315
-                new EE_Model_Query_Info_Carrier(
4316
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4317
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4318
-                )
4319
-            );
4320
-        }
4321
-        // now just join to the other table pointed to by the relation object, and add its data types
4322
-        $passed_in_query_info->merge(
4323
-            new EE_Model_Query_Info_Carrier(
4324
-                [$model_relation_chain => $model_name],
4325
-                $relation_obj->get_join_statement($model_relation_chain)
4326
-            )
4327
-        );
4328
-    }
4329
-
4330
-
4331
-    /**
4332
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4333
-     *
4334
-     * @param array $where_params @see
4335
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4336
-     * @return string of SQL
4337
-     * @throws EE_Error
4338
-     */
4339
-    private function _construct_where_clause($where_params)
4340
-    {
4341
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4342
-        if ($SQL) {
4343
-            return " WHERE " . $SQL;
4344
-        }
4345
-        return '';
4346
-    }
4347
-
4348
-
4349
-    /**
4350
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4351
-     * and should be passed HAVING parameters, not WHERE parameters
4352
-     *
4353
-     * @param array $having_params
4354
-     * @return string
4355
-     * @throws EE_Error
4356
-     */
4357
-    private function _construct_having_clause($having_params)
4358
-    {
4359
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4360
-        if ($SQL) {
4361
-            return " HAVING " . $SQL;
4362
-        }
4363
-        return '';
4364
-    }
4365
-
4366
-
4367
-    /**
4368
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4369
-     * Event_Meta.meta_value = 'foo'))"
4370
-     *
4371
-     * @param array  $where_params @see
4372
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4373
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4374
-     * @return string of SQL
4375
-     * @throws EE_Error
4376
-     */
4377
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4378
-    {
4379
-        $where_clauses = [];
4380
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4381
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4382
-            if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4383
-                switch ($query_param) {
4384
-                    case 'not':
4385
-                    case 'NOT':
4386
-                        $where_clauses[] = "! ("
4387
-                                           . $this->_construct_condition_clause_recursive(
4388
-                                               $op_and_value_or_sub_condition,
4389
-                                               $glue
4390
-                                           )
4391
-                                           . ")";
4392
-                        break;
4393
-                    case 'and':
4394
-                    case 'AND':
4395
-                        $where_clauses[] = " ("
4396
-                                           . $this->_construct_condition_clause_recursive(
4397
-                                               $op_and_value_or_sub_condition,
4398
-                                               ' AND '
4399
-                                           )
4400
-                                           . ")";
4401
-                        break;
4402
-                    case 'or':
4403
-                    case 'OR':
4404
-                        $where_clauses[] = " ("
4405
-                                           . $this->_construct_condition_clause_recursive(
4406
-                                               $op_and_value_or_sub_condition,
4407
-                                               ' OR '
4408
-                                           )
4409
-                                           . ")";
4410
-                        break;
4411
-                }
4412
-            } else {
4413
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4414
-                // if it's not a normal field, maybe it's a custom selection?
4415
-                if (! $field_obj) {
4416
-                    if ($this->_custom_selections instanceof CustomSelects) {
4417
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4418
-                    } else {
4419
-                        throw new EE_Error(
4420
-                            sprintf(
4421
-                                esc_html__(
4422
-                                    "%s is neither a valid model field name, nor a custom selection",
4423
-                                    "event_espresso"
4424
-                                ),
4425
-                                $query_param
4426
-                            )
4427
-                        );
4428
-                    }
4429
-                }
4430
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4431
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4432
-            }
4433
-        }
4434
-        return $where_clauses
4435
-            ? implode($glue, $where_clauses)
4436
-            : '';
4437
-    }
4438
-
4439
-
4440
-    /**
4441
-     * Takes the input parameter and extract the table name (alias) and column name
4442
-     *
4443
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4444
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4445
-     * @throws EE_Error
4446
-     */
4447
-    private function _deduce_column_name_from_query_param($query_param)
4448
-    {
4449
-        $field = $this->_deduce_field_from_query_param($query_param);
4450
-        if ($field) {
4451
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4452
-                $field->get_model_name(),
4453
-                $query_param
4454
-            );
4455
-            return $table_alias_prefix . $field->get_qualified_column();
4456
-        }
4457
-        if (
4458
-            $this->_custom_selections instanceof CustomSelects
4459
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4460
-        ) {
4461
-            // maybe it's custom selection item?
4462
-            // if so, just use it as the "column name"
4463
-            return $query_param;
4464
-        }
4465
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4466
-            ? implode(',', $this->_custom_selections->columnAliases())
4467
-            : '';
4468
-        throw new EE_Error(
4469
-            sprintf(
4470
-                esc_html__(
4471
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4472
-                    "event_espresso"
4473
-                ),
4474
-                $query_param,
4475
-                $custom_select_aliases
4476
-            )
4477
-        );
4478
-    }
4479
-
4480
-
4481
-    /**
4482
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4483
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4484
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4485
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4486
-     *
4487
-     * @param string $condition_query_param_key
4488
-     * @return string
4489
-     */
4490
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4491
-    {
4492
-        $pos_of_star = strpos($condition_query_param_key, '*');
4493
-        if ($pos_of_star === false) {
4494
-            return $condition_query_param_key;
4495
-        }
4496
-        return substr($condition_query_param_key, 0, $pos_of_star);
4497
-    }
4498
-
4499
-
4500
-    /**
4501
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4502
-     *
4503
-     * @param array|string               $op_and_value
4504
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4505
-     * @return string
4506
-     * @throws EE_Error
4507
-     */
4508
-    private function _construct_op_and_value($op_and_value, $field_obj)
4509
-    {
4510
-        $operator = '=';
4511
-        $value    = $op_and_value;
4512
-        if (is_array($op_and_value)) {
4513
-            $operator = isset($op_and_value[0])
4514
-                ? $this->_prepare_operator_for_sql($op_and_value[0])
4515
-                : null;
4516
-            if (! $operator) {
4517
-                $php_array_like_string = [];
4518
-                foreach ($op_and_value as $key => $value) {
4519
-                    $value = is_array($value) ? '[' . implode(",", $value) . ']' : $value;
4520
-                    $php_array_like_string[] = "$key=>$value";
4521
-                }
4522
-                throw new EE_Error(
4523
-                    sprintf(
4524
-                        esc_html__(
4525
-                            "You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4526
-                            "event_espresso"
4527
-                        ),
4528
-                        implode(",", $php_array_like_string)
4529
-                    )
4530
-                );
4531
-            }
4532
-            $value = $op_and_value[1] ?? null;
4533
-        }
4534
-
4535
-        // check to see if the value is actually another field
4536
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4537
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4538
-        }
4539
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4540
-            // in this case, the value should be an array, or at least a comma-separated list
4541
-            // it will need to handle a little differently
4542
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4543
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4544
-            return $operator . SP . $cleaned_value;
4545
-        }
4546
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4547
-            // the value should be an array with count of two.
4548
-            if (count($value) !== 2) {
4549
-                throw new EE_Error(
4550
-                    sprintf(
4551
-                        esc_html__(
4552
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4553
-                            'event_espresso'
4554
-                        ),
4555
-                        "BETWEEN"
4556
-                    )
4557
-                );
4558
-            }
4559
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4560
-            return $operator . SP . $cleaned_value;
4561
-        }
4562
-        if (in_array($operator, $this->valid_null_style_operators())) {
4563
-            if ($value !== null) {
4564
-                throw new EE_Error(
4565
-                    sprintf(
4566
-                        esc_html__(
4567
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4568
-                            "event_espresso"
4569
-                        ),
4570
-                        $value,
4571
-                        $operator
4572
-                    )
4573
-                );
4574
-            }
4575
-            return $operator;
4576
-        }
4577
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4578
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4579
-            // remove other junk. So just treat it as a string.
4580
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4581
-        }
4582
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4583
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4584
-        }
4585
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4586
-            throw new EE_Error(
4587
-                sprintf(
4588
-                    esc_html__(
4589
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4590
-                        'event_espresso'
4591
-                    ),
4592
-                    $operator,
4593
-                    $operator
4594
-                )
4595
-            );
4596
-        }
4597
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4598
-            throw new EE_Error(
4599
-                sprintf(
4600
-                    esc_html__(
4601
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4602
-                        'event_espresso'
4603
-                    ),
4604
-                    $operator,
4605
-                    $operator
4606
-                )
4607
-            );
4608
-        }
4609
-        throw new EE_Error(
4610
-            sprintf(
4611
-                esc_html__(
4612
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4613
-                    "event_espresso"
4614
-                ),
4615
-                http_build_query($op_and_value)
4616
-            )
4617
-        );
4618
-    }
4619
-
4620
-
4621
-    /**
4622
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4623
-     *
4624
-     * @param array                      $values
4625
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4626
-     *                                              '%s'
4627
-     * @return string
4628
-     * @throws EE_Error
4629
-     */
4630
-    public function _construct_between_value($values, $field_obj)
4631
-    {
4632
-        $cleaned_values = [];
4633
-        foreach ($values as $value) {
4634
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4635
-        }
4636
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4637
-    }
4638
-
4639
-
4640
-    /**
4641
-     * Takes an array or a comma-separated list of $values and cleans them
4642
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4643
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4644
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4645
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4646
-     *
4647
-     * @param mixed                      $values    array or comma-separated string
4648
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4649
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4650
-     * @throws EE_Error
4651
-     */
4652
-    public function _construct_in_value($values, $field_obj)
4653
-    {
4654
-        $prepped = [];
4655
-        // check if the value is a CSV list
4656
-        if (is_string($values)) {
4657
-            // in which case, turn it into an array
4658
-            $values = explode(',', $values);
4659
-        }
4660
-        // make sure we only have one of each value in the list
4661
-        $values = array_unique($values);
4662
-        foreach ($values as $value) {
4663
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4664
-        }
4665
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4666
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4667
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4668
-        if (empty($prepped)) {
4669
-            $all_fields  = $this->field_settings();
4670
-            $first_field = reset($all_fields);
4671
-            $main_table  = $this->_get_main_table();
4672
-            $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4673
-        }
4674
-        return '(' . implode(',', $prepped) . ')';
4675
-    }
4676
-
4677
-
4678
-    /**
4679
-     * @param mixed                      $value
4680
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4681
-     * @return false|null|string
4682
-     * @throws EE_Error
4683
-     */
4684
-    private function _wpdb_prepare_using_field($value, $field_obj)
4685
-    {
4686
-        /** @type WPDB $wpdb */
4687
-        global $wpdb;
4688
-        if ($field_obj instanceof EE_Model_Field_Base) {
4689
-            return $wpdb->prepare(
4690
-                $field_obj->get_wpdb_data_type(),
4691
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4692
-            );
4693
-        } //$field_obj should really just be a data type
4694
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4695
-            throw new EE_Error(
4696
-                sprintf(
4697
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4698
-                    $field_obj,
4699
-                    implode(",", $this->_valid_wpdb_data_types)
4700
-                )
4701
-            );
4702
-        }
4703
-        return $wpdb->prepare($field_obj, $value);
4704
-    }
4705
-
4706
-
4707
-    /**
4708
-     * Takes the input parameter and finds the model field that it indicates.
4709
-     *
4710
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4711
-     * @return EE_Model_Field_Base
4712
-     * @throws EE_Error
4713
-     */
4714
-    protected function _deduce_field_from_query_param($query_param_name)
4715
-    {
4716
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4717
-        // which will help us find the database table and column
4718
-        $query_param_parts = explode(".", $query_param_name);
4719
-        if (empty($query_param_parts)) {
4720
-            throw new EE_Error(
4721
-                sprintf(
4722
-                    esc_html__(
4723
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4724
-                        'event_espresso'
4725
-                    ),
4726
-                    $query_param_name
4727
-                )
4728
-            );
4729
-        }
4730
-        $number_of_parts       = count($query_param_parts);
4731
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4732
-        if ($number_of_parts === 1) {
4733
-            $field_name = $last_query_param_part;
4734
-            $model_obj  = $this;
4735
-        } else {// $number_of_parts >= 2
4736
-            // the last part is the column name, and there are only 2parts. therefore...
4737
-            $field_name = $last_query_param_part;
4738
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4739
-        }
4740
-        try {
4741
-            return $model_obj->field_settings_for($field_name);
4742
-        } catch (EE_Error $e) {
4743
-            return null;
4744
-        }
4745
-    }
4746
-
4747
-
4748
-    /**
4749
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4750
-     * alias and column which corresponds to it
4751
-     *
4752
-     * @param string $field_name
4753
-     * @return string
4754
-     * @throws EE_Error
4755
-     */
4756
-    public function _get_qualified_column_for_field($field_name)
4757
-    {
4758
-        $all_fields = $this->field_settings();
4759
-        $field      = $all_fields[ $field_name ] ?? false;
4760
-        if ($field) {
4761
-            return $field->get_qualified_column();
4762
-        }
4763
-        throw new EE_Error(
4764
-            sprintf(
4765
-                esc_html__(
4766
-                    "There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4767
-                    'event_espresso'
4768
-                ),
4769
-                $field_name,
4770
-                get_class($this)
4771
-            )
4772
-        );
4773
-    }
4774
-
4775
-
4776
-    /**
4777
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4778
-     * Example usage:
4779
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4780
-     *      array(),
4781
-     *      ARRAY_A,
4782
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4783
-     *  );
4784
-     * is equivalent to
4785
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4786
-     * and
4787
-     *  EEM_Event::instance()->get_all_wpdb_results(
4788
-     *      array(
4789
-     *          array(
4790
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4791
-     *          ),
4792
-     *          ARRAY_A,
4793
-     *          implode(
4794
-     *              ', ',
4795
-     *              array_merge(
4796
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4797
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4798
-     *              )
4799
-     *          )
4800
-     *      )
4801
-     *  );
4802
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4803
-     *
4804
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4805
-     *                                            and the one whose fields you are selecting for example: when querying
4806
-     *                                            tickets model and selecting fields from the tickets model you would
4807
-     *                                            leave this parameter empty, because no models are needed to join
4808
-     *                                            between the queried model and the selected one. Likewise when
4809
-     *                                            querying the datetime model and selecting fields from the tickets
4810
-     *                                            model, it would also be left empty, because there is a direct
4811
-     *                                            relation from datetimes to tickets, so no model is needed to join
4812
-     *                                            them together. However, when querying from the event model and
4813
-     *                                            selecting fields from the ticket model, you should provide the string
4814
-     *                                            'Datetime', indicating that the event model must first join to the
4815
-     *                                            datetime model in order to find its relation to ticket model.
4816
-     *                                            Also, when querying from the venue model and selecting fields from
4817
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4818
-     *                                            indicating you need to join the venue model to the event model,
4819
-     *                                            to the datetime model, in order to find its relation to the ticket
4820
-     *                                            model. This string is used to deduce the prefix that gets added onto
4821
-     *                                            the models' tables qualified columns
4822
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4823
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4824
-     *                                            qualified column names
4825
-     * @return array|string
4826
-     */
4827
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4828
-    {
4829
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4830
-                ? ''
4831
-                : '__');
4832
-        $qualified_columns = [];
4833
-        foreach ($this->field_settings() as $field_name => $field) {
4834
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4835
-        }
4836
-        return $return_string
4837
-            ? implode(', ', $qualified_columns)
4838
-            : $qualified_columns;
4839
-    }
4840
-
4841
-
4842
-    /**
4843
-     * constructs the select use on special limit joins
4844
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4845
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4846
-     * (as that is typically where the limits would be set).
4847
-     *
4848
-     * @param string       $table_alias The table the select is being built for
4849
-     * @param mixed|string $limit       The limit for this select
4850
-     * @return string                The final select join element for the query.
4851
-     * @throws EE_Error
4852
-     * @throws EE_Error
4853
-     */
4854
-    public function _construct_limit_join_select($table_alias, $limit)
4855
-    {
4856
-        $SQL = '';
4857
-        foreach ($this->_tables as $table_obj) {
4858
-            if ($table_obj instanceof EE_Primary_Table) {
4859
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4860
-                    ? $table_obj->get_select_join_limit($limit)
4861
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4862
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4863
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4864
-                    ? $table_obj->get_select_join_limit_join($limit)
4865
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4866
-            }
4867
-        }
4868
-        return $SQL;
4869
-    }
4870
-
4871
-
4872
-    /**
4873
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4874
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4875
-     *
4876
-     * @return string SQL
4877
-     * @throws EE_Error
4878
-     */
4879
-    public function _construct_internal_join()
4880
-    {
4881
-        $SQL = $this->_get_main_table()->get_table_sql();
4882
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4883
-        return $SQL;
4884
-    }
4885
-
4886
-
4887
-    /**
4888
-     * Constructs the SQL for joining all the tables on this model.
4889
-     * Normally $alias should be the primary table's alias, but in cases where
4890
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4891
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4892
-     * alias, this will construct SQL like:
4893
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4894
-     * With $alias being a secondary table's alias, this will construct SQL like:
4895
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4896
-     *
4897
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4898
-     * @return string
4899
-     * @throws EE_Error
4900
-     * @throws EE_Error
4901
-     */
4902
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4903
-    {
4904
-        $SQL               = '';
4905
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4906
-        foreach ($this->_tables as $table_obj) {
4907
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4908
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4909
-                    // so we're joining to this table, meaning the table is already in
4910
-                    // the FROM statement, BUT the primary table isn't. So we want
4911
-                    // to add the inverse join sql
4912
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4913
-                } else {
4914
-                    // just add a regular JOIN to this table from the primary table
4915
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4916
-                }
4917
-            }// if it's a primary table, dont add any SQL. it should already be in the FROM statement
4918
-        }
4919
-        return $SQL;
4920
-    }
4921
-
4922
-
4923
-    /**
4924
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4925
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4926
-     * their data type (eg, '%s', '%d', etc)
4927
-     *
4928
-     * @return array
4929
-     */
4930
-    public function _get_data_types()
4931
-    {
4932
-        $data_types = [];
4933
-        foreach ($this->field_settings() as $field_obj) {
4934
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4935
-            /** @var $field_obj EE_Model_Field_Base */
4936
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4937
-        }
4938
-        return $data_types;
4939
-    }
4940
-
4941
-
4942
-    /**
4943
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4944
-     *
4945
-     * @param string $model_name
4946
-     * @return EEM_Base
4947
-     * @throws EE_Error
4948
-     */
4949
-    public function get_related_model_obj($model_name)
4950
-    {
4951
-        $model_classname = "EEM_" . $model_name;
4952
-        if (! class_exists($model_classname)) {
4953
-            throw new EE_Error(
4954
-                sprintf(
4955
-                    esc_html__(
4956
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4957
-                        'event_espresso'
4958
-                    ),
4959
-                    $model_name,
4960
-                    $model_classname
4961
-                )
4962
-            );
4963
-        }
4964
-        return call_user_func($model_classname . "::instance");
4965
-    }
4966
-
4967
-
4968
-    /**
4969
-     * Returns the array of EE_ModelRelations for this model.
4970
-     *
4971
-     * @return EE_Model_Relation_Base[]
4972
-     */
4973
-    public function relation_settings()
4974
-    {
4975
-        return $this->_model_relations;
4976
-    }
4977
-
4978
-
4979
-    /**
4980
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4981
-     * because without THOSE models, this model probably doesn't have much purpose.
4982
-     * (Eg, without an event, datetimes have little purpose.)
4983
-     *
4984
-     * @return EE_Belongs_To_Relation[]
4985
-     */
4986
-    public function belongs_to_relations()
4987
-    {
4988
-        $belongs_to_relations = [];
4989
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4990
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4991
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4992
-            }
4993
-        }
4994
-        return $belongs_to_relations;
4995
-    }
4996
-
4997
-
4998
-    /**
4999
-     * Returns the specified EE_Model_Relation, or throws an exception
5000
-     *
5001
-     * @param string $relation_name name of relation, key in $this->_relatedModels
5002
-     * @return EE_Model_Relation_Base
5003
-     * @throws EE_Error
5004
-     */
5005
-    public function related_settings_for($relation_name)
5006
-    {
5007
-        $relatedModels = $this->relation_settings();
5008
-        if (! array_key_exists($relation_name, $relatedModels)) {
5009
-            throw new EE_Error(
5010
-                sprintf(
5011
-                    esc_html__(
5012
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
5013
-                        'event_espresso'
5014
-                    ),
5015
-                    $relation_name,
5016
-                    $this->_get_class_name(),
5017
-                    implode(', ', array_keys($relatedModels))
5018
-                )
5019
-            );
5020
-        }
5021
-        return $relatedModels[ $relation_name ];
5022
-    }
5023
-
5024
-
5025
-    /**
5026
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
5027
-     * fields
5028
-     *
5029
-     * @param string  $fieldName
5030
-     * @param boolean $include_db_only_fields
5031
-     * @return EE_Model_Field_Base
5032
-     * @throws EE_Error
5033
-     */
5034
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
5035
-    {
5036
-        $fieldSettings = $this->field_settings($include_db_only_fields);
5037
-        if (! array_key_exists($fieldName, $fieldSettings)) {
5038
-            throw new EE_Error(
5039
-                sprintf(
5040
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
5041
-                    $fieldName,
5042
-                    get_class($this)
5043
-                )
5044
-            );
5045
-        }
5046
-        return $fieldSettings[ $fieldName ];
5047
-    }
5048
-
5049
-
5050
-    /**
5051
-     * Checks if this field exists on this model
5052
-     *
5053
-     * @param string $fieldName a key in the model's _field_settings array
5054
-     * @return boolean
5055
-     */
5056
-    public function has_field($fieldName)
5057
-    {
5058
-        $fieldSettings = $this->field_settings(true);
5059
-        if (isset($fieldSettings[ $fieldName ])) {
5060
-            return true;
5061
-        }
5062
-        return false;
5063
-    }
5064
-
5065
-
5066
-    /**
5067
-     * Returns whether or not this model has a relation to the specified model
5068
-     *
5069
-     * @param string $relation_name possibly one of the keys in the relation_settings array
5070
-     * @return boolean
5071
-     */
5072
-    public function has_relation($relation_name)
5073
-    {
5074
-        $relations = $this->relation_settings();
5075
-        if (isset($relations[ $relation_name ])) {
5076
-            return true;
5077
-        }
5078
-        return false;
5079
-    }
5080
-
5081
-
5082
-    /**
5083
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5084
-     * Eg, on EE_Answer that would be ANS_ID field object
5085
-     *
5086
-     * @param $field_obj
5087
-     * @return boolean
5088
-     */
5089
-    public function is_primary_key_field($field_obj): bool
5090
-    {
5091
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
5092
-    }
5093
-
5094
-
5095
-    /**
5096
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5097
-     * Eg, on EE_Answer that would be ANS_ID field object
5098
-     *
5099
-     * @return EE_Primary_Key_Field_Base
5100
-     * @throws EE_Error
5101
-     */
5102
-    public function get_primary_key_field()
5103
-    {
5104
-        if ($this->_primary_key_field === null) {
5105
-            foreach ($this->field_settings(true) as $field_obj) {
5106
-                if ($this->is_primary_key_field($field_obj)) {
5107
-                    $this->_primary_key_field = $field_obj;
5108
-                    break;
5109
-                }
5110
-            }
5111
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5112
-                throw new EE_Error(
5113
-                    sprintf(
5114
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5115
-                        get_class($this)
5116
-                    )
5117
-                );
5118
-            }
5119
-        }
5120
-        return $this->_primary_key_field;
5121
-    }
5122
-
5123
-
5124
-    /**
5125
-     * Returns whether or not not there is a primary key on this model.
5126
-     * Internally does some caching.
5127
-     *
5128
-     * @return boolean
5129
-     */
5130
-    public function has_primary_key_field()
5131
-    {
5132
-        if ($this->_has_primary_key_field === null) {
5133
-            try {
5134
-                $this->get_primary_key_field();
5135
-                $this->_has_primary_key_field = true;
5136
-            } catch (EE_Error $e) {
5137
-                $this->_has_primary_key_field = false;
5138
-            }
5139
-        }
5140
-        return $this->_has_primary_key_field;
5141
-    }
5142
-
5143
-
5144
-    /**
5145
-     * Finds the first field of type $field_class_name.
5146
-     *
5147
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5148
-     *                                 EE_Foreign_Key_Field, etc
5149
-     * @return EE_Model_Field_Base or null if none is found
5150
-     */
5151
-    public function get_a_field_of_type($field_class_name)
5152
-    {
5153
-        foreach ($this->field_settings() as $field) {
5154
-            if ($field instanceof $field_class_name) {
5155
-                return $field;
5156
-            }
5157
-        }
5158
-        return null;
5159
-    }
5160
-
5161
-
5162
-    /**
5163
-     * Gets a foreign key field pointing to model.
5164
-     *
5165
-     * @param string $model_name eg Event, Registration, not EEM_Event
5166
-     * @return EE_Foreign_Key_Field_Base
5167
-     * @throws EE_Error
5168
-     */
5169
-    public function get_foreign_key_to($model_name)
5170
-    {
5171
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5172
-            foreach ($this->field_settings() as $field) {
5173
-                if (
5174
-                    $field instanceof EE_Foreign_Key_Field_Base
5175
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5176
-                ) {
5177
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5178
-                    break;
5179
-                }
5180
-            }
5181
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5182
-                throw new EE_Error(
5183
-                    sprintf(
5184
-                        esc_html__(
5185
-                            "There is no foreign key field pointing to model %s on model %s",
5186
-                            'event_espresso'
5187
-                        ),
5188
-                        $model_name,
5189
-                        get_class($this)
5190
-                    )
5191
-                );
5192
-            }
5193
-        }
5194
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5195
-    }
5196
-
5197
-
5198
-    /**
5199
-     * Gets the table name (including $wpdb->prefix) for the table alias
5200
-     *
5201
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5202
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5203
-     *                            Either one works
5204
-     * @return string
5205
-     */
5206
-    public function get_table_for_alias($table_alias)
5207
-    {
5208
-        $table_alias_sans_model_relation_chain_prefix =
5209
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5210
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5211
-    }
5212
-
5213
-
5214
-    /**
5215
-     * Returns a flat array of all field son this model, instead of organizing them
5216
-     * by table_alias as they are in the constructor.
5217
-     *
5218
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5219
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5220
-     */
5221
-    public function field_settings($include_db_only_fields = false)
5222
-    {
5223
-        if ($include_db_only_fields) {
5224
-            if ($this->_cached_fields === null) {
5225
-                $this->_cached_fields = [];
5226
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5227
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5228
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5229
-                    }
5230
-                }
5231
-            }
5232
-            return $this->_cached_fields;
5233
-        }
5234
-        if ($this->_cached_fields_non_db_only === null) {
5235
-            $this->_cached_fields_non_db_only = [];
5236
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5237
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238
-                    /** @var $field_obj EE_Model_Field_Base */
5239
-                    if (! $field_obj->is_db_only_field()) {
5240
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5241
-                    }
5242
-                }
5243
-            }
5244
-        }
5245
-        return $this->_cached_fields_non_db_only;
5246
-    }
5247
-
5248
-
5249
-    /**
5250
-     *        cycle though array of attendees and create objects out of each item
5251
-     *
5252
-     * @access        private
5253
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5254
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5255
-     *                           numerically indexed)
5256
-     * @throws EE_Error
5257
-     * @throws ReflectionException
5258
-     */
5259
-    protected function _create_objects($rows = [])
5260
-    {
5261
-        $array_of_objects = [];
5262
-        if (empty($rows)) {
5263
-            return [];
5264
-        }
5265
-        $count_if_model_has_no_primary_key = 0;
5266
-        $has_primary_key                   = $this->has_primary_key_field();
5267
-        $primary_key_field                 = $has_primary_key
5268
-            ? $this->get_primary_key_field()
5269
-            : null;
5270
-        foreach ((array) $rows as $row) {
5271
-            if (empty($row)) {
5272
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5273
-                return [];
5274
-            }
5275
-            // check if we've already set this object in the results array,
5276
-            // in which case there's no need to process it further (again)
5277
-            if ($has_primary_key) {
5278
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5279
-                    $row,
5280
-                    $primary_key_field->get_qualified_column(),
5281
-                    $primary_key_field->get_table_column()
5282
-                );
5283
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5284
-                    continue;
5285
-                }
5286
-            }
5287
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5288
-            if (! $classInstance) {
5289
-                throw new EE_Error(
5290
-                    sprintf(
5291
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5292
-                        $this->get_this_model_name(),
5293
-                        http_build_query($row)
5294
-                    )
5295
-                );
5296
-            }
5297
-            // set the timezone on the instantiated objects
5298
-            $classInstance->set_timezone($this->_timezone);
5299
-            // make sure if there is any timezone setting present that we set the timezone for the object
5300
-            $key                      = $has_primary_key
5301
-                ? $classInstance->ID()
5302
-                : $count_if_model_has_no_primary_key++;
5303
-            $array_of_objects[ $key ] = $classInstance;
5304
-            // also, for all the relations of type BelongsTo, see if we can cache
5305
-            // those related models
5306
-            // (we could do this for other relations too, but if there are conditions
5307
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5308
-            // so it requires a little more thought than just caching them immediately...)
5309
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5310
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5311
-                    // check if this model's INFO is present. If so, cache it on the model
5312
-                    $other_model           = $relation_obj->get_other_model();
5313
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5314
-                    // if we managed to make a model object from the results, cache it on the main model object
5315
-                    if ($other_model_obj_maybe) {
5316
-                        // set timezone on these other model objects if they are present
5317
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5318
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5319
-                    }
5320
-                }
5321
-            }
5322
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5323
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5324
-            // the field in the CustomSelects object
5325
-            if ($this->_custom_selections instanceof CustomSelects) {
5326
-                $classInstance->setCustomSelectsValues(
5327
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5328
-                );
5329
-            }
5330
-        }
5331
-        return $array_of_objects;
5332
-    }
5333
-
5334
-
5335
-    /**
5336
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5337
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5338
-     *
5339
-     * @param array $db_results_row
5340
-     * @return array
5341
-     */
5342
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5343
-    {
5344
-        $results = [];
5345
-        if ($this->_custom_selections instanceof CustomSelects) {
5346
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5347
-                if (isset($db_results_row[ $alias ])) {
5348
-                    $results[ $alias ] = $this->convertValueToDataType(
5349
-                        $db_results_row[ $alias ],
5350
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5351
-                    );
5352
-                }
5353
-            }
5354
-        }
5355
-        return $results;
5356
-    }
5357
-
5358
-
5359
-    /**
5360
-     * This will set the value for the given alias
5361
-     *
5362
-     * @param string $value
5363
-     * @param string $datatype (one of %d, %s, %f)
5364
-     * @return int|string|float (int for %d, string for %s, float for %f)
5365
-     */
5366
-    protected function convertValueToDataType($value, $datatype)
5367
-    {
5368
-        switch ($datatype) {
5369
-            case '%f':
5370
-                return (float) $value;
5371
-            case '%d':
5372
-                return (int) $value;
5373
-            default:
5374
-                return (string) $value;
5375
-        }
5376
-    }
5377
-
5378
-
5379
-    /**
5380
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5381
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5382
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5383
-     * object (as set in the model_field!).
5384
-     *
5385
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5386
-     * @throws EE_Error
5387
-     * @throws ReflectionException
5388
-     */
5389
-    public function create_default_object()
5390
-    {
5391
-        $this_model_fields_and_values = [];
5392
-        // setup the row using default values;
5393
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5394
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5395
-        }
5396
-        $className = $this->_get_class_name();
5397
-        return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5398
-    }
5399
-
5400
-
5401
-    /**
5402
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5403
-     *                             or an stdClass where each property is the name of a column,
5404
-     * @return EE_Base_Class
5405
-     * @throws EE_Error
5406
-     * @throws ReflectionException
5407
-     */
5408
-    public function instantiate_class_from_array_or_object($cols_n_values)
5409
-    {
5410
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5411
-            $cols_n_values = get_object_vars($cols_n_values);
5412
-        }
5413
-        $primary_key = null;
5414
-        // make sure the array only has keys that are fields/columns on this model
5415
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5416
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5417
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5418
-        }
5419
-        $className = $this->_get_class_name();
5420
-        // check we actually found results that we can use to build our model object
5421
-        // if not, return null
5422
-        if ($this->has_primary_key_field()) {
5423
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5424
-                return null;
5425
-            }
5426
-        } elseif ($this->unique_indexes()) {
5427
-            $first_column = reset($this_model_fields_n_values);
5428
-            if (empty($first_column)) {
5429
-                return null;
5430
-            }
5431
-        }
5432
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5433
-        if ($primary_key) {
5434
-            $classInstance = $this->get_from_entity_map($primary_key);
5435
-            if (! $classInstance) {
5436
-                $classInstance = EE_Registry::instance()
5437
-                                            ->load_class(
5438
-                                                $className,
5439
-                                                [$this_model_fields_n_values, $this->_timezone],
5440
-                                                true,
5441
-                                                false
5442
-                                            );
5443
-                // add this new object to the entity map
5444
-                $classInstance = $this->add_to_entity_map($classInstance);
5445
-            }
5446
-        } else {
5447
-            $classInstance = EE_Registry::instance()->load_class(
5448
-                $className,
5449
-                [$this_model_fields_n_values, $this->_timezone],
5450
-                true,
5451
-                false
5452
-            );
5453
-        }
5454
-        return $classInstance;
5455
-    }
5456
-
5457
-
5458
-    /**
5459
-     * Gets the model object from the  entity map if it exists
5460
-     *
5461
-     * @param int|string $id the ID of the model object
5462
-     * @return EE_Base_Class
5463
-     */
5464
-    public function get_from_entity_map($id)
5465
-    {
5466
-        return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5467
-    }
5468
-
5469
-
5470
-    /**
5471
-     * add_to_entity_map
5472
-     * Adds the object to the model's entity mappings
5473
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5474
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5475
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5476
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5477
-     *        then this method should be called immediately after the update query
5478
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5479
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5480
-     *
5481
-     * @param EE_Base_Class $object
5482
-     * @return EE_Base_Class
5483
-     * @throws EE_Error
5484
-     * @throws ReflectionException
5485
-     */
5486
-    public function add_to_entity_map(EE_Base_Class $object)
5487
-    {
5488
-        $className = $this->_get_class_name();
5489
-        if (! $object instanceof $className) {
5490
-            throw new EE_Error(
5491
-                sprintf(
5492
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5493
-                    is_object($object)
5494
-                        ? get_class($object)
5495
-                        : $object,
5496
-                    $className
5497
-                )
5498
-            );
5499
-        }
5500
-
5501
-        if (! $object->ID()) {
5502
-            throw new EE_Error(
5503
-                sprintf(
5504
-                    esc_html__(
5505
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5506
-                        "event_espresso"
5507
-                    ),
5508
-                    get_class($this)
5509
-                )
5510
-            );
5511
-        }
5512
-        // double check it's not already there
5513
-        $classInstance = $this->get_from_entity_map($object->ID());
5514
-        if ($classInstance) {
5515
-            return $classInstance;
5516
-        }
5517
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5518
-        return $object;
5519
-    }
5520
-
5521
-
5522
-    /**
5523
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5524
-     * if no identifier is provided, then the entire entity map is emptied
5525
-     *
5526
-     * @param int|string $id the ID of the model object
5527
-     * @return boolean
5528
-     */
5529
-    public function clear_entity_map($id = null)
5530
-    {
5531
-        if (empty($id)) {
5532
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5533
-            return true;
5534
-        }
5535
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5536
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5537
-            return true;
5538
-        }
5539
-        return false;
5540
-    }
5541
-
5542
-
5543
-    /**
5544
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5545
-     * Given an array where keys are column (or column alias) names and values,
5546
-     * returns an array of their corresponding field names and database values
5547
-     *
5548
-     * @param array $cols_n_values
5549
-     * @return array
5550
-     * @throws EE_Error
5551
-     * @throws ReflectionException
5552
-     */
5553
-    public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5554
-    {
5555
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5556
-    }
5557
-
5558
-
5559
-    /**
5560
-     * _deduce_fields_n_values_from_cols_n_values
5561
-     * Given an array where keys are column (or column alias) names and values,
5562
-     * returns an array of their corresponding field names and database values
5563
-     *
5564
-     * @param array|stdClass $cols_n_values
5565
-     * @return array
5566
-     * @throws EE_Error
5567
-     * @throws ReflectionException
5568
-     */
5569
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5570
-    {
5571
-        if ($cols_n_values instanceof stdClass) {
5572
-            $cols_n_values = get_object_vars($cols_n_values);
5573
-        }
5574
-        $this_model_fields_n_values = [];
5575
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5576
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5577
-                $cols_n_values,
5578
-                $table_obj->get_fully_qualified_pk_column(),
5579
-                $table_obj->get_pk_column()
5580
-            );
5581
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5582
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5583
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5584
-                    if (! $field_obj->is_db_only_field()) {
5585
-                        // prepare field as if its coming from db
5586
-                        $prepared_value                            =
5587
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5588
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5589
-                    }
5590
-                }
5591
-            } else {
5592
-                // the table's rows existed. Use their values
5593
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
-                    if (! $field_obj->is_db_only_field()) {
5595
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5596
-                            $cols_n_values,
5597
-                            $field_obj->get_qualified_column(),
5598
-                            $field_obj->get_table_column()
5599
-                        );
5600
-                    }
5601
-                }
5602
-            }
5603
-        }
5604
-        return $this_model_fields_n_values;
5605
-    }
5606
-
5607
-
5608
-    /**
5609
-     * @param $cols_n_values
5610
-     * @param $qualified_column
5611
-     * @param $regular_column
5612
-     * @return null
5613
-     * @throws EE_Error
5614
-     * @throws ReflectionException
5615
-     */
5616
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5617
-    {
5618
-        $value = null;
5619
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5620
-        // does the field on the model relate to this column retrieved from the db?
5621
-        // or is it a db-only field? (not relating to the model)
5622
-        if (isset($cols_n_values[ $qualified_column ])) {
5623
-            $value = $cols_n_values[ $qualified_column ];
5624
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5625
-            $value = $cols_n_values[ $regular_column ];
5626
-        } elseif (! empty($this->foreign_key_aliases)) {
5627
-            // no PK?  ok check if there is a foreign key alias set for this table
5628
-            // then check if that alias exists in the incoming data
5629
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5630
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5631
-                if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5632
-                    $value = $cols_n_values[ $FK_alias ];
5633
-                    [$pk_class] = explode('.', $PK_column);
5634
-                    $pk_model_name = "EEM_{$pk_class}";
5635
-                    /** @var EEM_Base $pk_model */
5636
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5637
-                    if ($pk_model instanceof EEM_Base) {
5638
-                        // make sure object is pulled from db and added to entity map
5639
-                        $pk_model->get_one_by_ID($value);
5640
-                    }
5641
-                    break;
5642
-                }
5643
-            }
5644
-        }
5645
-        return $value;
5646
-    }
5647
-
5648
-
5649
-    /**
5650
-     * refresh_entity_map_from_db
5651
-     * Makes sure the model object in the entity map at $id assumes the values
5652
-     * of the database (opposite of EE_base_Class::save())
5653
-     *
5654
-     * @param int|string $id
5655
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5656
-     * @throws EE_Error
5657
-     * @throws ReflectionException
5658
-     */
5659
-    public function refresh_entity_map_from_db($id)
5660
-    {
5661
-        $obj_in_map = $this->get_from_entity_map($id);
5662
-        if ($obj_in_map) {
5663
-            $wpdb_results = $this->_get_all_wpdb_results(
5664
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5665
-            );
5666
-            if ($wpdb_results && is_array($wpdb_results)) {
5667
-                $one_row = reset($wpdb_results);
5668
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5669
-                    $obj_in_map->set_from_db($field_name, $db_value);
5670
-                }
5671
-                // clear the cache of related model objects
5672
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5673
-                    $obj_in_map->clear_cache($relation_name, null, true);
5674
-                }
5675
-            }
5676
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5677
-            return $obj_in_map;
5678
-        }
5679
-        return $this->get_one_by_ID($id);
5680
-    }
5681
-
5682
-
5683
-    /**
5684
-     * refresh_entity_map_with
5685
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5686
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5687
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5688
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5689
-     *
5690
-     * @param int|string    $id
5691
-     * @param EE_Base_Class $replacing_model_obj
5692
-     * @return EE_Base_Class
5693
-     * @throws EE_Error
5694
-     * @throws ReflectionException
5695
-     */
5696
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5697
-    {
5698
-        $obj_in_map = $this->get_from_entity_map($id);
5699
-        if ($obj_in_map) {
5700
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5701
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5702
-                    $obj_in_map->set($field_name, $value);
5703
-                }
5704
-                // make the model object in the entity map's cache match the $replacing_model_obj
5705
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5706
-                    $obj_in_map->clear_cache($relation_name, null, true);
5707
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5708
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5709
-                    }
5710
-                }
5711
-            }
5712
-            return $obj_in_map;
5713
-        }
5714
-        $this->add_to_entity_map($replacing_model_obj);
5715
-        return $replacing_model_obj;
5716
-    }
5717
-
5718
-
5719
-    /**
5720
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5721
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5722
-     * require_once($this->_getClassName().".class.php");
5723
-     *
5724
-     * @return string
5725
-     */
5726
-    private function _get_class_name()
5727
-    {
5728
-        return "EE_" . $this->get_this_model_name();
5729
-    }
5730
-
5731
-
5732
-    /**
5733
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5734
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5735
-     * it would be 'Events'.
5736
-     *
5737
-     * @param int|float|null $quantity
5738
-     * @return string
5739
-     */
5740
-    public function item_name($quantity = 1): string
5741
-    {
5742
-        $quantity = floor($quantity);
5743
-        return apply_filters(
5744
-            'FHEE__EEM_Base__item_name__plural_or_singular',
5745
-            $quantity > 1
5746
-                ? $this->plural_item
5747
-                : $this->singular_item,
5748
-            $quantity,
5749
-            $this->plural_item,
5750
-            $this->singular_item
5751
-        );
5752
-    }
5753
-
5754
-
5755
-    /**
5756
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5757
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5758
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5759
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5760
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5761
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5762
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5763
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5764
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5765
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5766
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5767
-     *        return $previousReturnValue.$returnString;
5768
-     * }
5769
-     * require('EEM_Answer.model.php');
5770
-     * echo EEM_Answer::instance()->my_callback('monkeys',100);
5771
-     * // will output "you called my_callback! and passed args:monkeys,100"
5772
-     *
5773
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5774
-     * @param array  $args       array of original arguments passed to the function
5775
-     * @return mixed whatever the plugin which calls add_filter decides
5776
-     * @throws EE_Error
5777
-     */
5778
-    public function __call($methodName, $args)
5779
-    {
5780
-        $className = get_class($this);
5781
-        $tagName   = "FHEE__{$className}__{$methodName}";
5782
-        if (! has_filter($tagName)) {
5783
-            throw new EE_Error(
5784
-                sprintf(
5785
-                    esc_html__(
5786
-                        'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5787
-                        'event_espresso'
5788
-                    ),
5789
-                    $methodName,
5790
-                    $className,
5791
-                    $tagName,
5792
-                    '<br />'
5793
-                )
5794
-            );
5795
-        }
5796
-        return apply_filters($tagName, null, $this, $args);
5797
-    }
5798
-
5799
-
5800
-    /**
5801
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5802
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5803
-     *
5804
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5805
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5806
-     *                                                       the object's class name
5807
-     *                                                       or object's ID
5808
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5809
-     *                                                       exists in the database. If it does not, we add it
5810
-     * @return EE_Base_Class
5811
-     * @throws EE_Error
5812
-     * @throws ReflectionException
5813
-     */
5814
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5815
-    {
5816
-        $className = $this->_get_class_name();
5817
-        if ($base_class_obj_or_id instanceof $className) {
5818
-            $model_object = $base_class_obj_or_id;
5819
-        } else {
5820
-            $primary_key_field = $this->get_primary_key_field();
5821
-            if (
5822
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5823
-                && (
5824
-                    is_int($base_class_obj_or_id)
5825
-                    || is_string($base_class_obj_or_id)
5826
-                )
5827
-            ) {
5828
-                // assume it's an ID.
5829
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5830
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5831
-            } elseif (
5832
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5833
-                && is_string($base_class_obj_or_id)
5834
-            ) {
5835
-                // assume it's a string representation of the object
5836
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5837
-            } else {
5838
-                throw new EE_Error(
5839
-                    sprintf(
5840
-                        esc_html__(
5841
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5842
-                            'event_espresso'
5843
-                        ),
5844
-                        $base_class_obj_or_id,
5845
-                        $this->_get_class_name(),
5846
-                        print_r($base_class_obj_or_id, true)
5847
-                    )
5848
-                );
5849
-            }
5850
-        }
5851
-        if ($ensure_is_in_db && $model_object instanceof EE_Base_Class && $model_object->ID() !== null) {
5852
-            $model_object->save();
5853
-        }
5854
-        return $model_object;
5855
-    }
5856
-
5857
-
5858
-    /**
5859
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5860
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5861
-     * returns it ID.
5862
-     *
5863
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5864
-     * @return int|string depending on the type of this model object's ID
5865
-     * @throws EE_Error
5866
-     * @throws ReflectionException
5867
-     */
5868
-    public function ensure_is_ID($base_class_obj_or_id)
5869
-    {
5870
-        $className = $this->_get_class_name();
5871
-        if ($base_class_obj_or_id instanceof $className) {
5872
-            /** @var $base_class_obj_or_id EE_Base_Class */
5873
-            $id = $base_class_obj_or_id->ID();
5874
-        } elseif (is_int($base_class_obj_or_id)) {
5875
-            // assume it's an ID
5876
-            $id = $base_class_obj_or_id;
5877
-        } elseif (is_string($base_class_obj_or_id)) {
5878
-            // assume its a string representation of the object
5879
-            $id = $base_class_obj_or_id;
5880
-        } else {
5881
-            throw new EE_Error(
5882
-                sprintf(
5883
-                    esc_html__(
5884
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5885
-                        'event_espresso'
5886
-                    ),
5887
-                    $base_class_obj_or_id,
5888
-                    $this->_get_class_name(),
5889
-                    print_r($base_class_obj_or_id, true)
5890
-                )
5891
-            );
5892
-        }
5893
-        return $id;
5894
-    }
5895
-
5896
-
5897
-    /**
5898
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5899
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5900
-     * been sanitized and converted into the appropriate domain.
5901
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5902
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5903
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5904
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5905
-     * $EVT = EEM_Event::instance(); $old_setting =
5906
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5907
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5908
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5909
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5910
-     *
5911
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5912
-     * @return void
5913
-     */
5914
-    public function assume_values_already_prepared_by_model_object(
5915
-        $values_already_prepared = self::not_prepared_by_model_object
5916
-    ) {
5917
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5918
-    }
5919
-
5920
-
5921
-    /**
5922
-     * Read comments for assume_values_already_prepared_by_model_object()
5923
-     *
5924
-     * @return int
5925
-     */
5926
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5927
-    {
5928
-        return $this->_values_already_prepared_by_model_object;
5929
-    }
5930
-
5931
-
5932
-    /**
5933
-     * Gets all the indexes on this model
5934
-     *
5935
-     * @return EE_Index[]
5936
-     */
5937
-    public function indexes()
5938
-    {
5939
-        return $this->_indexes;
5940
-    }
5941
-
5942
-
5943
-    /**
5944
-     * Gets all the Unique Indexes on this model
5945
-     *
5946
-     * @return EE_Unique_Index[]
5947
-     */
5948
-    public function unique_indexes()
5949
-    {
5950
-        $unique_indexes = [];
5951
-        foreach ($this->_indexes as $name => $index) {
5952
-            if ($index instanceof EE_Unique_Index) {
5953
-                $unique_indexes [ $name ] = $index;
5954
-            }
5955
-        }
5956
-        return $unique_indexes;
5957
-    }
5958
-
5959
-
5960
-    /**
5961
-     * Gets all the fields which, when combined, make the primary key.
5962
-     * This is usually just an array with 1 element (the primary key), but in cases
5963
-     * where there is no primary key, it's a combination of fields as defined
5964
-     * on a primary index
5965
-     *
5966
-     * @return EE_Model_Field_Base[] indexed by the field's name
5967
-     * @throws EE_Error
5968
-     */
5969
-    public function get_combined_primary_key_fields()
5970
-    {
5971
-        foreach ($this->indexes() as $index) {
5972
-            if ($index instanceof EE_Primary_Key_Index) {
5973
-                return $index->fields();
5974
-            }
5975
-        }
5976
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5977
-    }
5978
-
5979
-
5980
-    /**
5981
-     * Used to build a primary key string (when the model has no primary key),
5982
-     * which can be used a unique string to identify this model object.
5983
-     *
5984
-     * @param array $fields_n_values keys are field names, values are their values.
5985
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5986
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5987
-     *                               before passing it to this function (that will convert it from columns-n-values
5988
-     *                               to field-names-n-values).
5989
-     * @return string
5990
-     * @throws EE_Error
5991
-     */
5992
-    public function get_index_primary_key_string($fields_n_values)
5993
-    {
5994
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5995
-            $fields_n_values,
5996
-            $this->get_combined_primary_key_fields()
5997
-        );
5998
-        return http_build_query($cols_n_values_for_primary_key_index);
5999
-    }
6000
-
6001
-
6002
-    /**
6003
-     * Gets the field values from the primary key string
6004
-     *
6005
-     * @param string $index_primary_key_string
6006
-     * @return null|array
6007
-     * @throws EE_Error
6008
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
6009
-     */
6010
-    public function parse_index_primary_key_string($index_primary_key_string)
6011
-    {
6012
-        $key_fields = $this->get_combined_primary_key_fields();
6013
-        // check all of them are in the $id
6014
-        $key_vals_in_combined_pk = [];
6015
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6016
-        foreach ($key_fields as $key_field_name => $field_obj) {
6017
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6018
-                return null;
6019
-            }
6020
-        }
6021
-        return $key_vals_in_combined_pk;
6022
-    }
6023
-
6024
-
6025
-    /**
6026
-     * verifies that an array of key-value pairs for model fields has a key
6027
-     * for each field comprising the primary key index
6028
-     *
6029
-     * @param array $key_vals
6030
-     * @return boolean
6031
-     * @throws EE_Error
6032
-     */
6033
-    public function has_all_combined_primary_key_fields($key_vals)
6034
-    {
6035
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6036
-        foreach ($keys_it_should_have as $key) {
6037
-            if (! isset($key_vals[ $key ])) {
6038
-                return false;
6039
-            }
6040
-        }
6041
-        return true;
6042
-    }
6043
-
6044
-
6045
-    /**
6046
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
6047
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
6048
-     *
6049
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
6050
-     * @param array               $query_params                     @see
6051
-     *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
6052
-     * @throws EE_Error
6053
-     * @throws ReflectionException
6054
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
6055
-     *                                                              indexed)
6056
-     */
6057
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
6058
-    {
6059
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
6060
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
6061
-        } elseif (is_array($model_object_or_attributes_array)) {
6062
-            $attributes_array = $model_object_or_attributes_array;
6063
-        } else {
6064
-            throw new EE_Error(
6065
-                sprintf(
6066
-                    esc_html__(
6067
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
6068
-                        "event_espresso"
6069
-                    ),
6070
-                    $model_object_or_attributes_array
6071
-                )
6072
-            );
6073
-        }
6074
-        // even copies obviously won't have the same ID, so remove the primary key
6075
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
6076
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6077
-            unset($attributes_array[ $this->primary_key_name() ]);
6078
-        }
6079
-        if (isset($query_params[0])) {
6080
-            $query_params[0] = array_merge($attributes_array, $query_params);
6081
-        } else {
6082
-            $query_params[0] = $attributes_array;
6083
-        }
6084
-        return $this->get_all($query_params);
6085
-    }
6086
-
6087
-
6088
-    /**
6089
-     * Gets the first copy we find. See get_all_copies for more details
6090
-     *
6091
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6092
-     * @param array $query_params
6093
-     * @return EE_Base_Class
6094
-     * @throws EE_Error
6095
-     * @throws ReflectionException
6096
-     */
6097
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6098
-    {
6099
-        if (! is_array($query_params)) {
6100
-            EE_Error::doing_it_wrong(
6101
-                'EEM_Base::get_one_copy',
6102
-                sprintf(
6103
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6104
-                    gettype($query_params)
6105
-                ),
6106
-                '4.6.0'
6107
-            );
6108
-            $query_params = [];
6109
-        }
6110
-        $query_params['limit'] = 1;
6111
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6112
-        if (is_array($copies)) {
6113
-            return array_shift($copies);
6114
-        }
6115
-        return null;
6116
-    }
6117
-
6118
-
6119
-    /**
6120
-     * Updates the item with the specified id. Ignores default query parameters because
6121
-     * we have specified the ID, and its assumed we KNOW what we're doing
6122
-     *
6123
-     * @param array      $fields_n_values keys are field names, values are their new values
6124
-     * @param int|string $id              the value of the primary key to update
6125
-     * @return int number of rows updated
6126
-     * @throws EE_Error
6127
-     * @throws ReflectionException
6128
-     */
6129
-    public function update_by_ID($fields_n_values, $id)
6130
-    {
6131
-        $query_params = [
6132
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6133
-            'default_where_conditions' => EE_Default_Where_Conditions::OTHER_MODELS_ONLY,
6134
-        ];
6135
-        return $this->update($fields_n_values, $query_params);
6136
-    }
6137
-
6138
-
6139
-    /**
6140
-     * Changes an operator which was supplied to the models into one usable in SQL
6141
-     *
6142
-     * @param string $operator_supplied
6143
-     * @return string an operator which can be used in SQL
6144
-     * @throws EE_Error
6145
-     */
6146
-    private function _prepare_operator_for_sql($operator_supplied)
6147
-    {
6148
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6149
-        if ($sql_operator) {
6150
-            return $sql_operator;
6151
-        }
6152
-        throw new EE_Error(
6153
-            sprintf(
6154
-                esc_html__(
6155
-                    "The operator '%s' is not in the list of valid operators: %s",
6156
-                    "event_espresso"
6157
-                ),
6158
-                $operator_supplied,
6159
-                implode(",", array_keys($this->_valid_operators))
6160
-            )
6161
-        );
6162
-    }
6163
-
6164
-
6165
-    /**
6166
-     * Gets the valid operators
6167
-     *
6168
-     * @return array keys are accepted strings, values are the SQL they are converted to
6169
-     */
6170
-    public function valid_operators()
6171
-    {
6172
-        return $this->_valid_operators;
6173
-    }
6174
-
6175
-
6176
-    /**
6177
-     * Gets the between-style operators (take 2 arguments).
6178
-     *
6179
-     * @return array keys are accepted strings, values are the SQL they are converted to
6180
-     */
6181
-    public function valid_between_style_operators()
6182
-    {
6183
-        return array_intersect(
6184
-            $this->valid_operators(),
6185
-            $this->_between_style_operators
6186
-        );
6187
-    }
6188
-
6189
-
6190
-    /**
6191
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6192
-     *
6193
-     * @return array keys are accepted strings, values are the SQL they are converted to
6194
-     */
6195
-    public function valid_like_style_operators()
6196
-    {
6197
-        return array_intersect(
6198
-            $this->valid_operators(),
6199
-            $this->_like_style_operators
6200
-        );
6201
-    }
6202
-
6203
-
6204
-    /**
6205
-     * Gets the "in"-style operators
6206
-     *
6207
-     * @return array keys are accepted strings, values are the SQL they are converted to
6208
-     */
6209
-    public function valid_in_style_operators()
6210
-    {
6211
-        return array_intersect(
6212
-            $this->valid_operators(),
6213
-            $this->_in_style_operators
6214
-        );
6215
-    }
6216
-
6217
-
6218
-    /**
6219
-     * Gets the "null"-style operators (accept no arguments)
6220
-     *
6221
-     * @return array keys are accepted strings, values are the SQL they are converted to
6222
-     */
6223
-    public function valid_null_style_operators()
6224
-    {
6225
-        return array_intersect(
6226
-            $this->valid_operators(),
6227
-            $this->_null_style_operators
6228
-        );
6229
-    }
6230
-
6231
-
6232
-    /**
6233
-     * Gets an array where keys are the primary keys and values are their 'names'
6234
-     * (as determined by the model object's name() function, which is often overridden)
6235
-     *
6236
-     * @param array $query_params like get_all's
6237
-     * @return string[]
6238
-     * @throws EE_Error
6239
-     * @throws ReflectionException
6240
-     */
6241
-    public function get_all_names($query_params = [])
6242
-    {
6243
-        $objs  = $this->get_all($query_params);
6244
-        $names = [];
6245
-        foreach ($objs as $obj) {
6246
-            $names[ $obj->ID() ] = $obj->name();
6247
-        }
6248
-        return $names;
6249
-    }
6250
-
6251
-
6252
-    /**
6253
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6254
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6255
-     * this is duplicated effort and reduces efficiency) you would be better to use
6256
-     * array_keys() on $model_objects.
6257
-     *
6258
-     * @param \EE_Base_Class[] $model_objects
6259
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6260
-     *                                               in the returned array
6261
-     * @return array
6262
-     * @throws EE_Error
6263
-     * @throws ReflectionException
6264
-     */
6265
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6266
-    {
6267
-        if (! $this->has_primary_key_field()) {
6268
-            if (defined('WP_DEBUG') && WP_DEBUG) {
6269
-                EE_Error::add_error(
6270
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6271
-                    __FILE__,
6272
-                    __FUNCTION__,
6273
-                    __LINE__
6274
-                );
6275
-            }
6276
-        }
6277
-        $IDs = [];
6278
-        foreach ($model_objects as $model_object) {
6279
-            $id = $model_object->ID();
6280
-            if (! $id) {
6281
-                if ($filter_out_empty_ids) {
6282
-                    continue;
6283
-                }
6284
-                if (defined('WP_DEBUG') && WP_DEBUG) {
6285
-                    EE_Error::add_error(
6286
-                        esc_html__(
6287
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6288
-                            'event_espresso'
6289
-                        ),
6290
-                        __FILE__,
6291
-                        __FUNCTION__,
6292
-                        __LINE__
6293
-                    );
6294
-                }
6295
-            }
6296
-            $IDs[] = $id;
6297
-        }
6298
-        return $IDs;
6299
-    }
6300
-
6301
-
6302
-    /**
6303
-     * Returns the string used in capabilities relating to this model. If there
6304
-     * are no capabilities that relate to this model returns false
6305
-     *
6306
-     * @return string|false
6307
-     */
6308
-    public function cap_slug()
6309
-    {
6310
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6311
-    }
6312
-
6313
-
6314
-    /**
6315
-     * Returns the capability-restrictions array (@param string $context
6316
-     *
6317
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6318
-     * @throws EE_Error
6319
-     * @see EEM_Base::_cap_restrictions).
6320
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6321
-     *      only returns the cap restrictions array in that context (ie, the array
6322
-     *      at that key)
6323
-     */
6324
-    public function cap_restrictions($context = EEM_Base::caps_read)
6325
-    {
6326
-        EEM_Base::verify_is_valid_cap_context($context);
6327
-        // check if we ought to run the restriction generator first
6328
-        if (
6329
-            isset($this->_cap_restriction_generators[ $context ])
6330
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6331
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6332
-        ) {
6333
-            $this->_cap_restrictions[ $context ] = array_merge(
6334
-                $this->_cap_restrictions[ $context ],
6335
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6336
-            );
6337
-        }
6338
-        // and make sure we've finalized the construction of each restriction
6339
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6340
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6341
-                $where_conditions_obj->_finalize_construct($this);
6342
-            }
6343
-        }
6344
-        return $this->_cap_restrictions[ $context ];
6345
-    }
6346
-
6347
-
6348
-    /**
6349
-     * Indicating whether or not this model thinks its a wp core model
6350
-     *
6351
-     * @return boolean
6352
-     */
6353
-    public function is_wp_core_model()
6354
-    {
6355
-        return $this->_wp_core_model;
6356
-    }
6357
-
6358
-
6359
-    /**
6360
-     * Gets all the caps that are missing which impose a restriction on
6361
-     * queries made in this context
6362
-     *
6363
-     * @param string $context one of EEM_Base::caps_ constants
6364
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6365
-     * @throws EE_Error
6366
-     */
6367
-    public function caps_missing($context = EEM_Base::caps_read)
6368
-    {
6369
-        $missing_caps     = [];
6370
-        $cap_restrictions = $this->cap_restrictions($context);
6371
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6372
-            if (
6373
-                ! EE_Capabilities::instance()
6374
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6375
-            ) {
6376
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6377
-            }
6378
-        }
6379
-        return $missing_caps;
6380
-    }
6381
-
6382
-
6383
-    /**
6384
-     * Gets the mapping from capability contexts to action strings used in capability names
6385
-     *
6386
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6387
-     * one of 'read', 'edit', or 'delete'
6388
-     */
6389
-    public function cap_contexts_to_cap_action_map()
6390
-    {
6391
-        return apply_filters(
6392
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6393
-            $this->_cap_contexts_to_cap_action_map,
6394
-            $this
6395
-        );
6396
-    }
6397
-
6398
-
6399
-    /**
6400
-     * Gets the action string for the specified capability context
6401
-     *
6402
-     * @param string $context
6403
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6404
-     * @throws EE_Error
6405
-     */
6406
-    public function cap_action_for_context($context)
6407
-    {
6408
-        $mapping = $this->cap_contexts_to_cap_action_map();
6409
-        if (isset($mapping[ $context ])) {
6410
-            return $mapping[ $context ];
6411
-        }
6412
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6413
-            return $action;
6414
-        }
6415
-        throw new EE_Error(
6416
-            sprintf(
6417
-                esc_html__(
6418
-                    'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6419
-                    'event_espresso'
6420
-                ),
6421
-                $context,
6422
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6423
-            )
6424
-        );
6425
-    }
6426
-
6427
-
6428
-    /**
6429
-     * Returns all the capability contexts which are valid when querying models
6430
-     *
6431
-     * @return array
6432
-     */
6433
-    public static function valid_cap_contexts(): array
6434
-    {
6435
-        return (array) apply_filters(
6436
-            'FHEE__EEM_Base__valid_cap_contexts',
6437
-            [
6438
-                self::caps_read,
6439
-                self::caps_read_admin,
6440
-                self::caps_edit,
6441
-                self::caps_delete,
6442
-            ]
6443
-        );
6444
-    }
6445
-
6446
-
6447
-    /**
6448
-     * Returns all valid options for 'default_where_conditions'
6449
-     *
6450
-     * @return array
6451
-     */
6452
-    public static function valid_default_where_conditions(): array
6453
-    {
6454
-        return [
6455
-            EE_Default_Where_Conditions::ALL,
6456
-            EE_Default_Where_Conditions::THIS_MODEL_ONLY,
6457
-            EE_Default_Where_Conditions::OTHER_MODELS_ONLY,
6458
-            EE_Default_Where_Conditions::MINIMUM_ALL,
6459
-            EE_Default_Where_Conditions::MINIMUM_OTHERS,
6460
-            EE_Default_Where_Conditions::NONE,
6461
-        ];
6462
-    }
6463
-
6464
-    // public static function default_where_conditions_full
6465
-
6466
-
6467
-    /**
6468
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6469
-     *
6470
-     * @param string $context
6471
-     * @return bool
6472
-     * @throws EE_Error
6473
-     */
6474
-    public static function verify_is_valid_cap_context($context): bool
6475
-    {
6476
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6477
-        if (in_array($context, $valid_cap_contexts)) {
6478
-            return true;
6479
-        }
6480
-        throw new EE_Error(
6481
-            sprintf(
6482
-                esc_html__(
6483
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6484
-                    'event_espresso'
6485
-                ),
6486
-                $context,
6487
-                'EEM_Base',
6488
-                implode(',', $valid_cap_contexts)
6489
-            )
6490
-        );
6491
-    }
6492
-
6493
-
6494
-    /**
6495
-     * Clears all the models field caches. This is only useful when a sub-class
6496
-     * might have added a field or something and these caches might be invalidated
6497
-     */
6498
-    protected function _invalidate_field_caches()
6499
-    {
6500
-        $this->_cache_foreign_key_to_fields = [];
6501
-        $this->_cached_fields               = null;
6502
-        $this->_cached_fields_non_db_only   = null;
6503
-    }
6504
-
6505
-
6506
-    /**
6507
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6508
-     * (eg "and", "or", "not").
6509
-     *
6510
-     * @return array
6511
-     */
6512
-    public function logic_query_param_keys(): array
6513
-    {
6514
-        return $this->_logic_query_param_keys;
6515
-    }
6516
-
6517
-
6518
-    /**
6519
-     * Determines whether or not the where query param array key is for a logic query param.
6520
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6521
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6522
-     *
6523
-     * @param $query_param_key
6524
-     * @return bool
6525
-     */
6526
-    public function is_logic_query_param_key($query_param_key): bool
6527
-    {
6528
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6529
-            if (
6530
-                $query_param_key === $logic_query_param_key
6531
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6532
-            ) {
6533
-                return true;
6534
-            }
6535
-        }
6536
-        return false;
6537
-    }
6538
-
6539
-
6540
-    /**
6541
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6542
-     *
6543
-     * @return boolean
6544
-     * @since 4.9.74.p
6545
-     */
6546
-    public function hasPassword(): bool
6547
-    {
6548
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6549
-        if ($this->has_password_field === null) {
6550
-            $password_field           = $this->getPasswordField();
6551
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6552
-        }
6553
-        return $this->has_password_field;
6554
-    }
6555
-
6556
-
6557
-    /**
6558
-     * Returns the password field on this model, if there is one
6559
-     *
6560
-     * @return EE_Password_Field|null
6561
-     * @since 4.9.74.p
6562
-     */
6563
-    public function getPasswordField()
6564
-    {
6565
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6566
-        // there's no need to search for it. If we don't know yet, then find out
6567
-        if ($this->has_password_field === null && $this->password_field === null) {
6568
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6569
-        }
6570
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6571
-        return $this->password_field;
6572
-    }
6573
-
6574
-
6575
-    /**
6576
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6577
-     *
6578
-     * @return EE_Model_Field_Base[]
6579
-     * @throws EE_Error
6580
-     * @since 4.9.74.p
6581
-     */
6582
-    public function getPasswordProtectedFields()
6583
-    {
6584
-        $password_field = $this->getPasswordField();
6585
-        $fields         = [];
6586
-        if ($password_field instanceof EE_Password_Field) {
6587
-            $field_names = $password_field->protectedFields();
6588
-            foreach ($field_names as $field_name) {
6589
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6590
-            }
6591
-        }
6592
-        return $fields;
6593
-    }
6594
-
6595
-
6596
-    /**
6597
-     * Checks if the current user can perform the requested action on this model
6598
-     *
6599
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6600
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6601
-     * @return bool
6602
-     * @throws EE_Error
6603
-     * @throws InvalidArgumentException
6604
-     * @throws InvalidDataTypeException
6605
-     * @throws InvalidInterfaceException
6606
-     * @throws ReflectionException
6607
-     * @throws UnexpectedEntityException
6608
-     * @since 4.9.74.p
6609
-     */
6610
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6611
-    {
6612
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6613
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6614
-        }
6615
-        if (! is_array($model_obj_or_fields_n_values)) {
6616
-            throw new UnexpectedEntityException(
6617
-                $model_obj_or_fields_n_values,
6618
-                'EE_Base_Class',
6619
-                sprintf(
6620
-                    esc_html__(
6621
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6622
-                        'event_espresso'
6623
-                    ),
6624
-                    __FUNCTION__
6625
-                )
6626
-            );
6627
-        }
6628
-        return $this->exists(
6629
-            $this->alter_query_params_to_restrict_by_ID(
6630
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6631
-                [
6632
-                    'default_where_conditions' => 'none',
6633
-                    'caps'                     => $cap_to_check,
6634
-                ]
6635
-            )
6636
-        );
6637
-    }
6638
-
6639
-
6640
-    /**
6641
-     * Returns the query param where conditions key to the password affecting this model.
6642
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6643
-     *
6644
-     * @return null|string
6645
-     * @throws EE_Error
6646
-     * @throws InvalidArgumentException
6647
-     * @throws InvalidDataTypeException
6648
-     * @throws InvalidInterfaceException
6649
-     * @throws ModelConfigurationException
6650
-     * @throws ReflectionException
6651
-     * @since 4.9.74.p
6652
-     */
6653
-    public function modelChainAndPassword()
6654
-    {
6655
-        if ($this->model_chain_to_password === null) {
6656
-            throw new ModelConfigurationException(
6657
-                $this,
6658
-                esc_html_x(
6659
-                // @codingStandardsIgnoreStart
6660
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6661
-                    // @codingStandardsIgnoreEnd
6662
-                    '1: model name',
6663
-                    'event_espresso'
6664
-                )
6665
-            );
6666
-        }
6667
-        if ($this->model_chain_to_password === '') {
6668
-            $model_with_password = $this;
6669
-        } else {
6670
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6671
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6672
-            } else {
6673
-                $last_model_in_chain = $this->model_chain_to_password;
6674
-            }
6675
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6676
-        }
6677
-
6678
-        $password_field = $model_with_password->getPasswordField();
6679
-        if ($password_field instanceof EE_Password_Field) {
6680
-            $password_field_name = $password_field->get_name();
6681
-        } else {
6682
-            throw new ModelConfigurationException(
6683
-                $this,
6684
-                sprintf(
6685
-                    esc_html_x(
6686
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6687
-                        '1: model name, 2: special string',
6688
-                        'event_espresso'
6689
-                    ),
6690
-                    $model_with_password->get_this_model_name(),
6691
-                    $this->model_chain_to_password
6692
-                )
6693
-            );
6694
-        }
6695
-        return (
6696
-               $this->model_chain_to_password
6697
-                   ? $this->model_chain_to_password . '.'
6698
-                   : ''
6699
-               ) . $password_field_name;
6700
-    }
6701
-
6702
-
6703
-    /**
6704
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6705
-     * or if this model itself has a password affecting access to some of its other fields.
6706
-     *
6707
-     * @return boolean
6708
-     * @since 4.9.74.p
6709
-     */
6710
-    public function restrictedByRelatedModelPassword(): bool
6711
-    {
6712
-        return $this->model_chain_to_password !== null;
6713
-    }
3950
+		}
3951
+		return $null_friendly_where_conditions;
3952
+	}
3953
+
3954
+
3955
+	/**
3956
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3957
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3958
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3959
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3960
+	 *
3961
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3962
+	 * @return array @see
3963
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3964
+	 * @throws EE_Error
3965
+	 * @throws EE_Error
3966
+	 */
3967
+	private function _get_default_where_conditions($model_relation_path = '')
3968
+	{
3969
+		if ($this->_ignore_where_strategy) {
3970
+			return [];
3971
+		}
3972
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3973
+	}
3974
+
3975
+
3976
+	/**
3977
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3978
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3979
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3980
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3981
+	 * Similar to _get_default_where_conditions
3982
+	 *
3983
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3984
+	 * @return array @see
3985
+	 *                                    https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3986
+	 * @throws EE_Error
3987
+	 * @throws EE_Error
3988
+	 */
3989
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3990
+	{
3991
+		if ($this->_ignore_where_strategy) {
3992
+			return [];
3993
+		}
3994
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3995
+	}
3996
+
3997
+
3998
+	/**
3999
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
4000
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
4001
+	 *
4002
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
4003
+	 * @return string
4004
+	 * @throws EE_Error
4005
+	 */
4006
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
4007
+	{
4008
+		$selects = $this->_get_columns_to_select_for_this_model();
4009
+		foreach (
4010
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
4011
+		) {
4012
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
4013
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
4014
+			foreach ($other_model_selects as $key => $value) {
4015
+				$selects[] = $value;
4016
+			}
4017
+		}
4018
+		return implode(", ", $selects);
4019
+	}
4020
+
4021
+
4022
+	/**
4023
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
4024
+	 * So that's going to be the columns for all the fields on the model
4025
+	 *
4026
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
4027
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
4028
+	 */
4029
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
4030
+	{
4031
+		$fields                                       = $this->field_settings();
4032
+		$selects                                      = [];
4033
+		$table_alias_with_model_relation_chain_prefix =
4034
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
4035
+				$model_relation_chain,
4036
+				$this->get_this_model_name()
4037
+			);
4038
+		foreach ($fields as $field_obj) {
4039
+			$selects[] = $table_alias_with_model_relation_chain_prefix
4040
+						 . $field_obj->get_table_alias()
4041
+						 . "."
4042
+						 . $field_obj->get_table_column()
4043
+						 . " AS '"
4044
+						 . $table_alias_with_model_relation_chain_prefix
4045
+						 . $field_obj->get_table_alias()
4046
+						 . "."
4047
+						 . $field_obj->get_table_column()
4048
+						 . "'";
4049
+		}
4050
+		// make sure we are also getting the PKs of each table
4051
+		$tables = $this->get_tables();
4052
+		if (count($tables) > 1) {
4053
+			foreach ($tables as $table_obj) {
4054
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4055
+									   . $table_obj->get_fully_qualified_pk_column();
4056
+				if (! in_array($qualified_pk_column, $selects)) {
4057
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4058
+				}
4059
+			}
4060
+		}
4061
+		return $selects;
4062
+	}
4063
+
4064
+
4065
+	/**
4066
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
4067
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
4068
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
4069
+	 * SQL for joining, and the data types
4070
+	 *
4071
+	 * @param null|string                 $original_query_param
4072
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
4073
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4074
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
4075
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
4076
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
4077
+	 *                                                          or 'Registration's
4078
+	 * @param string                      $original_query_param what it originally was (eg
4079
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
4080
+	 *                                                          matches $query_param
4081
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
4082
+	 * @throws EE_Error
4083
+	 */
4084
+	private function _extract_related_model_info_from_query_param(
4085
+		$query_param,
4086
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4087
+		$query_param_type,
4088
+		$original_query_param = null
4089
+	) {
4090
+		if ($original_query_param === null) {
4091
+			$original_query_param = $query_param;
4092
+		}
4093
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4094
+		// check to see if we have a field on this model
4095
+		$this_model_fields = $this->field_settings(true);
4096
+		if (array_key_exists($query_param, $this_model_fields)) {
4097
+			$field_is_allowed = in_array(
4098
+				$query_param_type,
4099
+				[0, 'where', 'having', 'order_by', 'group_by', 'order', 'custom_selects'],
4100
+				true
4101
+			);
4102
+			if ($field_is_allowed) {
4103
+				return;
4104
+			}
4105
+			throw new EE_Error(
4106
+				sprintf(
4107
+					esc_html__(
4108
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4109
+						"event_espresso"
4110
+					),
4111
+					$query_param,
4112
+					get_class($this),
4113
+					$query_param_type,
4114
+					$original_query_param
4115
+				)
4116
+			);
4117
+		}
4118
+		// check if this is a special logic query param
4119
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4120
+			$operator_is_allowed = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4121
+			if ($operator_is_allowed) {
4122
+				return;
4123
+			}
4124
+			throw new EE_Error(
4125
+				sprintf(
4126
+					esc_html__(
4127
+						'Logic query params ("%1$s") are being used incorrectly with the following query param ("%2$s") on model %3$s. %4$sAdditional Info:%4$s%5$s',
4128
+						'event_espresso'
4129
+					),
4130
+					implode('", "', $this->_logic_query_param_keys),
4131
+					$query_param,
4132
+					get_class($this),
4133
+					'<br />',
4134
+					"\t"
4135
+					. ' $passed_in_query_info = <pre>'
4136
+					. print_r($passed_in_query_info, true)
4137
+					. '</pre>'
4138
+					. "\n\t"
4139
+					. ' $query_param_type = '
4140
+					. $query_param_type
4141
+					. "\n\t"
4142
+					. ' $original_query_param = '
4143
+					. $original_query_param
4144
+				)
4145
+			);
4146
+		}
4147
+		// check if it's a custom selection
4148
+		if (
4149
+			$this->_custom_selections instanceof CustomSelects
4150
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4151
+		) {
4152
+			return;
4153
+		}
4154
+		// check if has a model name at the beginning
4155
+		// and
4156
+		// check if it's a field on a related model
4157
+		if (
4158
+			$this->extractJoinModelFromQueryParams(
4159
+				$passed_in_query_info,
4160
+				$query_param,
4161
+				$original_query_param,
4162
+				$query_param_type
4163
+			)
4164
+		) {
4165
+			return;
4166
+		}
4167
+
4168
+		// ok so $query_param didn't start with a model name
4169
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4170
+		// it's wack, that's what it is
4171
+		throw new EE_Error(
4172
+			sprintf(
4173
+				esc_html__(
4174
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4175
+					"event_espresso"
4176
+				),
4177
+				$query_param,
4178
+				get_class($this),
4179
+				$query_param_type,
4180
+				$original_query_param
4181
+			)
4182
+		);
4183
+	}
4184
+
4185
+
4186
+	/**
4187
+	 * Extracts any possible join model information from the provided possible_join_string.
4188
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4189
+	 * join
4190
+	 * parts that should be added to the query.
4191
+	 *
4192
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4193
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4194
+	 * @param null|string                 $original_query_param
4195
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4196
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4197
+	 *                                                           etc.)
4198
+	 * @return bool  returns true if a join was added and false if not.
4199
+	 * @throws EE_Error
4200
+	 */
4201
+	private function extractJoinModelFromQueryParams(
4202
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4203
+		$possible_join_string,
4204
+		$original_query_param,
4205
+		$query_parameter_type
4206
+	) {
4207
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4208
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4209
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4210
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4211
+				if ($possible_join_string === '') {
4212
+					// nothing left to $query_param
4213
+					// we should actually end in a field name, not a model like this!
4214
+					throw new EE_Error(
4215
+						sprintf(
4216
+							esc_html__(
4217
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4218
+								"event_espresso"
4219
+							),
4220
+							$possible_join_string,
4221
+							$query_parameter_type,
4222
+							get_class($this),
4223
+							$valid_related_model_name
4224
+						)
4225
+					);
4226
+				}
4227
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4228
+				$related_model_obj->_extract_related_model_info_from_query_param(
4229
+					$possible_join_string,
4230
+					$query_info_carrier,
4231
+					$query_parameter_type,
4232
+					$original_query_param
4233
+				);
4234
+				return true;
4235
+			}
4236
+			if ($possible_join_string === $valid_related_model_name) {
4237
+				$this->_add_join_to_model(
4238
+					$valid_related_model_name,
4239
+					$query_info_carrier,
4240
+					$original_query_param
4241
+				);
4242
+				return true;
4243
+			}
4244
+		}
4245
+		return false;
4246
+	}
4247
+
4248
+
4249
+	/**
4250
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4251
+	 *
4252
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4253
+	 * @throws EE_Error
4254
+	 */
4255
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4256
+	{
4257
+		if (
4258
+			$this->_custom_selections instanceof CustomSelects
4259
+			&& (
4260
+				$this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4261
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4262
+			)
4263
+		) {
4264
+			$original_selects = $this->_custom_selections->originalSelects();
4265
+			foreach ($original_selects as $alias => $select_configuration) {
4266
+				$this->extractJoinModelFromQueryParams(
4267
+					$query_info_carrier,
4268
+					$select_configuration[0],
4269
+					$select_configuration[0],
4270
+					'custom_selects'
4271
+				);
4272
+			}
4273
+		}
4274
+	}
4275
+
4276
+
4277
+	/**
4278
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4279
+	 * and store it on $passed_in_query_info
4280
+	 *
4281
+	 * @param string                      $model_name
4282
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4283
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4284
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4285
+	 *                                                          and are adding a join to 'Payment' with the original
4286
+	 *                                                          query param key
4287
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4288
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4289
+	 *                                                          Payment wants to add default query params so that it
4290
+	 *                                                          will know what models to prepend onto its default query
4291
+	 *                                                          params or in case it wants to rename tables (in case
4292
+	 *                                                          there are multiple joins to the same table)
4293
+	 * @return void
4294
+	 * @throws EE_Error
4295
+	 */
4296
+	private function _add_join_to_model(
4297
+		$model_name,
4298
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4299
+		$original_query_param
4300
+	) {
4301
+		$relation_obj         = $this->related_settings_for($model_name);
4302
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4303
+		// check if the relation is HABTM, because then we're essentially doing two joins
4304
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4305
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4306
+			$join_model_obj = $relation_obj->get_join_model();
4307
+			// replace the model specified with the join model for this relation chain, whi
4308
+			$relation_chain_to_join_model =
4309
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4310
+					$model_name,
4311
+					$join_model_obj->get_this_model_name(),
4312
+					$model_relation_chain
4313
+				);
4314
+			$passed_in_query_info->merge(
4315
+				new EE_Model_Query_Info_Carrier(
4316
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4317
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4318
+				)
4319
+			);
4320
+		}
4321
+		// now just join to the other table pointed to by the relation object, and add its data types
4322
+		$passed_in_query_info->merge(
4323
+			new EE_Model_Query_Info_Carrier(
4324
+				[$model_relation_chain => $model_name],
4325
+				$relation_obj->get_join_statement($model_relation_chain)
4326
+			)
4327
+		);
4328
+	}
4329
+
4330
+
4331
+	/**
4332
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4333
+	 *
4334
+	 * @param array $where_params @see
4335
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4336
+	 * @return string of SQL
4337
+	 * @throws EE_Error
4338
+	 */
4339
+	private function _construct_where_clause($where_params)
4340
+	{
4341
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4342
+		if ($SQL) {
4343
+			return " WHERE " . $SQL;
4344
+		}
4345
+		return '';
4346
+	}
4347
+
4348
+
4349
+	/**
4350
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4351
+	 * and should be passed HAVING parameters, not WHERE parameters
4352
+	 *
4353
+	 * @param array $having_params
4354
+	 * @return string
4355
+	 * @throws EE_Error
4356
+	 */
4357
+	private function _construct_having_clause($having_params)
4358
+	{
4359
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4360
+		if ($SQL) {
4361
+			return " HAVING " . $SQL;
4362
+		}
4363
+		return '';
4364
+	}
4365
+
4366
+
4367
+	/**
4368
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4369
+	 * Event_Meta.meta_value = 'foo'))"
4370
+	 *
4371
+	 * @param array  $where_params @see
4372
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4373
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4374
+	 * @return string of SQL
4375
+	 * @throws EE_Error
4376
+	 */
4377
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4378
+	{
4379
+		$where_clauses = [];
4380
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4381
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4382
+			if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4383
+				switch ($query_param) {
4384
+					case 'not':
4385
+					case 'NOT':
4386
+						$where_clauses[] = "! ("
4387
+										   . $this->_construct_condition_clause_recursive(
4388
+											   $op_and_value_or_sub_condition,
4389
+											   $glue
4390
+										   )
4391
+										   . ")";
4392
+						break;
4393
+					case 'and':
4394
+					case 'AND':
4395
+						$where_clauses[] = " ("
4396
+										   . $this->_construct_condition_clause_recursive(
4397
+											   $op_and_value_or_sub_condition,
4398
+											   ' AND '
4399
+										   )
4400
+										   . ")";
4401
+						break;
4402
+					case 'or':
4403
+					case 'OR':
4404
+						$where_clauses[] = " ("
4405
+										   . $this->_construct_condition_clause_recursive(
4406
+											   $op_and_value_or_sub_condition,
4407
+											   ' OR '
4408
+										   )
4409
+										   . ")";
4410
+						break;
4411
+				}
4412
+			} else {
4413
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4414
+				// if it's not a normal field, maybe it's a custom selection?
4415
+				if (! $field_obj) {
4416
+					if ($this->_custom_selections instanceof CustomSelects) {
4417
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4418
+					} else {
4419
+						throw new EE_Error(
4420
+							sprintf(
4421
+								esc_html__(
4422
+									"%s is neither a valid model field name, nor a custom selection",
4423
+									"event_espresso"
4424
+								),
4425
+								$query_param
4426
+							)
4427
+						);
4428
+					}
4429
+				}
4430
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4431
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4432
+			}
4433
+		}
4434
+		return $where_clauses
4435
+			? implode($glue, $where_clauses)
4436
+			: '';
4437
+	}
4438
+
4439
+
4440
+	/**
4441
+	 * Takes the input parameter and extract the table name (alias) and column name
4442
+	 *
4443
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4444
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4445
+	 * @throws EE_Error
4446
+	 */
4447
+	private function _deduce_column_name_from_query_param($query_param)
4448
+	{
4449
+		$field = $this->_deduce_field_from_query_param($query_param);
4450
+		if ($field) {
4451
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4452
+				$field->get_model_name(),
4453
+				$query_param
4454
+			);
4455
+			return $table_alias_prefix . $field->get_qualified_column();
4456
+		}
4457
+		if (
4458
+			$this->_custom_selections instanceof CustomSelects
4459
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4460
+		) {
4461
+			// maybe it's custom selection item?
4462
+			// if so, just use it as the "column name"
4463
+			return $query_param;
4464
+		}
4465
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4466
+			? implode(',', $this->_custom_selections->columnAliases())
4467
+			: '';
4468
+		throw new EE_Error(
4469
+			sprintf(
4470
+				esc_html__(
4471
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4472
+					"event_espresso"
4473
+				),
4474
+				$query_param,
4475
+				$custom_select_aliases
4476
+			)
4477
+		);
4478
+	}
4479
+
4480
+
4481
+	/**
4482
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4483
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4484
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4485
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4486
+	 *
4487
+	 * @param string $condition_query_param_key
4488
+	 * @return string
4489
+	 */
4490
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4491
+	{
4492
+		$pos_of_star = strpos($condition_query_param_key, '*');
4493
+		if ($pos_of_star === false) {
4494
+			return $condition_query_param_key;
4495
+		}
4496
+		return substr($condition_query_param_key, 0, $pos_of_star);
4497
+	}
4498
+
4499
+
4500
+	/**
4501
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4502
+	 *
4503
+	 * @param array|string               $op_and_value
4504
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4505
+	 * @return string
4506
+	 * @throws EE_Error
4507
+	 */
4508
+	private function _construct_op_and_value($op_and_value, $field_obj)
4509
+	{
4510
+		$operator = '=';
4511
+		$value    = $op_and_value;
4512
+		if (is_array($op_and_value)) {
4513
+			$operator = isset($op_and_value[0])
4514
+				? $this->_prepare_operator_for_sql($op_and_value[0])
4515
+				: null;
4516
+			if (! $operator) {
4517
+				$php_array_like_string = [];
4518
+				foreach ($op_and_value as $key => $value) {
4519
+					$value = is_array($value) ? '[' . implode(",", $value) . ']' : $value;
4520
+					$php_array_like_string[] = "$key=>$value";
4521
+				}
4522
+				throw new EE_Error(
4523
+					sprintf(
4524
+						esc_html__(
4525
+							"You setup a query parameter like you were going to specify an operator, but didn't. You provided '(%s)', but the operator should be at array key index 0 (eg array('>',32))",
4526
+							"event_espresso"
4527
+						),
4528
+						implode(",", $php_array_like_string)
4529
+					)
4530
+				);
4531
+			}
4532
+			$value = $op_and_value[1] ?? null;
4533
+		}
4534
+
4535
+		// check to see if the value is actually another field
4536
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4537
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4538
+		}
4539
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4540
+			// in this case, the value should be an array, or at least a comma-separated list
4541
+			// it will need to handle a little differently
4542
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4543
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4544
+			return $operator . SP . $cleaned_value;
4545
+		}
4546
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4547
+			// the value should be an array with count of two.
4548
+			if (count($value) !== 2) {
4549
+				throw new EE_Error(
4550
+					sprintf(
4551
+						esc_html__(
4552
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4553
+							'event_espresso'
4554
+						),
4555
+						"BETWEEN"
4556
+					)
4557
+				);
4558
+			}
4559
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4560
+			return $operator . SP . $cleaned_value;
4561
+		}
4562
+		if (in_array($operator, $this->valid_null_style_operators())) {
4563
+			if ($value !== null) {
4564
+				throw new EE_Error(
4565
+					sprintf(
4566
+						esc_html__(
4567
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4568
+							"event_espresso"
4569
+						),
4570
+						$value,
4571
+						$operator
4572
+					)
4573
+				);
4574
+			}
4575
+			return $operator;
4576
+		}
4577
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4578
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4579
+			// remove other junk. So just treat it as a string.
4580
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4581
+		}
4582
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4583
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4584
+		}
4585
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4586
+			throw new EE_Error(
4587
+				sprintf(
4588
+					esc_html__(
4589
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4590
+						'event_espresso'
4591
+					),
4592
+					$operator,
4593
+					$operator
4594
+				)
4595
+			);
4596
+		}
4597
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4598
+			throw new EE_Error(
4599
+				sprintf(
4600
+					esc_html__(
4601
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4602
+						'event_espresso'
4603
+					),
4604
+					$operator,
4605
+					$operator
4606
+				)
4607
+			);
4608
+		}
4609
+		throw new EE_Error(
4610
+			sprintf(
4611
+				esc_html__(
4612
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4613
+					"event_espresso"
4614
+				),
4615
+				http_build_query($op_and_value)
4616
+			)
4617
+		);
4618
+	}
4619
+
4620
+
4621
+	/**
4622
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4623
+	 *
4624
+	 * @param array                      $values
4625
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4626
+	 *                                              '%s'
4627
+	 * @return string
4628
+	 * @throws EE_Error
4629
+	 */
4630
+	public function _construct_between_value($values, $field_obj)
4631
+	{
4632
+		$cleaned_values = [];
4633
+		foreach ($values as $value) {
4634
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4635
+		}
4636
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4637
+	}
4638
+
4639
+
4640
+	/**
4641
+	 * Takes an array or a comma-separated list of $values and cleans them
4642
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4643
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4644
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4645
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4646
+	 *
4647
+	 * @param mixed                      $values    array or comma-separated string
4648
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4649
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4650
+	 * @throws EE_Error
4651
+	 */
4652
+	public function _construct_in_value($values, $field_obj)
4653
+	{
4654
+		$prepped = [];
4655
+		// check if the value is a CSV list
4656
+		if (is_string($values)) {
4657
+			// in which case, turn it into an array
4658
+			$values = explode(',', $values);
4659
+		}
4660
+		// make sure we only have one of each value in the list
4661
+		$values = array_unique($values);
4662
+		foreach ($values as $value) {
4663
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4664
+		}
4665
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4666
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4667
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4668
+		if (empty($prepped)) {
4669
+			$all_fields  = $this->field_settings();
4670
+			$first_field = reset($all_fields);
4671
+			$main_table  = $this->_get_main_table();
4672
+			$prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4673
+		}
4674
+		return '(' . implode(',', $prepped) . ')';
4675
+	}
4676
+
4677
+
4678
+	/**
4679
+	 * @param mixed                      $value
4680
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4681
+	 * @return false|null|string
4682
+	 * @throws EE_Error
4683
+	 */
4684
+	private function _wpdb_prepare_using_field($value, $field_obj)
4685
+	{
4686
+		/** @type WPDB $wpdb */
4687
+		global $wpdb;
4688
+		if ($field_obj instanceof EE_Model_Field_Base) {
4689
+			return $wpdb->prepare(
4690
+				$field_obj->get_wpdb_data_type(),
4691
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4692
+			);
4693
+		} //$field_obj should really just be a data type
4694
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4695
+			throw new EE_Error(
4696
+				sprintf(
4697
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4698
+					$field_obj,
4699
+					implode(",", $this->_valid_wpdb_data_types)
4700
+				)
4701
+			);
4702
+		}
4703
+		return $wpdb->prepare($field_obj, $value);
4704
+	}
4705
+
4706
+
4707
+	/**
4708
+	 * Takes the input parameter and finds the model field that it indicates.
4709
+	 *
4710
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4711
+	 * @return EE_Model_Field_Base
4712
+	 * @throws EE_Error
4713
+	 */
4714
+	protected function _deduce_field_from_query_param($query_param_name)
4715
+	{
4716
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4717
+		// which will help us find the database table and column
4718
+		$query_param_parts = explode(".", $query_param_name);
4719
+		if (empty($query_param_parts)) {
4720
+			throw new EE_Error(
4721
+				sprintf(
4722
+					esc_html__(
4723
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4724
+						'event_espresso'
4725
+					),
4726
+					$query_param_name
4727
+				)
4728
+			);
4729
+		}
4730
+		$number_of_parts       = count($query_param_parts);
4731
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4732
+		if ($number_of_parts === 1) {
4733
+			$field_name = $last_query_param_part;
4734
+			$model_obj  = $this;
4735
+		} else {// $number_of_parts >= 2
4736
+			// the last part is the column name, and there are only 2parts. therefore...
4737
+			$field_name = $last_query_param_part;
4738
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4739
+		}
4740
+		try {
4741
+			return $model_obj->field_settings_for($field_name);
4742
+		} catch (EE_Error $e) {
4743
+			return null;
4744
+		}
4745
+	}
4746
+
4747
+
4748
+	/**
4749
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4750
+	 * alias and column which corresponds to it
4751
+	 *
4752
+	 * @param string $field_name
4753
+	 * @return string
4754
+	 * @throws EE_Error
4755
+	 */
4756
+	public function _get_qualified_column_for_field($field_name)
4757
+	{
4758
+		$all_fields = $this->field_settings();
4759
+		$field      = $all_fields[ $field_name ] ?? false;
4760
+		if ($field) {
4761
+			return $field->get_qualified_column();
4762
+		}
4763
+		throw new EE_Error(
4764
+			sprintf(
4765
+				esc_html__(
4766
+					"There is no field titled %s on model %s. Either the query trying to use it is bad, or you need to add it to the list of fields on the model.",
4767
+					'event_espresso'
4768
+				),
4769
+				$field_name,
4770
+				get_class($this)
4771
+			)
4772
+		);
4773
+	}
4774
+
4775
+
4776
+	/**
4777
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4778
+	 * Example usage:
4779
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4780
+	 *      array(),
4781
+	 *      ARRAY_A,
4782
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4783
+	 *  );
4784
+	 * is equivalent to
4785
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4786
+	 * and
4787
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4788
+	 *      array(
4789
+	 *          array(
4790
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4791
+	 *          ),
4792
+	 *          ARRAY_A,
4793
+	 *          implode(
4794
+	 *              ', ',
4795
+	 *              array_merge(
4796
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4797
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4798
+	 *              )
4799
+	 *          )
4800
+	 *      )
4801
+	 *  );
4802
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4803
+	 *
4804
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4805
+	 *                                            and the one whose fields you are selecting for example: when querying
4806
+	 *                                            tickets model and selecting fields from the tickets model you would
4807
+	 *                                            leave this parameter empty, because no models are needed to join
4808
+	 *                                            between the queried model and the selected one. Likewise when
4809
+	 *                                            querying the datetime model and selecting fields from the tickets
4810
+	 *                                            model, it would also be left empty, because there is a direct
4811
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4812
+	 *                                            them together. However, when querying from the event model and
4813
+	 *                                            selecting fields from the ticket model, you should provide the string
4814
+	 *                                            'Datetime', indicating that the event model must first join to the
4815
+	 *                                            datetime model in order to find its relation to ticket model.
4816
+	 *                                            Also, when querying from the venue model and selecting fields from
4817
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4818
+	 *                                            indicating you need to join the venue model to the event model,
4819
+	 *                                            to the datetime model, in order to find its relation to the ticket
4820
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4821
+	 *                                            the models' tables qualified columns
4822
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4823
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4824
+	 *                                            qualified column names
4825
+	 * @return array|string
4826
+	 */
4827
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4828
+	{
4829
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4830
+				? ''
4831
+				: '__');
4832
+		$qualified_columns = [];
4833
+		foreach ($this->field_settings() as $field_name => $field) {
4834
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4835
+		}
4836
+		return $return_string
4837
+			? implode(', ', $qualified_columns)
4838
+			: $qualified_columns;
4839
+	}
4840
+
4841
+
4842
+	/**
4843
+	 * constructs the select use on special limit joins
4844
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4845
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4846
+	 * (as that is typically where the limits would be set).
4847
+	 *
4848
+	 * @param string       $table_alias The table the select is being built for
4849
+	 * @param mixed|string $limit       The limit for this select
4850
+	 * @return string                The final select join element for the query.
4851
+	 * @throws EE_Error
4852
+	 * @throws EE_Error
4853
+	 */
4854
+	public function _construct_limit_join_select($table_alias, $limit)
4855
+	{
4856
+		$SQL = '';
4857
+		foreach ($this->_tables as $table_obj) {
4858
+			if ($table_obj instanceof EE_Primary_Table) {
4859
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4860
+					? $table_obj->get_select_join_limit($limit)
4861
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4862
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4863
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4864
+					? $table_obj->get_select_join_limit_join($limit)
4865
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4866
+			}
4867
+		}
4868
+		return $SQL;
4869
+	}
4870
+
4871
+
4872
+	/**
4873
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4874
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4875
+	 *
4876
+	 * @return string SQL
4877
+	 * @throws EE_Error
4878
+	 */
4879
+	public function _construct_internal_join()
4880
+	{
4881
+		$SQL = $this->_get_main_table()->get_table_sql();
4882
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4883
+		return $SQL;
4884
+	}
4885
+
4886
+
4887
+	/**
4888
+	 * Constructs the SQL for joining all the tables on this model.
4889
+	 * Normally $alias should be the primary table's alias, but in cases where
4890
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4891
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4892
+	 * alias, this will construct SQL like:
4893
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4894
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4895
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4896
+	 *
4897
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4898
+	 * @return string
4899
+	 * @throws EE_Error
4900
+	 * @throws EE_Error
4901
+	 */
4902
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4903
+	{
4904
+		$SQL               = '';
4905
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4906
+		foreach ($this->_tables as $table_obj) {
4907
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4908
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4909
+					// so we're joining to this table, meaning the table is already in
4910
+					// the FROM statement, BUT the primary table isn't. So we want
4911
+					// to add the inverse join sql
4912
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4913
+				} else {
4914
+					// just add a regular JOIN to this table from the primary table
4915
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4916
+				}
4917
+			}// if it's a primary table, dont add any SQL. it should already be in the FROM statement
4918
+		}
4919
+		return $SQL;
4920
+	}
4921
+
4922
+
4923
+	/**
4924
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4925
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4926
+	 * their data type (eg, '%s', '%d', etc)
4927
+	 *
4928
+	 * @return array
4929
+	 */
4930
+	public function _get_data_types()
4931
+	{
4932
+		$data_types = [];
4933
+		foreach ($this->field_settings() as $field_obj) {
4934
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4935
+			/** @var $field_obj EE_Model_Field_Base */
4936
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4937
+		}
4938
+		return $data_types;
4939
+	}
4940
+
4941
+
4942
+	/**
4943
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4944
+	 *
4945
+	 * @param string $model_name
4946
+	 * @return EEM_Base
4947
+	 * @throws EE_Error
4948
+	 */
4949
+	public function get_related_model_obj($model_name)
4950
+	{
4951
+		$model_classname = "EEM_" . $model_name;
4952
+		if (! class_exists($model_classname)) {
4953
+			throw new EE_Error(
4954
+				sprintf(
4955
+					esc_html__(
4956
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4957
+						'event_espresso'
4958
+					),
4959
+					$model_name,
4960
+					$model_classname
4961
+				)
4962
+			);
4963
+		}
4964
+		return call_user_func($model_classname . "::instance");
4965
+	}
4966
+
4967
+
4968
+	/**
4969
+	 * Returns the array of EE_ModelRelations for this model.
4970
+	 *
4971
+	 * @return EE_Model_Relation_Base[]
4972
+	 */
4973
+	public function relation_settings()
4974
+	{
4975
+		return $this->_model_relations;
4976
+	}
4977
+
4978
+
4979
+	/**
4980
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4981
+	 * because without THOSE models, this model probably doesn't have much purpose.
4982
+	 * (Eg, without an event, datetimes have little purpose.)
4983
+	 *
4984
+	 * @return EE_Belongs_To_Relation[]
4985
+	 */
4986
+	public function belongs_to_relations()
4987
+	{
4988
+		$belongs_to_relations = [];
4989
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4990
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4991
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4992
+			}
4993
+		}
4994
+		return $belongs_to_relations;
4995
+	}
4996
+
4997
+
4998
+	/**
4999
+	 * Returns the specified EE_Model_Relation, or throws an exception
5000
+	 *
5001
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
5002
+	 * @return EE_Model_Relation_Base
5003
+	 * @throws EE_Error
5004
+	 */
5005
+	public function related_settings_for($relation_name)
5006
+	{
5007
+		$relatedModels = $this->relation_settings();
5008
+		if (! array_key_exists($relation_name, $relatedModels)) {
5009
+			throw new EE_Error(
5010
+				sprintf(
5011
+					esc_html__(
5012
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
5013
+						'event_espresso'
5014
+					),
5015
+					$relation_name,
5016
+					$this->_get_class_name(),
5017
+					implode(', ', array_keys($relatedModels))
5018
+				)
5019
+			);
5020
+		}
5021
+		return $relatedModels[ $relation_name ];
5022
+	}
5023
+
5024
+
5025
+	/**
5026
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
5027
+	 * fields
5028
+	 *
5029
+	 * @param string  $fieldName
5030
+	 * @param boolean $include_db_only_fields
5031
+	 * @return EE_Model_Field_Base
5032
+	 * @throws EE_Error
5033
+	 */
5034
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
5035
+	{
5036
+		$fieldSettings = $this->field_settings($include_db_only_fields);
5037
+		if (! array_key_exists($fieldName, $fieldSettings)) {
5038
+			throw new EE_Error(
5039
+				sprintf(
5040
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
5041
+					$fieldName,
5042
+					get_class($this)
5043
+				)
5044
+			);
5045
+		}
5046
+		return $fieldSettings[ $fieldName ];
5047
+	}
5048
+
5049
+
5050
+	/**
5051
+	 * Checks if this field exists on this model
5052
+	 *
5053
+	 * @param string $fieldName a key in the model's _field_settings array
5054
+	 * @return boolean
5055
+	 */
5056
+	public function has_field($fieldName)
5057
+	{
5058
+		$fieldSettings = $this->field_settings(true);
5059
+		if (isset($fieldSettings[ $fieldName ])) {
5060
+			return true;
5061
+		}
5062
+		return false;
5063
+	}
5064
+
5065
+
5066
+	/**
5067
+	 * Returns whether or not this model has a relation to the specified model
5068
+	 *
5069
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
5070
+	 * @return boolean
5071
+	 */
5072
+	public function has_relation($relation_name)
5073
+	{
5074
+		$relations = $this->relation_settings();
5075
+		if (isset($relations[ $relation_name ])) {
5076
+			return true;
5077
+		}
5078
+		return false;
5079
+	}
5080
+
5081
+
5082
+	/**
5083
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5084
+	 * Eg, on EE_Answer that would be ANS_ID field object
5085
+	 *
5086
+	 * @param $field_obj
5087
+	 * @return boolean
5088
+	 */
5089
+	public function is_primary_key_field($field_obj): bool
5090
+	{
5091
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
5092
+	}
5093
+
5094
+
5095
+	/**
5096
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5097
+	 * Eg, on EE_Answer that would be ANS_ID field object
5098
+	 *
5099
+	 * @return EE_Primary_Key_Field_Base
5100
+	 * @throws EE_Error
5101
+	 */
5102
+	public function get_primary_key_field()
5103
+	{
5104
+		if ($this->_primary_key_field === null) {
5105
+			foreach ($this->field_settings(true) as $field_obj) {
5106
+				if ($this->is_primary_key_field($field_obj)) {
5107
+					$this->_primary_key_field = $field_obj;
5108
+					break;
5109
+				}
5110
+			}
5111
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5112
+				throw new EE_Error(
5113
+					sprintf(
5114
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5115
+						get_class($this)
5116
+					)
5117
+				);
5118
+			}
5119
+		}
5120
+		return $this->_primary_key_field;
5121
+	}
5122
+
5123
+
5124
+	/**
5125
+	 * Returns whether or not not there is a primary key on this model.
5126
+	 * Internally does some caching.
5127
+	 *
5128
+	 * @return boolean
5129
+	 */
5130
+	public function has_primary_key_field()
5131
+	{
5132
+		if ($this->_has_primary_key_field === null) {
5133
+			try {
5134
+				$this->get_primary_key_field();
5135
+				$this->_has_primary_key_field = true;
5136
+			} catch (EE_Error $e) {
5137
+				$this->_has_primary_key_field = false;
5138
+			}
5139
+		}
5140
+		return $this->_has_primary_key_field;
5141
+	}
5142
+
5143
+
5144
+	/**
5145
+	 * Finds the first field of type $field_class_name.
5146
+	 *
5147
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5148
+	 *                                 EE_Foreign_Key_Field, etc
5149
+	 * @return EE_Model_Field_Base or null if none is found
5150
+	 */
5151
+	public function get_a_field_of_type($field_class_name)
5152
+	{
5153
+		foreach ($this->field_settings() as $field) {
5154
+			if ($field instanceof $field_class_name) {
5155
+				return $field;
5156
+			}
5157
+		}
5158
+		return null;
5159
+	}
5160
+
5161
+
5162
+	/**
5163
+	 * Gets a foreign key field pointing to model.
5164
+	 *
5165
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5166
+	 * @return EE_Foreign_Key_Field_Base
5167
+	 * @throws EE_Error
5168
+	 */
5169
+	public function get_foreign_key_to($model_name)
5170
+	{
5171
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5172
+			foreach ($this->field_settings() as $field) {
5173
+				if (
5174
+					$field instanceof EE_Foreign_Key_Field_Base
5175
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5176
+				) {
5177
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5178
+					break;
5179
+				}
5180
+			}
5181
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5182
+				throw new EE_Error(
5183
+					sprintf(
5184
+						esc_html__(
5185
+							"There is no foreign key field pointing to model %s on model %s",
5186
+							'event_espresso'
5187
+						),
5188
+						$model_name,
5189
+						get_class($this)
5190
+					)
5191
+				);
5192
+			}
5193
+		}
5194
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5195
+	}
5196
+
5197
+
5198
+	/**
5199
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5200
+	 *
5201
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5202
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5203
+	 *                            Either one works
5204
+	 * @return string
5205
+	 */
5206
+	public function get_table_for_alias($table_alias)
5207
+	{
5208
+		$table_alias_sans_model_relation_chain_prefix =
5209
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5210
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5211
+	}
5212
+
5213
+
5214
+	/**
5215
+	 * Returns a flat array of all field son this model, instead of organizing them
5216
+	 * by table_alias as they are in the constructor.
5217
+	 *
5218
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5219
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5220
+	 */
5221
+	public function field_settings($include_db_only_fields = false)
5222
+	{
5223
+		if ($include_db_only_fields) {
5224
+			if ($this->_cached_fields === null) {
5225
+				$this->_cached_fields = [];
5226
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5227
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5228
+						$this->_cached_fields[ $field_name ] = $field_obj;
5229
+					}
5230
+				}
5231
+			}
5232
+			return $this->_cached_fields;
5233
+		}
5234
+		if ($this->_cached_fields_non_db_only === null) {
5235
+			$this->_cached_fields_non_db_only = [];
5236
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5237
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238
+					/** @var $field_obj EE_Model_Field_Base */
5239
+					if (! $field_obj->is_db_only_field()) {
5240
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5241
+					}
5242
+				}
5243
+			}
5244
+		}
5245
+		return $this->_cached_fields_non_db_only;
5246
+	}
5247
+
5248
+
5249
+	/**
5250
+	 *        cycle though array of attendees and create objects out of each item
5251
+	 *
5252
+	 * @access        private
5253
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5254
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5255
+	 *                           numerically indexed)
5256
+	 * @throws EE_Error
5257
+	 * @throws ReflectionException
5258
+	 */
5259
+	protected function _create_objects($rows = [])
5260
+	{
5261
+		$array_of_objects = [];
5262
+		if (empty($rows)) {
5263
+			return [];
5264
+		}
5265
+		$count_if_model_has_no_primary_key = 0;
5266
+		$has_primary_key                   = $this->has_primary_key_field();
5267
+		$primary_key_field                 = $has_primary_key
5268
+			? $this->get_primary_key_field()
5269
+			: null;
5270
+		foreach ((array) $rows as $row) {
5271
+			if (empty($row)) {
5272
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5273
+				return [];
5274
+			}
5275
+			// check if we've already set this object in the results array,
5276
+			// in which case there's no need to process it further (again)
5277
+			if ($has_primary_key) {
5278
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5279
+					$row,
5280
+					$primary_key_field->get_qualified_column(),
5281
+					$primary_key_field->get_table_column()
5282
+				);
5283
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5284
+					continue;
5285
+				}
5286
+			}
5287
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5288
+			if (! $classInstance) {
5289
+				throw new EE_Error(
5290
+					sprintf(
5291
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5292
+						$this->get_this_model_name(),
5293
+						http_build_query($row)
5294
+					)
5295
+				);
5296
+			}
5297
+			// set the timezone on the instantiated objects
5298
+			$classInstance->set_timezone($this->_timezone);
5299
+			// make sure if there is any timezone setting present that we set the timezone for the object
5300
+			$key                      = $has_primary_key
5301
+				? $classInstance->ID()
5302
+				: $count_if_model_has_no_primary_key++;
5303
+			$array_of_objects[ $key ] = $classInstance;
5304
+			// also, for all the relations of type BelongsTo, see if we can cache
5305
+			// those related models
5306
+			// (we could do this for other relations too, but if there are conditions
5307
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5308
+			// so it requires a little more thought than just caching them immediately...)
5309
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5310
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5311
+					// check if this model's INFO is present. If so, cache it on the model
5312
+					$other_model           = $relation_obj->get_other_model();
5313
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5314
+					// if we managed to make a model object from the results, cache it on the main model object
5315
+					if ($other_model_obj_maybe) {
5316
+						// set timezone on these other model objects if they are present
5317
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5318
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5319
+					}
5320
+				}
5321
+			}
5322
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5323
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5324
+			// the field in the CustomSelects object
5325
+			if ($this->_custom_selections instanceof CustomSelects) {
5326
+				$classInstance->setCustomSelectsValues(
5327
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5328
+				);
5329
+			}
5330
+		}
5331
+		return $array_of_objects;
5332
+	}
5333
+
5334
+
5335
+	/**
5336
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5337
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5338
+	 *
5339
+	 * @param array $db_results_row
5340
+	 * @return array
5341
+	 */
5342
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5343
+	{
5344
+		$results = [];
5345
+		if ($this->_custom_selections instanceof CustomSelects) {
5346
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5347
+				if (isset($db_results_row[ $alias ])) {
5348
+					$results[ $alias ] = $this->convertValueToDataType(
5349
+						$db_results_row[ $alias ],
5350
+						$this->_custom_selections->getDataTypeForAlias($alias)
5351
+					);
5352
+				}
5353
+			}
5354
+		}
5355
+		return $results;
5356
+	}
5357
+
5358
+
5359
+	/**
5360
+	 * This will set the value for the given alias
5361
+	 *
5362
+	 * @param string $value
5363
+	 * @param string $datatype (one of %d, %s, %f)
5364
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5365
+	 */
5366
+	protected function convertValueToDataType($value, $datatype)
5367
+	{
5368
+		switch ($datatype) {
5369
+			case '%f':
5370
+				return (float) $value;
5371
+			case '%d':
5372
+				return (int) $value;
5373
+			default:
5374
+				return (string) $value;
5375
+		}
5376
+	}
5377
+
5378
+
5379
+	/**
5380
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5381
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5382
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5383
+	 * object (as set in the model_field!).
5384
+	 *
5385
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5386
+	 * @throws EE_Error
5387
+	 * @throws ReflectionException
5388
+	 */
5389
+	public function create_default_object()
5390
+	{
5391
+		$this_model_fields_and_values = [];
5392
+		// setup the row using default values;
5393
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5394
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5395
+		}
5396
+		$className = $this->_get_class_name();
5397
+		return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
5398
+	}
5399
+
5400
+
5401
+	/**
5402
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5403
+	 *                             or an stdClass where each property is the name of a column,
5404
+	 * @return EE_Base_Class
5405
+	 * @throws EE_Error
5406
+	 * @throws ReflectionException
5407
+	 */
5408
+	public function instantiate_class_from_array_or_object($cols_n_values)
5409
+	{
5410
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5411
+			$cols_n_values = get_object_vars($cols_n_values);
5412
+		}
5413
+		$primary_key = null;
5414
+		// make sure the array only has keys that are fields/columns on this model
5415
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5416
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5417
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5418
+		}
5419
+		$className = $this->_get_class_name();
5420
+		// check we actually found results that we can use to build our model object
5421
+		// if not, return null
5422
+		if ($this->has_primary_key_field()) {
5423
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5424
+				return null;
5425
+			}
5426
+		} elseif ($this->unique_indexes()) {
5427
+			$first_column = reset($this_model_fields_n_values);
5428
+			if (empty($first_column)) {
5429
+				return null;
5430
+			}
5431
+		}
5432
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5433
+		if ($primary_key) {
5434
+			$classInstance = $this->get_from_entity_map($primary_key);
5435
+			if (! $classInstance) {
5436
+				$classInstance = EE_Registry::instance()
5437
+											->load_class(
5438
+												$className,
5439
+												[$this_model_fields_n_values, $this->_timezone],
5440
+												true,
5441
+												false
5442
+											);
5443
+				// add this new object to the entity map
5444
+				$classInstance = $this->add_to_entity_map($classInstance);
5445
+			}
5446
+		} else {
5447
+			$classInstance = EE_Registry::instance()->load_class(
5448
+				$className,
5449
+				[$this_model_fields_n_values, $this->_timezone],
5450
+				true,
5451
+				false
5452
+			);
5453
+		}
5454
+		return $classInstance;
5455
+	}
5456
+
5457
+
5458
+	/**
5459
+	 * Gets the model object from the  entity map if it exists
5460
+	 *
5461
+	 * @param int|string $id the ID of the model object
5462
+	 * @return EE_Base_Class
5463
+	 */
5464
+	public function get_from_entity_map($id)
5465
+	{
5466
+		return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5467
+	}
5468
+
5469
+
5470
+	/**
5471
+	 * add_to_entity_map
5472
+	 * Adds the object to the model's entity mappings
5473
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5474
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5475
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5476
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5477
+	 *        then this method should be called immediately after the update query
5478
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5479
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5480
+	 *
5481
+	 * @param EE_Base_Class $object
5482
+	 * @return EE_Base_Class
5483
+	 * @throws EE_Error
5484
+	 * @throws ReflectionException
5485
+	 */
5486
+	public function add_to_entity_map(EE_Base_Class $object)
5487
+	{
5488
+		$className = $this->_get_class_name();
5489
+		if (! $object instanceof $className) {
5490
+			throw new EE_Error(
5491
+				sprintf(
5492
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5493
+					is_object($object)
5494
+						? get_class($object)
5495
+						: $object,
5496
+					$className
5497
+				)
5498
+			);
5499
+		}
5500
+
5501
+		if (! $object->ID()) {
5502
+			throw new EE_Error(
5503
+				sprintf(
5504
+					esc_html__(
5505
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5506
+						"event_espresso"
5507
+					),
5508
+					get_class($this)
5509
+				)
5510
+			);
5511
+		}
5512
+		// double check it's not already there
5513
+		$classInstance = $this->get_from_entity_map($object->ID());
5514
+		if ($classInstance) {
5515
+			return $classInstance;
5516
+		}
5517
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5518
+		return $object;
5519
+	}
5520
+
5521
+
5522
+	/**
5523
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5524
+	 * if no identifier is provided, then the entire entity map is emptied
5525
+	 *
5526
+	 * @param int|string $id the ID of the model object
5527
+	 * @return boolean
5528
+	 */
5529
+	public function clear_entity_map($id = null)
5530
+	{
5531
+		if (empty($id)) {
5532
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5533
+			return true;
5534
+		}
5535
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5536
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5537
+			return true;
5538
+		}
5539
+		return false;
5540
+	}
5541
+
5542
+
5543
+	/**
5544
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5545
+	 * Given an array where keys are column (or column alias) names and values,
5546
+	 * returns an array of their corresponding field names and database values
5547
+	 *
5548
+	 * @param array $cols_n_values
5549
+	 * @return array
5550
+	 * @throws EE_Error
5551
+	 * @throws ReflectionException
5552
+	 */
5553
+	public function deduce_fields_n_values_from_cols_n_values(array $cols_n_values): array
5554
+	{
5555
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5556
+	}
5557
+
5558
+
5559
+	/**
5560
+	 * _deduce_fields_n_values_from_cols_n_values
5561
+	 * Given an array where keys are column (or column alias) names and values,
5562
+	 * returns an array of their corresponding field names and database values
5563
+	 *
5564
+	 * @param array|stdClass $cols_n_values
5565
+	 * @return array
5566
+	 * @throws EE_Error
5567
+	 * @throws ReflectionException
5568
+	 */
5569
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values): array
5570
+	{
5571
+		if ($cols_n_values instanceof stdClass) {
5572
+			$cols_n_values = get_object_vars($cols_n_values);
5573
+		}
5574
+		$this_model_fields_n_values = [];
5575
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5576
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5577
+				$cols_n_values,
5578
+				$table_obj->get_fully_qualified_pk_column(),
5579
+				$table_obj->get_pk_column()
5580
+			);
5581
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5582
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5583
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5584
+					if (! $field_obj->is_db_only_field()) {
5585
+						// prepare field as if its coming from db
5586
+						$prepared_value                            =
5587
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5588
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5589
+					}
5590
+				}
5591
+			} else {
5592
+				// the table's rows existed. Use their values
5593
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
+					if (! $field_obj->is_db_only_field()) {
5595
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5596
+							$cols_n_values,
5597
+							$field_obj->get_qualified_column(),
5598
+							$field_obj->get_table_column()
5599
+						);
5600
+					}
5601
+				}
5602
+			}
5603
+		}
5604
+		return $this_model_fields_n_values;
5605
+	}
5606
+
5607
+
5608
+	/**
5609
+	 * @param $cols_n_values
5610
+	 * @param $qualified_column
5611
+	 * @param $regular_column
5612
+	 * @return null
5613
+	 * @throws EE_Error
5614
+	 * @throws ReflectionException
5615
+	 */
5616
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5617
+	{
5618
+		$value = null;
5619
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5620
+		// does the field on the model relate to this column retrieved from the db?
5621
+		// or is it a db-only field? (not relating to the model)
5622
+		if (isset($cols_n_values[ $qualified_column ])) {
5623
+			$value = $cols_n_values[ $qualified_column ];
5624
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5625
+			$value = $cols_n_values[ $regular_column ];
5626
+		} elseif (! empty($this->foreign_key_aliases)) {
5627
+			// no PK?  ok check if there is a foreign key alias set for this table
5628
+			// then check if that alias exists in the incoming data
5629
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5630
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5631
+				if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5632
+					$value = $cols_n_values[ $FK_alias ];
5633
+					[$pk_class] = explode('.', $PK_column);
5634
+					$pk_model_name = "EEM_{$pk_class}";
5635
+					/** @var EEM_Base $pk_model */
5636
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5637
+					if ($pk_model instanceof EEM_Base) {
5638
+						// make sure object is pulled from db and added to entity map
5639
+						$pk_model->get_one_by_ID($value);
5640
+					}
5641
+					break;
5642
+				}
5643
+			}
5644
+		}
5645
+		return $value;
5646
+	}
5647
+
5648
+
5649
+	/**
5650
+	 * refresh_entity_map_from_db
5651
+	 * Makes sure the model object in the entity map at $id assumes the values
5652
+	 * of the database (opposite of EE_base_Class::save())
5653
+	 *
5654
+	 * @param int|string $id
5655
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|mixed|null
5656
+	 * @throws EE_Error
5657
+	 * @throws ReflectionException
5658
+	 */
5659
+	public function refresh_entity_map_from_db($id)
5660
+	{
5661
+		$obj_in_map = $this->get_from_entity_map($id);
5662
+		if ($obj_in_map) {
5663
+			$wpdb_results = $this->_get_all_wpdb_results(
5664
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5665
+			);
5666
+			if ($wpdb_results && is_array($wpdb_results)) {
5667
+				$one_row = reset($wpdb_results);
5668
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5669
+					$obj_in_map->set_from_db($field_name, $db_value);
5670
+				}
5671
+				// clear the cache of related model objects
5672
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5673
+					$obj_in_map->clear_cache($relation_name, null, true);
5674
+				}
5675
+			}
5676
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5677
+			return $obj_in_map;
5678
+		}
5679
+		return $this->get_one_by_ID($id);
5680
+	}
5681
+
5682
+
5683
+	/**
5684
+	 * refresh_entity_map_with
5685
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5686
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5687
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5688
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5689
+	 *
5690
+	 * @param int|string    $id
5691
+	 * @param EE_Base_Class $replacing_model_obj
5692
+	 * @return EE_Base_Class
5693
+	 * @throws EE_Error
5694
+	 * @throws ReflectionException
5695
+	 */
5696
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5697
+	{
5698
+		$obj_in_map = $this->get_from_entity_map($id);
5699
+		if ($obj_in_map) {
5700
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5701
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5702
+					$obj_in_map->set($field_name, $value);
5703
+				}
5704
+				// make the model object in the entity map's cache match the $replacing_model_obj
5705
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5706
+					$obj_in_map->clear_cache($relation_name, null, true);
5707
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5708
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5709
+					}
5710
+				}
5711
+			}
5712
+			return $obj_in_map;
5713
+		}
5714
+		$this->add_to_entity_map($replacing_model_obj);
5715
+		return $replacing_model_obj;
5716
+	}
5717
+
5718
+
5719
+	/**
5720
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5721
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5722
+	 * require_once($this->_getClassName().".class.php");
5723
+	 *
5724
+	 * @return string
5725
+	 */
5726
+	private function _get_class_name()
5727
+	{
5728
+		return "EE_" . $this->get_this_model_name();
5729
+	}
5730
+
5731
+
5732
+	/**
5733
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5734
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5735
+	 * it would be 'Events'.
5736
+	 *
5737
+	 * @param int|float|null $quantity
5738
+	 * @return string
5739
+	 */
5740
+	public function item_name($quantity = 1): string
5741
+	{
5742
+		$quantity = floor($quantity);
5743
+		return apply_filters(
5744
+			'FHEE__EEM_Base__item_name__plural_or_singular',
5745
+			$quantity > 1
5746
+				? $this->plural_item
5747
+				: $this->singular_item,
5748
+			$quantity,
5749
+			$this->plural_item,
5750
+			$this->singular_item
5751
+		);
5752
+	}
5753
+
5754
+
5755
+	/**
5756
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5757
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5758
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5759
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5760
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5761
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5762
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5763
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5764
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5765
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5766
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5767
+	 *        return $previousReturnValue.$returnString;
5768
+	 * }
5769
+	 * require('EEM_Answer.model.php');
5770
+	 * echo EEM_Answer::instance()->my_callback('monkeys',100);
5771
+	 * // will output "you called my_callback! and passed args:monkeys,100"
5772
+	 *
5773
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5774
+	 * @param array  $args       array of original arguments passed to the function
5775
+	 * @return mixed whatever the plugin which calls add_filter decides
5776
+	 * @throws EE_Error
5777
+	 */
5778
+	public function __call($methodName, $args)
5779
+	{
5780
+		$className = get_class($this);
5781
+		$tagName   = "FHEE__{$className}__{$methodName}";
5782
+		if (! has_filter($tagName)) {
5783
+			throw new EE_Error(
5784
+				sprintf(
5785
+					esc_html__(
5786
+						'Method %1$s on model %2$s does not exist! You can create one with the following code in functions.php or in a plugin: %4$s function my_callback(%4$s \$previousReturnValue, EEM_Base \$object\ $argsArray=NULL ){%4$s     /*function body*/%4$s      return \$whatever;%4$s }%4$s add_filter( \'%3$s\', \'my_callback\', 10, 3 );',
5787
+						'event_espresso'
5788
+					),
5789
+					$methodName,
5790
+					$className,
5791
+					$tagName,
5792
+					'<br />'
5793
+				)
5794
+			);
5795
+		}
5796
+		return apply_filters($tagName, null, $this, $args);
5797
+	}
5798
+
5799
+
5800
+	/**
5801
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5802
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5803
+	 *
5804
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5805
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5806
+	 *                                                       the object's class name
5807
+	 *                                                       or object's ID
5808
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5809
+	 *                                                       exists in the database. If it does not, we add it
5810
+	 * @return EE_Base_Class
5811
+	 * @throws EE_Error
5812
+	 * @throws ReflectionException
5813
+	 */
5814
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5815
+	{
5816
+		$className = $this->_get_class_name();
5817
+		if ($base_class_obj_or_id instanceof $className) {
5818
+			$model_object = $base_class_obj_or_id;
5819
+		} else {
5820
+			$primary_key_field = $this->get_primary_key_field();
5821
+			if (
5822
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5823
+				&& (
5824
+					is_int($base_class_obj_or_id)
5825
+					|| is_string($base_class_obj_or_id)
5826
+				)
5827
+			) {
5828
+				// assume it's an ID.
5829
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5830
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5831
+			} elseif (
5832
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5833
+				&& is_string($base_class_obj_or_id)
5834
+			) {
5835
+				// assume it's a string representation of the object
5836
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5837
+			} else {
5838
+				throw new EE_Error(
5839
+					sprintf(
5840
+						esc_html__(
5841
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5842
+							'event_espresso'
5843
+						),
5844
+						$base_class_obj_or_id,
5845
+						$this->_get_class_name(),
5846
+						print_r($base_class_obj_or_id, true)
5847
+					)
5848
+				);
5849
+			}
5850
+		}
5851
+		if ($ensure_is_in_db && $model_object instanceof EE_Base_Class && $model_object->ID() !== null) {
5852
+			$model_object->save();
5853
+		}
5854
+		return $model_object;
5855
+	}
5856
+
5857
+
5858
+	/**
5859
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5860
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5861
+	 * returns it ID.
5862
+	 *
5863
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5864
+	 * @return int|string depending on the type of this model object's ID
5865
+	 * @throws EE_Error
5866
+	 * @throws ReflectionException
5867
+	 */
5868
+	public function ensure_is_ID($base_class_obj_or_id)
5869
+	{
5870
+		$className = $this->_get_class_name();
5871
+		if ($base_class_obj_or_id instanceof $className) {
5872
+			/** @var $base_class_obj_or_id EE_Base_Class */
5873
+			$id = $base_class_obj_or_id->ID();
5874
+		} elseif (is_int($base_class_obj_or_id)) {
5875
+			// assume it's an ID
5876
+			$id = $base_class_obj_or_id;
5877
+		} elseif (is_string($base_class_obj_or_id)) {
5878
+			// assume its a string representation of the object
5879
+			$id = $base_class_obj_or_id;
5880
+		} else {
5881
+			throw new EE_Error(
5882
+				sprintf(
5883
+					esc_html__(
5884
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5885
+						'event_espresso'
5886
+					),
5887
+					$base_class_obj_or_id,
5888
+					$this->_get_class_name(),
5889
+					print_r($base_class_obj_or_id, true)
5890
+				)
5891
+			);
5892
+		}
5893
+		return $id;
5894
+	}
5895
+
5896
+
5897
+	/**
5898
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5899
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5900
+	 * been sanitized and converted into the appropriate domain.
5901
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5902
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5903
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5904
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5905
+	 * $EVT = EEM_Event::instance(); $old_setting =
5906
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5907
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5908
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5909
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5910
+	 *
5911
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5912
+	 * @return void
5913
+	 */
5914
+	public function assume_values_already_prepared_by_model_object(
5915
+		$values_already_prepared = self::not_prepared_by_model_object
5916
+	) {
5917
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5918
+	}
5919
+
5920
+
5921
+	/**
5922
+	 * Read comments for assume_values_already_prepared_by_model_object()
5923
+	 *
5924
+	 * @return int
5925
+	 */
5926
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5927
+	{
5928
+		return $this->_values_already_prepared_by_model_object;
5929
+	}
5930
+
5931
+
5932
+	/**
5933
+	 * Gets all the indexes on this model
5934
+	 *
5935
+	 * @return EE_Index[]
5936
+	 */
5937
+	public function indexes()
5938
+	{
5939
+		return $this->_indexes;
5940
+	}
5941
+
5942
+
5943
+	/**
5944
+	 * Gets all the Unique Indexes on this model
5945
+	 *
5946
+	 * @return EE_Unique_Index[]
5947
+	 */
5948
+	public function unique_indexes()
5949
+	{
5950
+		$unique_indexes = [];
5951
+		foreach ($this->_indexes as $name => $index) {
5952
+			if ($index instanceof EE_Unique_Index) {
5953
+				$unique_indexes [ $name ] = $index;
5954
+			}
5955
+		}
5956
+		return $unique_indexes;
5957
+	}
5958
+
5959
+
5960
+	/**
5961
+	 * Gets all the fields which, when combined, make the primary key.
5962
+	 * This is usually just an array with 1 element (the primary key), but in cases
5963
+	 * where there is no primary key, it's a combination of fields as defined
5964
+	 * on a primary index
5965
+	 *
5966
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5967
+	 * @throws EE_Error
5968
+	 */
5969
+	public function get_combined_primary_key_fields()
5970
+	{
5971
+		foreach ($this->indexes() as $index) {
5972
+			if ($index instanceof EE_Primary_Key_Index) {
5973
+				return $index->fields();
5974
+			}
5975
+		}
5976
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5977
+	}
5978
+
5979
+
5980
+	/**
5981
+	 * Used to build a primary key string (when the model has no primary key),
5982
+	 * which can be used a unique string to identify this model object.
5983
+	 *
5984
+	 * @param array $fields_n_values keys are field names, values are their values.
5985
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5986
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5987
+	 *                               before passing it to this function (that will convert it from columns-n-values
5988
+	 *                               to field-names-n-values).
5989
+	 * @return string
5990
+	 * @throws EE_Error
5991
+	 */
5992
+	public function get_index_primary_key_string($fields_n_values)
5993
+	{
5994
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5995
+			$fields_n_values,
5996
+			$this->get_combined_primary_key_fields()
5997
+		);
5998
+		return http_build_query($cols_n_values_for_primary_key_index);
5999
+	}
6000
+
6001
+
6002
+	/**
6003
+	 * Gets the field values from the primary key string
6004
+	 *
6005
+	 * @param string $index_primary_key_string
6006
+	 * @return null|array
6007
+	 * @throws EE_Error
6008
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
6009
+	 */
6010
+	public function parse_index_primary_key_string($index_primary_key_string)
6011
+	{
6012
+		$key_fields = $this->get_combined_primary_key_fields();
6013
+		// check all of them are in the $id
6014
+		$key_vals_in_combined_pk = [];
6015
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6016
+		foreach ($key_fields as $key_field_name => $field_obj) {
6017
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6018
+				return null;
6019
+			}
6020
+		}
6021
+		return $key_vals_in_combined_pk;
6022
+	}
6023
+
6024
+
6025
+	/**
6026
+	 * verifies that an array of key-value pairs for model fields has a key
6027
+	 * for each field comprising the primary key index
6028
+	 *
6029
+	 * @param array $key_vals
6030
+	 * @return boolean
6031
+	 * @throws EE_Error
6032
+	 */
6033
+	public function has_all_combined_primary_key_fields($key_vals)
6034
+	{
6035
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6036
+		foreach ($keys_it_should_have as $key) {
6037
+			if (! isset($key_vals[ $key ])) {
6038
+				return false;
6039
+			}
6040
+		}
6041
+		return true;
6042
+	}
6043
+
6044
+
6045
+	/**
6046
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
6047
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
6048
+	 *
6049
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
6050
+	 * @param array               $query_params                     @see
6051
+	 *                                                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
6052
+	 * @throws EE_Error
6053
+	 * @throws ReflectionException
6054
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
6055
+	 *                                                              indexed)
6056
+	 */
6057
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
6058
+	{
6059
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
6060
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
6061
+		} elseif (is_array($model_object_or_attributes_array)) {
6062
+			$attributes_array = $model_object_or_attributes_array;
6063
+		} else {
6064
+			throw new EE_Error(
6065
+				sprintf(
6066
+					esc_html__(
6067
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
6068
+						"event_espresso"
6069
+					),
6070
+					$model_object_or_attributes_array
6071
+				)
6072
+			);
6073
+		}
6074
+		// even copies obviously won't have the same ID, so remove the primary key
6075
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
6076
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6077
+			unset($attributes_array[ $this->primary_key_name() ]);
6078
+		}
6079
+		if (isset($query_params[0])) {
6080
+			$query_params[0] = array_merge($attributes_array, $query_params);
6081
+		} else {
6082
+			$query_params[0] = $attributes_array;
6083
+		}
6084
+		return $this->get_all($query_params);
6085
+	}
6086
+
6087
+
6088
+	/**
6089
+	 * Gets the first copy we find. See get_all_copies for more details
6090
+	 *
6091
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
6092
+	 * @param array $query_params
6093
+	 * @return EE_Base_Class
6094
+	 * @throws EE_Error
6095
+	 * @throws ReflectionException
6096
+	 */
6097
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6098
+	{
6099
+		if (! is_array($query_params)) {
6100
+			EE_Error::doing_it_wrong(
6101
+				'EEM_Base::get_one_copy',
6102
+				sprintf(
6103
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
6104
+					gettype($query_params)
6105
+				),
6106
+				'4.6.0'
6107
+			);
6108
+			$query_params = [];
6109
+		}
6110
+		$query_params['limit'] = 1;
6111
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
6112
+		if (is_array($copies)) {
6113
+			return array_shift($copies);
6114
+		}
6115
+		return null;
6116
+	}
6117
+
6118
+
6119
+	/**
6120
+	 * Updates the item with the specified id. Ignores default query parameters because
6121
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6122
+	 *
6123
+	 * @param array      $fields_n_values keys are field names, values are their new values
6124
+	 * @param int|string $id              the value of the primary key to update
6125
+	 * @return int number of rows updated
6126
+	 * @throws EE_Error
6127
+	 * @throws ReflectionException
6128
+	 */
6129
+	public function update_by_ID($fields_n_values, $id)
6130
+	{
6131
+		$query_params = [
6132
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6133
+			'default_where_conditions' => EE_Default_Where_Conditions::OTHER_MODELS_ONLY,
6134
+		];
6135
+		return $this->update($fields_n_values, $query_params);
6136
+	}
6137
+
6138
+
6139
+	/**
6140
+	 * Changes an operator which was supplied to the models into one usable in SQL
6141
+	 *
6142
+	 * @param string $operator_supplied
6143
+	 * @return string an operator which can be used in SQL
6144
+	 * @throws EE_Error
6145
+	 */
6146
+	private function _prepare_operator_for_sql($operator_supplied)
6147
+	{
6148
+		$sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6149
+		if ($sql_operator) {
6150
+			return $sql_operator;
6151
+		}
6152
+		throw new EE_Error(
6153
+			sprintf(
6154
+				esc_html__(
6155
+					"The operator '%s' is not in the list of valid operators: %s",
6156
+					"event_espresso"
6157
+				),
6158
+				$operator_supplied,
6159
+				implode(",", array_keys($this->_valid_operators))
6160
+			)
6161
+		);
6162
+	}
6163
+
6164
+
6165
+	/**
6166
+	 * Gets the valid operators
6167
+	 *
6168
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6169
+	 */
6170
+	public function valid_operators()
6171
+	{
6172
+		return $this->_valid_operators;
6173
+	}
6174
+
6175
+
6176
+	/**
6177
+	 * Gets the between-style operators (take 2 arguments).
6178
+	 *
6179
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6180
+	 */
6181
+	public function valid_between_style_operators()
6182
+	{
6183
+		return array_intersect(
6184
+			$this->valid_operators(),
6185
+			$this->_between_style_operators
6186
+		);
6187
+	}
6188
+
6189
+
6190
+	/**
6191
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6192
+	 *
6193
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6194
+	 */
6195
+	public function valid_like_style_operators()
6196
+	{
6197
+		return array_intersect(
6198
+			$this->valid_operators(),
6199
+			$this->_like_style_operators
6200
+		);
6201
+	}
6202
+
6203
+
6204
+	/**
6205
+	 * Gets the "in"-style operators
6206
+	 *
6207
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6208
+	 */
6209
+	public function valid_in_style_operators()
6210
+	{
6211
+		return array_intersect(
6212
+			$this->valid_operators(),
6213
+			$this->_in_style_operators
6214
+		);
6215
+	}
6216
+
6217
+
6218
+	/**
6219
+	 * Gets the "null"-style operators (accept no arguments)
6220
+	 *
6221
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6222
+	 */
6223
+	public function valid_null_style_operators()
6224
+	{
6225
+		return array_intersect(
6226
+			$this->valid_operators(),
6227
+			$this->_null_style_operators
6228
+		);
6229
+	}
6230
+
6231
+
6232
+	/**
6233
+	 * Gets an array where keys are the primary keys and values are their 'names'
6234
+	 * (as determined by the model object's name() function, which is often overridden)
6235
+	 *
6236
+	 * @param array $query_params like get_all's
6237
+	 * @return string[]
6238
+	 * @throws EE_Error
6239
+	 * @throws ReflectionException
6240
+	 */
6241
+	public function get_all_names($query_params = [])
6242
+	{
6243
+		$objs  = $this->get_all($query_params);
6244
+		$names = [];
6245
+		foreach ($objs as $obj) {
6246
+			$names[ $obj->ID() ] = $obj->name();
6247
+		}
6248
+		return $names;
6249
+	}
6250
+
6251
+
6252
+	/**
6253
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6254
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6255
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6256
+	 * array_keys() on $model_objects.
6257
+	 *
6258
+	 * @param \EE_Base_Class[] $model_objects
6259
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6260
+	 *                                               in the returned array
6261
+	 * @return array
6262
+	 * @throws EE_Error
6263
+	 * @throws ReflectionException
6264
+	 */
6265
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6266
+	{
6267
+		if (! $this->has_primary_key_field()) {
6268
+			if (defined('WP_DEBUG') && WP_DEBUG) {
6269
+				EE_Error::add_error(
6270
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6271
+					__FILE__,
6272
+					__FUNCTION__,
6273
+					__LINE__
6274
+				);
6275
+			}
6276
+		}
6277
+		$IDs = [];
6278
+		foreach ($model_objects as $model_object) {
6279
+			$id = $model_object->ID();
6280
+			if (! $id) {
6281
+				if ($filter_out_empty_ids) {
6282
+					continue;
6283
+				}
6284
+				if (defined('WP_DEBUG') && WP_DEBUG) {
6285
+					EE_Error::add_error(
6286
+						esc_html__(
6287
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6288
+							'event_espresso'
6289
+						),
6290
+						__FILE__,
6291
+						__FUNCTION__,
6292
+						__LINE__
6293
+					);
6294
+				}
6295
+			}
6296
+			$IDs[] = $id;
6297
+		}
6298
+		return $IDs;
6299
+	}
6300
+
6301
+
6302
+	/**
6303
+	 * Returns the string used in capabilities relating to this model. If there
6304
+	 * are no capabilities that relate to this model returns false
6305
+	 *
6306
+	 * @return string|false
6307
+	 */
6308
+	public function cap_slug()
6309
+	{
6310
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6311
+	}
6312
+
6313
+
6314
+	/**
6315
+	 * Returns the capability-restrictions array (@param string $context
6316
+	 *
6317
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6318
+	 * @throws EE_Error
6319
+	 * @see EEM_Base::_cap_restrictions).
6320
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6321
+	 *      only returns the cap restrictions array in that context (ie, the array
6322
+	 *      at that key)
6323
+	 */
6324
+	public function cap_restrictions($context = EEM_Base::caps_read)
6325
+	{
6326
+		EEM_Base::verify_is_valid_cap_context($context);
6327
+		// check if we ought to run the restriction generator first
6328
+		if (
6329
+			isset($this->_cap_restriction_generators[ $context ])
6330
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6331
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6332
+		) {
6333
+			$this->_cap_restrictions[ $context ] = array_merge(
6334
+				$this->_cap_restrictions[ $context ],
6335
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6336
+			);
6337
+		}
6338
+		// and make sure we've finalized the construction of each restriction
6339
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6340
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6341
+				$where_conditions_obj->_finalize_construct($this);
6342
+			}
6343
+		}
6344
+		return $this->_cap_restrictions[ $context ];
6345
+	}
6346
+
6347
+
6348
+	/**
6349
+	 * Indicating whether or not this model thinks its a wp core model
6350
+	 *
6351
+	 * @return boolean
6352
+	 */
6353
+	public function is_wp_core_model()
6354
+	{
6355
+		return $this->_wp_core_model;
6356
+	}
6357
+
6358
+
6359
+	/**
6360
+	 * Gets all the caps that are missing which impose a restriction on
6361
+	 * queries made in this context
6362
+	 *
6363
+	 * @param string $context one of EEM_Base::caps_ constants
6364
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6365
+	 * @throws EE_Error
6366
+	 */
6367
+	public function caps_missing($context = EEM_Base::caps_read)
6368
+	{
6369
+		$missing_caps     = [];
6370
+		$cap_restrictions = $this->cap_restrictions($context);
6371
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6372
+			if (
6373
+				! EE_Capabilities::instance()
6374
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6375
+			) {
6376
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6377
+			}
6378
+		}
6379
+		return $missing_caps;
6380
+	}
6381
+
6382
+
6383
+	/**
6384
+	 * Gets the mapping from capability contexts to action strings used in capability names
6385
+	 *
6386
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6387
+	 * one of 'read', 'edit', or 'delete'
6388
+	 */
6389
+	public function cap_contexts_to_cap_action_map()
6390
+	{
6391
+		return apply_filters(
6392
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6393
+			$this->_cap_contexts_to_cap_action_map,
6394
+			$this
6395
+		);
6396
+	}
6397
+
6398
+
6399
+	/**
6400
+	 * Gets the action string for the specified capability context
6401
+	 *
6402
+	 * @param string $context
6403
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6404
+	 * @throws EE_Error
6405
+	 */
6406
+	public function cap_action_for_context($context)
6407
+	{
6408
+		$mapping = $this->cap_contexts_to_cap_action_map();
6409
+		if (isset($mapping[ $context ])) {
6410
+			return $mapping[ $context ];
6411
+		}
6412
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6413
+			return $action;
6414
+		}
6415
+		throw new EE_Error(
6416
+			sprintf(
6417
+				esc_html__(
6418
+					'Cannot find capability restrictions for context "%1$s", allowed values are:%2$s',
6419
+					'event_espresso'
6420
+				),
6421
+				$context,
6422
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6423
+			)
6424
+		);
6425
+	}
6426
+
6427
+
6428
+	/**
6429
+	 * Returns all the capability contexts which are valid when querying models
6430
+	 *
6431
+	 * @return array
6432
+	 */
6433
+	public static function valid_cap_contexts(): array
6434
+	{
6435
+		return (array) apply_filters(
6436
+			'FHEE__EEM_Base__valid_cap_contexts',
6437
+			[
6438
+				self::caps_read,
6439
+				self::caps_read_admin,
6440
+				self::caps_edit,
6441
+				self::caps_delete,
6442
+			]
6443
+		);
6444
+	}
6445
+
6446
+
6447
+	/**
6448
+	 * Returns all valid options for 'default_where_conditions'
6449
+	 *
6450
+	 * @return array
6451
+	 */
6452
+	public static function valid_default_where_conditions(): array
6453
+	{
6454
+		return [
6455
+			EE_Default_Where_Conditions::ALL,
6456
+			EE_Default_Where_Conditions::THIS_MODEL_ONLY,
6457
+			EE_Default_Where_Conditions::OTHER_MODELS_ONLY,
6458
+			EE_Default_Where_Conditions::MINIMUM_ALL,
6459
+			EE_Default_Where_Conditions::MINIMUM_OTHERS,
6460
+			EE_Default_Where_Conditions::NONE,
6461
+		];
6462
+	}
6463
+
6464
+	// public static function default_where_conditions_full
6465
+
6466
+
6467
+	/**
6468
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6469
+	 *
6470
+	 * @param string $context
6471
+	 * @return bool
6472
+	 * @throws EE_Error
6473
+	 */
6474
+	public static function verify_is_valid_cap_context($context): bool
6475
+	{
6476
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6477
+		if (in_array($context, $valid_cap_contexts)) {
6478
+			return true;
6479
+		}
6480
+		throw new EE_Error(
6481
+			sprintf(
6482
+				esc_html__(
6483
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6484
+					'event_espresso'
6485
+				),
6486
+				$context,
6487
+				'EEM_Base',
6488
+				implode(',', $valid_cap_contexts)
6489
+			)
6490
+		);
6491
+	}
6492
+
6493
+
6494
+	/**
6495
+	 * Clears all the models field caches. This is only useful when a sub-class
6496
+	 * might have added a field or something and these caches might be invalidated
6497
+	 */
6498
+	protected function _invalidate_field_caches()
6499
+	{
6500
+		$this->_cache_foreign_key_to_fields = [];
6501
+		$this->_cached_fields               = null;
6502
+		$this->_cached_fields_non_db_only   = null;
6503
+	}
6504
+
6505
+
6506
+	/**
6507
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6508
+	 * (eg "and", "or", "not").
6509
+	 *
6510
+	 * @return array
6511
+	 */
6512
+	public function logic_query_param_keys(): array
6513
+	{
6514
+		return $this->_logic_query_param_keys;
6515
+	}
6516
+
6517
+
6518
+	/**
6519
+	 * Determines whether or not the where query param array key is for a logic query param.
6520
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6521
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6522
+	 *
6523
+	 * @param $query_param_key
6524
+	 * @return bool
6525
+	 */
6526
+	public function is_logic_query_param_key($query_param_key): bool
6527
+	{
6528
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6529
+			if (
6530
+				$query_param_key === $logic_query_param_key
6531
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6532
+			) {
6533
+				return true;
6534
+			}
6535
+		}
6536
+		return false;
6537
+	}
6538
+
6539
+
6540
+	/**
6541
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6542
+	 *
6543
+	 * @return boolean
6544
+	 * @since 4.9.74.p
6545
+	 */
6546
+	public function hasPassword(): bool
6547
+	{
6548
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6549
+		if ($this->has_password_field === null) {
6550
+			$password_field           = $this->getPasswordField();
6551
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6552
+		}
6553
+		return $this->has_password_field;
6554
+	}
6555
+
6556
+
6557
+	/**
6558
+	 * Returns the password field on this model, if there is one
6559
+	 *
6560
+	 * @return EE_Password_Field|null
6561
+	 * @since 4.9.74.p
6562
+	 */
6563
+	public function getPasswordField()
6564
+	{
6565
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6566
+		// there's no need to search for it. If we don't know yet, then find out
6567
+		if ($this->has_password_field === null && $this->password_field === null) {
6568
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6569
+		}
6570
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6571
+		return $this->password_field;
6572
+	}
6573
+
6574
+
6575
+	/**
6576
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6577
+	 *
6578
+	 * @return EE_Model_Field_Base[]
6579
+	 * @throws EE_Error
6580
+	 * @since 4.9.74.p
6581
+	 */
6582
+	public function getPasswordProtectedFields()
6583
+	{
6584
+		$password_field = $this->getPasswordField();
6585
+		$fields         = [];
6586
+		if ($password_field instanceof EE_Password_Field) {
6587
+			$field_names = $password_field->protectedFields();
6588
+			foreach ($field_names as $field_name) {
6589
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6590
+			}
6591
+		}
6592
+		return $fields;
6593
+	}
6594
+
6595
+
6596
+	/**
6597
+	 * Checks if the current user can perform the requested action on this model
6598
+	 *
6599
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6600
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6601
+	 * @return bool
6602
+	 * @throws EE_Error
6603
+	 * @throws InvalidArgumentException
6604
+	 * @throws InvalidDataTypeException
6605
+	 * @throws InvalidInterfaceException
6606
+	 * @throws ReflectionException
6607
+	 * @throws UnexpectedEntityException
6608
+	 * @since 4.9.74.p
6609
+	 */
6610
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6611
+	{
6612
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6613
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6614
+		}
6615
+		if (! is_array($model_obj_or_fields_n_values)) {
6616
+			throw new UnexpectedEntityException(
6617
+				$model_obj_or_fields_n_values,
6618
+				'EE_Base_Class',
6619
+				sprintf(
6620
+					esc_html__(
6621
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6622
+						'event_espresso'
6623
+					),
6624
+					__FUNCTION__
6625
+				)
6626
+			);
6627
+		}
6628
+		return $this->exists(
6629
+			$this->alter_query_params_to_restrict_by_ID(
6630
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6631
+				[
6632
+					'default_where_conditions' => 'none',
6633
+					'caps'                     => $cap_to_check,
6634
+				]
6635
+			)
6636
+		);
6637
+	}
6638
+
6639
+
6640
+	/**
6641
+	 * Returns the query param where conditions key to the password affecting this model.
6642
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6643
+	 *
6644
+	 * @return null|string
6645
+	 * @throws EE_Error
6646
+	 * @throws InvalidArgumentException
6647
+	 * @throws InvalidDataTypeException
6648
+	 * @throws InvalidInterfaceException
6649
+	 * @throws ModelConfigurationException
6650
+	 * @throws ReflectionException
6651
+	 * @since 4.9.74.p
6652
+	 */
6653
+	public function modelChainAndPassword()
6654
+	{
6655
+		if ($this->model_chain_to_password === null) {
6656
+			throw new ModelConfigurationException(
6657
+				$this,
6658
+				esc_html_x(
6659
+				// @codingStandardsIgnoreStart
6660
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6661
+					// @codingStandardsIgnoreEnd
6662
+					'1: model name',
6663
+					'event_espresso'
6664
+				)
6665
+			);
6666
+		}
6667
+		if ($this->model_chain_to_password === '') {
6668
+			$model_with_password = $this;
6669
+		} else {
6670
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6671
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6672
+			} else {
6673
+				$last_model_in_chain = $this->model_chain_to_password;
6674
+			}
6675
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6676
+		}
6677
+
6678
+		$password_field = $model_with_password->getPasswordField();
6679
+		if ($password_field instanceof EE_Password_Field) {
6680
+			$password_field_name = $password_field->get_name();
6681
+		} else {
6682
+			throw new ModelConfigurationException(
6683
+				$this,
6684
+				sprintf(
6685
+					esc_html_x(
6686
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6687
+						'1: model name, 2: special string',
6688
+						'event_espresso'
6689
+					),
6690
+					$model_with_password->get_this_model_name(),
6691
+					$this->model_chain_to_password
6692
+				)
6693
+			);
6694
+		}
6695
+		return (
6696
+			   $this->model_chain_to_password
6697
+				   ? $this->model_chain_to_password . '.'
6698
+				   : ''
6699
+			   ) . $password_field_name;
6700
+	}
6701
+
6702
+
6703
+	/**
6704
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6705
+	 * or if this model itself has a password affecting access to some of its other fields.
6706
+	 *
6707
+	 * @return boolean
6708
+	 * @since 4.9.74.p
6709
+	 */
6710
+	public function restrictedByRelatedModelPassword(): bool
6711
+	{
6712
+		return $this->model_chain_to_password !== null;
6713
+	}
6714 6714
 }
Please login to merge, or discard this patch.
Spacing   +232 added lines, -232 removed lines patch added patch discarded remove patch
@@ -547,7 +547,7 @@  discard block
 block discarded – undo
547 547
     protected function __construct($timezone = '')
548 548
     {
549 549
         // check that the model has not been loaded too soon
550
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
550
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
551 551
             throw new EE_Error(
552 552
                 sprintf(
553 553
                     esc_html__(
@@ -570,7 +570,7 @@  discard block
 block discarded – undo
570 570
          *
571 571
          * @var EE_Table_Base[] $_tables
572 572
          */
573
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
573
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
574 574
         foreach ($this->_tables as $table_alias => $table_obj) {
575 575
             /** @var $table_obj EE_Table_Base */
576 576
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -584,10 +584,10 @@  discard block
 block discarded – undo
584 584
          *
585 585
          * @param EE_Model_Field_Base[] $_fields
586 586
          */
587
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
587
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
588 588
         $this->_invalidate_field_caches();
589 589
         foreach ($this->_fields as $table_alias => $fields_for_table) {
590
-            if (! array_key_exists($table_alias, $this->_tables)) {
590
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
591 591
                 throw new EE_Error(
592 592
                     sprintf(
593 593
                         esc_html__(
@@ -624,7 +624,7 @@  discard block
 block discarded – undo
624 624
          * @param EE_Model_Relation_Base[] $_model_relations
625 625
          */
626 626
         $this->_model_relations = (array) apply_filters(
627
-            'FHEE__' . get_class($this) . '__construct__model_relations',
627
+            'FHEE__'.get_class($this).'__construct__model_relations',
628 628
             $this->_model_relations
629 629
         );
630 630
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -636,12 +636,12 @@  discard block
 block discarded – undo
636 636
         }
637 637
         $this->set_timezone($timezone);
638 638
         // finalize default where condition strategy, or set default
639
-        if (! $this->_default_where_conditions_strategy) {
639
+        if ( ! $this->_default_where_conditions_strategy) {
640 640
             // nothing was set during child constructor, so set default
641 641
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
642 642
         }
643 643
         $this->_default_where_conditions_strategy->_finalize_construct($this);
644
-        if (! $this->_minimum_where_conditions_strategy) {
644
+        if ( ! $this->_minimum_where_conditions_strategy) {
645 645
             // nothing was set during child constructor, so set default
646 646
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
647 647
         }
@@ -654,8 +654,8 @@  discard block
 block discarded – undo
654 654
         // initialize the standard cap restriction generators if none were specified by the child constructor
655 655
         if (is_array($this->_cap_restriction_generators)) {
656 656
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
657
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
658
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
657
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
658
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
659 659
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
660 660
                         new EE_Restriction_Generator_Protected(),
661 661
                         $cap_context,
@@ -667,10 +667,10 @@  discard block
 block discarded – undo
667 667
         // if there are cap restriction generators, use them to make the default cap restrictions
668 668
         if (is_array($this->_cap_restriction_generators)) {
669 669
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
670
-                if (! $generator_object) {
670
+                if ( ! $generator_object) {
671 671
                     continue;
672 672
                 }
673
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
673
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
674 674
                     throw new EE_Error(
675 675
                         sprintf(
676 676
                             esc_html__(
@@ -683,12 +683,12 @@  discard block
 block discarded – undo
683 683
                     );
684 684
                 }
685 685
                 $action = $this->cap_action_for_context($context);
686
-                if (! $generator_object->construction_finalized()) {
686
+                if ( ! $generator_object->construction_finalized()) {
687 687
                     $generator_object->_construct_finalize($this, $action);
688 688
                 }
689 689
             }
690 690
         }
691
-        do_action('AHEE__' . get_class($this) . '__construct__end');
691
+        do_action('AHEE__'.get_class($this).'__construct__end');
692 692
     }
693 693
 
694 694
 
@@ -700,7 +700,7 @@  discard block
 block discarded – undo
700 700
      */
701 701
     protected static function getLoader(): LoaderInterface
702 702
     {
703
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
703
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
704 704
             EEM_Base::$loader = LoaderFactory::getLoader();
705 705
         }
706 706
         return EEM_Base::$loader;
@@ -713,7 +713,7 @@  discard block
 block discarded – undo
713 713
      */
714 714
     private static function getMirror(): Mirror
715 715
     {
716
-        if (! EEM_Base::$mirror instanceof Mirror) {
716
+        if ( ! EEM_Base::$mirror instanceof Mirror) {
717 717
             EEM_Base::$mirror = EEM_Base::getLoader()->getShared(Mirror::class);
718 718
         }
719 719
         return EEM_Base::$mirror;
@@ -769,7 +769,7 @@  discard block
 block discarded – undo
769 769
     public static function instance($timezone = '')
770 770
     {
771 771
         // check if instance of Espresso_model already exists
772
-        if (! static::$_instance instanceof static) {
772
+        if ( ! static::$_instance instanceof static) {
773 773
             $arguments = EEM_Base::getModelArguments(static::class, (string) $timezone);
774 774
             $model     = new static(...$arguments);
775 775
             EEM_Base::getLoader()->share(static::class, $model, $arguments);
@@ -798,7 +798,7 @@  discard block
 block discarded – undo
798 798
      */
799 799
     public static function reset($timezone = '')
800 800
     {
801
-        if (! static::$_instance instanceof EEM_Base) {
801
+        if ( ! static::$_instance instanceof EEM_Base) {
802 802
             return null;
803 803
         }
804 804
         // Let's NOT swap out the current instance for a new one
@@ -809,7 +809,7 @@  discard block
 block discarded – undo
809 809
         foreach (EEM_Base::getMirror()->getDefaultProperties(static::class) as $property => $value) {
810 810
             // don't set instance to null like it was originally,
811 811
             // but it's static anyways, and we're ignoring static properties (for now at least)
812
-            if (! isset($static_properties[ $property ])) {
812
+            if ( ! isset($static_properties[$property])) {
813 813
                 static::$_instance->{$property} = $value;
814 814
             }
815 815
         }
@@ -858,7 +858,7 @@  discard block
 block discarded – undo
858 858
      */
859 859
     public function status_array($translated = false)
860 860
     {
861
-        if (! array_key_exists('Status', $this->_model_relations)) {
861
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
862 862
             return [];
863 863
         }
864 864
         $model_name   = $this->get_this_model_name();
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
         $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
867 867
         $status_array = [];
868 868
         foreach ($stati as $status) {
869
-            $status_array[ $status->ID() ] = $status->get('STS_code');
869
+            $status_array[$status->ID()] = $status->get('STS_code');
870 870
         }
871 871
         return $translated
872 872
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -931,7 +931,7 @@  discard block
 block discarded – undo
931 931
     {
932 932
         $wp_user_field_name = $this->wp_user_field_name();
933 933
         if ($wp_user_field_name) {
934
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
934
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
935 935
         }
936 936
         return $query_params;
937 937
     }
@@ -950,17 +950,17 @@  discard block
 block discarded – undo
950 950
     public function wp_user_field_name()
951 951
     {
952 952
         try {
953
-            if (! empty($this->_model_chain_to_wp_user)) {
953
+            if ( ! empty($this->_model_chain_to_wp_user)) {
954 954
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
955 955
                 $last_model_name              = end($models_to_follow_to_wp_users);
956 956
                 $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
957
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
957
+                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user.'.';
958 958
             } else {
959 959
                 $model_with_fk_to_wp_users = $this;
960 960
                 $model_chain_to_wp_user    = '';
961 961
             }
962 962
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
963
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
963
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
964 964
         } catch (EE_Error $e) {
965 965
             return false;
966 966
         }
@@ -1036,11 +1036,11 @@  discard block
 block discarded – undo
1036 1036
         if ($this->_custom_selections instanceof CustomSelects) {
1037 1037
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1038 1038
             $select_expressions .= $select_expressions
1039
-                ? ', ' . $custom_expressions
1039
+                ? ', '.$custom_expressions
1040 1040
                 : $custom_expressions;
1041 1041
         }
1042 1042
 
1043
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1043
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1044 1044
         return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1045 1045
     }
1046 1046
 
@@ -1057,7 +1057,7 @@  discard block
 block discarded – undo
1057 1057
      */
1058 1058
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1059 1059
     {
1060
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1060
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1061 1061
             return null;
1062 1062
         }
1063 1063
         $selects = $query_params['extra_selects'] ?? $columns_to_select;
@@ -1108,7 +1108,7 @@  discard block
 block discarded – undo
1108 1108
         if (is_array($columns_to_select)) {
1109 1109
             $select_sql_array = [];
1110 1110
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1111
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1111
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1112 1112
                     throw new EE_Error(
1113 1113
                         sprintf(
1114 1114
                             esc_html__(
@@ -1120,7 +1120,7 @@  discard block
 block discarded – undo
1120 1120
                         )
1121 1121
                     );
1122 1122
                 }
1123
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1123
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1124 1124
                     throw new EE_Error(
1125 1125
                         sprintf(
1126 1126
                             esc_html__(
@@ -1182,7 +1182,7 @@  discard block
 block discarded – undo
1182 1182
                 ['default_where_conditions' => EE_Default_Where_Conditions::MINIMUM_ALL]
1183 1183
             )
1184 1184
         );
1185
-        $className    = $this->_get_class_name();
1185
+        $className = $this->_get_class_name();
1186 1186
         if ($model_object instanceof $className) {
1187 1187
             // make sure valid objects get added to the entity map
1188 1188
             // so that the next call to this method doesn't trigger another trip to the db
@@ -1205,12 +1205,12 @@  discard block
 block discarded – undo
1205 1205
      */
1206 1206
     public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1207 1207
     {
1208
-        if (! isset($query_params[0])) {
1208
+        if ( ! isset($query_params[0])) {
1209 1209
             $query_params[0] = [];
1210 1210
         }
1211 1211
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1212 1212
         if ($conditions_from_id === null) {
1213
-            $query_params[0][ $this->primary_key_name() ] = $id;
1213
+            $query_params[0][$this->primary_key_name()] = $id;
1214 1214
         } else {
1215 1215
             // no primary key, so the $id must be from the get_index_primary_key_string()
1216 1216
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1230,7 +1230,7 @@  discard block
 block discarded – undo
1230 1230
      */
1231 1231
     public function get_one($query_params = [])
1232 1232
     {
1233
-        if (! is_array($query_params)) {
1233
+        if ( ! is_array($query_params)) {
1234 1234
             EE_Error::doing_it_wrong(
1235 1235
                 'EEM_Base::get_one',
1236 1236
                 sprintf(
@@ -1439,7 +1439,7 @@  discard block
 block discarded – undo
1439 1439
                 return [];
1440 1440
             }
1441 1441
         }
1442
-        if (! is_array($query_params)) {
1442
+        if ( ! is_array($query_params)) {
1443 1443
             EE_Error::doing_it_wrong(
1444 1444
                 'EEM_Base::_get_consecutive',
1445 1445
                 sprintf(
@@ -1451,7 +1451,7 @@  discard block
 block discarded – undo
1451 1451
             $query_params = [];
1452 1452
         }
1453 1453
         // let's add the where query param for consecutive look up.
1454
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1454
+        $query_params[0][$field_to_order_by] = [$operand, $current_field_value];
1455 1455
         $query_params['limit']                 = $limit;
1456 1456
         // set direction
1457 1457
         $incoming_orderby         = isset($query_params['order_by'])
@@ -1477,7 +1477,7 @@  discard block
 block discarded – undo
1477 1477
      */
1478 1478
     public function set_timezone(?string $timezone = '')
1479 1479
     {
1480
-        if (! $timezone) {
1480
+        if ( ! $timezone) {
1481 1481
             return;
1482 1482
         }
1483 1483
         $this->_timezone = $timezone;
@@ -1534,7 +1534,7 @@  discard block
 block discarded – undo
1534 1534
     {
1535 1535
         $field_settings = $this->field_settings_for($field_name);
1536 1536
         // if not a valid EE_Datetime_Field then throw error
1537
-        if (! $field_settings instanceof EE_Datetime_Field) {
1537
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1538 1538
             throw new EE_Error(
1539 1539
                 sprintf(
1540 1540
                     esc_html__(
@@ -1621,7 +1621,7 @@  discard block
 block discarded – undo
1621 1621
         // just using this to ensure the timezone is set correctly internally
1622 1622
         $this->get_formats_for($field_name);
1623 1623
         // load EEH_DTT_Helper
1624
-        $timezone_string     = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1624
+        $timezone_string = ! empty($timezone_string) ? $timezone_string : EEH_DTT_Helper::get_timezone();
1625 1625
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($timezone_string));
1626 1626
         EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1627 1627
         return DbSafeDateTime::createFromDateTime($incomingDateTime);
@@ -1691,7 +1691,7 @@  discard block
 block discarded – undo
1691 1691
      */
1692 1692
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1693 1693
     {
1694
-        if (! is_array($query_params)) {
1694
+        if ( ! is_array($query_params)) {
1695 1695
             EE_Error::doing_it_wrong(
1696 1696
                 'EEM_Base::update',
1697 1697
                 sprintf(
@@ -1739,7 +1739,7 @@  discard block
 block discarded – undo
1739 1739
             $wpdb_result = (array) $wpdb_result;
1740 1740
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1741 1741
             if ($this->has_primary_key_field()) {
1742
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1742
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1743 1743
             } else {
1744 1744
                 // if there's no primary key, we basically can't support having a 2nd table on the model (we could but it would be lots of work)
1745 1745
                 $main_table_pk_value = null;
@@ -1755,7 +1755,7 @@  discard block
 block discarded – undo
1755 1755
                     // in this table, right? so insert a row in the current table, using any fields available
1756 1756
                     if (
1757 1757
                         ! (array_key_exists($this_table_pk_column, $wpdb_result)
1758
-                           && $wpdb_result[ $this_table_pk_column ])
1758
+                           && $wpdb_result[$this_table_pk_column])
1759 1759
                     ) {
1760 1760
                         $success = $this->_insert_into_specific_table(
1761 1761
                             $table_obj,
@@ -1763,7 +1763,7 @@  discard block
 block discarded – undo
1763 1763
                             $main_table_pk_value
1764 1764
                         );
1765 1765
                         // if we died here, report the error
1766
-                        if (! $success) {
1766
+                        if ( ! $success) {
1767 1767
                             return false;
1768 1768
                         }
1769 1769
                     }
@@ -1791,10 +1791,10 @@  discard block
 block discarded – undo
1791 1791
                 $model_objs_affected_ids     = [];
1792 1792
                 foreach ($models_affected_key_columns as $row) {
1793 1793
                     $combined_index_key                             = $this->get_index_primary_key_string($row);
1794
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1794
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1795 1795
                 }
1796 1796
             }
1797
-            if (! $model_objs_affected_ids) {
1797
+            if ( ! $model_objs_affected_ids) {
1798 1798
                 // wait wait wait- if nothing was affected let's stop here
1799 1799
                 return 0;
1800 1800
             }
@@ -1823,8 +1823,8 @@  discard block
 block discarded – undo
1823 1823
         $rows_affected = $this->_do_wpdb_query(
1824 1824
             'query',
1825 1825
             [
1826
-                "UPDATE " . $model_query_info->get_full_join_sql()
1827
-                . " SET " . $this->_construct_update_sql($fields_n_values)
1826
+                "UPDATE ".$model_query_info->get_full_join_sql()
1827
+                . " SET ".$this->_construct_update_sql($fields_n_values)
1828 1828
                 . $model_query_info->get_where_sql(),
1829 1829
             ]
1830 1830
         );
@@ -1838,7 +1838,7 @@  discard block
 block discarded – undo
1838 1838
          * @param int      $rows_affected
1839 1839
          */
1840 1840
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1841
-        return $rows_affected;// how many supposedly got updated
1841
+        return $rows_affected; // how many supposedly got updated
1842 1842
     }
1843 1843
 
1844 1844
 
@@ -1871,7 +1871,7 @@  discard block
 block discarded – undo
1871 1871
         $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1872 1872
         $select_expressions = $field->get_qualified_column();
1873 1873
         $SQL                =
1874
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1874
+            "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1875 1875
         return $this->_do_wpdb_query('get_col', [$SQL]);
1876 1876
     }
1877 1877
 
@@ -1890,7 +1890,7 @@  discard block
 block discarded – undo
1890 1890
     {
1891 1891
         $query_params['limit'] = 1;
1892 1892
         $col                   = $this->get_col($query_params, $field_to_select);
1893
-        if (! empty($col)) {
1893
+        if ( ! empty($col)) {
1894 1894
             return reset($col);
1895 1895
         }
1896 1896
         return null;
@@ -1921,7 +1921,7 @@  discard block
 block discarded – undo
1921 1921
             $value_sql       = $prepared_value === null
1922 1922
                 ? 'NULL'
1923 1923
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1924
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1924
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1925 1925
         }
1926 1926
         return implode(",", $cols_n_values);
1927 1927
     }
@@ -2059,7 +2059,7 @@  discard block
 block discarded – undo
2059 2059
                                 . $model_query_info->get_full_join_sql()
2060 2060
                                 . " WHERE "
2061 2061
                                 . $deletion_where_query_part;
2062
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
2062
+            $rows_deleted = $this->_do_wpdb_query('query', [$SQL]);
2063 2063
         }
2064 2064
 
2065 2065
         // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
@@ -2067,12 +2067,12 @@  discard block
 block discarded – undo
2067 2067
         if (
2068 2068
             $this->has_primary_key_field()
2069 2069
             && $rows_deleted !== false
2070
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2070
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2071 2071
         ) {
2072
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2072
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2073 2073
             foreach ($ids_for_removal as $id) {
2074
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2075
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2074
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2075
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2076 2076
                 }
2077 2077
             }
2078 2078
 
@@ -2112,7 +2112,7 @@  discard block
 block discarded – undo
2112 2112
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2113 2113
          */
2114 2114
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2115
-        return (int) $rows_deleted;// how many supposedly got deleted
2115
+        return (int) $rows_deleted; // how many supposedly got deleted
2116 2116
     }
2117 2117
 
2118 2118
 
@@ -2216,15 +2216,15 @@  discard block
 block discarded – undo
2216 2216
                 if (
2217 2217
                     $block_deletes
2218 2218
                     && $this->delete_is_blocked_by_related_models(
2219
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2219
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2220 2220
                     )
2221 2221
                 ) {
2222 2222
                     continue;
2223 2223
                 }
2224 2224
                 // primary table deletes
2225
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2226
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2227
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2225
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2226
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2227
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2228 2228
                 }
2229 2229
             }
2230 2230
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2233,8 +2233,8 @@  discard block
 block discarded – undo
2233 2233
                 $ids_to_delete_indexed_by_column_for_row = [];
2234 2234
                 foreach ($fields as $cpk_field) {
2235 2235
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2236
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2237
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2236
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2237
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2238 2238
                     }
2239 2239
                 }
2240 2240
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2272,7 +2272,7 @@  discard block
 block discarded – undo
2272 2272
         } elseif ($this->has_primary_key_field()) {
2273 2273
             $query = [];
2274 2274
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2275
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2275
+                $query[] = $column.' IN'.$this->_construct_in_value($ids, $this->_primary_key_field);
2276 2276
             }
2277 2277
             $query_part = ! empty($query)
2278 2278
                 ? implode(' AND ', $query)
@@ -2282,7 +2282,7 @@  discard block
 block discarded – undo
2282 2282
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2283 2283
                 $values_for_each_combined_primary_key_for_a_row = [];
2284 2284
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2285
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2285
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2286 2286
                 }
2287 2287
                 $ways_to_identify_a_row[] = '('
2288 2288
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2358,10 +2358,10 @@  discard block
 block discarded – undo
2358 2358
             }
2359 2359
         }
2360 2360
         $column_to_count = $distinct
2361
-            ? "DISTINCT " . $column_to_count
2361
+            ? "DISTINCT ".$column_to_count
2362 2362
             : $column_to_count;
2363 2363
         $SQL             =
2364
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2364
+            "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2365 2365
         return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2366 2366
     }
2367 2367
 
@@ -2386,7 +2386,7 @@  discard block
 block discarded – undo
2386 2386
         }
2387 2387
         $column_to_count = $field_obj->get_qualified_column();
2388 2388
         $SQL             =
2389
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2389
+            "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2390 2390
         $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2391 2391
         $data_type       = $field_obj->get_wpdb_data_type();
2392 2392
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2422,7 +2422,7 @@  discard block
 block discarded – undo
2422 2422
         }
2423 2423
         /** @type WPDB $wpdb */
2424 2424
         global $wpdb;
2425
-        if (! method_exists($wpdb, $wpdb_method)) {
2425
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2426 2426
             throw new DomainException(
2427 2427
                 sprintf(
2428 2428
                     esc_html__(
@@ -2441,7 +2441,7 @@  discard block
 block discarded – undo
2441 2441
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2442 2442
         if (defined('WP_DEBUG') && WP_DEBUG) {
2443 2443
             $wpdb->show_errors($old_show_errors_value);
2444
-            if (! empty($wpdb->last_error)) {
2444
+            if ( ! empty($wpdb->last_error)) {
2445 2445
                 throw new EE_Error(sprintf(esc_html__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2446 2446
             }
2447 2447
             if ($result === false) {
@@ -2511,7 +2511,7 @@  discard block
 block discarded – undo
2511 2511
                     // ummmm... you in trouble
2512 2512
                     return $result;
2513 2513
             }
2514
-            if (! empty($error_message)) {
2514
+            if ( ! empty($error_message)) {
2515 2515
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2516 2516
                 trigger_error($error_message);
2517 2517
             }
@@ -2592,11 +2592,11 @@  discard block
 block discarded – undo
2592 2592
      */
2593 2593
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2594 2594
     {
2595
-        return " FROM " . $model_query_info->get_full_join_sql() .
2596
-               $model_query_info->get_where_sql() .
2597
-               $model_query_info->get_group_by_sql() .
2598
-               $model_query_info->get_having_sql() .
2599
-               $model_query_info->get_order_by_sql() .
2595
+        return " FROM ".$model_query_info->get_full_join_sql().
2596
+               $model_query_info->get_where_sql().
2597
+               $model_query_info->get_group_by_sql().
2598
+               $model_query_info->get_having_sql().
2599
+               $model_query_info->get_order_by_sql().
2600 2600
                $model_query_info->get_limit_sql();
2601 2601
     }
2602 2602
 
@@ -2621,7 +2621,7 @@  discard block
 block discarded – undo
2621 2621
             $left = is_admin() ? '12rem' : '2rem';
2622 2622
             echo "
2623 2623
             <div class='ee-status-outline ee-status-bg--attention' style='margin: 2rem 2rem 2rem $left;'>
2624
-                " . esc_html($sql_query) . "
2624
+                ".esc_html($sql_query)."
2625 2625
             </div>";
2626 2626
             $this->_show_next_x_db_queries--;
2627 2627
         }
@@ -2797,12 +2797,12 @@  discard block
 block discarded – undo
2797 2797
         $related_model = $this->get_related_model_obj($model_name);
2798 2798
         // we're just going to use the query params on the related model's normal get_all query,
2799 2799
         // except add a condition to say to match the current mod
2800
-        if (! isset($query_params['default_where_conditions'])) {
2800
+        if ( ! isset($query_params['default_where_conditions'])) {
2801 2801
             $query_params['default_where_conditions'] = EE_Default_Where_Conditions::NONE;
2802 2802
         }
2803 2803
         $this_model_name                                                 = $this->get_this_model_name();
2804 2804
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2805
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2805
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2806 2806
         return $related_model->count($query_params, $field_to_count, $distinct);
2807 2807
     }
2808 2808
 
@@ -2823,7 +2823,7 @@  discard block
 block discarded – undo
2823 2823
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2824 2824
     {
2825 2825
         $related_model = $this->get_related_model_obj($model_name);
2826
-        if (! is_array($query_params)) {
2826
+        if ( ! is_array($query_params)) {
2827 2827
             EE_Error::doing_it_wrong(
2828 2828
                 'EEM_Base::sum_related',
2829 2829
                 sprintf(
@@ -2836,12 +2836,12 @@  discard block
 block discarded – undo
2836 2836
         }
2837 2837
         // we're just going to use the query params on the related model's normal get_all query,
2838 2838
         // except add a condition to say to match the current mod
2839
-        if (! isset($query_params['default_where_conditions'])) {
2839
+        if ( ! isset($query_params['default_where_conditions'])) {
2840 2840
             $query_params['default_where_conditions'] = EE_Default_Where_Conditions::NONE;
2841 2841
         }
2842 2842
         $this_model_name                                                 = $this->get_this_model_name();
2843 2843
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2844
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2844
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2845 2845
         return $related_model->sum($query_params, $field_to_sum);
2846 2846
     }
2847 2847
 
@@ -2893,7 +2893,7 @@  discard block
 block discarded – undo
2893 2893
                 $field_with_model_name = $field;
2894 2894
             }
2895 2895
         }
2896
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2896
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2897 2897
             throw new EE_Error(
2898 2898
                 sprintf(
2899 2899
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -3032,14 +3032,14 @@  discard block
 block discarded – undo
3032 3032
                 || $this->get_primary_key_field()
3033 3033
                    instanceof
3034 3034
                    EE_Primary_Key_String_Field)
3035
-            && isset($fields_n_values[ $this->primary_key_name() ])
3035
+            && isset($fields_n_values[$this->primary_key_name()])
3036 3036
         ) {
3037
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
3037
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
3038 3038
         }
3039 3039
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
3040 3040
             $uniqueness_where_params                              =
3041 3041
                 array_intersect_key($fields_n_values, $unique_index->fields());
3042
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
3042
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
3043 3043
         }
3044 3044
         // if there is nothing to base this search on, then we shouldn't find anything
3045 3045
         if (empty($query_params)) {
@@ -3116,16 +3116,16 @@  discard block
 block discarded – undo
3116 3116
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3117 3117
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3118 3118
             if ($prepared_value !== null) {
3119
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3119
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3120 3120
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3121 3121
             }
3122 3122
         }
3123 3123
         if ($table instanceof EE_Secondary_Table && $new_id) {
3124 3124
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3125 3125
             // so add the fk to the main table as a column
3126
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3126
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3127 3127
             $format_for_insertion[]                              =
3128
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3128
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3129 3129
         }
3130 3130
 
3131 3131
         // insert the new entry
@@ -3143,7 +3143,7 @@  discard block
 block discarded – undo
3143 3143
             }
3144 3144
             // it's not an auto-increment primary key, so
3145 3145
             // it must have been supplied
3146
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3146
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3147 3147
         }
3148 3148
         // we can't return a  primary key because there is none. instead return
3149 3149
         // a unique string indicating this model
@@ -3165,10 +3165,10 @@  discard block
 block discarded – undo
3165 3165
     {
3166 3166
         $field_name = $field_obj->get_name();
3167 3167
         // if this field doesn't allow nullable, don't allow it
3168
-        if (! $field_obj->is_nullable() && ! isset($fields_n_values[ $field_name ])) {
3169
-            $fields_n_values[ $field_name ] = $field_obj->get_default_value();
3168
+        if ( ! $field_obj->is_nullable() && ! isset($fields_n_values[$field_name])) {
3169
+            $fields_n_values[$field_name] = $field_obj->get_default_value();
3170 3170
         }
3171
-        $unprepared_value = $fields_n_values[ $field_name ] ?? null;
3171
+        $unprepared_value = $fields_n_values[$field_name] ?? null;
3172 3172
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3173 3173
     }
3174 3174
 
@@ -3271,7 +3271,7 @@  discard block
 block discarded – undo
3271 3271
      */
3272 3272
     public function get_table_obj_by_alias($table_alias = '')
3273 3273
     {
3274
-        return $this->_tables[ $table_alias ] ?? null;
3274
+        return $this->_tables[$table_alias] ?? null;
3275 3275
     }
3276 3276
 
3277 3277
 
@@ -3285,7 +3285,7 @@  discard block
 block discarded – undo
3285 3285
         $other_tables = [];
3286 3286
         foreach ($this->_tables as $table_alias => $table) {
3287 3287
             if ($table instanceof EE_Secondary_Table) {
3288
-                $other_tables[ $table_alias ] = $table;
3288
+                $other_tables[$table_alias] = $table;
3289 3289
             }
3290 3290
         }
3291 3291
         return $other_tables;
@@ -3300,7 +3300,7 @@  discard block
 block discarded – undo
3300 3300
      */
3301 3301
     public function _get_fields_for_table($table_alias)
3302 3302
     {
3303
-        return $this->_fields[ $table_alias ];
3303
+        return $this->_fields[$table_alias];
3304 3304
     }
3305 3305
 
3306 3306
 
@@ -3329,7 +3329,7 @@  discard block
 block discarded – undo
3329 3329
                     $query_info_carrier,
3330 3330
                     'group_by'
3331 3331
                 );
3332
-            } elseif (! empty($query_params['group_by'])) {
3332
+            } elseif ( ! empty($query_params['group_by'])) {
3333 3333
                 $this->_extract_related_model_info_from_query_param(
3334 3334
                     $query_params['group_by'],
3335 3335
                     $query_info_carrier,
@@ -3351,7 +3351,7 @@  discard block
 block discarded – undo
3351 3351
                     $query_info_carrier,
3352 3352
                     'order_by'
3353 3353
                 );
3354
-            } elseif (! empty($query_params['order_by'])) {
3354
+            } elseif ( ! empty($query_params['order_by'])) {
3355 3355
                 $this->_extract_related_model_info_from_query_param(
3356 3356
                     $query_params['order_by'],
3357 3357
                     $query_info_carrier,
@@ -3386,7 +3386,7 @@  discard block
 block discarded – undo
3386 3386
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3387 3387
         $query_param_type
3388 3388
     ) {
3389
-        if (! empty($sub_query_params)) {
3389
+        if ( ! empty($sub_query_params)) {
3390 3390
             $sub_query_params = (array) $sub_query_params;
3391 3391
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3392 3392
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3402,7 +3402,7 @@  discard block
 block discarded – undo
3402 3402
                 $query_param_sans_stars =
3403 3403
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3404 3404
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3405
-                    if (! is_array($possibly_array_of_params)) {
3405
+                    if ( ! is_array($possibly_array_of_params)) {
3406 3406
                         throw new EE_Error(
3407 3407
                             sprintf(
3408 3408
                                 esc_html__(
@@ -3428,7 +3428,7 @@  discard block
 block discarded – undo
3428 3428
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3429 3429
                     // indicating that $possible_array_of_params[1] is actually a field name,
3430 3430
                     // from which we should extract query parameters!
3431
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3431
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3432 3432
                         throw new EE_Error(
3433 3433
                             sprintf(
3434 3434
                                 esc_html__(
@@ -3468,8 +3468,8 @@  discard block
 block discarded – undo
3468 3468
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3469 3469
         $query_param_type
3470 3470
     ) {
3471
-        if (! empty($sub_query_params)) {
3472
-            if (! is_array($sub_query_params)) {
3471
+        if ( ! empty($sub_query_params)) {
3472
+            if ( ! is_array($sub_query_params)) {
3473 3473
                 throw new EE_Error(
3474 3474
                     sprintf(
3475 3475
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3507,7 +3507,7 @@  discard block
 block discarded – undo
3507 3507
      */
3508 3508
     public function _create_model_query_info_carrier($query_params)
3509 3509
     {
3510
-        if (! is_array($query_params)) {
3510
+        if ( ! is_array($query_params)) {
3511 3511
             EE_Error::doing_it_wrong(
3512 3512
                 'EEM_Base::_create_model_query_info_carrier',
3513 3513
                 sprintf(
@@ -3538,7 +3538,7 @@  discard block
 block discarded – undo
3538 3538
             // only include if related to a cpt where no password has been set
3539 3539
             $query_params[0]['OR*nopassword'] = [
3540 3540
                 $where_param_key_for_password       => '',
3541
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3541
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3542 3542
             ];
3543 3543
         }
3544 3544
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3592,7 +3592,7 @@  discard block
 block discarded – undo
3592 3592
         // set limit
3593 3593
         if (array_key_exists('limit', $query_params)) {
3594 3594
             if (is_array($query_params['limit'])) {
3595
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3595
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3596 3596
                     $e = sprintf(
3597 3597
                         esc_html__(
3598 3598
                             "Invalid DB query. You passed '%s' for the LIMIT, but only the following are valid: an integer, string representing an integer, a string like 'int,int', or an array like array(int,int)",
@@ -3600,12 +3600,12 @@  discard block
 block discarded – undo
3600 3600
                         ),
3601 3601
                         http_build_query($query_params['limit'])
3602 3602
                     );
3603
-                    throw new EE_Error($e . "|" . $e);
3603
+                    throw new EE_Error($e."|".$e);
3604 3604
                 }
3605 3605
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3606
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3607
-            } elseif (! empty($query_params['limit'])) {
3608
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3606
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3607
+            } elseif ( ! empty($query_params['limit'])) {
3608
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3609 3609
             }
3610 3610
         }
3611 3611
         // set order by
@@ -3637,10 +3637,10 @@  discard block
 block discarded – undo
3637 3637
                 $order_array = [];
3638 3638
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3639 3639
                     $order         = $this->_extract_order($order);
3640
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3640
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3641 3641
                 }
3642
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3643
-            } elseif (! empty($query_params['order_by'])) {
3642
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3643
+            } elseif ( ! empty($query_params['order_by'])) {
3644 3644
                 $this->_extract_related_model_info_from_query_param(
3645 3645
                     $query_params['order_by'],
3646 3646
                     $query_object,
@@ -3651,7 +3651,7 @@  discard block
 block discarded – undo
3651 3651
                     ? $this->_extract_order($query_params['order'])
3652 3652
                     : 'DESC';
3653 3653
                 $query_object->set_order_by_sql(
3654
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3654
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3655 3655
                 );
3656 3656
             }
3657 3657
         }
@@ -3663,7 +3663,7 @@  discard block
 block discarded – undo
3663 3663
         ) {
3664 3664
             $pk_field = $this->get_primary_key_field();
3665 3665
             $order    = $this->_extract_order($query_params['order']);
3666
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3666
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3667 3667
         }
3668 3668
         // set group by
3669 3669
         if (array_key_exists('group_by', $query_params)) {
@@ -3673,10 +3673,10 @@  discard block
 block discarded – undo
3673 3673
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3674 3674
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3675 3675
                 }
3676
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3677
-            } elseif (! empty($query_params['group_by'])) {
3676
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3677
+            } elseif ( ! empty($query_params['group_by'])) {
3678 3678
                 $query_object->set_group_by_sql(
3679
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3679
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3680 3680
                 );
3681 3681
             }
3682 3682
         }
@@ -3686,7 +3686,7 @@  discard block
 block discarded – undo
3686 3686
         }
3687 3687
         // now, just verify they didn't pass anything wack
3688 3688
         foreach ($query_params as $query_key => $query_value) {
3689
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3689
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3690 3690
                 throw new EE_Error(
3691 3691
                     sprintf(
3692 3692
                         esc_html__(
@@ -3791,7 +3791,7 @@  discard block
 block discarded – undo
3791 3791
         $where_query_params = []
3792 3792
     ) {
3793 3793
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3794
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3794
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3795 3795
             throw new EE_Error(
3796 3796
                 sprintf(
3797 3797
                     esc_html__(
@@ -3821,7 +3821,7 @@  discard block
 block discarded – undo
3821 3821
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3822 3822
                 continue;
3823 3823
             }
3824
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3824
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3825 3825
                 $related_model_universal_where_params,
3826 3826
                 $where_query_params,
3827 3827
                 $related_model,
@@ -3930,19 +3930,19 @@  discard block
 block discarded – undo
3930 3930
     ) {
3931 3931
         $null_friendly_where_conditions = [];
3932 3932
         $none_overridden                = true;
3933
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3933
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3934 3934
         foreach ($default_where_conditions as $key => $val) {
3935
-            if (isset($provided_where_conditions[ $key ])) {
3935
+            if (isset($provided_where_conditions[$key])) {
3936 3936
                 $none_overridden = false;
3937 3937
             } else {
3938
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3938
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3939 3939
             }
3940 3940
         }
3941 3941
         if ($none_overridden && $default_where_conditions) {
3942 3942
             if ($model->has_primary_key_field()) {
3943
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3943
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3944 3944
                                                                                    . "."
3945
-                                                                                   . $model->primary_key_name() ] =
3945
+                                                                                   . $model->primary_key_name()] =
3946 3946
                     ['IS NULL'];
3947 3947
             }/*else{
3948 3948
                 //@todo NO PK, use other defaults
@@ -4053,7 +4053,7 @@  discard block
 block discarded – undo
4053 4053
             foreach ($tables as $table_obj) {
4054 4054
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
4055 4055
                                        . $table_obj->get_fully_qualified_pk_column();
4056
-                if (! in_array($qualified_pk_column, $selects)) {
4056
+                if ( ! in_array($qualified_pk_column, $selects)) {
4057 4057
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
4058 4058
                 }
4059 4059
             }
@@ -4205,9 +4205,9 @@  discard block
 block discarded – undo
4205 4205
         $query_parameter_type
4206 4206
     ) {
4207 4207
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4208
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4208
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4209 4209
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4210
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4210
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4211 4211
                 if ($possible_join_string === '') {
4212 4212
                     // nothing left to $query_param
4213 4213
                     // we should actually end in a field name, not a model like this!
@@ -4340,7 +4340,7 @@  discard block
 block discarded – undo
4340 4340
     {
4341 4341
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4342 4342
         if ($SQL) {
4343
-            return " WHERE " . $SQL;
4343
+            return " WHERE ".$SQL;
4344 4344
         }
4345 4345
         return '';
4346 4346
     }
@@ -4358,7 +4358,7 @@  discard block
 block discarded – undo
4358 4358
     {
4359 4359
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4360 4360
         if ($SQL) {
4361
-            return " HAVING " . $SQL;
4361
+            return " HAVING ".$SQL;
4362 4362
         }
4363 4363
         return '';
4364 4364
     }
@@ -4412,7 +4412,7 @@  discard block
 block discarded – undo
4412 4412
             } else {
4413 4413
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4414 4414
                 // if it's not a normal field, maybe it's a custom selection?
4415
-                if (! $field_obj) {
4415
+                if ( ! $field_obj) {
4416 4416
                     if ($this->_custom_selections instanceof CustomSelects) {
4417 4417
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4418 4418
                     } else {
@@ -4428,7 +4428,7 @@  discard block
 block discarded – undo
4428 4428
                     }
4429 4429
                 }
4430 4430
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4431
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4431
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4432 4432
             }
4433 4433
         }
4434 4434
         return $where_clauses
@@ -4452,7 +4452,7 @@  discard block
 block discarded – undo
4452 4452
                 $field->get_model_name(),
4453 4453
                 $query_param
4454 4454
             );
4455
-            return $table_alias_prefix . $field->get_qualified_column();
4455
+            return $table_alias_prefix.$field->get_qualified_column();
4456 4456
         }
4457 4457
         if (
4458 4458
             $this->_custom_selections instanceof CustomSelects
@@ -4513,10 +4513,10 @@  discard block
 block discarded – undo
4513 4513
             $operator = isset($op_and_value[0])
4514 4514
                 ? $this->_prepare_operator_for_sql($op_and_value[0])
4515 4515
                 : null;
4516
-            if (! $operator) {
4516
+            if ( ! $operator) {
4517 4517
                 $php_array_like_string = [];
4518 4518
                 foreach ($op_and_value as $key => $value) {
4519
-                    $value = is_array($value) ? '[' . implode(",", $value) . ']' : $value;
4519
+                    $value = is_array($value) ? '['.implode(",", $value).']' : $value;
4520 4520
                     $php_array_like_string[] = "$key=>$value";
4521 4521
                 }
4522 4522
                 throw new EE_Error(
@@ -4534,14 +4534,14 @@  discard block
 block discarded – undo
4534 4534
 
4535 4535
         // check to see if the value is actually another field
4536 4536
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2]) {
4537
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4537
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4538 4538
         }
4539 4539
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4540 4540
             // in this case, the value should be an array, or at least a comma-separated list
4541 4541
             // it will need to handle a little differently
4542 4542
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4543 4543
             // note: $cleaned_value has already been run through $wpdb->prepare()
4544
-            return $operator . SP . $cleaned_value;
4544
+            return $operator.SP.$cleaned_value;
4545 4545
         }
4546 4546
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4547 4547
             // the value should be an array with count of two.
@@ -4557,7 +4557,7 @@  discard block
 block discarded – undo
4557 4557
                 );
4558 4558
             }
4559 4559
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4560
-            return $operator . SP . $cleaned_value;
4560
+            return $operator.SP.$cleaned_value;
4561 4561
         }
4562 4562
         if (in_array($operator, $this->valid_null_style_operators())) {
4563 4563
             if ($value !== null) {
@@ -4577,10 +4577,10 @@  discard block
 block discarded – undo
4577 4577
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4578 4578
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4579 4579
             // remove other junk. So just treat it as a string.
4580
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4580
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4581 4581
         }
4582
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4583
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4582
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4583
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4584 4584
         }
4585 4585
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4586 4586
             throw new EE_Error(
@@ -4594,7 +4594,7 @@  discard block
 block discarded – undo
4594 4594
                 )
4595 4595
             );
4596 4596
         }
4597
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4597
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4598 4598
             throw new EE_Error(
4599 4599
                 sprintf(
4600 4600
                     esc_html__(
@@ -4633,7 +4633,7 @@  discard block
 block discarded – undo
4633 4633
         foreach ($values as $value) {
4634 4634
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4635 4635
         }
4636
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4636
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4637 4637
     }
4638 4638
 
4639 4639
 
@@ -4671,7 +4671,7 @@  discard block
 block discarded – undo
4671 4671
             $main_table  = $this->_get_main_table();
4672 4672
             $prepped[]   = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4673 4673
         }
4674
-        return '(' . implode(',', $prepped) . ')';
4674
+        return '('.implode(',', $prepped).')';
4675 4675
     }
4676 4676
 
4677 4677
 
@@ -4691,7 +4691,7 @@  discard block
 block discarded – undo
4691 4691
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4692 4692
             );
4693 4693
         } //$field_obj should really just be a data type
4694
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4694
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4695 4695
             throw new EE_Error(
4696 4696
                 sprintf(
4697 4697
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4728,14 +4728,14 @@  discard block
 block discarded – undo
4728 4728
             );
4729 4729
         }
4730 4730
         $number_of_parts       = count($query_param_parts);
4731
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4731
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4732 4732
         if ($number_of_parts === 1) {
4733 4733
             $field_name = $last_query_param_part;
4734 4734
             $model_obj  = $this;
4735 4735
         } else {// $number_of_parts >= 2
4736 4736
             // the last part is the column name, and there are only 2parts. therefore...
4737 4737
             $field_name = $last_query_param_part;
4738
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4738
+            $model_obj  = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4739 4739
         }
4740 4740
         try {
4741 4741
             return $model_obj->field_settings_for($field_name);
@@ -4756,7 +4756,7 @@  discard block
 block discarded – undo
4756 4756
     public function _get_qualified_column_for_field($field_name)
4757 4757
     {
4758 4758
         $all_fields = $this->field_settings();
4759
-        $field      = $all_fields[ $field_name ] ?? false;
4759
+        $field      = $all_fields[$field_name] ?? false;
4760 4760
         if ($field) {
4761 4761
             return $field->get_qualified_column();
4762 4762
         }
@@ -4826,12 +4826,12 @@  discard block
 block discarded – undo
4826 4826
      */
4827 4827
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4828 4828
     {
4829
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain)
4829
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain)
4830 4830
                 ? ''
4831 4831
                 : '__');
4832 4832
         $qualified_columns = [];
4833 4833
         foreach ($this->field_settings() as $field_name => $field) {
4834
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4834
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4835 4835
         }
4836 4836
         return $return_string
4837 4837
             ? implode(', ', $qualified_columns)
@@ -4858,11 +4858,11 @@  discard block
 block discarded – undo
4858 4858
             if ($table_obj instanceof EE_Primary_Table) {
4859 4859
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4860 4860
                     ? $table_obj->get_select_join_limit($limit)
4861
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4861
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4862 4862
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4863 4863
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4864 4864
                     ? $table_obj->get_select_join_limit_join($limit)
4865
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4865
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4866 4866
             }
4867 4867
         }
4868 4868
         return $SQL;
@@ -4933,7 +4933,7 @@  discard block
 block discarded – undo
4933 4933
         foreach ($this->field_settings() as $field_obj) {
4934 4934
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4935 4935
             /** @var $field_obj EE_Model_Field_Base */
4936
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4936
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4937 4937
         }
4938 4938
         return $data_types;
4939 4939
     }
@@ -4948,8 +4948,8 @@  discard block
 block discarded – undo
4948 4948
      */
4949 4949
     public function get_related_model_obj($model_name)
4950 4950
     {
4951
-        $model_classname = "EEM_" . $model_name;
4952
-        if (! class_exists($model_classname)) {
4951
+        $model_classname = "EEM_".$model_name;
4952
+        if ( ! class_exists($model_classname)) {
4953 4953
             throw new EE_Error(
4954 4954
                 sprintf(
4955 4955
                     esc_html__(
@@ -4961,7 +4961,7 @@  discard block
 block discarded – undo
4961 4961
                 )
4962 4962
             );
4963 4963
         }
4964
-        return call_user_func($model_classname . "::instance");
4964
+        return call_user_func($model_classname."::instance");
4965 4965
     }
4966 4966
 
4967 4967
 
@@ -4988,7 +4988,7 @@  discard block
 block discarded – undo
4988 4988
         $belongs_to_relations = [];
4989 4989
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4990 4990
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4991
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4991
+                $belongs_to_relations[$model_name] = $relation_obj;
4992 4992
             }
4993 4993
         }
4994 4994
         return $belongs_to_relations;
@@ -5005,7 +5005,7 @@  discard block
 block discarded – undo
5005 5005
     public function related_settings_for($relation_name)
5006 5006
     {
5007 5007
         $relatedModels = $this->relation_settings();
5008
-        if (! array_key_exists($relation_name, $relatedModels)) {
5008
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
5009 5009
             throw new EE_Error(
5010 5010
                 sprintf(
5011 5011
                     esc_html__(
@@ -5018,7 +5018,7 @@  discard block
 block discarded – undo
5018 5018
                 )
5019 5019
             );
5020 5020
         }
5021
-        return $relatedModels[ $relation_name ];
5021
+        return $relatedModels[$relation_name];
5022 5022
     }
5023 5023
 
5024 5024
 
@@ -5034,7 +5034,7 @@  discard block
 block discarded – undo
5034 5034
     public function field_settings_for($fieldName, $include_db_only_fields = true)
5035 5035
     {
5036 5036
         $fieldSettings = $this->field_settings($include_db_only_fields);
5037
-        if (! array_key_exists($fieldName, $fieldSettings)) {
5037
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
5038 5038
             throw new EE_Error(
5039 5039
                 sprintf(
5040 5040
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -5043,7 +5043,7 @@  discard block
 block discarded – undo
5043 5043
                 )
5044 5044
             );
5045 5045
         }
5046
-        return $fieldSettings[ $fieldName ];
5046
+        return $fieldSettings[$fieldName];
5047 5047
     }
5048 5048
 
5049 5049
 
@@ -5056,7 +5056,7 @@  discard block
 block discarded – undo
5056 5056
     public function has_field($fieldName)
5057 5057
     {
5058 5058
         $fieldSettings = $this->field_settings(true);
5059
-        if (isset($fieldSettings[ $fieldName ])) {
5059
+        if (isset($fieldSettings[$fieldName])) {
5060 5060
             return true;
5061 5061
         }
5062 5062
         return false;
@@ -5072,7 +5072,7 @@  discard block
 block discarded – undo
5072 5072
     public function has_relation($relation_name)
5073 5073
     {
5074 5074
         $relations = $this->relation_settings();
5075
-        if (isset($relations[ $relation_name ])) {
5075
+        if (isset($relations[$relation_name])) {
5076 5076
             return true;
5077 5077
         }
5078 5078
         return false;
@@ -5108,7 +5108,7 @@  discard block
 block discarded – undo
5108 5108
                     break;
5109 5109
                 }
5110 5110
             }
5111
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5111
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5112 5112
                 throw new EE_Error(
5113 5113
                     sprintf(
5114 5114
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5168,17 +5168,17 @@  discard block
 block discarded – undo
5168 5168
      */
5169 5169
     public function get_foreign_key_to($model_name)
5170 5170
     {
5171
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5171
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5172 5172
             foreach ($this->field_settings() as $field) {
5173 5173
                 if (
5174 5174
                     $field instanceof EE_Foreign_Key_Field_Base
5175 5175
                     && in_array($model_name, $field->get_model_names_pointed_to())
5176 5176
                 ) {
5177
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5177
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5178 5178
                     break;
5179 5179
                 }
5180 5180
             }
5181
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5181
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5182 5182
                 throw new EE_Error(
5183 5183
                     sprintf(
5184 5184
                         esc_html__(
@@ -5191,7 +5191,7 @@  discard block
 block discarded – undo
5191 5191
                 );
5192 5192
             }
5193 5193
         }
5194
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5194
+        return $this->_cache_foreign_key_to_fields[$model_name];
5195 5195
     }
5196 5196
 
5197 5197
 
@@ -5207,7 +5207,7 @@  discard block
 block discarded – undo
5207 5207
     {
5208 5208
         $table_alias_sans_model_relation_chain_prefix =
5209 5209
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5210
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5210
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5211 5211
     }
5212 5212
 
5213 5213
 
@@ -5225,7 +5225,7 @@  discard block
 block discarded – undo
5225 5225
                 $this->_cached_fields = [];
5226 5226
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5227 5227
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5228
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5228
+                        $this->_cached_fields[$field_name] = $field_obj;
5229 5229
                     }
5230 5230
                 }
5231 5231
             }
@@ -5236,8 +5236,8 @@  discard block
 block discarded – undo
5236 5236
             foreach ($this->_fields as $fields_corresponding_to_table) {
5237 5237
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5238 5238
                     /** @var $field_obj EE_Model_Field_Base */
5239
-                    if (! $field_obj->is_db_only_field()) {
5240
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5239
+                    if ( ! $field_obj->is_db_only_field()) {
5240
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5241 5241
                     }
5242 5242
                 }
5243 5243
             }
@@ -5280,12 +5280,12 @@  discard block
 block discarded – undo
5280 5280
                     $primary_key_field->get_qualified_column(),
5281 5281
                     $primary_key_field->get_table_column()
5282 5282
                 );
5283
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5283
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5284 5284
                     continue;
5285 5285
                 }
5286 5286
             }
5287 5287
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5288
-            if (! $classInstance) {
5288
+            if ( ! $classInstance) {
5289 5289
                 throw new EE_Error(
5290 5290
                     sprintf(
5291 5291
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5300,7 +5300,7 @@  discard block
 block discarded – undo
5300 5300
             $key                      = $has_primary_key
5301 5301
                 ? $classInstance->ID()
5302 5302
                 : $count_if_model_has_no_primary_key++;
5303
-            $array_of_objects[ $key ] = $classInstance;
5303
+            $array_of_objects[$key] = $classInstance;
5304 5304
             // also, for all the relations of type BelongsTo, see if we can cache
5305 5305
             // those related models
5306 5306
             // (we could do this for other relations too, but if there are conditions
@@ -5344,9 +5344,9 @@  discard block
 block discarded – undo
5344 5344
         $results = [];
5345 5345
         if ($this->_custom_selections instanceof CustomSelects) {
5346 5346
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5347
-                if (isset($db_results_row[ $alias ])) {
5348
-                    $results[ $alias ] = $this->convertValueToDataType(
5349
-                        $db_results_row[ $alias ],
5347
+                if (isset($db_results_row[$alias])) {
5348
+                    $results[$alias] = $this->convertValueToDataType(
5349
+                        $db_results_row[$alias],
5350 5350
                         $this->_custom_selections->getDataTypeForAlias($alias)
5351 5351
                     );
5352 5352
                 }
@@ -5391,7 +5391,7 @@  discard block
 block discarded – undo
5391 5391
         $this_model_fields_and_values = [];
5392 5392
         // setup the row using default values;
5393 5393
         foreach ($this->field_settings() as $field_name => $field_obj) {
5394
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5394
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5395 5395
         }
5396 5396
         $className = $this->_get_class_name();
5397 5397
         return EE_Registry::instance()->load_class($className, [$this_model_fields_and_values], false, false);
@@ -5407,20 +5407,20 @@  discard block
 block discarded – undo
5407 5407
      */
5408 5408
     public function instantiate_class_from_array_or_object($cols_n_values)
5409 5409
     {
5410
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5410
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5411 5411
             $cols_n_values = get_object_vars($cols_n_values);
5412 5412
         }
5413 5413
         $primary_key = null;
5414 5414
         // make sure the array only has keys that are fields/columns on this model
5415 5415
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5416
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5417
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5416
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5417
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5418 5418
         }
5419 5419
         $className = $this->_get_class_name();
5420 5420
         // check we actually found results that we can use to build our model object
5421 5421
         // if not, return null
5422 5422
         if ($this->has_primary_key_field()) {
5423
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5423
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5424 5424
                 return null;
5425 5425
             }
5426 5426
         } elseif ($this->unique_indexes()) {
@@ -5432,7 +5432,7 @@  discard block
 block discarded – undo
5432 5432
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5433 5433
         if ($primary_key) {
5434 5434
             $classInstance = $this->get_from_entity_map($primary_key);
5435
-            if (! $classInstance) {
5435
+            if ( ! $classInstance) {
5436 5436
                 $classInstance = EE_Registry::instance()
5437 5437
                                             ->load_class(
5438 5438
                                                 $className,
@@ -5463,7 +5463,7 @@  discard block
 block discarded – undo
5463 5463
      */
5464 5464
     public function get_from_entity_map($id)
5465 5465
     {
5466
-        return $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] ?? null;
5466
+        return $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] ?? null;
5467 5467
     }
5468 5468
 
5469 5469
 
@@ -5486,7 +5486,7 @@  discard block
 block discarded – undo
5486 5486
     public function add_to_entity_map(EE_Base_Class $object)
5487 5487
     {
5488 5488
         $className = $this->_get_class_name();
5489
-        if (! $object instanceof $className) {
5489
+        if ( ! $object instanceof $className) {
5490 5490
             throw new EE_Error(
5491 5491
                 sprintf(
5492 5492
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5498,7 +5498,7 @@  discard block
 block discarded – undo
5498 5498
             );
5499 5499
         }
5500 5500
 
5501
-        if (! $object->ID()) {
5501
+        if ( ! $object->ID()) {
5502 5502
             throw new EE_Error(
5503 5503
                 sprintf(
5504 5504
                     esc_html__(
@@ -5514,7 +5514,7 @@  discard block
 block discarded – undo
5514 5514
         if ($classInstance) {
5515 5515
             return $classInstance;
5516 5516
         }
5517
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5517
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5518 5518
         return $object;
5519 5519
     }
5520 5520
 
@@ -5529,11 +5529,11 @@  discard block
 block discarded – undo
5529 5529
     public function clear_entity_map($id = null)
5530 5530
     {
5531 5531
         if (empty($id)) {
5532
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5532
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5533 5533
             return true;
5534 5534
         }
5535
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5536
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5535
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5536
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5537 5537
             return true;
5538 5538
         }
5539 5539
         return false;
@@ -5581,18 +5581,18 @@  discard block
 block discarded – undo
5581 5581
             // there is a primary key on this table and its not set. Use defaults for all its columns
5582 5582
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5583 5583
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5584
-                    if (! $field_obj->is_db_only_field()) {
5584
+                    if ( ! $field_obj->is_db_only_field()) {
5585 5585
                         // prepare field as if its coming from db
5586 5586
                         $prepared_value                            =
5587 5587
                             $field_obj->prepare_for_set($field_obj->get_default_value());
5588
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5588
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5589 5589
                     }
5590 5590
                 }
5591 5591
             } else {
5592 5592
                 // the table's rows existed. Use their values
5593 5593
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5594
-                    if (! $field_obj->is_db_only_field()) {
5595
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5594
+                    if ( ! $field_obj->is_db_only_field()) {
5595
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5596 5596
                             $cols_n_values,
5597 5597
                             $field_obj->get_qualified_column(),
5598 5598
                             $field_obj->get_table_column()
@@ -5619,17 +5619,17 @@  discard block
 block discarded – undo
5619 5619
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5620 5620
         // does the field on the model relate to this column retrieved from the db?
5621 5621
         // or is it a db-only field? (not relating to the model)
5622
-        if (isset($cols_n_values[ $qualified_column ])) {
5623
-            $value = $cols_n_values[ $qualified_column ];
5624
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5625
-            $value = $cols_n_values[ $regular_column ];
5626
-        } elseif (! empty($this->foreign_key_aliases)) {
5622
+        if (isset($cols_n_values[$qualified_column])) {
5623
+            $value = $cols_n_values[$qualified_column];
5624
+        } elseif (isset($cols_n_values[$regular_column])) {
5625
+            $value = $cols_n_values[$regular_column];
5626
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5627 5627
             // no PK?  ok check if there is a foreign key alias set for this table
5628 5628
             // then check if that alias exists in the incoming data
5629 5629
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5630 5630
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5631
-                if ($PK_column === $qualified_column && !empty($cols_n_values[ $FK_alias ])) {
5632
-                    $value = $cols_n_values[ $FK_alias ];
5631
+                if ($PK_column === $qualified_column && ! empty($cols_n_values[$FK_alias])) {
5632
+                    $value = $cols_n_values[$FK_alias];
5633 5633
                     [$pk_class] = explode('.', $PK_column);
5634 5634
                     $pk_model_name = "EEM_{$pk_class}";
5635 5635
                     /** @var EEM_Base $pk_model */
@@ -5673,7 +5673,7 @@  discard block
 block discarded – undo
5673 5673
                     $obj_in_map->clear_cache($relation_name, null, true);
5674 5674
                 }
5675 5675
             }
5676
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5676
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5677 5677
             return $obj_in_map;
5678 5678
         }
5679 5679
         return $this->get_one_by_ID($id);
@@ -5725,7 +5725,7 @@  discard block
 block discarded – undo
5725 5725
      */
5726 5726
     private function _get_class_name()
5727 5727
     {
5728
-        return "EE_" . $this->get_this_model_name();
5728
+        return "EE_".$this->get_this_model_name();
5729 5729
     }
5730 5730
 
5731 5731
 
@@ -5779,7 +5779,7 @@  discard block
 block discarded – undo
5779 5779
     {
5780 5780
         $className = get_class($this);
5781 5781
         $tagName   = "FHEE__{$className}__{$methodName}";
5782
-        if (! has_filter($tagName)) {
5782
+        if ( ! has_filter($tagName)) {
5783 5783
             throw new EE_Error(
5784 5784
                 sprintf(
5785 5785
                     esc_html__(
@@ -5950,7 +5950,7 @@  discard block
 block discarded – undo
5950 5950
         $unique_indexes = [];
5951 5951
         foreach ($this->_indexes as $name => $index) {
5952 5952
             if ($index instanceof EE_Unique_Index) {
5953
-                $unique_indexes [ $name ] = $index;
5953
+                $unique_indexes [$name] = $index;
5954 5954
             }
5955 5955
         }
5956 5956
         return $unique_indexes;
@@ -6014,7 +6014,7 @@  discard block
 block discarded – undo
6014 6014
         $key_vals_in_combined_pk = [];
6015 6015
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
6016 6016
         foreach ($key_fields as $key_field_name => $field_obj) {
6017
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
6017
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
6018 6018
                 return null;
6019 6019
             }
6020 6020
         }
@@ -6034,7 +6034,7 @@  discard block
 block discarded – undo
6034 6034
     {
6035 6035
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
6036 6036
         foreach ($keys_it_should_have as $key) {
6037
-            if (! isset($key_vals[ $key ])) {
6037
+            if ( ! isset($key_vals[$key])) {
6038 6038
                 return false;
6039 6039
             }
6040 6040
         }
@@ -6073,8 +6073,8 @@  discard block
 block discarded – undo
6073 6073
         }
6074 6074
         // even copies obviously won't have the same ID, so remove the primary key
6075 6075
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
6076
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
6077
-            unset($attributes_array[ $this->primary_key_name() ]);
6076
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
6077
+            unset($attributes_array[$this->primary_key_name()]);
6078 6078
         }
6079 6079
         if (isset($query_params[0])) {
6080 6080
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -6096,7 +6096,7 @@  discard block
 block discarded – undo
6096 6096
      */
6097 6097
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
6098 6098
     {
6099
-        if (! is_array($query_params)) {
6099
+        if ( ! is_array($query_params)) {
6100 6100
             EE_Error::doing_it_wrong(
6101 6101
                 'EEM_Base::get_one_copy',
6102 6102
                 sprintf(
@@ -6145,7 +6145,7 @@  discard block
 block discarded – undo
6145 6145
      */
6146 6146
     private function _prepare_operator_for_sql($operator_supplied)
6147 6147
     {
6148
-        $sql_operator = $this->_valid_operators[ $operator_supplied ] ?? null;
6148
+        $sql_operator = $this->_valid_operators[$operator_supplied] ?? null;
6149 6149
         if ($sql_operator) {
6150 6150
             return $sql_operator;
6151 6151
         }
@@ -6243,7 +6243,7 @@  discard block
 block discarded – undo
6243 6243
         $objs  = $this->get_all($query_params);
6244 6244
         $names = [];
6245 6245
         foreach ($objs as $obj) {
6246
-            $names[ $obj->ID() ] = $obj->name();
6246
+            $names[$obj->ID()] = $obj->name();
6247 6247
         }
6248 6248
         return $names;
6249 6249
     }
@@ -6264,7 +6264,7 @@  discard block
 block discarded – undo
6264 6264
      */
6265 6265
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6266 6266
     {
6267
-        if (! $this->has_primary_key_field()) {
6267
+        if ( ! $this->has_primary_key_field()) {
6268 6268
             if (defined('WP_DEBUG') && WP_DEBUG) {
6269 6269
                 EE_Error::add_error(
6270 6270
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6277,7 +6277,7 @@  discard block
 block discarded – undo
6277 6277
         $IDs = [];
6278 6278
         foreach ($model_objects as $model_object) {
6279 6279
             $id = $model_object->ID();
6280
-            if (! $id) {
6280
+            if ( ! $id) {
6281 6281
                 if ($filter_out_empty_ids) {
6282 6282
                     continue;
6283 6283
                 }
@@ -6326,22 +6326,22 @@  discard block
 block discarded – undo
6326 6326
         EEM_Base::verify_is_valid_cap_context($context);
6327 6327
         // check if we ought to run the restriction generator first
6328 6328
         if (
6329
-            isset($this->_cap_restriction_generators[ $context ])
6330
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6331
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6329
+            isset($this->_cap_restriction_generators[$context])
6330
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6331
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6332 6332
         ) {
6333
-            $this->_cap_restrictions[ $context ] = array_merge(
6334
-                $this->_cap_restrictions[ $context ],
6335
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6333
+            $this->_cap_restrictions[$context] = array_merge(
6334
+                $this->_cap_restrictions[$context],
6335
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6336 6336
             );
6337 6337
         }
6338 6338
         // and make sure we've finalized the construction of each restriction
6339
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6339
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6340 6340
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6341 6341
                 $where_conditions_obj->_finalize_construct($this);
6342 6342
             }
6343 6343
         }
6344
-        return $this->_cap_restrictions[ $context ];
6344
+        return $this->_cap_restrictions[$context];
6345 6345
     }
6346 6346
 
6347 6347
 
@@ -6371,9 +6371,9 @@  discard block
 block discarded – undo
6371 6371
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6372 6372
             if (
6373 6373
                 ! EE_Capabilities::instance()
6374
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6374
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6375 6375
             ) {
6376
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6376
+                $missing_caps[$cap] = $restriction_if_no_cap;
6377 6377
             }
6378 6378
         }
6379 6379
         return $missing_caps;
@@ -6406,8 +6406,8 @@  discard block
 block discarded – undo
6406 6406
     public function cap_action_for_context($context)
6407 6407
     {
6408 6408
         $mapping = $this->cap_contexts_to_cap_action_map();
6409
-        if (isset($mapping[ $context ])) {
6410
-            return $mapping[ $context ];
6409
+        if (isset($mapping[$context])) {
6410
+            return $mapping[$context];
6411 6411
         }
6412 6412
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6413 6413
             return $action;
@@ -6528,7 +6528,7 @@  discard block
 block discarded – undo
6528 6528
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6529 6529
             if (
6530 6530
                 $query_param_key === $logic_query_param_key
6531
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6531
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6532 6532
             ) {
6533 6533
                 return true;
6534 6534
             }
@@ -6586,7 +6586,7 @@  discard block
 block discarded – undo
6586 6586
         if ($password_field instanceof EE_Password_Field) {
6587 6587
             $field_names = $password_field->protectedFields();
6588 6588
             foreach ($field_names as $field_name) {
6589
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6589
+                $fields[$field_name] = $this->field_settings_for($field_name);
6590 6590
             }
6591 6591
         }
6592 6592
         return $fields;
@@ -6612,7 +6612,7 @@  discard block
 block discarded – undo
6612 6612
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6613 6613
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6614 6614
         }
6615
-        if (! is_array($model_obj_or_fields_n_values)) {
6615
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6616 6616
             throw new UnexpectedEntityException(
6617 6617
                 $model_obj_or_fields_n_values,
6618 6618
                 'EE_Base_Class',
@@ -6694,9 +6694,9 @@  discard block
 block discarded – undo
6694 6694
         }
6695 6695
         return (
6696 6696
                $this->model_chain_to_password
6697
-                   ? $this->model_chain_to_password . '.'
6697
+                   ? $this->model_chain_to_password.'.'
6698 6698
                    : ''
6699
-               ) . $password_field_name;
6699
+               ).$password_field_name;
6700 6700
     }
6701 6701
 
6702 6702
 
Please login to merge, or discard this patch.
core/db_models/EEM_Form_Submission.model.php 1 patch
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -11,124 +11,124 @@
 block discarded – undo
11 11
  */
12 12
 class EEM_Form_Submission extends EEM_Base
13 13
 {
14
-    protected static ?EEM_Form_Submission $_instance = null;
14
+	protected static ?EEM_Form_Submission $_instance = null;
15 15
 
16
-    private RequestInterface $request;
16
+	private RequestInterface $request;
17 17
 
18 18
 
19
-    /**
20
-     * EEM_Form_Submission constructor.
21
-     *
22
-     * @param string|null $timezone
23
-     * @throws EE_Error
24
-     */
25
-    protected function __construct(?string $timezone = '')
26
-    {
27
-        $this->singular_item = esc_html__('Form Submission', 'event_espresso');
28
-        $this->plural_item   = esc_html__('Form Submissions', 'event_espresso');
19
+	/**
20
+	 * EEM_Form_Submission constructor.
21
+	 *
22
+	 * @param string|null $timezone
23
+	 * @throws EE_Error
24
+	 */
25
+	protected function __construct(?string $timezone = '')
26
+	{
27
+		$this->singular_item = esc_html__('Form Submission', 'event_espresso');
28
+		$this->plural_item   = esc_html__('Form Submissions', 'event_espresso');
29 29
 
30
-        $this->_tables          = [
31
-            'Form_Submission' => new EE_Primary_Table('esp_form_submission', 'FSB_UUID'),
32
-        ];
33
-        $this->_fields          = [
34
-            'Form_Submission' => [
35
-                'FSB_UUID'      => new EE_Primary_Key_String_Field(
36
-                    'FSB_UUID',
37
-                    esc_html__('Form Submission UUID (universally unique identifier)', 'event_espresso')
38
-                ),
39
-                'FSC_UUID'      => new EE_Foreign_Key_String_Field(
40
-                    'FSC_UUID',
41
-                    esc_html__('Form Section UUID (universally unique identifier)', 'event_espresso'),
42
-                    false,
43
-                    '',
44
-                    'Form_Section',
45
-                    false
46
-                ),
47
-                'TXN_ID'        => new EE_Foreign_Key_Int_Field(
48
-                    'TXN_ID',
49
-                    esc_html__('Transaction ID', 'event_espresso'),
50
-                    false,
51
-                    0,
52
-                    'Transaction'
53
-                ),
54
-                'FSB_data'      => new EE_JSON_Field(
55
-                    'FSB_data',
56
-                    esc_html__('Serialized form submission data', 'event_espresso'),
57
-                    true,
58
-                    null
59
-                ),
60
-                'FSB_submitted' => new EE_Datetime_Field(
61
-                    'FSB_submitted',
62
-                    esc_html__('Form submission timestamp', 'event_espresso'),
63
-                    false,
64
-                    EE_Datetime_Field::now,
65
-                    $timezone
66
-                ),
67
-            ],
68
-        ];
69
-        $this->_model_relations = [
70
-            'Form_Section' => new EE_Belongs_To_Relation(),
71
-            'Transaction'  => new EE_Belongs_To_Relation(),
72
-        ];
73
-        parent::__construct($timezone);
74
-        $this->request = $this->getLoader()->getShared('EventEspresso\core\services\request\RequestInterface');
75
-    }
30
+		$this->_tables          = [
31
+			'Form_Submission' => new EE_Primary_Table('esp_form_submission', 'FSB_UUID'),
32
+		];
33
+		$this->_fields          = [
34
+			'Form_Submission' => [
35
+				'FSB_UUID'      => new EE_Primary_Key_String_Field(
36
+					'FSB_UUID',
37
+					esc_html__('Form Submission UUID (universally unique identifier)', 'event_espresso')
38
+				),
39
+				'FSC_UUID'      => new EE_Foreign_Key_String_Field(
40
+					'FSC_UUID',
41
+					esc_html__('Form Section UUID (universally unique identifier)', 'event_espresso'),
42
+					false,
43
+					'',
44
+					'Form_Section',
45
+					false
46
+				),
47
+				'TXN_ID'        => new EE_Foreign_Key_Int_Field(
48
+					'TXN_ID',
49
+					esc_html__('Transaction ID', 'event_espresso'),
50
+					false,
51
+					0,
52
+					'Transaction'
53
+				),
54
+				'FSB_data'      => new EE_JSON_Field(
55
+					'FSB_data',
56
+					esc_html__('Serialized form submission data', 'event_espresso'),
57
+					true,
58
+					null
59
+				),
60
+				'FSB_submitted' => new EE_Datetime_Field(
61
+					'FSB_submitted',
62
+					esc_html__('Form submission timestamp', 'event_espresso'),
63
+					false,
64
+					EE_Datetime_Field::now,
65
+					$timezone
66
+				),
67
+			],
68
+		];
69
+		$this->_model_relations = [
70
+			'Form_Section' => new EE_Belongs_To_Relation(),
71
+			'Transaction'  => new EE_Belongs_To_Relation(),
72
+		];
73
+		parent::__construct($timezone);
74
+		$this->request = $this->getLoader()->getShared('EventEspresso\core\services\request\RequestInterface');
75
+	}
76 76
 
77 77
 
78
-    /**
79
-     * adds all default where conditions unless the current request originates from the admin
80
-     *
81
-     * @param array $query_params
82
-     * @return array
83
-     */
84
-    private function addDefaultWhereConditions(array $query_params): array
85
-    {
86
-        // might need to add a way to identify GQL requests for admin domains
87
-        $query_params['default_where_conditions'] = $this->request->isAdmin() || $this->request->isAdminAjax()
88
-            ? EE_Default_Where_Conditions::NONE
89
-            : EE_Default_Where_Conditions::ALL;
90
-        return $query_params;
91
-    }
78
+	/**
79
+	 * adds all default where conditions unless the current request originates from the admin
80
+	 *
81
+	 * @param array $query_params
82
+	 * @return array
83
+	 */
84
+	private function addDefaultWhereConditions(array $query_params): array
85
+	{
86
+		// might need to add a way to identify GQL requests for admin domains
87
+		$query_params['default_where_conditions'] = $this->request->isAdmin() || $this->request->isAdminAjax()
88
+			? EE_Default_Where_Conditions::NONE
89
+			: EE_Default_Where_Conditions::ALL;
90
+		return $query_params;
91
+	}
92 92
 
93 93
 
94
-    /**
95
-     * form sections should always be sorted in ascending order via the FSC_order field
96
-     *
97
-     * @param array $query_params
98
-     * @return array
99
-     */
100
-    private function addOrderByQueryParams(array $query_params): array
101
-    {
102
-        $query_params['order_by'] = ['FSB_submitted' => 'ASC'];
103
-        return $query_params;
104
-    }
94
+	/**
95
+	 * form sections should always be sorted in ascending order via the FSC_order field
96
+	 *
97
+	 * @param array $query_params
98
+	 * @return array
99
+	 */
100
+	private function addOrderByQueryParams(array $query_params): array
101
+	{
102
+		$query_params['order_by'] = ['FSB_submitted' => 'ASC'];
103
+		return $query_params;
104
+	}
105 105
 
106 106
 
107
-    /**
108
-     * @param EE_Event $event
109
-     * @return EE_Form_Submission[]|null
110
-     * @throws EE_Error
111
-     * @throws ReflectionException
112
-     */
113
-    public function getAllFormSubmissionsForEvent(EE_Event $event): ?array
114
-    {
115
-        $query_params = [['FSC_UUID' => $event->registrationFormUuid()]];
116
-        $query_params = $this->addDefaultWhereConditions($query_params);
117
-        $query_params = $this->addOrderByQueryParams($query_params);
118
-        return $this->get_all($query_params);
119
-    }
107
+	/**
108
+	 * @param EE_Event $event
109
+	 * @return EE_Form_Submission[]|null
110
+	 * @throws EE_Error
111
+	 * @throws ReflectionException
112
+	 */
113
+	public function getAllFormSubmissionsForEvent(EE_Event $event): ?array
114
+	{
115
+		$query_params = [['FSC_UUID' => $event->registrationFormUuid()]];
116
+		$query_params = $this->addDefaultWhereConditions($query_params);
117
+		$query_params = $this->addOrderByQueryParams($query_params);
118
+		return $this->get_all($query_params);
119
+	}
120 120
 
121 121
 
122
-    /**
123
-     * @param EE_Transaction $transaction
124
-     * @return EE_Form_Submission|null
125
-     * @throws EE_Error
126
-     * @throws ReflectionException
127
-     */
128
-    public function getFormSubmissionForTransaction(EE_Transaction $transaction): ?EE_Form_Submission
129
-    {
130
-        $query_params = [['TXN_ID' => $transaction->ID()]];
131
-        $query_params = $this->addDefaultWhereConditions($query_params);
132
-        return $this->get_one($query_params);
133
-    }
122
+	/**
123
+	 * @param EE_Transaction $transaction
124
+	 * @return EE_Form_Submission|null
125
+	 * @throws EE_Error
126
+	 * @throws ReflectionException
127
+	 */
128
+	public function getFormSubmissionForTransaction(EE_Transaction $transaction): ?EE_Form_Submission
129
+	{
130
+		$query_params = [['TXN_ID' => $transaction->ID()]];
131
+		$query_params = $this->addDefaultWhereConditions($query_params);
132
+		return $this->get_one($query_params);
133
+	}
134 134
 }
Please login to merge, or discard this patch.
core/EE_Dependency_Map.core.php 1 patch
Indentation   +1205 added lines, -1205 removed lines patch added patch discarded remove patch
@@ -20,1209 +20,1209 @@
 block discarded – undo
20 20
  */
21 21
 class EE_Dependency_Map
22 22
 {
23
-    /**
24
-     * This means that the requested class dependency is not present in the dependency map
25
-     */
26
-    const not_registered = 0;
27
-
28
-    /**
29
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
30
-     */
31
-    const load_new_object = 1;
32
-
33
-    /**
34
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
35
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
36
-     */
37
-    const load_from_cache = 2;
38
-
39
-    /**
40
-     * When registering a dependency,
41
-     * this indicates to keep any existing dependencies that already exist,
42
-     * and simply discard any new dependencies declared in the incoming data
43
-     */
44
-    const KEEP_EXISTING_DEPENDENCIES = 0;
45
-
46
-    /**
47
-     * When registering a dependency,
48
-     * this indicates to overwrite any existing dependencies that already exist using the incoming data
49
-     */
50
-    const OVERWRITE_DEPENDENCIES = 1;
51
-
52
-    protected static ?EE_Dependency_Map $_instance = null;
53
-
54
-    private ClassInterfaceCache $class_cache;
55
-
56
-    protected ?RequestInterface $request = null;
57
-
58
-    protected ?LegacyRequestInterface $legacy_request = null;
59
-
60
-    protected ?ResponseInterface $response = null;
61
-
62
-    protected ?LoaderInterface $loader = null;
63
-
64
-    protected array $_dependency_map = [];
65
-
66
-    protected array $_class_loaders = [];
67
-
68
-
69
-    /**
70
-     * EE_Dependency_Map constructor.
71
-     *
72
-     * @param ClassInterfaceCache $class_cache
73
-     */
74
-    protected function __construct(ClassInterfaceCache $class_cache)
75
-    {
76
-        $this->class_cache = $class_cache;
77
-        do_action('EE_Dependency_Map____construct', $this);
78
-    }
79
-
80
-
81
-    /**
82
-     * @return void
83
-     * @throws InvalidAliasException
84
-     */
85
-    public function initialize()
86
-    {
87
-        $this->_register_core_dependencies();
88
-        $this->_register_core_class_loaders();
89
-        $this->_register_core_aliases();
90
-    }
91
-
92
-
93
-    /**
94
-     * @singleton method used to instantiate class object
95
-     * @param ClassInterfaceCache|null $class_cache
96
-     * @return EE_Dependency_Map
97
-     */
98
-    public static function instance(ClassInterfaceCache $class_cache = null): EE_Dependency_Map
99
-    {
100
-        // check if class object is instantiated, and instantiated properly
101
-        if (
102
-            ! EE_Dependency_Map::$_instance instanceof EE_Dependency_Map
103
-            && $class_cache instanceof ClassInterfaceCache
104
-        ) {
105
-            EE_Dependency_Map::$_instance = new EE_Dependency_Map($class_cache);
106
-        }
107
-        return EE_Dependency_Map::$_instance;
108
-    }
109
-
110
-
111
-    /**
112
-     * @param RequestInterface $request
113
-     */
114
-    public function setRequest(RequestInterface $request)
115
-    {
116
-        $this->request = $request;
117
-    }
118
-
119
-
120
-    /**
121
-     * @param LegacyRequestInterface $legacy_request
122
-     */
123
-    public function setLegacyRequest(LegacyRequestInterface $legacy_request)
124
-    {
125
-        $this->legacy_request = $legacy_request;
126
-    }
127
-
128
-
129
-    /**
130
-     * @param ResponseInterface $response
131
-     */
132
-    public function setResponse(ResponseInterface $response)
133
-    {
134
-        $this->response = $response;
135
-    }
136
-
137
-
138
-    /**
139
-     * @param LoaderInterface $loader
140
-     */
141
-    public function setLoader(LoaderInterface $loader)
142
-    {
143
-        $this->loader = $loader;
144
-    }
145
-
146
-
147
-    /**
148
-     * @param string $class
149
-     * @param array  $dependencies
150
-     * @param int    $overwrite
151
-     * @return bool
152
-     */
153
-    public static function register_dependencies(
154
-        string $class,
155
-        array $dependencies,
156
-        int $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
157
-    ): bool {
158
-        return EE_Dependency_Map::$_instance->registerDependencies($class, $dependencies, $overwrite);
159
-    }
160
-
161
-
162
-    /**
163
-     * Assigns an array of class names and corresponding load sources (new or cached)
164
-     * to the class specified by the first parameter.
165
-     * IMPORTANT !!!
166
-     * The order of elements in the incoming $dependencies array MUST match
167
-     * the order of the constructor parameters for the class in question.
168
-     * This is especially important when overriding any existing dependencies that are registered.
169
-     * the third parameter controls whether any duplicate dependencies are overwritten or not.
170
-     *
171
-     * @param string $class
172
-     * @param array  $dependencies
173
-     * @param int    $overwrite
174
-     * @return bool
175
-     */
176
-    public function registerDependencies(
177
-        string $class,
178
-        array $dependencies,
179
-        int $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
180
-    ): bool {
181
-        if (empty($dependencies)) {
182
-            return false;
183
-        }
184
-        $class      = trim($class, '\\');
185
-        $registered = false;
186
-        if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
187
-            EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
188
-        }
189
-        // we need to make sure that any aliases used when registering a dependency
190
-        // get resolved to the correct class name
191
-        foreach ($dependencies as $dependency => $load_source) {
192
-            $alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
193
-            if (
194
-                $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
195
-                || ! isset(
196
-                    EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $dependency ],
197
-                    EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ]
198
-                )
199
-            ) {
200
-                unset($dependencies[ $dependency ]);
201
-                $dependencies[ $alias ] = $load_source;
202
-                $registered             = true;
203
-            }
204
-        }
205
-        // now add our two lists of dependencies together.
206
-        // using Union (+=) favours the arrays in precedence from left to right,
207
-        // so $dependencies is NOT overwritten because it is listed first
208
-        // ie: with A = B + C, entries in B take precedence over duplicate entries in C
209
-        // Union is way faster than array_merge() but should be used with caution...
210
-        // especially with numerically indexed arrays
211
-        $dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
212
-        // now we need to ensure that the resulting dependencies
213
-        // array only has the entries that are required for the class
214
-        // so first count how many dependencies were originally registered for the class
215
-        $dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
216
-        // if that count is non-zero (meaning dependencies were already registered)
217
-        EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
218
-            // then truncate the  final array to match that count
219
-            ? array_slice($dependencies, 0, $dependency_count)
220
-            // otherwise just take the incoming array because nothing previously existed
221
-            : $dependencies;
222
-        return $registered
223
-            || count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]) === count($dependencies);
224
-    }
225
-
226
-
227
-    /**
228
-     * @param string          $class_name
229
-     * @param callable|string $loader
230
-     * @param bool            $overwrite
231
-     * @return bool
232
-     * @throws DomainException
233
-     */
234
-    public static function register_class_loader(
235
-        string $class_name,
236
-        $loader = 'load_core',
237
-        bool $overwrite = false
238
-    ): bool {
239
-        return EE_Dependency_Map::$_instance->registerClassLoader($class_name, $loader, $overwrite);
240
-    }
241
-
242
-
243
-    /**
244
-     * @param string         $class_name
245
-     * @param Closure|string $loader
246
-     * @param bool           $overwrite
247
-     * @return bool
248
-     * @throws DomainException
249
-     */
250
-    public function registerClassLoader(string $class_name, $loader = 'load_core', bool $overwrite = false): bool
251
-    {
252
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
253
-            throw new DomainException(
254
-                esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
255
-            );
256
-        }
257
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
258
-        if (
259
-            ! is_callable($loader)
260
-            && (
261
-                strpos($loader, 'load_') !== 0
262
-                || ! method_exists('EE_Registry', $loader)
263
-            )
264
-        ) {
265
-            throw new DomainException(
266
-                sprintf(
267
-                    esc_html__(
268
-                        '"%1$s" is not a valid loader method on EE_Registry.',
269
-                        'event_espresso'
270
-                    ),
271
-                    $loader
272
-                )
273
-            );
274
-        }
275
-        $class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
276
-        if ($overwrite || ! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
277
-            EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
278
-            return true;
279
-        }
280
-        return false;
281
-    }
282
-
283
-
284
-    /**
285
-     * @return array
286
-     */
287
-    public function dependency_map(): array
288
-    {
289
-        return $this->_dependency_map;
290
-    }
291
-
292
-
293
-    /**
294
-     * returns TRUE if dependency map contains a listing for the provided class name
295
-     *
296
-     * @param string $class_name
297
-     * @return boolean
298
-     */
299
-    public function has(string $class_name = ''): bool
300
-    {
301
-        // all legacy models have the same dependencies
302
-        if (strpos($class_name, 'EEM_') === 0) {
303
-            $class_name = 'LEGACY_MODELS';
304
-        }
305
-        return isset($this->_dependency_map[ $class_name ]);
306
-    }
307
-
308
-
309
-    /**
310
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
311
-     *
312
-     * @param string $class_name
313
-     * @param string $dependency
314
-     * @return bool
315
-     */
316
-    public function has_dependency_for_class(string $class_name = '', string $dependency = ''): bool
317
-    {
318
-        // all legacy models have the same dependencies
319
-        if (strpos($class_name, 'EEM_') === 0) {
320
-            $class_name = 'LEGACY_MODELS';
321
-        }
322
-        $dependency = $this->getFqnForAlias($dependency, $class_name);
323
-        return isset($this->_dependency_map[ $class_name ][ $dependency ]);
324
-    }
325
-
326
-
327
-    /**
328
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
329
-     *
330
-     * @param string $class_name
331
-     * @param string $dependency
332
-     * @return int
333
-     */
334
-    public function loading_strategy_for_class_dependency(string $class_name = '', string $dependency = ''): int
335
-    {
336
-        // all legacy models have the same dependencies
337
-        if (strpos($class_name, 'EEM_') === 0) {
338
-            $class_name = 'LEGACY_MODELS';
339
-        }
340
-        $dependency = $this->getFqnForAlias($dependency);
341
-        return $this->has_dependency_for_class($class_name, $dependency)
342
-            ? $this->_dependency_map[ $class_name ][ $dependency ]
343
-            : EE_Dependency_Map::not_registered;
344
-    }
345
-
346
-
347
-    /**
348
-     * @param string $class_name
349
-     * @return string | Closure
350
-     */
351
-    public function class_loader(string $class_name)
352
-    {
353
-        // all legacy models use load_model()
354
-        if (strpos($class_name, 'EEM_') === 0) {
355
-            return 'load_model';
356
-        }
357
-        // EE_CPT_*_Strategy classes like EE_CPT_Event_Strategy, EE_CPT_Venue_Strategy, etc
358
-        // perform strpos() first to avoid loading regex every time we load a class
359
-        if (
360
-            strpos($class_name, 'EE_CPT_') === 0
361
-            && preg_match('/^EE_CPT_([a-zA-Z]+)_Strategy$/', $class_name)
362
-        ) {
363
-            return 'load_core';
364
-        }
365
-        $class_name = $this->getFqnForAlias($class_name);
366
-        return $this->_class_loaders[ $class_name ] ?? '';
367
-    }
368
-
369
-
370
-    /**
371
-     * @return array
372
-     */
373
-    public function class_loaders(): array
374
-    {
375
-        return $this->_class_loaders;
376
-    }
377
-
378
-
379
-    /**
380
-     * adds an alias for a classname
381
-     *
382
-     * @param string $fqcn      the class name that should be used (concrete class to replace interface)
383
-     * @param string $alias     the class name that would be type hinted for (abstract parent or interface)
384
-     * @param string $for_class the class that has the dependency (is type hinting for the interface)
385
-     * @throws InvalidAliasException
386
-     */
387
-    public function add_alias(string $fqcn, string $alias, string $for_class = '')
388
-    {
389
-        $this->class_cache->addAlias($fqcn, $alias, $for_class);
390
-    }
391
-
392
-
393
-    /**
394
-     * Returns TRUE if the provided fully qualified name IS an alias
395
-     * WHY?
396
-     * Because if a class is type hinting for a concretion,
397
-     * then why would we need to find another class to supply it?
398
-     * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
399
-     * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
400
-     * Don't go looking for some substitute.
401
-     * Whereas if a class is type hinting for an interface...
402
-     * then we need to find an actual class to use.
403
-     * So the interface IS the alias for some other FQN,
404
-     * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
405
-     * represents some other class.
406
-     *
407
-     * @param string $fqn
408
-     * @param string $for_class
409
-     * @return bool
410
-     */
411
-    public function isAlias(string $fqn = '', string $for_class = ''): bool
412
-    {
413
-        return $this->class_cache->isAlias($fqn, $for_class);
414
-    }
415
-
416
-
417
-    /**
418
-     * Returns a FQN for provided alias if one exists, otherwise returns the original $alias
419
-     * functions recursively, so that multiple aliases can be used to drill down to a FQN
420
-     *  for example:
421
-     *      if the following two entries were added to the _aliases array:
422
-     *          array(
423
-     *              'interface_alias'           => 'some\namespace\interface'
424
-     *              'some\namespace\interface'  => 'some\namespace\classname'
425
-     *          )
426
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
427
-     *      to load an instance of 'some\namespace\classname'
428
-     *
429
-     * @param string $alias
430
-     * @param string $for_class
431
-     * @return string
432
-     */
433
-    public function getFqnForAlias(string $alias = '', string $for_class = ''): string
434
-    {
435
-        return $this->class_cache->getFqnForAlias($alias, $for_class);
436
-    }
437
-
438
-
439
-    /**
440
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
441
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
442
-     * This is done by using the following class constants:
443
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
444
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
445
-     */
446
-    protected function _register_core_dependencies()
447
-    {
448
-        $this->_dependency_map = [
449
-            'EE_Admin'                                                                                                           => [
450
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
451
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
452
-            ],
453
-            'EE_Maintenance_Mode'                                                                                                => [
454
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
455
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
456
-            ],
457
-            'EE_Request_Handler'                                                                                                 => [
458
-                'EventEspresso\core\services\request\Request'  => EE_Dependency_Map::load_from_cache,
459
-                'EventEspresso\core\services\request\Response' => EE_Dependency_Map::load_from_cache,
460
-            ],
461
-            'EE_System'                                                                                                   => [
462
-                'EventEspresso\core\services\loaders\Loader'                   => EE_Dependency_Map::load_from_cache,
463
-                'EE_Maintenance_Mode'                                          => EE_Dependency_Map::load_from_cache,
464
-                'EE_Registry'                                                  => EE_Dependency_Map::load_from_cache,
465
-                'EventEspresso\core\services\request\Request'                  => EE_Dependency_Map::load_from_cache,
466
-                'EventEspresso\core\services\routing\Router'                   => EE_Dependency_Map::load_from_cache,
467
-                'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
468
-            ],
469
-            'EE_Session'                                                                                                         => [
470
-                'EventEspresso\core\services\cache\TransientCacheStorage'  => EE_Dependency_Map::load_from_cache,
471
-                'EventEspresso\core\domain\values\session\SessionLifespan' => EE_Dependency_Map::load_from_cache,
472
-                'EventEspresso\core\services\request\Request'              => EE_Dependency_Map::load_from_cache,
473
-                'EventEspresso\core\services\session\SessionStartHandler'  => EE_Dependency_Map::load_from_cache,
474
-                'EventEspresso\core\services\encryption\Base64Encoder'     => EE_Dependency_Map::load_from_cache,
475
-            ],
476
-            'EventEspresso\core\services\session\SessionStartHandler'                                                            => [
477
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
478
-            ],
479
-            'EE_Cart'                                                                                                            => [
480
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
481
-            ],
482
-            'EE_Messenger_Collection_Loader'                                                                                     => [
483
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
484
-            ],
485
-            'EE_Message_Type_Collection_Loader'                                                                                  => [
486
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
487
-            ],
488
-            'EE_Message_Resource_Manager'                                                                                        => [
489
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
490
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
491
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
492
-            ],
493
-            'EE_Message_Factory'                                                                                                 => [
494
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
495
-            ],
496
-            'EE_messages'                                                                                                        => [
497
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
498
-            ],
499
-            'EE_Messages_Generator'                                                                                              => [
500
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
501
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
502
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
503
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
504
-            ],
505
-            'EE_Messages_Processor'                                                                                              => [
506
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
507
-            ],
508
-            'EE_Messages_Queue'                                                                                                  => [
509
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
510
-            ],
511
-            'EE_Messages_Template_Defaults'                                                                                      => [
512
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
513
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
514
-            ],
515
-            'EE_Message_To_Generate_From_Request'                                                                                => [
516
-                'EE_Message_Resource_Manager'                 => EE_Dependency_Map::load_from_cache,
517
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
518
-            ],
519
-            'EventEspresso\core\services\commands\CommandBus'                                                                    => [
520
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
521
-            ],
522
-            'EventEspresso\services\commands\CommandHandler'                                                                     => [
523
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
524
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
525
-            ],
526
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                         => [
527
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
528
-            ],
529
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                       => [
530
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
531
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
532
-            ],
533
-            'EventEspresso\core\services\commands\CommandFactory'                                                                => [
534
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
535
-            ],
536
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                         => [
537
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
538
-            ],
539
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                                => [
540
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
541
-            ],
542
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                            => [
543
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
544
-            ],
545
-            'EventEspresso\core\domain\services\commands\registration\CreateRegistrationCommandHandler'                          => [
546
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
547
-            ],
548
-            'EventEspresso\core\domain\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => [
549
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
550
-            ],
551
-            'EventEspresso\core\domain\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => [
552
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
553
-            ],
554
-            'EventEspresso\core\domain\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => [
555
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
556
-            ],
557
-            'EventEspresso\core\domain\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => [
558
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
559
-            ],
560
-            'EventEspresso\core\domain\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => [
561
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
562
-            ],
563
-            'EventEspresso\core\domain\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => [
564
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
565
-            ],
566
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                          => [
567
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
568
-            ],
569
-            'EventEspresso\core\domain\services\commands\attendee\CreateAttendeeCommandHandler'                                  => [
570
-                'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
571
-            ],
572
-            'EventEspresso\core\domain\values\session\SessionLifespan'                                                           => [
573
-                'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
574
-            ],
575
-            'EventEspresso\caffeinated\admin\extend\registration_form\forms\SessionLifespanForm'                                 => [
576
-                'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
577
-                'EE_Registration_Config'                                         => EE_Dependency_Map::load_from_cache,
578
-            ],
579
-            'EventEspresso\caffeinated\admin\extend\registration_form\forms\SessionLifespanFormHandler'                          => [
580
-                'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
581
-                'EE_Config'                                                      => EE_Dependency_Map::load_from_cache,
582
-            ],
583
-            'EventEspresso\core\services\database\TableManager'                                                                  => [
584
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
585
-            ],
586
-            'EE_Data_Migration_Class_Base'                                                                                       => [
587
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
588
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
589
-            ],
590
-            'EE_DMS_Core_4_1_0'                                                                                                  => [
591
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
592
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
593
-            ],
594
-            'EE_DMS_Core_4_2_0'                                                                                                  => [
595
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
596
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
597
-            ],
598
-            'EE_DMS_Core_4_3_0'                                                                                                  => [
599
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
600
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
601
-            ],
602
-            'EE_DMS_Core_4_4_0'                                                                                                  => [
603
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
604
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
605
-            ],
606
-            'EE_DMS_Core_4_5_0'                                                                                                  => [
607
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
608
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
609
-            ],
610
-            'EE_DMS_Core_4_6_0'                                                                                                  => [
611
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
612
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
613
-            ],
614
-            'EE_DMS_Core_4_7_0'                                                                                                  => [
615
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
616
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
617
-            ],
618
-            'EE_DMS_Core_4_8_0'                                                                                                  => [
619
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
620
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
621
-            ],
622
-            'EE_DMS_Core_4_9_0'                                                                                                  => [
623
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
624
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
625
-            ],
626
-            'EE_DMS_Core_4_10_0'                                                                                                 => [
627
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
628
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
629
-                'EE_DMS_Core_4_9_0'                                  => EE_Dependency_Map::load_from_cache,
630
-            ],
631
-            'EE_DMS_Core_5_0_0'                                                                                                  => [
632
-                'EE_DMS_Core_4_10_0'                                 => EE_Dependency_Map::load_from_cache,
633
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
634
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
635
-            ],
636
-            'EventEspresso\core\services\assets\I18nRegistry'                                                                    => [
637
-                'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
638
-            ],
639
-            'EventEspresso\core\services\assets\Registry'                                                                        => [
640
-                'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_from_cache,
641
-                'EventEspresso\core\services\assets\AssetManifest'   => EE_Dependency_Map::load_from_cache,
642
-            ],
643
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                                    => [
644
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
645
-            ],
646
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                                     => [
647
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
648
-            ],
649
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                               => [
650
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
651
-            ],
652
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                       => [
653
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
654
-            ],
655
-            'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                                     => [
656
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
657
-            ],
658
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                               => [
659
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
660
-            ],
661
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                                      => [
662
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
663
-            ],
664
-            'EventEspresso\core\services\cache\BasicCacheManager'                                                                => [
665
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
666
-            ],
667
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                          => [
668
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
669
-            ],
670
-            'EventEspresso\core\domain\services\validation\email\EmailValidationService'                                         => [
671
-                'EE_Registration_Config'                     => EE_Dependency_Map::load_from_cache,
672
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
673
-            ],
674
-            'EventEspresso\core\domain\values\EmailAddress'                                                                      => [
675
-                null,
676
-                'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
677
-            ],
678
-            'EventEspresso\core\services\orm\ModelFieldFactory'                                                                  => [
679
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
680
-            ],
681
-            'LEGACY_MODELS'                                                                                                      => [
682
-                null,
683
-                'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
684
-            ],
685
-            'EE_Module_Request_Router'                                                                                           => [
686
-                'EventEspresso\core\services\request\Request'             => EE_Dependency_Map::load_from_cache,
687
-                'EventEspresso\core\services\modules\ModuleRoutesManager' => EE_Dependency_Map::load_from_cache,
688
-            ],
689
-            'EE_Registration_Processor'                                                                                          => [
690
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
691
-            ],
692
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'                                             => [
693
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
694
-                'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
695
-            ],
696
-            'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha'                                           => [
697
-                'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
698
-                'EE_Session'             => EE_Dependency_Map::load_from_cache,
699
-            ],
700
-            'EventEspresso\modules\ticket_selector\DisplayTicketSelector'                                                        => [
701
-                'EventEspresso\core\domain\entities\users\CurrentUser' => EE_Dependency_Map::load_from_cache,
702
-                'EventEspresso\core\services\request\Request'          => EE_Dependency_Map::load_from_cache,
703
-                'EE_Ticket_Selector_Config'                            => EE_Dependency_Map::load_from_cache,
704
-            ],
705
-            'EventEspresso\modules\ticket_selector\ProcessTicketSelector'                                                        => [
706
-                'EE_Core_Config'                                                          => EE_Dependency_Map::load_from_cache,
707
-                'EventEspresso\core\services\request\Request'                             => EE_Dependency_Map::load_from_cache,
708
-                'EE_Session'                                                              => EE_Dependency_Map::load_from_cache,
709
-                'EEM_Ticket'                                                              => EE_Dependency_Map::load_from_cache,
710
-                'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
711
-            ],
712
-            'EventEspresso\modules\ticket_selector\ProcessTicketSelectorPostData'                                                => [
713
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
714
-                'EEM_Event'                                   => EE_Dependency_Map::load_from_cache,
715
-            ],
716
-            'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker'                                            => [
717
-                'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
718
-            ],
719
-            'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'                                     => [
720
-                'EE_Core_Config'                             => EE_Dependency_Map::load_from_cache,
721
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
722
-            ],
723
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'                                       => [
724
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
725
-            ],
726
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'                                      => [
727
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
728
-            ],
729
-            'EE_CPT_Strategy'                                                                                                    => [
730
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
731
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
732
-            ],
733
-            'EventEspresso\core\services\loaders\ObjectIdentifier'                                                               => [
734
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
735
-            ],
736
-            'EventEspresso\core\CPTs\CptQueryModifier'                                                                           => [
737
-                null,
738
-                null,
739
-                null,
740
-                'EventEspresso\core\services\request\CurrentPage' => EE_Dependency_Map::load_from_cache,
741
-                'EventEspresso\core\services\request\Request'     => EE_Dependency_Map::load_from_cache,
742
-                'EventEspresso\core\services\loaders\Loader'      => EE_Dependency_Map::load_from_cache,
743
-            ],
744
-            'EventEspresso\core\services\dependencies\DependencyResolver'                                                        => [
745
-                'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
746
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
747
-                'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
748
-            ],
749
-            'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver'                                      => [
750
-                'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
751
-                'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
752
-                'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
753
-            ],
754
-            'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'                                                 => [
755
-                'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver' => EE_Dependency_Map::load_from_cache,
756
-                'EventEspresso\core\services\loaders\Loader'                                    => EE_Dependency_Map::load_from_cache,
757
-            ],
758
-            'EventEspresso\core\services\routing\RouteMatchSpecificationManager'                                                 => [
759
-                'EventEspresso\core\services\routing\RouteMatchSpecificationCollection' => EE_Dependency_Map::load_from_cache,
760
-                'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'    => EE_Dependency_Map::load_from_cache,
761
-            ],
762
-            'EventEspresso\core\services\request\files\FilesDataHandler'                                                         => [
763
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
764
-            ],
765
-            'EventEspresso\core\libraries\batch\BatchRequestProcessor'                                                           => [
766
-                'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
767
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
768
-            ],
769
-            'EventEspresso\core\domain\services\converters\RestApiSpoofer'                                                       => [
770
-                'WP_REST_Server'                                               => EE_Dependency_Map::load_from_cache,
771
-                'EED_Core_Rest_Api'                                            => EE_Dependency_Map::load_from_cache,
772
-                'EventEspresso\core\libraries\rest_api\controllers\model\Read' => EE_Dependency_Map::load_from_cache,
773
-                null,
774
-            ],
775
-            'EventEspresso\core\services\routing\RouteHandler'                                                                   => [
776
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
777
-                'EventEspresso\core\services\json\JsonDataNodeHandler'                => EE_Dependency_Map::load_from_cache,
778
-                'EventEspresso\core\services\loaders\Loader'                          => EE_Dependency_Map::load_from_cache,
779
-                'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
780
-                'EventEspresso\core\services\routing\RouteCollection'                 => EE_Dependency_Map::load_from_cache,
781
-            ],
782
-            'EventEspresso\core\services\json\JsonDataNodeHandler'                                                               => [
783
-                'EventEspresso\core\services\json\JsonDataNodeValidator' => EE_Dependency_Map::load_from_cache,
784
-            ],
785
-            'EventEspresso\core\services\routing\Router'                                                                         => [
786
-                'EE_Dependency_Map'                                => EE_Dependency_Map::load_from_cache,
787
-                'EventEspresso\core\services\loaders\Loader'       => EE_Dependency_Map::load_from_cache,
788
-                'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
789
-            ],
790
-            'EventEspresso\core\services\assets\AssetManifest'                                                                   => [
791
-                'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
792
-            ],
793
-            'EventEspresso\core\services\assets\AssetManifestFactory'                                                            => [
794
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
795
-            ],
796
-            'EventEspresso\core\services\assets\BaristaFactory'                                                                  => [
797
-                'EventEspresso\core\services\assets\AssetManifestFactory' => EE_Dependency_Map::load_from_cache,
798
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
799
-            ],
800
-            'EventEspresso\core\domain\services\capabilities\FeatureFlagsConfig' => [
801
-                'EventEspresso\core\domain\Domain'                                    => EE_Dependency_Map::load_from_cache,
802
-                'EventEspresso\core\services\json\JsonDataHandler'                    => EE_Dependency_Map::load_from_cache,
803
-            ],
804
-            'EventEspresso\core\domain\services\capabilities\FeatureFlags'       => [
805
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
806
-                'EventEspresso\core\domain\services\capabilities\FeatureFlagsConfig'  => EE_Dependency_Map::load_from_cache,
807
-            ],
808
-            'EventEspresso\core\services\addon\AddonManager'                                                                     => [
809
-                'EventEspresso\core\services\addon\AddonCollection'              => EE_Dependency_Map::load_from_cache,
810
-                'EE_Dependency_Map'                                              => EE_Dependency_Map::load_from_cache,
811
-                'EventEspresso\core\services\addon\api\IncompatibleAddonHandler' => EE_Dependency_Map::load_from_cache,
812
-                'EventEspresso\core\services\addon\api\v1\RegisterAddon'         => EE_Dependency_Map::load_from_cache,
813
-                'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'  => EE_Dependency_Map::load_from_cache,
814
-            ],
815
-            'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'                                                      => [
816
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
817
-            ],
818
-            'EventEspresso\core\libraries\batch\JobHandlers\ExecuteBatchDeletion'                                                => [
819
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
820
-            ],
821
-            'EventEspresso\core\libraries\batch\JobHandlers\PreviewEventDeletion'                                                => [
822
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
823
-            ],
824
-            'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion'                                               => [
825
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
826
-                'EEM_Event'                                                   => EE_Dependency_Map::load_from_cache,
827
-                'EEM_Datetime'                                                => EE_Dependency_Map::load_from_cache,
828
-                'EEM_Registration'                                            => EE_Dependency_Map::load_from_cache,
829
-            ],
830
-            'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion'                                               => [
831
-                'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
832
-            ],
833
-            'EventEspresso\core\services\request\CurrentPage'                                                                    => [
834
-                'EE_CPT_Strategy'                             => EE_Dependency_Map::load_from_cache,
835
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
836
-            ],
837
-            'EventEspresso\core\services\shortcodes\LegacyShortcodesManager'                                                     => [
838
-                'EE_Registry'                                     => EE_Dependency_Map::load_from_cache,
839
-                'EventEspresso\core\services\request\CurrentPage' => EE_Dependency_Map::load_from_cache,
840
-            ],
841
-            'EventEspresso\core\services\shortcodes\ShortcodesManager'                                                           => [
842
-                'EventEspresso\core\services\shortcodes\LegacyShortcodesManager' => EE_Dependency_Map::load_from_cache,
843
-                'EventEspresso\core\services\request\CurrentPage'                => EE_Dependency_Map::load_from_cache,
844
-            ],
845
-            'EventEspresso\core\domain\entities\users\CurrentUser'                                                               => [
846
-                'EventEspresso\core\domain\entities\users\EventManagers' => EE_Dependency_Map::load_from_cache,
847
-            ],
848
-            'EventEspresso\core\services\form\meta\InputTypes'                                                                   => [
849
-                'EventEspresso\core\services\form\meta\inputs\Block'    => EE_Dependency_Map::load_from_cache,
850
-                'EventEspresso\core\services\form\meta\inputs\Button'   => EE_Dependency_Map::load_from_cache,
851
-                'EventEspresso\core\services\form\meta\inputs\DateTime' => EE_Dependency_Map::load_from_cache,
852
-                'EventEspresso\core\services\form\meta\inputs\Input'    => EE_Dependency_Map::load_from_cache,
853
-                'EventEspresso\core\services\form\meta\inputs\Number'   => EE_Dependency_Map::load_from_cache,
854
-                'EventEspresso\core\services\form\meta\inputs\Phone'    => EE_Dependency_Map::load_from_cache,
855
-                'EventEspresso\core\services\form\meta\inputs\Select'   => EE_Dependency_Map::load_from_cache,
856
-                'EventEspresso\core\services\form\meta\inputs\Text'     => EE_Dependency_Map::load_from_cache,
857
-            ],
858
-            'EventEspresso\core\domain\services\registration\form\v1\RegFormDependencyHandler'                                   => [
859
-                'EE_Dependency_Map' => EE_Dependency_Map::load_from_cache,
860
-            ],
861
-            'EventEspresso\core\services\calculators\LineItemCalculator'                                                         => [
862
-                'EventEspresso\core\services\helpers\DecimalValues' => EE_Dependency_Map::load_from_cache,
863
-            ],
864
-            'EventEspresso\core\services\helpers\DecimalValues'                                                                  => [
865
-                'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
866
-            ],
867
-            'EE_Brewing_Regular'                                                                                                 => [
868
-                'EE_Dependency_Map'                                  => EE_Dependency_Map::load_from_cache,
869
-                'EventEspresso\core\services\loaders\Loader'         => EE_Dependency_Map::load_from_cache,
870
-                'EventEspresso\core\services\routing\RouteHandler'   => EE_Dependency_Map::load_from_cache,
871
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
872
-            ],
873
-            'EventEspresso\core\domain\services\messages\MessageTemplateRequestData'                                             => [
874
-                'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
875
-            ],
876
-            'EventEspresso\core\domain\services\messages\MessageTemplateValidator'                                               => [
877
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
878
-            ],
879
-            'EventEspresso\core\domain\services\messages\MessageTemplateManager'                                                 => [
880
-                'EEM_Message_Template'                                                   => EE_Dependency_Map::load_from_cache,
881
-                'EEM_Message_Template_Group'                                             => EE_Dependency_Map::load_from_cache,
882
-                'EventEspresso\core\domain\services\messages\MessageTemplateRequestData' => EE_Dependency_Map::load_from_cache,
883
-                'EventEspresso\core\domain\services\messages\MessageTemplateValidator'   => EE_Dependency_Map::load_from_cache,
884
-                'EventEspresso\core\services\request\Request'                            => EE_Dependency_Map::load_from_cache,
885
-            ],
886
-            'EventEspresso\core\services\request\sanitizers\RequestSanitizer'                                                    => [
887
-                'EventEspresso\core\domain\services\validation\email\strategies\Basic' => EE_Dependency_Map::load_from_cache,
888
-            ],
889
-            'EE_CPT_Event_Strategy'                                                    => [
890
-                null,
891
-                null,
892
-                'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
893
-            ],
894
-            'EventEspresso\core\services\licensing\LicenseManager' => [
895
-                'EventEspresso\core\services\licensing\LicenseAPI'              => EE_Dependency_Map::load_from_cache,
896
-                'EventEspresso\core\services\licensing\LicenseKeyData'          => EE_Dependency_Map::load_from_cache,
897
-                'EventEspresso\core\services\licensing\PluginLicenseCollection' => EE_Dependency_Map::load_from_cache,
898
-            ],
899
-            'EventEspresso\core\domain\services\licensing\LicenseKeyFormInput'                                                    => [
900
-                'EventEspresso\core\services\licensing\PluginLicense'  => EE_Dependency_Map::not_registered,
901
-                'EventEspresso\core\services\licensing\LicenseManager' => EE_Dependency_Map::load_from_cache,
902
-            ],
903
-            'EventEspresso\core\services\payments\IpnHandler' => [
904
-                'EEM_Payment_Method'                                    => EE_Dependency_Map::not_registered,
905
-                'EEM_Transaction'                                       => EE_Dependency_Map::load_from_cache,
906
-                'EE_Core_Config'                                        => EE_Dependency_Map::load_from_cache,
907
-                'EE_Organization_Config'                                => EE_Dependency_Map::load_from_cache,
908
-                'EventEspresso\core\services\payments\PaymentProcessor' => EE_Dependency_Map::load_from_cache,
909
-            ],
910
-            'EventEspresso\core\services\payments\PaymentProcessor' => [
911
-                'EEM_Payment_Method'                                           => EE_Dependency_Map::not_registered,
912
-                'EEM_Transaction'                                              => EE_Dependency_Map::load_from_cache,
913
-                'EE_Organization_Config'                                       => EE_Dependency_Map::load_from_cache,
914
-                'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
915
-                'EventEspresso\core\services\payments\PaymentProcessorFees'    => EE_Dependency_Map::load_from_cache,
916
-                'EventEspresso\core\services\payments\PostPaymentProcessor'    => EE_Dependency_Map::load_from_cache,
917
-                'EventEspresso\core\services\payments\RegistrationPayments'    => EE_Dependency_Map::load_from_cache,
918
-            ],
919
-            'EventEspresso\core\services\payments\PostPaymentProcessor' => [
920
-                'EE_Transaction_Processor' => EE_Dependency_Map::load_from_cache,
921
-            ],
922
-            'EventEspresso\core\services\payments\PaymentProcessorFees' => [
923
-                'EventEspresso\core\domain\values\gateways\GracePeriod'    => EE_Dependency_Map::load_from_cache,
924
-                'EventEspresso\core\domain\services\licensing\LicenseData' => EE_Dependency_Map::load_from_cache,
925
-            ],
926
-            'EventEspresso\core\domain\services\licensing\LicenseData'  => [
927
-                'EventEspresso\core\domain\Domain'                             => EE_Dependency_Map::load_from_cache,
928
-                'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
929
-            ],
930
-            'EventEspresso\core\domain\services\licensing\LicenseDataEDD' => [
931
-                'EventEspresso\core\services\licensing\LicenseKeyData' => EE_Dependency_Map::load_from_cache,
932
-            ],
933
-            'EventEspresso\core\domain\services\licensing\LicenseDataPue' => [
934
-                'EE_Network_Core_Config' => EE_Dependency_Map::load_from_cache,
935
-            ],
936
-            'EventEspresso\core\services\addon\api\DependencyHandlers' => [
937
-                'EE_Dependency_Map' => EE_Dependency_Map::load_from_cache,
938
-            ],
939
-            'EventEspresso\core\services\addon\api\AddonRoutes' => [
940
-                'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
941
-            ],
942
-        ];
943
-    }
944
-
945
-
946
-    /**
947
-     * Registers how core classes are loaded.
948
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
949
-     *        'EE_Request_Handler' => 'load_core'
950
-     *        'EE_Messages_Queue'  => 'load_lib'
951
-     *        'EEH_Debug_Tools'    => 'load_helper'
952
-     * or, if greater control is required, by providing a custom closure. For example:
953
-     *        'Some_Class' => function () {
954
-     *            return new Some_Class();
955
-     *        },
956
-     * This is required for instantiating dependencies
957
-     * where an interface has been type hinted in a class constructor. For example:
958
-     *        'Required_Interface' => function () {
959
-     *            return new A_Class_That_Implements_Required_Interface();
960
-     *        },
961
-     */
962
-    protected function _register_core_class_loaders()
963
-    {
964
-        $this->_class_loaders = [
965
-            // load_core
966
-            'EE_Dependency_Map'                            => function () {
967
-                return $this;
968
-            },
969
-            'EE_Capabilities'                              => 'load_core',
970
-            'EE_Encryption'                                => 'load_core',
971
-            'EE_Front_Controller'                          => 'load_core',
972
-            'EE_Module_Request_Router'                     => 'load_core',
973
-            'EE_Registry'                                  => 'load_core',
974
-            'EE_Request'                                   => function () {
975
-                return $this->legacy_request;
976
-            },
977
-            'EventEspresso\core\services\request\Request'  => function () {
978
-                return $this->request;
979
-            },
980
-            'EventEspresso\core\services\request\Response' => function () {
981
-                return $this->response;
982
-            },
983
-            'EE_Base'                                      => 'load_core',
984
-            'EE_Request_Handler'                           => 'load_core',
985
-            'EE_Session'                                   => 'load_core',
986
-            'EE_Cron_Tasks'                                => 'load_core',
987
-            'EE_System'                                    => 'load_core',
988
-            'EE_Maintenance_Mode'                          => 'load_core',
989
-            'EE_Register_CPTs'                             => 'load_core',
990
-            'EE_Admin'                                     => 'load_core',
991
-            'EE_CPT_Strategy'                              => 'load_core',
992
-            // load_class
993
-            'EE_Registration_Processor'                    => 'load_class',
994
-            'EE_Transaction_Payments'                      => 'load_class',
995
-            'EE_Transaction_Processor'                     => 'load_class',
996
-            // load_lib
997
-            'EE_Message_Resource_Manager'                  => 'load_lib',
998
-            'EE_Message_Type_Collection'                   => 'load_lib',
999
-            'EE_Message_Type_Collection_Loader'            => 'load_lib',
1000
-            'EE_Messenger_Collection'                      => 'load_lib',
1001
-            'EE_Messenger_Collection_Loader'               => 'load_lib',
1002
-            'EE_Messages_Processor'                        => 'load_lib',
1003
-            'EE_Message_Repository'                        => 'load_lib',
1004
-            'EE_Messages_Queue'                            => 'load_lib',
1005
-            'EE_Messages_Data_Handler_Collection'          => 'load_lib',
1006
-            'EE_Message_Template_Group_Collection'         => 'load_lib',
1007
-            'EE_Payment_Method_Manager'                    => 'load_lib',
1008
-            'EE_Payment_Processor'                         => 'load_core',
1009
-            'EE_DMS_Core_4_1_0'                            => 'load_dms',
1010
-            'EE_DMS_Core_4_2_0'                            => 'load_dms',
1011
-            'EE_DMS_Core_4_3_0'                            => 'load_dms',
1012
-            'EE_DMS_Core_4_5_0'                            => 'load_dms',
1013
-            'EE_DMS_Core_4_6_0'                            => 'load_dms',
1014
-            'EE_DMS_Core_4_7_0'                            => 'load_dms',
1015
-            'EE_DMS_Core_4_8_0'                            => 'load_dms',
1016
-            'EE_DMS_Core_4_9_0'                            => 'load_dms',
1017
-            'EE_DMS_Core_4_10_0'                           => 'load_dms',
1018
-            'EE_DMS_Core_5_0_0'                            => 'load_dms',
1019
-            'EE_Messages_Generator'                        => static function () {
1020
-                return EE_Registry::instance()->load_lib(
1021
-                    'Messages_Generator',
1022
-                    [],
1023
-                    false,
1024
-                    false
1025
-                );
1026
-            },
1027
-            'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
1028
-                return EE_Registry::instance()->load_lib(
1029
-                    'Messages_Template_Defaults',
1030
-                    $arguments,
1031
-                    false,
1032
-                    false
1033
-                );
1034
-            },
1035
-            // load_helper
1036
-            'EEH_Parse_Shortcodes'                         => static function () {
1037
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
1038
-                    return new EEH_Parse_Shortcodes();
1039
-                }
1040
-                return null;
1041
-            },
1042
-            'EE_Template_Config'                           => static function () {
1043
-                return EE_Config::instance()->template_settings;
1044
-            },
1045
-            'EE_Currency_Config'                           => static function () {
1046
-                return EE_Currency_Config::getCurrencyConfig();
1047
-            },
1048
-            'EE_Registration_Config'                       => static function () {
1049
-                return EE_Config::instance()->registration;
1050
-            },
1051
-            'EE_Core_Config'                               => static function () {
1052
-                return EE_Config::instance()->core;
1053
-            },
1054
-            'EventEspresso\core\services\loaders\Loader'   => static function () {
1055
-                return LoaderFactory::getLoader();
1056
-            },
1057
-            'EE_Network_Config'                            => static function () {
1058
-                return EE_Network_Config::instance();
1059
-            },
1060
-            'EE_Config'                                    => static function () {
1061
-                return EE_Config::instance();
1062
-            },
1063
-            'EventEspresso\core\domain\Domain'             => static function () {
1064
-                return DomainFactory::getEventEspressoCoreDomain();
1065
-            },
1066
-            'EE_Admin_Config'                              => static function () {
1067
-                return EE_Config::instance()->admin;
1068
-            },
1069
-            'EE_Organization_Config'                       => static function () {
1070
-                return EE_Config::instance()->organization;
1071
-            },
1072
-            'EE_Network_Core_Config'                       => static function () {
1073
-                return EE_Network_Config::instance()->core;
1074
-            },
1075
-            'EE_Environment_Config'                        => static function () {
1076
-                return EE_Config::instance()->environment;
1077
-            },
1078
-            'EED_Core_Rest_Api'                            => static function () {
1079
-                return EED_Core_Rest_Api::instance();
1080
-            },
1081
-            'WP_REST_Server'                               => static function () {
1082
-                return rest_get_server();
1083
-            },
1084
-            'EventEspresso\core\Psr4Autoloader'            => static function () {
1085
-                return EE_Psr4AutoloaderInit::psr4_loader();
1086
-            },
1087
-            'EE_Ticket_Selector_Config'                    => function () {
1088
-                return EE_Config::instance()->template_settings->EED_Ticket_Selector;
1089
-            },
1090
-        ];
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     * can be used for supplying alternate names for classes,
1096
-     * or for connecting interface names to instantiable classes
1097
-     *
1098
-     * @throws InvalidAliasException
1099
-     */
1100
-    protected function _register_core_aliases()
1101
-    {
1102
-        $aliases = [
1103
-            'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
1104
-            'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
1105
-            'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
1106
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
1107
-            'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
1108
-            'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
1109
-            'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
1110
-            'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
1111
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
1112
-            'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
1113
-            'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\domain\services\commands\registration\CreateRegistrationCommand',
1114
-            'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\domain\services\commands\registration\CopyRegistrationDetailsCommand',
1115
-            'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\domain\services\commands\registration\CopyRegistrationPaymentsCommand',
1116
-            'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\domain\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
1117
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\domain\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
1118
-            'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\domain\services\commands\ticket\CreateTicketLineItemCommand',
1119
-            'CreateTransactionCommandHandler'                                              => 'EventEspresso\core\domain\services\commands\transaction\CreateTransactionCommandHandler',
1120
-            'CreateAttendeeCommandHandler'                                                 => 'EventEspresso\core\domain\services\commands\attendee\CreateAttendeeCommandHandler',
1121
-            'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
1122
-            'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
1123
-            'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
1124
-            'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
1125
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
1126
-            'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
1127
-            'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
1128
-            'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
1129
-            'CommandFactoryInterface'                                                      => 'EventEspresso\core\services\commands\CommandFactoryInterface',
1130
-            'EventEspresso\core\services\commands\CommandFactoryInterface'                 => 'EventEspresso\core\services\commands\CommandFactory',
1131
-            'EmailValidatorInterface'                                                      => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
1132
-            'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface'  => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
1133
-            'NoticeConverterInterface'                                                     => 'EventEspresso\core\services\notices\NoticeConverterInterface',
1134
-            'EventEspresso\core\services\notices\NoticeConverterInterface'                 => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
1135
-            'NoticesContainerInterface'                                                    => 'EventEspresso\core\services\notices\NoticesContainerInterface',
1136
-            'EventEspresso\core\services\notices\NoticesContainerInterface'                => 'EventEspresso\core\services\notices\NoticesContainer',
1137
-            'EventEspresso\core\services\request\RequestInterface'                         => 'EventEspresso\core\services\request\Request',
1138
-            'EventEspresso\core\services\request\ResponseInterface'                        => 'EventEspresso\core\services\request\Response',
1139
-            'EventEspresso\core\domain\DomainInterface'                                    => 'EventEspresso\core\domain\Domain',
1140
-            'Registration_Processor'                                                       => 'EE_Registration_Processor',
1141
-            'EventEspresso\core\services\assets\AssetManifestInterface'                    => 'EventEspresso\core\services\assets\AssetManifest',
1142
-        ];
1143
-        foreach ($aliases as $alias => $fqn) {
1144
-            if (is_array($fqn)) {
1145
-                foreach ($fqn as $class => $for_class) {
1146
-                    $this->class_cache->addAlias($class, $alias, $for_class);
1147
-                }
1148
-                continue;
1149
-            }
1150
-            $this->class_cache->addAlias($fqn, $alias);
1151
-        }
1152
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1153
-            $this->class_cache->addAlias(
1154
-                'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
1155
-                'EventEspresso\core\services\notices\NoticeConverterInterface'
1156
-            );
1157
-        }
1158
-    }
1159
-
1160
-
1161
-    public function debug($for_class = '')
1162
-    {
1163
-        if (method_exists($this->class_cache, 'debug')) {
1164
-            $this->class_cache->debug($for_class);
1165
-        }
1166
-    }
1167
-
1168
-
1169
-    /**
1170
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
1171
-     * request Primarily used by unit tests.
1172
-     */
1173
-    public function reset()
1174
-    {
1175
-        $this->_register_core_class_loaders();
1176
-        $this->_register_core_dependencies();
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * PLZ NOTE: a better name for this method would be is_alias()
1182
-     * because it returns TRUE if the provided fully qualified name IS an alias
1183
-     * WHY?
1184
-     * Because if a class is type hinting for a concretion,
1185
-     * then why would we need to find another class to supply it?
1186
-     * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
1187
-     * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
1188
-     * Don't go looking for some substitute.
1189
-     * Whereas if a class is type hinting for an interface...
1190
-     * then we need to find an actual class to use.
1191
-     * So the interface IS the alias for some other FQN,
1192
-     * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
1193
-     * represents some other class.
1194
-     *
1195
-     * @param string $fqn
1196
-     * @param string $for_class
1197
-     * @return bool
1198
-     * @deprecated 4.9.62.p
1199
-     */
1200
-    public function has_alias(string $fqn = '', string $for_class = ''): bool
1201
-    {
1202
-        return $this->isAlias($fqn, $for_class);
1203
-    }
1204
-
1205
-
1206
-    /**
1207
-     * PLZ NOTE: a better name for this method would be get_fqn_for_alias()
1208
-     * because it returns a FQN for provided alias if one exists, otherwise returns the original $alias
1209
-     * functions recursively, so that multiple aliases can be used to drill down to a FQN
1210
-     *  for example:
1211
-     *      if the following two entries were added to the _aliases array:
1212
-     *          array(
1213
-     *              'interface_alias'           => 'some\namespace\interface'
1214
-     *              'some\namespace\interface'  => 'some\namespace\classname'
1215
-     *          )
1216
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
1217
-     *      to load an instance of 'some\namespace\classname'
1218
-     *
1219
-     * @param string $alias
1220
-     * @param string $for_class
1221
-     * @return string
1222
-     * @deprecated 4.9.62.p
1223
-     */
1224
-    public function get_alias(string $alias = '', string $for_class = ''): string
1225
-    {
1226
-        return $this->getFqnForAlias($alias, $for_class);
1227
-    }
23
+	/**
24
+	 * This means that the requested class dependency is not present in the dependency map
25
+	 */
26
+	const not_registered = 0;
27
+
28
+	/**
29
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
30
+	 */
31
+	const load_new_object = 1;
32
+
33
+	/**
34
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
35
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
36
+	 */
37
+	const load_from_cache = 2;
38
+
39
+	/**
40
+	 * When registering a dependency,
41
+	 * this indicates to keep any existing dependencies that already exist,
42
+	 * and simply discard any new dependencies declared in the incoming data
43
+	 */
44
+	const KEEP_EXISTING_DEPENDENCIES = 0;
45
+
46
+	/**
47
+	 * When registering a dependency,
48
+	 * this indicates to overwrite any existing dependencies that already exist using the incoming data
49
+	 */
50
+	const OVERWRITE_DEPENDENCIES = 1;
51
+
52
+	protected static ?EE_Dependency_Map $_instance = null;
53
+
54
+	private ClassInterfaceCache $class_cache;
55
+
56
+	protected ?RequestInterface $request = null;
57
+
58
+	protected ?LegacyRequestInterface $legacy_request = null;
59
+
60
+	protected ?ResponseInterface $response = null;
61
+
62
+	protected ?LoaderInterface $loader = null;
63
+
64
+	protected array $_dependency_map = [];
65
+
66
+	protected array $_class_loaders = [];
67
+
68
+
69
+	/**
70
+	 * EE_Dependency_Map constructor.
71
+	 *
72
+	 * @param ClassInterfaceCache $class_cache
73
+	 */
74
+	protected function __construct(ClassInterfaceCache $class_cache)
75
+	{
76
+		$this->class_cache = $class_cache;
77
+		do_action('EE_Dependency_Map____construct', $this);
78
+	}
79
+
80
+
81
+	/**
82
+	 * @return void
83
+	 * @throws InvalidAliasException
84
+	 */
85
+	public function initialize()
86
+	{
87
+		$this->_register_core_dependencies();
88
+		$this->_register_core_class_loaders();
89
+		$this->_register_core_aliases();
90
+	}
91
+
92
+
93
+	/**
94
+	 * @singleton method used to instantiate class object
95
+	 * @param ClassInterfaceCache|null $class_cache
96
+	 * @return EE_Dependency_Map
97
+	 */
98
+	public static function instance(ClassInterfaceCache $class_cache = null): EE_Dependency_Map
99
+	{
100
+		// check if class object is instantiated, and instantiated properly
101
+		if (
102
+			! EE_Dependency_Map::$_instance instanceof EE_Dependency_Map
103
+			&& $class_cache instanceof ClassInterfaceCache
104
+		) {
105
+			EE_Dependency_Map::$_instance = new EE_Dependency_Map($class_cache);
106
+		}
107
+		return EE_Dependency_Map::$_instance;
108
+	}
109
+
110
+
111
+	/**
112
+	 * @param RequestInterface $request
113
+	 */
114
+	public function setRequest(RequestInterface $request)
115
+	{
116
+		$this->request = $request;
117
+	}
118
+
119
+
120
+	/**
121
+	 * @param LegacyRequestInterface $legacy_request
122
+	 */
123
+	public function setLegacyRequest(LegacyRequestInterface $legacy_request)
124
+	{
125
+		$this->legacy_request = $legacy_request;
126
+	}
127
+
128
+
129
+	/**
130
+	 * @param ResponseInterface $response
131
+	 */
132
+	public function setResponse(ResponseInterface $response)
133
+	{
134
+		$this->response = $response;
135
+	}
136
+
137
+
138
+	/**
139
+	 * @param LoaderInterface $loader
140
+	 */
141
+	public function setLoader(LoaderInterface $loader)
142
+	{
143
+		$this->loader = $loader;
144
+	}
145
+
146
+
147
+	/**
148
+	 * @param string $class
149
+	 * @param array  $dependencies
150
+	 * @param int    $overwrite
151
+	 * @return bool
152
+	 */
153
+	public static function register_dependencies(
154
+		string $class,
155
+		array $dependencies,
156
+		int $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
157
+	): bool {
158
+		return EE_Dependency_Map::$_instance->registerDependencies($class, $dependencies, $overwrite);
159
+	}
160
+
161
+
162
+	/**
163
+	 * Assigns an array of class names and corresponding load sources (new or cached)
164
+	 * to the class specified by the first parameter.
165
+	 * IMPORTANT !!!
166
+	 * The order of elements in the incoming $dependencies array MUST match
167
+	 * the order of the constructor parameters for the class in question.
168
+	 * This is especially important when overriding any existing dependencies that are registered.
169
+	 * the third parameter controls whether any duplicate dependencies are overwritten or not.
170
+	 *
171
+	 * @param string $class
172
+	 * @param array  $dependencies
173
+	 * @param int    $overwrite
174
+	 * @return bool
175
+	 */
176
+	public function registerDependencies(
177
+		string $class,
178
+		array $dependencies,
179
+		int $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
180
+	): bool {
181
+		if (empty($dependencies)) {
182
+			return false;
183
+		}
184
+		$class      = trim($class, '\\');
185
+		$registered = false;
186
+		if (empty(EE_Dependency_Map::$_instance->_dependency_map[ $class ])) {
187
+			EE_Dependency_Map::$_instance->_dependency_map[ $class ] = [];
188
+		}
189
+		// we need to make sure that any aliases used when registering a dependency
190
+		// get resolved to the correct class name
191
+		foreach ($dependencies as $dependency => $load_source) {
192
+			$alias = EE_Dependency_Map::$_instance->getFqnForAlias($dependency);
193
+			if (
194
+				$overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
195
+				|| ! isset(
196
+					EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $dependency ],
197
+					EE_Dependency_Map::$_instance->_dependency_map[ $class ][ $alias ]
198
+				)
199
+			) {
200
+				unset($dependencies[ $dependency ]);
201
+				$dependencies[ $alias ] = $load_source;
202
+				$registered             = true;
203
+			}
204
+		}
205
+		// now add our two lists of dependencies together.
206
+		// using Union (+=) favours the arrays in precedence from left to right,
207
+		// so $dependencies is NOT overwritten because it is listed first
208
+		// ie: with A = B + C, entries in B take precedence over duplicate entries in C
209
+		// Union is way faster than array_merge() but should be used with caution...
210
+		// especially with numerically indexed arrays
211
+		$dependencies += EE_Dependency_Map::$_instance->_dependency_map[ $class ];
212
+		// now we need to ensure that the resulting dependencies
213
+		// array only has the entries that are required for the class
214
+		// so first count how many dependencies were originally registered for the class
215
+		$dependency_count = count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]);
216
+		// if that count is non-zero (meaning dependencies were already registered)
217
+		EE_Dependency_Map::$_instance->_dependency_map[ $class ] = $dependency_count
218
+			// then truncate the  final array to match that count
219
+			? array_slice($dependencies, 0, $dependency_count)
220
+			// otherwise just take the incoming array because nothing previously existed
221
+			: $dependencies;
222
+		return $registered
223
+			|| count(EE_Dependency_Map::$_instance->_dependency_map[ $class ]) === count($dependencies);
224
+	}
225
+
226
+
227
+	/**
228
+	 * @param string          $class_name
229
+	 * @param callable|string $loader
230
+	 * @param bool            $overwrite
231
+	 * @return bool
232
+	 * @throws DomainException
233
+	 */
234
+	public static function register_class_loader(
235
+		string $class_name,
236
+		$loader = 'load_core',
237
+		bool $overwrite = false
238
+	): bool {
239
+		return EE_Dependency_Map::$_instance->registerClassLoader($class_name, $loader, $overwrite);
240
+	}
241
+
242
+
243
+	/**
244
+	 * @param string         $class_name
245
+	 * @param Closure|string $loader
246
+	 * @param bool           $overwrite
247
+	 * @return bool
248
+	 * @throws DomainException
249
+	 */
250
+	public function registerClassLoader(string $class_name, $loader = 'load_core', bool $overwrite = false): bool
251
+	{
252
+		if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
253
+			throw new DomainException(
254
+				esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
255
+			);
256
+		}
257
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
258
+		if (
259
+			! is_callable($loader)
260
+			&& (
261
+				strpos($loader, 'load_') !== 0
262
+				|| ! method_exists('EE_Registry', $loader)
263
+			)
264
+		) {
265
+			throw new DomainException(
266
+				sprintf(
267
+					esc_html__(
268
+						'"%1$s" is not a valid loader method on EE_Registry.',
269
+						'event_espresso'
270
+					),
271
+					$loader
272
+				)
273
+			);
274
+		}
275
+		$class_name = EE_Dependency_Map::$_instance->getFqnForAlias($class_name);
276
+		if ($overwrite || ! isset(EE_Dependency_Map::$_instance->_class_loaders[ $class_name ])) {
277
+			EE_Dependency_Map::$_instance->_class_loaders[ $class_name ] = $loader;
278
+			return true;
279
+		}
280
+		return false;
281
+	}
282
+
283
+
284
+	/**
285
+	 * @return array
286
+	 */
287
+	public function dependency_map(): array
288
+	{
289
+		return $this->_dependency_map;
290
+	}
291
+
292
+
293
+	/**
294
+	 * returns TRUE if dependency map contains a listing for the provided class name
295
+	 *
296
+	 * @param string $class_name
297
+	 * @return boolean
298
+	 */
299
+	public function has(string $class_name = ''): bool
300
+	{
301
+		// all legacy models have the same dependencies
302
+		if (strpos($class_name, 'EEM_') === 0) {
303
+			$class_name = 'LEGACY_MODELS';
304
+		}
305
+		return isset($this->_dependency_map[ $class_name ]);
306
+	}
307
+
308
+
309
+	/**
310
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
311
+	 *
312
+	 * @param string $class_name
313
+	 * @param string $dependency
314
+	 * @return bool
315
+	 */
316
+	public function has_dependency_for_class(string $class_name = '', string $dependency = ''): bool
317
+	{
318
+		// all legacy models have the same dependencies
319
+		if (strpos($class_name, 'EEM_') === 0) {
320
+			$class_name = 'LEGACY_MODELS';
321
+		}
322
+		$dependency = $this->getFqnForAlias($dependency, $class_name);
323
+		return isset($this->_dependency_map[ $class_name ][ $dependency ]);
324
+	}
325
+
326
+
327
+	/**
328
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
329
+	 *
330
+	 * @param string $class_name
331
+	 * @param string $dependency
332
+	 * @return int
333
+	 */
334
+	public function loading_strategy_for_class_dependency(string $class_name = '', string $dependency = ''): int
335
+	{
336
+		// all legacy models have the same dependencies
337
+		if (strpos($class_name, 'EEM_') === 0) {
338
+			$class_name = 'LEGACY_MODELS';
339
+		}
340
+		$dependency = $this->getFqnForAlias($dependency);
341
+		return $this->has_dependency_for_class($class_name, $dependency)
342
+			? $this->_dependency_map[ $class_name ][ $dependency ]
343
+			: EE_Dependency_Map::not_registered;
344
+	}
345
+
346
+
347
+	/**
348
+	 * @param string $class_name
349
+	 * @return string | Closure
350
+	 */
351
+	public function class_loader(string $class_name)
352
+	{
353
+		// all legacy models use load_model()
354
+		if (strpos($class_name, 'EEM_') === 0) {
355
+			return 'load_model';
356
+		}
357
+		// EE_CPT_*_Strategy classes like EE_CPT_Event_Strategy, EE_CPT_Venue_Strategy, etc
358
+		// perform strpos() first to avoid loading regex every time we load a class
359
+		if (
360
+			strpos($class_name, 'EE_CPT_') === 0
361
+			&& preg_match('/^EE_CPT_([a-zA-Z]+)_Strategy$/', $class_name)
362
+		) {
363
+			return 'load_core';
364
+		}
365
+		$class_name = $this->getFqnForAlias($class_name);
366
+		return $this->_class_loaders[ $class_name ] ?? '';
367
+	}
368
+
369
+
370
+	/**
371
+	 * @return array
372
+	 */
373
+	public function class_loaders(): array
374
+	{
375
+		return $this->_class_loaders;
376
+	}
377
+
378
+
379
+	/**
380
+	 * adds an alias for a classname
381
+	 *
382
+	 * @param string $fqcn      the class name that should be used (concrete class to replace interface)
383
+	 * @param string $alias     the class name that would be type hinted for (abstract parent or interface)
384
+	 * @param string $for_class the class that has the dependency (is type hinting for the interface)
385
+	 * @throws InvalidAliasException
386
+	 */
387
+	public function add_alias(string $fqcn, string $alias, string $for_class = '')
388
+	{
389
+		$this->class_cache->addAlias($fqcn, $alias, $for_class);
390
+	}
391
+
392
+
393
+	/**
394
+	 * Returns TRUE if the provided fully qualified name IS an alias
395
+	 * WHY?
396
+	 * Because if a class is type hinting for a concretion,
397
+	 * then why would we need to find another class to supply it?
398
+	 * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
399
+	 * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
400
+	 * Don't go looking for some substitute.
401
+	 * Whereas if a class is type hinting for an interface...
402
+	 * then we need to find an actual class to use.
403
+	 * So the interface IS the alias for some other FQN,
404
+	 * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
405
+	 * represents some other class.
406
+	 *
407
+	 * @param string $fqn
408
+	 * @param string $for_class
409
+	 * @return bool
410
+	 */
411
+	public function isAlias(string $fqn = '', string $for_class = ''): bool
412
+	{
413
+		return $this->class_cache->isAlias($fqn, $for_class);
414
+	}
415
+
416
+
417
+	/**
418
+	 * Returns a FQN for provided alias if one exists, otherwise returns the original $alias
419
+	 * functions recursively, so that multiple aliases can be used to drill down to a FQN
420
+	 *  for example:
421
+	 *      if the following two entries were added to the _aliases array:
422
+	 *          array(
423
+	 *              'interface_alias'           => 'some\namespace\interface'
424
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
425
+	 *          )
426
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
427
+	 *      to load an instance of 'some\namespace\classname'
428
+	 *
429
+	 * @param string $alias
430
+	 * @param string $for_class
431
+	 * @return string
432
+	 */
433
+	public function getFqnForAlias(string $alias = '', string $for_class = ''): string
434
+	{
435
+		return $this->class_cache->getFqnForAlias($alias, $for_class);
436
+	}
437
+
438
+
439
+	/**
440
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
441
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
442
+	 * This is done by using the following class constants:
443
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
444
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
445
+	 */
446
+	protected function _register_core_dependencies()
447
+	{
448
+		$this->_dependency_map = [
449
+			'EE_Admin'                                                                                                           => [
450
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
451
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
452
+			],
453
+			'EE_Maintenance_Mode'                                                                                                => [
454
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
455
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
456
+			],
457
+			'EE_Request_Handler'                                                                                                 => [
458
+				'EventEspresso\core\services\request\Request'  => EE_Dependency_Map::load_from_cache,
459
+				'EventEspresso\core\services\request\Response' => EE_Dependency_Map::load_from_cache,
460
+			],
461
+			'EE_System'                                                                                                   => [
462
+				'EventEspresso\core\services\loaders\Loader'                   => EE_Dependency_Map::load_from_cache,
463
+				'EE_Maintenance_Mode'                                          => EE_Dependency_Map::load_from_cache,
464
+				'EE_Registry'                                                  => EE_Dependency_Map::load_from_cache,
465
+				'EventEspresso\core\services\request\Request'                  => EE_Dependency_Map::load_from_cache,
466
+				'EventEspresso\core\services\routing\Router'                   => EE_Dependency_Map::load_from_cache,
467
+				'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
468
+			],
469
+			'EE_Session'                                                                                                         => [
470
+				'EventEspresso\core\services\cache\TransientCacheStorage'  => EE_Dependency_Map::load_from_cache,
471
+				'EventEspresso\core\domain\values\session\SessionLifespan' => EE_Dependency_Map::load_from_cache,
472
+				'EventEspresso\core\services\request\Request'              => EE_Dependency_Map::load_from_cache,
473
+				'EventEspresso\core\services\session\SessionStartHandler'  => EE_Dependency_Map::load_from_cache,
474
+				'EventEspresso\core\services\encryption\Base64Encoder'     => EE_Dependency_Map::load_from_cache,
475
+			],
476
+			'EventEspresso\core\services\session\SessionStartHandler'                                                            => [
477
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
478
+			],
479
+			'EE_Cart'                                                                                                            => [
480
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
481
+			],
482
+			'EE_Messenger_Collection_Loader'                                                                                     => [
483
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
484
+			],
485
+			'EE_Message_Type_Collection_Loader'                                                                                  => [
486
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
487
+			],
488
+			'EE_Message_Resource_Manager'                                                                                        => [
489
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
490
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
491
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
492
+			],
493
+			'EE_Message_Factory'                                                                                                 => [
494
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
495
+			],
496
+			'EE_messages'                                                                                                        => [
497
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
498
+			],
499
+			'EE_Messages_Generator'                                                                                              => [
500
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
501
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
502
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
503
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
504
+			],
505
+			'EE_Messages_Processor'                                                                                              => [
506
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
507
+			],
508
+			'EE_Messages_Queue'                                                                                                  => [
509
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
510
+			],
511
+			'EE_Messages_Template_Defaults'                                                                                      => [
512
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
513
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
514
+			],
515
+			'EE_Message_To_Generate_From_Request'                                                                                => [
516
+				'EE_Message_Resource_Manager'                 => EE_Dependency_Map::load_from_cache,
517
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
518
+			],
519
+			'EventEspresso\core\services\commands\CommandBus'                                                                    => [
520
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
521
+			],
522
+			'EventEspresso\services\commands\CommandHandler'                                                                     => [
523
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
524
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
525
+			],
526
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                         => [
527
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
528
+			],
529
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                       => [
530
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
531
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
532
+			],
533
+			'EventEspresso\core\services\commands\CommandFactory'                                                                => [
534
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
535
+			],
536
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                         => [
537
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
538
+			],
539
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                                => [
540
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
541
+			],
542
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                            => [
543
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
544
+			],
545
+			'EventEspresso\core\domain\services\commands\registration\CreateRegistrationCommandHandler'                          => [
546
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
547
+			],
548
+			'EventEspresso\core\domain\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => [
549
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
550
+			],
551
+			'EventEspresso\core\domain\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => [
552
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
553
+			],
554
+			'EventEspresso\core\domain\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => [
555
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
556
+			],
557
+			'EventEspresso\core\domain\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => [
558
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
559
+			],
560
+			'EventEspresso\core\domain\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => [
561
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
562
+			],
563
+			'EventEspresso\core\domain\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => [
564
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
565
+			],
566
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                          => [
567
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
568
+			],
569
+			'EventEspresso\core\domain\services\commands\attendee\CreateAttendeeCommandHandler'                                  => [
570
+				'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
571
+			],
572
+			'EventEspresso\core\domain\values\session\SessionLifespan'                                                           => [
573
+				'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
574
+			],
575
+			'EventEspresso\caffeinated\admin\extend\registration_form\forms\SessionLifespanForm'                                 => [
576
+				'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
577
+				'EE_Registration_Config'                                         => EE_Dependency_Map::load_from_cache,
578
+			],
579
+			'EventEspresso\caffeinated\admin\extend\registration_form\forms\SessionLifespanFormHandler'                          => [
580
+				'EventEspresso\core\domain\values\session\SessionLifespanOption' => EE_Dependency_Map::load_from_cache,
581
+				'EE_Config'                                                      => EE_Dependency_Map::load_from_cache,
582
+			],
583
+			'EventEspresso\core\services\database\TableManager'                                                                  => [
584
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
585
+			],
586
+			'EE_Data_Migration_Class_Base'                                                                                       => [
587
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
588
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
589
+			],
590
+			'EE_DMS_Core_4_1_0'                                                                                                  => [
591
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
592
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
593
+			],
594
+			'EE_DMS_Core_4_2_0'                                                                                                  => [
595
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
596
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
597
+			],
598
+			'EE_DMS_Core_4_3_0'                                                                                                  => [
599
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
600
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
601
+			],
602
+			'EE_DMS_Core_4_4_0'                                                                                                  => [
603
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
604
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
605
+			],
606
+			'EE_DMS_Core_4_5_0'                                                                                                  => [
607
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
608
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
609
+			],
610
+			'EE_DMS_Core_4_6_0'                                                                                                  => [
611
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
612
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
613
+			],
614
+			'EE_DMS_Core_4_7_0'                                                                                                  => [
615
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
616
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
617
+			],
618
+			'EE_DMS_Core_4_8_0'                                                                                                  => [
619
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
620
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
621
+			],
622
+			'EE_DMS_Core_4_9_0'                                                                                                  => [
623
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
624
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
625
+			],
626
+			'EE_DMS_Core_4_10_0'                                                                                                 => [
627
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
628
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
629
+				'EE_DMS_Core_4_9_0'                                  => EE_Dependency_Map::load_from_cache,
630
+			],
631
+			'EE_DMS_Core_5_0_0'                                                                                                  => [
632
+				'EE_DMS_Core_4_10_0'                                 => EE_Dependency_Map::load_from_cache,
633
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
634
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
635
+			],
636
+			'EventEspresso\core\services\assets\I18nRegistry'                                                                    => [
637
+				'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
638
+			],
639
+			'EventEspresso\core\services\assets\Registry'                                                                        => [
640
+				'EventEspresso\core\services\assets\AssetCollection' => EE_Dependency_Map::load_from_cache,
641
+				'EventEspresso\core\services\assets\AssetManifest'   => EE_Dependency_Map::load_from_cache,
642
+			],
643
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                                    => [
644
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
645
+			],
646
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                                     => [
647
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
648
+			],
649
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                               => [
650
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
651
+			],
652
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                       => [
653
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
654
+			],
655
+			'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                                     => [
656
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
657
+			],
658
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                               => [
659
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
660
+			],
661
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                                      => [
662
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
663
+			],
664
+			'EventEspresso\core\services\cache\BasicCacheManager'                                                                => [
665
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
666
+			],
667
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                                                          => [
668
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
669
+			],
670
+			'EventEspresso\core\domain\services\validation\email\EmailValidationService'                                         => [
671
+				'EE_Registration_Config'                     => EE_Dependency_Map::load_from_cache,
672
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
673
+			],
674
+			'EventEspresso\core\domain\values\EmailAddress'                                                                      => [
675
+				null,
676
+				'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
677
+			],
678
+			'EventEspresso\core\services\orm\ModelFieldFactory'                                                                  => [
679
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
680
+			],
681
+			'LEGACY_MODELS'                                                                                                      => [
682
+				null,
683
+				'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
684
+			],
685
+			'EE_Module_Request_Router'                                                                                           => [
686
+				'EventEspresso\core\services\request\Request'             => EE_Dependency_Map::load_from_cache,
687
+				'EventEspresso\core\services\modules\ModuleRoutesManager' => EE_Dependency_Map::load_from_cache,
688
+			],
689
+			'EE_Registration_Processor'                                                                                          => [
690
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
691
+			],
692
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'                                             => [
693
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
694
+				'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
695
+			],
696
+			'EventEspresso\caffeinated\modules\recaptcha_invisible\InvisibleRecaptcha'                                           => [
697
+				'EE_Registration_Config' => EE_Dependency_Map::load_from_cache,
698
+				'EE_Session'             => EE_Dependency_Map::load_from_cache,
699
+			],
700
+			'EventEspresso\modules\ticket_selector\DisplayTicketSelector'                                                        => [
701
+				'EventEspresso\core\domain\entities\users\CurrentUser' => EE_Dependency_Map::load_from_cache,
702
+				'EventEspresso\core\services\request\Request'          => EE_Dependency_Map::load_from_cache,
703
+				'EE_Ticket_Selector_Config'                            => EE_Dependency_Map::load_from_cache,
704
+			],
705
+			'EventEspresso\modules\ticket_selector\ProcessTicketSelector'                                                        => [
706
+				'EE_Core_Config'                                                          => EE_Dependency_Map::load_from_cache,
707
+				'EventEspresso\core\services\request\Request'                             => EE_Dependency_Map::load_from_cache,
708
+				'EE_Session'                                                              => EE_Dependency_Map::load_from_cache,
709
+				'EEM_Ticket'                                                              => EE_Dependency_Map::load_from_cache,
710
+				'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker' => EE_Dependency_Map::load_from_cache,
711
+			],
712
+			'EventEspresso\modules\ticket_selector\ProcessTicketSelectorPostData'                                                => [
713
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
714
+				'EEM_Event'                                   => EE_Dependency_Map::load_from_cache,
715
+			],
716
+			'EventEspresso\modules\ticket_selector\TicketDatetimeAvailabilityTracker'                                            => [
717
+				'EEM_Datetime' => EE_Dependency_Map::load_from_cache,
718
+			],
719
+			'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'                                     => [
720
+				'EE_Core_Config'                             => EE_Dependency_Map::load_from_cache,
721
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
722
+			],
723
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'                                       => [
724
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
725
+			],
726
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'                                      => [
727
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
728
+			],
729
+			'EE_CPT_Strategy'                                                                                                    => [
730
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions' => EE_Dependency_Map::load_from_cache,
731
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions' => EE_Dependency_Map::load_from_cache,
732
+			],
733
+			'EventEspresso\core\services\loaders\ObjectIdentifier'                                                               => [
734
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
735
+			],
736
+			'EventEspresso\core\CPTs\CptQueryModifier'                                                                           => [
737
+				null,
738
+				null,
739
+				null,
740
+				'EventEspresso\core\services\request\CurrentPage' => EE_Dependency_Map::load_from_cache,
741
+				'EventEspresso\core\services\request\Request'     => EE_Dependency_Map::load_from_cache,
742
+				'EventEspresso\core\services\loaders\Loader'      => EE_Dependency_Map::load_from_cache,
743
+			],
744
+			'EventEspresso\core\services\dependencies\DependencyResolver'                                                        => [
745
+				'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
746
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
747
+				'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
748
+			],
749
+			'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver'                                      => [
750
+				'EventEspresso\core\services\container\Mirror'            => EE_Dependency_Map::load_from_cache,
751
+				'EventEspresso\core\services\loaders\ClassInterfaceCache' => EE_Dependency_Map::load_from_cache,
752
+				'EE_Dependency_Map'                                       => EE_Dependency_Map::load_from_cache,
753
+			],
754
+			'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'                                                 => [
755
+				'EventEspresso\core\services\routing\RouteMatchSpecificationDependencyResolver' => EE_Dependency_Map::load_from_cache,
756
+				'EventEspresso\core\services\loaders\Loader'                                    => EE_Dependency_Map::load_from_cache,
757
+			],
758
+			'EventEspresso\core\services\routing\RouteMatchSpecificationManager'                                                 => [
759
+				'EventEspresso\core\services\routing\RouteMatchSpecificationCollection' => EE_Dependency_Map::load_from_cache,
760
+				'EventEspresso\core\services\routing\RouteMatchSpecificationFactory'    => EE_Dependency_Map::load_from_cache,
761
+			],
762
+			'EventEspresso\core\services\request\files\FilesDataHandler'                                                         => [
763
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
764
+			],
765
+			'EventEspresso\core\libraries\batch\BatchRequestProcessor'                                                           => [
766
+				'EventEspresso\core\services\loaders\Loader'  => EE_Dependency_Map::load_from_cache,
767
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
768
+			],
769
+			'EventEspresso\core\domain\services\converters\RestApiSpoofer'                                                       => [
770
+				'WP_REST_Server'                                               => EE_Dependency_Map::load_from_cache,
771
+				'EED_Core_Rest_Api'                                            => EE_Dependency_Map::load_from_cache,
772
+				'EventEspresso\core\libraries\rest_api\controllers\model\Read' => EE_Dependency_Map::load_from_cache,
773
+				null,
774
+			],
775
+			'EventEspresso\core\services\routing\RouteHandler'                                                                   => [
776
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
777
+				'EventEspresso\core\services\json\JsonDataNodeHandler'                => EE_Dependency_Map::load_from_cache,
778
+				'EventEspresso\core\services\loaders\Loader'                          => EE_Dependency_Map::load_from_cache,
779
+				'EventEspresso\core\services\request\Request'                         => EE_Dependency_Map::load_from_cache,
780
+				'EventEspresso\core\services\routing\RouteCollection'                 => EE_Dependency_Map::load_from_cache,
781
+			],
782
+			'EventEspresso\core\services\json\JsonDataNodeHandler'                                                               => [
783
+				'EventEspresso\core\services\json\JsonDataNodeValidator' => EE_Dependency_Map::load_from_cache,
784
+			],
785
+			'EventEspresso\core\services\routing\Router'                                                                         => [
786
+				'EE_Dependency_Map'                                => EE_Dependency_Map::load_from_cache,
787
+				'EventEspresso\core\services\loaders\Loader'       => EE_Dependency_Map::load_from_cache,
788
+				'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
789
+			],
790
+			'EventEspresso\core\services\assets\AssetManifest'                                                                   => [
791
+				'EventEspresso\core\domain\Domain' => EE_Dependency_Map::load_from_cache,
792
+			],
793
+			'EventEspresso\core\services\assets\AssetManifestFactory'                                                            => [
794
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
795
+			],
796
+			'EventEspresso\core\services\assets\BaristaFactory'                                                                  => [
797
+				'EventEspresso\core\services\assets\AssetManifestFactory' => EE_Dependency_Map::load_from_cache,
798
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
799
+			],
800
+			'EventEspresso\core\domain\services\capabilities\FeatureFlagsConfig' => [
801
+				'EventEspresso\core\domain\Domain'                                    => EE_Dependency_Map::load_from_cache,
802
+				'EventEspresso\core\services\json\JsonDataHandler'                    => EE_Dependency_Map::load_from_cache,
803
+			],
804
+			'EventEspresso\core\domain\services\capabilities\FeatureFlags'       => [
805
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
806
+				'EventEspresso\core\domain\services\capabilities\FeatureFlagsConfig'  => EE_Dependency_Map::load_from_cache,
807
+			],
808
+			'EventEspresso\core\services\addon\AddonManager'                                                                     => [
809
+				'EventEspresso\core\services\addon\AddonCollection'              => EE_Dependency_Map::load_from_cache,
810
+				'EE_Dependency_Map'                                              => EE_Dependency_Map::load_from_cache,
811
+				'EventEspresso\core\services\addon\api\IncompatibleAddonHandler' => EE_Dependency_Map::load_from_cache,
812
+				'EventEspresso\core\services\addon\api\v1\RegisterAddon'         => EE_Dependency_Map::load_from_cache,
813
+				'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'  => EE_Dependency_Map::load_from_cache,
814
+			],
815
+			'EventEspresso\core\services\addon\api\ThirdPartyPluginHandler'                                                      => [
816
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
817
+			],
818
+			'EventEspresso\core\libraries\batch\JobHandlers\ExecuteBatchDeletion'                                                => [
819
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
820
+			],
821
+			'EventEspresso\core\libraries\batch\JobHandlers\PreviewEventDeletion'                                                => [
822
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
823
+			],
824
+			'EventEspresso\core\domain\services\admin\events\data\PreviewDeletion'                                               => [
825
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
826
+				'EEM_Event'                                                   => EE_Dependency_Map::load_from_cache,
827
+				'EEM_Datetime'                                                => EE_Dependency_Map::load_from_cache,
828
+				'EEM_Registration'                                            => EE_Dependency_Map::load_from_cache,
829
+			],
830
+			'EventEspresso\core\domain\services\admin\events\data\ConfirmDeletion'                                               => [
831
+				'EventEspresso\core\services\orm\tree_traversal\NodeGroupDao' => EE_Dependency_Map::load_from_cache,
832
+			],
833
+			'EventEspresso\core\services\request\CurrentPage'                                                                    => [
834
+				'EE_CPT_Strategy'                             => EE_Dependency_Map::load_from_cache,
835
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
836
+			],
837
+			'EventEspresso\core\services\shortcodes\LegacyShortcodesManager'                                                     => [
838
+				'EE_Registry'                                     => EE_Dependency_Map::load_from_cache,
839
+				'EventEspresso\core\services\request\CurrentPage' => EE_Dependency_Map::load_from_cache,
840
+			],
841
+			'EventEspresso\core\services\shortcodes\ShortcodesManager'                                                           => [
842
+				'EventEspresso\core\services\shortcodes\LegacyShortcodesManager' => EE_Dependency_Map::load_from_cache,
843
+				'EventEspresso\core\services\request\CurrentPage'                => EE_Dependency_Map::load_from_cache,
844
+			],
845
+			'EventEspresso\core\domain\entities\users\CurrentUser'                                                               => [
846
+				'EventEspresso\core\domain\entities\users\EventManagers' => EE_Dependency_Map::load_from_cache,
847
+			],
848
+			'EventEspresso\core\services\form\meta\InputTypes'                                                                   => [
849
+				'EventEspresso\core\services\form\meta\inputs\Block'    => EE_Dependency_Map::load_from_cache,
850
+				'EventEspresso\core\services\form\meta\inputs\Button'   => EE_Dependency_Map::load_from_cache,
851
+				'EventEspresso\core\services\form\meta\inputs\DateTime' => EE_Dependency_Map::load_from_cache,
852
+				'EventEspresso\core\services\form\meta\inputs\Input'    => EE_Dependency_Map::load_from_cache,
853
+				'EventEspresso\core\services\form\meta\inputs\Number'   => EE_Dependency_Map::load_from_cache,
854
+				'EventEspresso\core\services\form\meta\inputs\Phone'    => EE_Dependency_Map::load_from_cache,
855
+				'EventEspresso\core\services\form\meta\inputs\Select'   => EE_Dependency_Map::load_from_cache,
856
+				'EventEspresso\core\services\form\meta\inputs\Text'     => EE_Dependency_Map::load_from_cache,
857
+			],
858
+			'EventEspresso\core\domain\services\registration\form\v1\RegFormDependencyHandler'                                   => [
859
+				'EE_Dependency_Map' => EE_Dependency_Map::load_from_cache,
860
+			],
861
+			'EventEspresso\core\services\calculators\LineItemCalculator'                                                         => [
862
+				'EventEspresso\core\services\helpers\DecimalValues' => EE_Dependency_Map::load_from_cache,
863
+			],
864
+			'EventEspresso\core\services\helpers\DecimalValues'                                                                  => [
865
+				'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
866
+			],
867
+			'EE_Brewing_Regular'                                                                                                 => [
868
+				'EE_Dependency_Map'                                  => EE_Dependency_Map::load_from_cache,
869
+				'EventEspresso\core\services\loaders\Loader'         => EE_Dependency_Map::load_from_cache,
870
+				'EventEspresso\core\services\routing\RouteHandler'   => EE_Dependency_Map::load_from_cache,
871
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
872
+			],
873
+			'EventEspresso\core\domain\services\messages\MessageTemplateRequestData'                                             => [
874
+				'EventEspresso\core\services\request\Request' => EE_Dependency_Map::load_from_cache,
875
+			],
876
+			'EventEspresso\core\domain\services\messages\MessageTemplateValidator'                                               => [
877
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
878
+			],
879
+			'EventEspresso\core\domain\services\messages\MessageTemplateManager'                                                 => [
880
+				'EEM_Message_Template'                                                   => EE_Dependency_Map::load_from_cache,
881
+				'EEM_Message_Template_Group'                                             => EE_Dependency_Map::load_from_cache,
882
+				'EventEspresso\core\domain\services\messages\MessageTemplateRequestData' => EE_Dependency_Map::load_from_cache,
883
+				'EventEspresso\core\domain\services\messages\MessageTemplateValidator'   => EE_Dependency_Map::load_from_cache,
884
+				'EventEspresso\core\services\request\Request'                            => EE_Dependency_Map::load_from_cache,
885
+			],
886
+			'EventEspresso\core\services\request\sanitizers\RequestSanitizer'                                                    => [
887
+				'EventEspresso\core\domain\services\validation\email\strategies\Basic' => EE_Dependency_Map::load_from_cache,
888
+			],
889
+			'EE_CPT_Event_Strategy'                                                    => [
890
+				null,
891
+				null,
892
+				'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
893
+			],
894
+			'EventEspresso\core\services\licensing\LicenseManager' => [
895
+				'EventEspresso\core\services\licensing\LicenseAPI'              => EE_Dependency_Map::load_from_cache,
896
+				'EventEspresso\core\services\licensing\LicenseKeyData'          => EE_Dependency_Map::load_from_cache,
897
+				'EventEspresso\core\services\licensing\PluginLicenseCollection' => EE_Dependency_Map::load_from_cache,
898
+			],
899
+			'EventEspresso\core\domain\services\licensing\LicenseKeyFormInput'                                                    => [
900
+				'EventEspresso\core\services\licensing\PluginLicense'  => EE_Dependency_Map::not_registered,
901
+				'EventEspresso\core\services\licensing\LicenseManager' => EE_Dependency_Map::load_from_cache,
902
+			],
903
+			'EventEspresso\core\services\payments\IpnHandler' => [
904
+				'EEM_Payment_Method'                                    => EE_Dependency_Map::not_registered,
905
+				'EEM_Transaction'                                       => EE_Dependency_Map::load_from_cache,
906
+				'EE_Core_Config'                                        => EE_Dependency_Map::load_from_cache,
907
+				'EE_Organization_Config'                                => EE_Dependency_Map::load_from_cache,
908
+				'EventEspresso\core\services\payments\PaymentProcessor' => EE_Dependency_Map::load_from_cache,
909
+			],
910
+			'EventEspresso\core\services\payments\PaymentProcessor' => [
911
+				'EEM_Payment_Method'                                           => EE_Dependency_Map::not_registered,
912
+				'EEM_Transaction'                                              => EE_Dependency_Map::load_from_cache,
913
+				'EE_Organization_Config'                                       => EE_Dependency_Map::load_from_cache,
914
+				'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
915
+				'EventEspresso\core\services\payments\PaymentProcessorFees'    => EE_Dependency_Map::load_from_cache,
916
+				'EventEspresso\core\services\payments\PostPaymentProcessor'    => EE_Dependency_Map::load_from_cache,
917
+				'EventEspresso\core\services\payments\RegistrationPayments'    => EE_Dependency_Map::load_from_cache,
918
+			],
919
+			'EventEspresso\core\services\payments\PostPaymentProcessor' => [
920
+				'EE_Transaction_Processor' => EE_Dependency_Map::load_from_cache,
921
+			],
922
+			'EventEspresso\core\services\payments\PaymentProcessorFees' => [
923
+				'EventEspresso\core\domain\values\gateways\GracePeriod'    => EE_Dependency_Map::load_from_cache,
924
+				'EventEspresso\core\domain\services\licensing\LicenseData' => EE_Dependency_Map::load_from_cache,
925
+			],
926
+			'EventEspresso\core\domain\services\licensing\LicenseData'  => [
927
+				'EventEspresso\core\domain\Domain'                             => EE_Dependency_Map::load_from_cache,
928
+				'EventEspresso\core\domain\services\capabilities\FeatureFlags' => EE_Dependency_Map::load_from_cache,
929
+			],
930
+			'EventEspresso\core\domain\services\licensing\LicenseDataEDD' => [
931
+				'EventEspresso\core\services\licensing\LicenseKeyData' => EE_Dependency_Map::load_from_cache,
932
+			],
933
+			'EventEspresso\core\domain\services\licensing\LicenseDataPue' => [
934
+				'EE_Network_Core_Config' => EE_Dependency_Map::load_from_cache,
935
+			],
936
+			'EventEspresso\core\services\addon\api\DependencyHandlers' => [
937
+				'EE_Dependency_Map' => EE_Dependency_Map::load_from_cache,
938
+			],
939
+			'EventEspresso\core\services\addon\api\AddonRoutes' => [
940
+				'EventEspresso\core\services\routing\RouteHandler' => EE_Dependency_Map::load_from_cache,
941
+			],
942
+		];
943
+	}
944
+
945
+
946
+	/**
947
+	 * Registers how core classes are loaded.
948
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
949
+	 *        'EE_Request_Handler' => 'load_core'
950
+	 *        'EE_Messages_Queue'  => 'load_lib'
951
+	 *        'EEH_Debug_Tools'    => 'load_helper'
952
+	 * or, if greater control is required, by providing a custom closure. For example:
953
+	 *        'Some_Class' => function () {
954
+	 *            return new Some_Class();
955
+	 *        },
956
+	 * This is required for instantiating dependencies
957
+	 * where an interface has been type hinted in a class constructor. For example:
958
+	 *        'Required_Interface' => function () {
959
+	 *            return new A_Class_That_Implements_Required_Interface();
960
+	 *        },
961
+	 */
962
+	protected function _register_core_class_loaders()
963
+	{
964
+		$this->_class_loaders = [
965
+			// load_core
966
+			'EE_Dependency_Map'                            => function () {
967
+				return $this;
968
+			},
969
+			'EE_Capabilities'                              => 'load_core',
970
+			'EE_Encryption'                                => 'load_core',
971
+			'EE_Front_Controller'                          => 'load_core',
972
+			'EE_Module_Request_Router'                     => 'load_core',
973
+			'EE_Registry'                                  => 'load_core',
974
+			'EE_Request'                                   => function () {
975
+				return $this->legacy_request;
976
+			},
977
+			'EventEspresso\core\services\request\Request'  => function () {
978
+				return $this->request;
979
+			},
980
+			'EventEspresso\core\services\request\Response' => function () {
981
+				return $this->response;
982
+			},
983
+			'EE_Base'                                      => 'load_core',
984
+			'EE_Request_Handler'                           => 'load_core',
985
+			'EE_Session'                                   => 'load_core',
986
+			'EE_Cron_Tasks'                                => 'load_core',
987
+			'EE_System'                                    => 'load_core',
988
+			'EE_Maintenance_Mode'                          => 'load_core',
989
+			'EE_Register_CPTs'                             => 'load_core',
990
+			'EE_Admin'                                     => 'load_core',
991
+			'EE_CPT_Strategy'                              => 'load_core',
992
+			// load_class
993
+			'EE_Registration_Processor'                    => 'load_class',
994
+			'EE_Transaction_Payments'                      => 'load_class',
995
+			'EE_Transaction_Processor'                     => 'load_class',
996
+			// load_lib
997
+			'EE_Message_Resource_Manager'                  => 'load_lib',
998
+			'EE_Message_Type_Collection'                   => 'load_lib',
999
+			'EE_Message_Type_Collection_Loader'            => 'load_lib',
1000
+			'EE_Messenger_Collection'                      => 'load_lib',
1001
+			'EE_Messenger_Collection_Loader'               => 'load_lib',
1002
+			'EE_Messages_Processor'                        => 'load_lib',
1003
+			'EE_Message_Repository'                        => 'load_lib',
1004
+			'EE_Messages_Queue'                            => 'load_lib',
1005
+			'EE_Messages_Data_Handler_Collection'          => 'load_lib',
1006
+			'EE_Message_Template_Group_Collection'         => 'load_lib',
1007
+			'EE_Payment_Method_Manager'                    => 'load_lib',
1008
+			'EE_Payment_Processor'                         => 'load_core',
1009
+			'EE_DMS_Core_4_1_0'                            => 'load_dms',
1010
+			'EE_DMS_Core_4_2_0'                            => 'load_dms',
1011
+			'EE_DMS_Core_4_3_0'                            => 'load_dms',
1012
+			'EE_DMS_Core_4_5_0'                            => 'load_dms',
1013
+			'EE_DMS_Core_4_6_0'                            => 'load_dms',
1014
+			'EE_DMS_Core_4_7_0'                            => 'load_dms',
1015
+			'EE_DMS_Core_4_8_0'                            => 'load_dms',
1016
+			'EE_DMS_Core_4_9_0'                            => 'load_dms',
1017
+			'EE_DMS_Core_4_10_0'                           => 'load_dms',
1018
+			'EE_DMS_Core_5_0_0'                            => 'load_dms',
1019
+			'EE_Messages_Generator'                        => static function () {
1020
+				return EE_Registry::instance()->load_lib(
1021
+					'Messages_Generator',
1022
+					[],
1023
+					false,
1024
+					false
1025
+				);
1026
+			},
1027
+			'EE_Messages_Template_Defaults'                => static function ($arguments = []) {
1028
+				return EE_Registry::instance()->load_lib(
1029
+					'Messages_Template_Defaults',
1030
+					$arguments,
1031
+					false,
1032
+					false
1033
+				);
1034
+			},
1035
+			// load_helper
1036
+			'EEH_Parse_Shortcodes'                         => static function () {
1037
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
1038
+					return new EEH_Parse_Shortcodes();
1039
+				}
1040
+				return null;
1041
+			},
1042
+			'EE_Template_Config'                           => static function () {
1043
+				return EE_Config::instance()->template_settings;
1044
+			},
1045
+			'EE_Currency_Config'                           => static function () {
1046
+				return EE_Currency_Config::getCurrencyConfig();
1047
+			},
1048
+			'EE_Registration_Config'                       => static function () {
1049
+				return EE_Config::instance()->registration;
1050
+			},
1051
+			'EE_Core_Config'                               => static function () {
1052
+				return EE_Config::instance()->core;
1053
+			},
1054
+			'EventEspresso\core\services\loaders\Loader'   => static function () {
1055
+				return LoaderFactory::getLoader();
1056
+			},
1057
+			'EE_Network_Config'                            => static function () {
1058
+				return EE_Network_Config::instance();
1059
+			},
1060
+			'EE_Config'                                    => static function () {
1061
+				return EE_Config::instance();
1062
+			},
1063
+			'EventEspresso\core\domain\Domain'             => static function () {
1064
+				return DomainFactory::getEventEspressoCoreDomain();
1065
+			},
1066
+			'EE_Admin_Config'                              => static function () {
1067
+				return EE_Config::instance()->admin;
1068
+			},
1069
+			'EE_Organization_Config'                       => static function () {
1070
+				return EE_Config::instance()->organization;
1071
+			},
1072
+			'EE_Network_Core_Config'                       => static function () {
1073
+				return EE_Network_Config::instance()->core;
1074
+			},
1075
+			'EE_Environment_Config'                        => static function () {
1076
+				return EE_Config::instance()->environment;
1077
+			},
1078
+			'EED_Core_Rest_Api'                            => static function () {
1079
+				return EED_Core_Rest_Api::instance();
1080
+			},
1081
+			'WP_REST_Server'                               => static function () {
1082
+				return rest_get_server();
1083
+			},
1084
+			'EventEspresso\core\Psr4Autoloader'            => static function () {
1085
+				return EE_Psr4AutoloaderInit::psr4_loader();
1086
+			},
1087
+			'EE_Ticket_Selector_Config'                    => function () {
1088
+				return EE_Config::instance()->template_settings->EED_Ticket_Selector;
1089
+			},
1090
+		];
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 * can be used for supplying alternate names for classes,
1096
+	 * or for connecting interface names to instantiable classes
1097
+	 *
1098
+	 * @throws InvalidAliasException
1099
+	 */
1100
+	protected function _register_core_aliases()
1101
+	{
1102
+		$aliases = [
1103
+			'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
1104
+			'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
1105
+			'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
1106
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
1107
+			'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
1108
+			'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
1109
+			'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
1110
+			'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
1111
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
1112
+			'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
1113
+			'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\domain\services\commands\registration\CreateRegistrationCommand',
1114
+			'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\domain\services\commands\registration\CopyRegistrationDetailsCommand',
1115
+			'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\domain\services\commands\registration\CopyRegistrationPaymentsCommand',
1116
+			'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\domain\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
1117
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\domain\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
1118
+			'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\domain\services\commands\ticket\CreateTicketLineItemCommand',
1119
+			'CreateTransactionCommandHandler'                                              => 'EventEspresso\core\domain\services\commands\transaction\CreateTransactionCommandHandler',
1120
+			'CreateAttendeeCommandHandler'                                                 => 'EventEspresso\core\domain\services\commands\attendee\CreateAttendeeCommandHandler',
1121
+			'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
1122
+			'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
1123
+			'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
1124
+			'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
1125
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
1126
+			'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
1127
+			'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
1128
+			'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
1129
+			'CommandFactoryInterface'                                                      => 'EventEspresso\core\services\commands\CommandFactoryInterface',
1130
+			'EventEspresso\core\services\commands\CommandFactoryInterface'                 => 'EventEspresso\core\services\commands\CommandFactory',
1131
+			'EmailValidatorInterface'                                                      => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
1132
+			'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface'  => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
1133
+			'NoticeConverterInterface'                                                     => 'EventEspresso\core\services\notices\NoticeConverterInterface',
1134
+			'EventEspresso\core\services\notices\NoticeConverterInterface'                 => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
1135
+			'NoticesContainerInterface'                                                    => 'EventEspresso\core\services\notices\NoticesContainerInterface',
1136
+			'EventEspresso\core\services\notices\NoticesContainerInterface'                => 'EventEspresso\core\services\notices\NoticesContainer',
1137
+			'EventEspresso\core\services\request\RequestInterface'                         => 'EventEspresso\core\services\request\Request',
1138
+			'EventEspresso\core\services\request\ResponseInterface'                        => 'EventEspresso\core\services\request\Response',
1139
+			'EventEspresso\core\domain\DomainInterface'                                    => 'EventEspresso\core\domain\Domain',
1140
+			'Registration_Processor'                                                       => 'EE_Registration_Processor',
1141
+			'EventEspresso\core\services\assets\AssetManifestInterface'                    => 'EventEspresso\core\services\assets\AssetManifest',
1142
+		];
1143
+		foreach ($aliases as $alias => $fqn) {
1144
+			if (is_array($fqn)) {
1145
+				foreach ($fqn as $class => $for_class) {
1146
+					$this->class_cache->addAlias($class, $alias, $for_class);
1147
+				}
1148
+				continue;
1149
+			}
1150
+			$this->class_cache->addAlias($fqn, $alias);
1151
+		}
1152
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && is_admin()) {
1153
+			$this->class_cache->addAlias(
1154
+				'EventEspresso\core\services\notices\ConvertNoticesToAdminNotices',
1155
+				'EventEspresso\core\services\notices\NoticeConverterInterface'
1156
+			);
1157
+		}
1158
+	}
1159
+
1160
+
1161
+	public function debug($for_class = '')
1162
+	{
1163
+		if (method_exists($this->class_cache, 'debug')) {
1164
+			$this->class_cache->debug($for_class);
1165
+		}
1166
+	}
1167
+
1168
+
1169
+	/**
1170
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
1171
+	 * request Primarily used by unit tests.
1172
+	 */
1173
+	public function reset()
1174
+	{
1175
+		$this->_register_core_class_loaders();
1176
+		$this->_register_core_dependencies();
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * PLZ NOTE: a better name for this method would be is_alias()
1182
+	 * because it returns TRUE if the provided fully qualified name IS an alias
1183
+	 * WHY?
1184
+	 * Because if a class is type hinting for a concretion,
1185
+	 * then why would we need to find another class to supply it?
1186
+	 * ie: if a class asks for `Fully/Qualified/Namespace/SpecificClassName`,
1187
+	 * then give it an instance of `Fully/Qualified/Namespace/SpecificClassName`.
1188
+	 * Don't go looking for some substitute.
1189
+	 * Whereas if a class is type hinting for an interface...
1190
+	 * then we need to find an actual class to use.
1191
+	 * So the interface IS the alias for some other FQN,
1192
+	 * and we need to find out if `Fully/Qualified/Namespace/SomeInterface`
1193
+	 * represents some other class.
1194
+	 *
1195
+	 * @param string $fqn
1196
+	 * @param string $for_class
1197
+	 * @return bool
1198
+	 * @deprecated 4.9.62.p
1199
+	 */
1200
+	public function has_alias(string $fqn = '', string $for_class = ''): bool
1201
+	{
1202
+		return $this->isAlias($fqn, $for_class);
1203
+	}
1204
+
1205
+
1206
+	/**
1207
+	 * PLZ NOTE: a better name for this method would be get_fqn_for_alias()
1208
+	 * because it returns a FQN for provided alias if one exists, otherwise returns the original $alias
1209
+	 * functions recursively, so that multiple aliases can be used to drill down to a FQN
1210
+	 *  for example:
1211
+	 *      if the following two entries were added to the _aliases array:
1212
+	 *          array(
1213
+	 *              'interface_alias'           => 'some\namespace\interface'
1214
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
1215
+	 *          )
1216
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
1217
+	 *      to load an instance of 'some\namespace\classname'
1218
+	 *
1219
+	 * @param string $alias
1220
+	 * @param string $for_class
1221
+	 * @return string
1222
+	 * @deprecated 4.9.62.p
1223
+	 */
1224
+	public function get_alias(string $alias = '', string $for_class = ''): string
1225
+	{
1226
+		return $this->getFqnForAlias($alias, $for_class);
1227
+	}
1228 1228
 }
Please login to merge, or discard this patch.
core/domain/entities/routing/handlers/admin/ActivationRequests.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -15,47 +15,47 @@
 block discarded – undo
15 15
  */
16 16
 class ActivationRequests extends PrimaryRoute
17 17
 {
18
-    /**
19
-     * returns true if the current request matches this route
20
-     *
21
-     * @return bool
22
-     * @since   5.0.0.p
23
-     */
24
-    public function matchesCurrentRequest(): bool
25
-    {
26
-        return $this->request->isActivation();
27
-    }
18
+	/**
19
+	 * returns true if the current request matches this route
20
+	 *
21
+	 * @return bool
22
+	 * @since   5.0.0.p
23
+	 */
24
+	public function matchesCurrentRequest(): bool
25
+	{
26
+		return $this->request->isActivation();
27
+	}
28 28
 
29 29
 
30
-    /**
31
-     * @since 5.0.0.p
32
-     */
33
-    protected function registerDependencies()
34
-    {
35
-        $this->dependency_map->registerDependencies(
36
-            'EventEspresso\core\domain\entities\routing\handlers\admin\AdminRoute',
37
-            AdminRoute::getDefaultDependencies()
38
-        );
39
-        $this->dependency_map->registerDependencies(
40
-            'EventEspresso\core\domain\entities\routing\handlers\admin\WordPressPluginsPage',
41
-            AdminRoute::getDefaultDependencies()
42
-        );
43
-        $this->dependency_map->registerDependencies(
44
-            'EventEspresso\core\domain\services\licensing\LicenseKeyActivationRoute',
45
-            Route::getDefaultDependencies()
46
-        );
47
-    }
30
+	/**
31
+	 * @since 5.0.0.p
32
+	 */
33
+	protected function registerDependencies()
34
+	{
35
+		$this->dependency_map->registerDependencies(
36
+			'EventEspresso\core\domain\entities\routing\handlers\admin\AdminRoute',
37
+			AdminRoute::getDefaultDependencies()
38
+		);
39
+		$this->dependency_map->registerDependencies(
40
+			'EventEspresso\core\domain\entities\routing\handlers\admin\WordPressPluginsPage',
41
+			AdminRoute::getDefaultDependencies()
42
+		);
43
+		$this->dependency_map->registerDependencies(
44
+			'EventEspresso\core\domain\services\licensing\LicenseKeyActivationRoute',
45
+			Route::getDefaultDependencies()
46
+		);
47
+	}
48 48
 
49 49
 
50
-    /**
51
-     * implements logic required to run during request
52
-     *
53
-     * @return bool
54
-     * @since   5.0.0.p
55
-     */
56
-    protected function requestHandler(): bool
57
-    {
58
-        $this->setRouteRequestType(PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION);
59
-        return true;
60
-    }
50
+	/**
51
+	 * implements logic required to run during request
52
+	 *
53
+	 * @return bool
54
+	 * @since   5.0.0.p
55
+	 */
56
+	protected function requestHandler(): bool
57
+	{
58
+		$this->setRouteRequestType(PrimaryRoute::ROUTE_REQUEST_TYPE_ACTIVATION);
59
+		return true;
60
+	}
61 61
 }
Please login to merge, or discard this patch.
domain/entities/routing/handlers/frontend/RegistrationCheckoutRequests.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -14,46 +14,46 @@
 block discarded – undo
14 14
  */
15 15
 class RegistrationCheckoutRequests extends FrontendRequests
16 16
 {
17
-    /**
18
-     * returns true if the current request matches this route
19
-     * child classes can override and use Request directly to match route with request
20
-     * or supply a RouteMatchSpecification class and just use the below
21
-     *
22
-     * @return bool
23
-     * @since   5.0.0.p
24
-     */
25
-    public function matchesCurrentRequest(): bool
26
-    {
27
-        return parent::matchesCurrentRequest()
28
-            && (
29
-                str_contains($this->request->requestUri(false, true), 'registration-checkout')
30
-                || $this->request->getRequestParam('action', '', DataType::STRING) === 'display_spco_reg_step'
31
-                || $this->request->getRequestParam('action', '', DataType::STRING) === 'process_reg_step'
32
-                || $this->request->getRequestParam('action', '', DataType::STRING) === 'update_reg_step'
33
-            );
34
-    }
35
-
36
-
37
-    /**
38
-     * @since 5.0.0.p
39
-     */
40
-    protected function registerDependencies()
41
-    {
42
-
43
-    }
44
-
45
-
46
-    /**
47
-     * implements logic required to run during request
48
-     *
49
-     * @return bool
50
-     * @since   5.0.0.p
51
-     */
52
-    protected function requestHandler(): bool
53
-    {
54
-        do_action(
55
-            'AHEE__EventEspresso_core_domain_entities_routing_handlers_frontend_RegistrationCheckoutRequests__requestHandler'
56
-        );
57
-        return true;
58
-    }
17
+	/**
18
+	 * returns true if the current request matches this route
19
+	 * child classes can override and use Request directly to match route with request
20
+	 * or supply a RouteMatchSpecification class and just use the below
21
+	 *
22
+	 * @return bool
23
+	 * @since   5.0.0.p
24
+	 */
25
+	public function matchesCurrentRequest(): bool
26
+	{
27
+		return parent::matchesCurrentRequest()
28
+			&& (
29
+				str_contains($this->request->requestUri(false, true), 'registration-checkout')
30
+				|| $this->request->getRequestParam('action', '', DataType::STRING) === 'display_spco_reg_step'
31
+				|| $this->request->getRequestParam('action', '', DataType::STRING) === 'process_reg_step'
32
+				|| $this->request->getRequestParam('action', '', DataType::STRING) === 'update_reg_step'
33
+			);
34
+	}
35
+
36
+
37
+	/**
38
+	 * @since 5.0.0.p
39
+	 */
40
+	protected function registerDependencies()
41
+	{
42
+
43
+	}
44
+
45
+
46
+	/**
47
+	 * implements logic required to run during request
48
+	 *
49
+	 * @return bool
50
+	 * @since   5.0.0.p
51
+	 */
52
+	protected function requestHandler(): bool
53
+	{
54
+		do_action(
55
+			'AHEE__EventEspresso_core_domain_entities_routing_handlers_frontend_RegistrationCheckoutRequests__requestHandler'
56
+		);
57
+		return true;
58
+	}
59 59
 }
Please login to merge, or discard this patch.
core/domain/Domain.php 1 patch
Indentation   +112 added lines, -112 removed lines patch added patch discarded remove patch
@@ -15,116 +15,116 @@
 block discarded – undo
15 15
  */
16 16
 class Domain extends DomainBase implements CaffeinatedInterface
17 17
 {
18
-    /**
19
-     * URL path component used to denote an API request
20
-     */
21
-    public const API_NAMESPACE   = 'ee/v';
22
-
23
-    public const ASSET_NAMESPACE = 'eventespresso';
24
-
25
-    public const LICENSE_PLUGIN_ID = '268';
26
-
27
-    public const LICENSE_PLUGIN_NAME = 'Event Espresso Core';
28
-
29
-    public const LICENSE_PLUGIN_SLUG = 'event_espresso_core';
30
-
31
-    public const TEXT_DOMAIN     = 'event_espresso';
32
-
33
-    /**
34
-     * Slug used for the context where a registration status is changed from a manual trigger in the Registration Admin
35
-     * Page ui.
36
-     */
37
-    public const CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN        = 'manual_registration_status_change_from_registration_admin';
38
-
39
-    public const CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN_NOTIFY = 'manual_registration_status_change_from_registration_admin_and_notify';
40
-
41
-
42
-    /**
43
-     * Whether EE core is the full premium version.
44
-     *
45
-     * @since 4.9.59.p
46
-     * @var bool
47
-     */
48
-    private bool $caffeinated = false;
49
-
50
-    /**
51
-     * @since 5.0.0.p
52
-     * @var bool
53
-     */
54
-    private bool $multisite;
55
-
56
-
57
-    public function __construct(FilePath $plugin_file, Version $version)
58
-    {
59
-        parent::__construct($plugin_file, $version);
60
-        $this->setCaffeinated();
61
-        $this->multisite = is_multisite();
62
-    }
63
-
64
-
65
-    /**
66
-     * Whether EE core is the full premium version.
67
-     *
68
-     * @return bool
69
-     * @since 4.9.59.p
70
-     */
71
-    public function isCaffeinated(): bool
72
-    {
73
-        return $this->caffeinated;
74
-    }
75
-
76
-
77
-    /**
78
-     * @return bool
79
-     * @since 5.0.22.p
80
-     */
81
-    public function isDecaf(): bool
82
-    {
83
-        return ! $this->isCaffeinated();
84
-    }
85
-
86
-
87
-    /**
88
-     * Setter for $is_caffeinated property.
89
-     *
90
-     * @since 4.9.59.p
91
-     */
92
-    private function setCaffeinated()
93
-    {
94
-        $this->caffeinated = ! (defined('EE_DECAF') && EE_DECAF)
95
-                             && is_readable($this->pluginPath() . 'caffeinated/brewing_regular.php');
96
-    }
97
-
98
-
99
-    /**
100
-     * This should be used everywhere the Event Espresso brand name is referenced in public facing interfaces
101
-     * to allow for filtering the brand.
102
-     *
103
-     * @return string
104
-     */
105
-    public static function brandName(): string
106
-    {
107
-        return (string) apply_filters('FHEE__EventEspresso_core_domain_Domain__brandName', 'Event Espresso');
108
-    }
109
-
110
-
111
-    /**
112
-     * @return bool
113
-     * @since 5.0.0.p
114
-     */
115
-    public function isMultiSite(): bool
116
-    {
117
-        return $this->multisite;
118
-    }
119
-
120
-
121
-    public static function pluginName(): string
122
-    {
123
-        return self::LICENSE_PLUGIN_NAME;
124
-    }
125
-
126
-    public static function pluginSlug(): string
127
-    {
128
-        return self::LICENSE_PLUGIN_SLUG;
129
-    }
18
+	/**
19
+	 * URL path component used to denote an API request
20
+	 */
21
+	public const API_NAMESPACE   = 'ee/v';
22
+
23
+	public const ASSET_NAMESPACE = 'eventespresso';
24
+
25
+	public const LICENSE_PLUGIN_ID = '268';
26
+
27
+	public const LICENSE_PLUGIN_NAME = 'Event Espresso Core';
28
+
29
+	public const LICENSE_PLUGIN_SLUG = 'event_espresso_core';
30
+
31
+	public const TEXT_DOMAIN     = 'event_espresso';
32
+
33
+	/**
34
+	 * Slug used for the context where a registration status is changed from a manual trigger in the Registration Admin
35
+	 * Page ui.
36
+	 */
37
+	public const CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN        = 'manual_registration_status_change_from_registration_admin';
38
+
39
+	public const CONTEXT_REGISTRATION_STATUS_CHANGE_REGISTRATION_ADMIN_NOTIFY = 'manual_registration_status_change_from_registration_admin_and_notify';
40
+
41
+
42
+	/**
43
+	 * Whether EE core is the full premium version.
44
+	 *
45
+	 * @since 4.9.59.p
46
+	 * @var bool
47
+	 */
48
+	private bool $caffeinated = false;
49
+
50
+	/**
51
+	 * @since 5.0.0.p
52
+	 * @var bool
53
+	 */
54
+	private bool $multisite;
55
+
56
+
57
+	public function __construct(FilePath $plugin_file, Version $version)
58
+	{
59
+		parent::__construct($plugin_file, $version);
60
+		$this->setCaffeinated();
61
+		$this->multisite = is_multisite();
62
+	}
63
+
64
+
65
+	/**
66
+	 * Whether EE core is the full premium version.
67
+	 *
68
+	 * @return bool
69
+	 * @since 4.9.59.p
70
+	 */
71
+	public function isCaffeinated(): bool
72
+	{
73
+		return $this->caffeinated;
74
+	}
75
+
76
+
77
+	/**
78
+	 * @return bool
79
+	 * @since 5.0.22.p
80
+	 */
81
+	public function isDecaf(): bool
82
+	{
83
+		return ! $this->isCaffeinated();
84
+	}
85
+
86
+
87
+	/**
88
+	 * Setter for $is_caffeinated property.
89
+	 *
90
+	 * @since 4.9.59.p
91
+	 */
92
+	private function setCaffeinated()
93
+	{
94
+		$this->caffeinated = ! (defined('EE_DECAF') && EE_DECAF)
95
+							 && is_readable($this->pluginPath() . 'caffeinated/brewing_regular.php');
96
+	}
97
+
98
+
99
+	/**
100
+	 * This should be used everywhere the Event Espresso brand name is referenced in public facing interfaces
101
+	 * to allow for filtering the brand.
102
+	 *
103
+	 * @return string
104
+	 */
105
+	public static function brandName(): string
106
+	{
107
+		return (string) apply_filters('FHEE__EventEspresso_core_domain_Domain__brandName', 'Event Espresso');
108
+	}
109
+
110
+
111
+	/**
112
+	 * @return bool
113
+	 * @since 5.0.0.p
114
+	 */
115
+	public function isMultiSite(): bool
116
+	{
117
+		return $this->multisite;
118
+	}
119
+
120
+
121
+	public static function pluginName(): string
122
+	{
123
+		return self::LICENSE_PLUGIN_NAME;
124
+	}
125
+
126
+	public static function pluginSlug(): string
127
+	{
128
+		return self::LICENSE_PLUGIN_SLUG;
129
+	}
130 130
 }
Please login to merge, or discard this patch.