Completed
Branch master (d65695)
by
unknown
04:25
created
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +3358 added lines, -3358 removed lines patch added patch discarded remove patch
@@ -13,3374 +13,3374 @@
 block discarded – undo
13 13
  */
14 14
 abstract class EE_Base_Class
15 15
 {
16
-    /**
17
-     * This is an array of the original properties and values provided during construction
18
-     * of this model object. (keys are model field names, values are their values).
19
-     * This list is important to remember so that when we are merging data from the db, we know
20
-     * which values to override and which to not override.
21
-     *
22
-     * @var array
23
-     */
24
-    protected $_props_n_values_provided_in_constructor;
25
-
26
-    /**
27
-     * Timezone
28
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
-     * access to it.
32
-     *
33
-     * @var string
34
-     */
35
-    protected $_timezone;
36
-
37
-    /**
38
-     * date format
39
-     * pattern or format for displaying dates
40
-     *
41
-     * @var string $_dt_frmt
42
-     */
43
-    protected $_dt_frmt;
44
-
45
-    /**
46
-     * time format
47
-     * pattern or format for displaying time
48
-     *
49
-     * @var string $_tm_frmt
50
-     */
51
-    protected $_tm_frmt;
52
-
53
-    /**
54
-     * This property is for holding a cached array of object properties indexed by property name as the key.
55
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
56
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
-     *
59
-     * @var array
60
-     */
61
-    protected $_cached_properties = array();
62
-
63
-    /**
64
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
65
-     * single
66
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
-     * all others have an array)
69
-     *
70
-     * @var array
71
-     */
72
-    protected $_model_relations = array();
73
-
74
-    /**
75
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
-     *
78
-     * @var array
79
-     */
80
-    protected $_fields = array();
81
-
82
-    /**
83
-     * @var boolean indicating whether or not this model object is intended to ever be saved
84
-     * For example, we might create model objects intended to only be used for the duration
85
-     * of this request and to be thrown away, and if they were accidentally saved
86
-     * it would be a bug.
87
-     */
88
-    protected $_allow_persist = true;
89
-
90
-    /**
91
-     * @var boolean indicating whether or not this model object's properties have changed since construction
92
-     */
93
-    protected $_has_changes = false;
94
-
95
-    /**
96
-     * @var EEM_Base
97
-     */
98
-    protected $_model;
99
-
100
-    /**
101
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
-     * array as:
107
-     * array(
108
-     *  'Registration_Count' => 24
109
-     * );
110
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
-     * info)
113
-     *
114
-     * @var array
115
-     */
116
-    protected $custom_selection_results = array();
117
-
118
-
119
-    /**
120
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
-     * play nice
122
-     *
123
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
-     *                                                         TXN_amount, QST_name, etc) and values are their values
126
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
-     *                                                         corresponding db model or not.
128
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
-     *                                                         be in when instantiating a EE_Base_Class object.
130
-     * @param array   $date_formats                            An array of date formats to set on construct where first
131
-     *                                                         value is the date_format and second value is the time
132
-     *                                                         format.
133
-     * @throws InvalidArgumentException
134
-     * @throws InvalidInterfaceException
135
-     * @throws InvalidDataTypeException
136
-     * @throws EE_Error
137
-     * @throws ReflectionException
138
-     */
139
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
-    {
141
-        $className = get_class($this);
142
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
-        $model = $this->get_model();
144
-        $model_fields = $model->field_settings(false);
145
-        // ensure $fieldValues is an array
146
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
-        // verify client code has not passed any invalid field names
148
-        foreach ($fieldValues as $field_name => $field_value) {
149
-            if (! isset($model_fields[ $field_name ])) {
150
-                throw new EE_Error(
151
-                    sprintf(
152
-                        esc_html__(
153
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
-                            'event_espresso'
155
-                        ),
156
-                        $field_name,
157
-                        get_class($this),
158
-                        implode(', ', array_keys($model_fields))
159
-                    )
160
-                );
161
-            }
162
-        }
163
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
-        if (! empty($date_formats) && is_array($date_formats)) {
165
-            [$this->_dt_frmt, $this->_tm_frmt] = $date_formats;
166
-        } else {
167
-            // set default formats for date and time
168
-            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
-            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
-        }
171
-        // if db model is instantiating
172
-        if ($bydb) {
173
-            // client code has indicated these field values are from the database
174
-            foreach ($model_fields as $fieldName => $field) {
175
-                $this->set_from_db(
176
-                    $fieldName,
177
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
-                );
179
-            }
180
-        } else {
181
-            // we're constructing a brand
182
-            // new instance of the model object. Generally, this means we'll need to do more field validation
183
-            foreach ($model_fields as $fieldName => $field) {
184
-                $this->set(
185
-                    $fieldName,
186
-                    isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
-                    true
188
-                );
189
-            }
190
-        }
191
-        // remember what values were passed to this constructor
192
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
193
-        // remember in entity mapper
194
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
-            $model->add_to_entity_map($this);
196
-        }
197
-        // setup all the relations
198
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
-                $this->_model_relations[ $relation_name ] = null;
201
-            } else {
202
-                $this->_model_relations[ $relation_name ] = array();
203
-            }
204
-        }
205
-        /**
206
-         * Action done at the end of each model object construction
207
-         *
208
-         * @param EE_Base_Class $this the model object just created
209
-         */
210
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
-    }
212
-
213
-
214
-    /**
215
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
216
-     *
217
-     * @return boolean
218
-     */
219
-    public function allow_persist()
220
-    {
221
-        return $this->_allow_persist;
222
-    }
223
-
224
-
225
-    /**
226
-     * Sets whether or not this model object should be allowed to be saved to the DB.
227
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
-     * you got new information that somehow made you change your mind.
229
-     *
230
-     * @param boolean $allow_persist
231
-     * @return boolean
232
-     */
233
-    public function set_allow_persist($allow_persist)
234
-    {
235
-        return $this->_allow_persist = $allow_persist;
236
-    }
237
-
238
-
239
-    /**
240
-     * Gets the field's original value when this object was constructed during this request.
241
-     * This can be helpful when determining if a model object has changed or not
242
-     *
243
-     * @param string $field_name
244
-     * @return mixed|null
245
-     * @throws ReflectionException
246
-     * @throws InvalidArgumentException
247
-     * @throws InvalidInterfaceException
248
-     * @throws InvalidDataTypeException
249
-     * @throws EE_Error
250
-     */
251
-    public function get_original($field_name)
252
-    {
253
-        if (
254
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
256
-        ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
-        }
259
-        return null;
260
-    }
261
-
262
-
263
-    /**
264
-     * @param EE_Base_Class $obj
265
-     * @return string
266
-     */
267
-    public function get_class($obj)
268
-    {
269
-        return get_class($obj);
270
-    }
271
-
272
-
273
-    /**
274
-     * Overrides parent because parent expects old models.
275
-     * This also doesn't do any validation, and won't work for serialized arrays
276
-     *
277
-     * @param    string $field_name
278
-     * @param    mixed  $field_value
279
-     * @param bool      $use_default
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidInterfaceException
282
-     * @throws InvalidDataTypeException
283
-     * @throws EE_Error
284
-     * @throws ReflectionException
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     */
288
-    public function set($field_name, $field_value, $use_default = false)
289
-    {
290
-        // if not using default and nothing has changed, and object has already been setup (has ID),
291
-        // then don't do anything
292
-        if (
293
-            ! $use_default
294
-            && $this->_fields[ $field_name ] === $field_value
295
-            && $this->ID()
296
-        ) {
297
-            return;
298
-        }
299
-        $model = $this->get_model();
300
-        $this->_has_changes = true;
301
-        $field_obj = $model->field_settings_for($field_name);
302
-        if ($field_obj instanceof EE_Model_Field_Base) {
303
-            // if ( method_exists( $field_obj, 'set_timezone' )) {
304
-            if ($field_obj instanceof EE_Datetime_Field) {
305
-                $field_obj->set_timezone($this->_timezone);
306
-                $field_obj->set_date_format($this->_dt_frmt);
307
-                $field_obj->set_time_format($this->_tm_frmt);
308
-            }
309
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
310
-            // should the value be null?
311
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
-                $this->_fields[ $field_name ] = $field_obj->get_default_value();
313
-                /**
314
-                 * To save having to refactor all the models, if a default value is used for a
315
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
-                 * object.
318
-                 *
319
-                 * @since 4.6.10+
320
-                 */
321
-                if (
322
-                    $field_obj instanceof EE_Datetime_Field
323
-                    && $this->_fields[ $field_name ] !== null
324
-                    && ! $this->_fields[ $field_name ] instanceof DateTime
325
-                ) {
326
-                    empty($this->_fields[ $field_name ])
327
-                        ? $this->set($field_name, time())
328
-                        : $this->set($field_name, $this->_fields[ $field_name ]);
329
-                }
330
-            } else {
331
-                $this->_fields[ $field_name ] = $holder_of_value;
332
-            }
333
-            // if we're not in the constructor...
334
-            // now check if what we set was a primary key
335
-            if (
16
+	/**
17
+	 * This is an array of the original properties and values provided during construction
18
+	 * of this model object. (keys are model field names, values are their values).
19
+	 * This list is important to remember so that when we are merging data from the db, we know
20
+	 * which values to override and which to not override.
21
+	 *
22
+	 * @var array
23
+	 */
24
+	protected $_props_n_values_provided_in_constructor;
25
+
26
+	/**
27
+	 * Timezone
28
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
29
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
30
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
31
+	 * access to it.
32
+	 *
33
+	 * @var string
34
+	 */
35
+	protected $_timezone;
36
+
37
+	/**
38
+	 * date format
39
+	 * pattern or format for displaying dates
40
+	 *
41
+	 * @var string $_dt_frmt
42
+	 */
43
+	protected $_dt_frmt;
44
+
45
+	/**
46
+	 * time format
47
+	 * pattern or format for displaying time
48
+	 *
49
+	 * @var string $_tm_frmt
50
+	 */
51
+	protected $_tm_frmt;
52
+
53
+	/**
54
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
55
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
56
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
57
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
58
+	 *
59
+	 * @var array
60
+	 */
61
+	protected $_cached_properties = array();
62
+
63
+	/**
64
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
65
+	 * single
66
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
67
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
68
+	 * all others have an array)
69
+	 *
70
+	 * @var array
71
+	 */
72
+	protected $_model_relations = array();
73
+
74
+	/**
75
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
76
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
77
+	 *
78
+	 * @var array
79
+	 */
80
+	protected $_fields = array();
81
+
82
+	/**
83
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
84
+	 * For example, we might create model objects intended to only be used for the duration
85
+	 * of this request and to be thrown away, and if they were accidentally saved
86
+	 * it would be a bug.
87
+	 */
88
+	protected $_allow_persist = true;
89
+
90
+	/**
91
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
92
+	 */
93
+	protected $_has_changes = false;
94
+
95
+	/**
96
+	 * @var EEM_Base
97
+	 */
98
+	protected $_model;
99
+
100
+	/**
101
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
102
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
103
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
104
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
105
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
106
+	 * array as:
107
+	 * array(
108
+	 *  'Registration_Count' => 24
109
+	 * );
110
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
111
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
112
+	 * info)
113
+	 *
114
+	 * @var array
115
+	 */
116
+	protected $custom_selection_results = array();
117
+
118
+
119
+	/**
120
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
121
+	 * play nice
122
+	 *
123
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
124
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
125
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
126
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
127
+	 *                                                         corresponding db model or not.
128
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
129
+	 *                                                         be in when instantiating a EE_Base_Class object.
130
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
131
+	 *                                                         value is the date_format and second value is the time
132
+	 *                                                         format.
133
+	 * @throws InvalidArgumentException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws EE_Error
137
+	 * @throws ReflectionException
138
+	 */
139
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
140
+	{
141
+		$className = get_class($this);
142
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
143
+		$model = $this->get_model();
144
+		$model_fields = $model->field_settings(false);
145
+		// ensure $fieldValues is an array
146
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
147
+		// verify client code has not passed any invalid field names
148
+		foreach ($fieldValues as $field_name => $field_value) {
149
+			if (! isset($model_fields[ $field_name ])) {
150
+				throw new EE_Error(
151
+					sprintf(
152
+						esc_html__(
153
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
154
+							'event_espresso'
155
+						),
156
+						$field_name,
157
+						get_class($this),
158
+						implode(', ', array_keys($model_fields))
159
+					)
160
+				);
161
+			}
162
+		}
163
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
164
+		if (! empty($date_formats) && is_array($date_formats)) {
165
+			[$this->_dt_frmt, $this->_tm_frmt] = $date_formats;
166
+		} else {
167
+			// set default formats for date and time
168
+			$this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
169
+			$this->_tm_frmt = (string) get_option('time_format', 'g:i a');
170
+		}
171
+		// if db model is instantiating
172
+		if ($bydb) {
173
+			// client code has indicated these field values are from the database
174
+			foreach ($model_fields as $fieldName => $field) {
175
+				$this->set_from_db(
176
+					$fieldName,
177
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null
178
+				);
179
+			}
180
+		} else {
181
+			// we're constructing a brand
182
+			// new instance of the model object. Generally, this means we'll need to do more field validation
183
+			foreach ($model_fields as $fieldName => $field) {
184
+				$this->set(
185
+					$fieldName,
186
+					isset($fieldValues[ $fieldName ]) ? $fieldValues[ $fieldName ] : null,
187
+					true
188
+				);
189
+			}
190
+		}
191
+		// remember what values were passed to this constructor
192
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
193
+		// remember in entity mapper
194
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
+			$model->add_to_entity_map($this);
196
+		}
197
+		// setup all the relations
198
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
199
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
200
+				$this->_model_relations[ $relation_name ] = null;
201
+			} else {
202
+				$this->_model_relations[ $relation_name ] = array();
203
+			}
204
+		}
205
+		/**
206
+		 * Action done at the end of each model object construction
207
+		 *
208
+		 * @param EE_Base_Class $this the model object just created
209
+		 */
210
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
211
+	}
212
+
213
+
214
+	/**
215
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
216
+	 *
217
+	 * @return boolean
218
+	 */
219
+	public function allow_persist()
220
+	{
221
+		return $this->_allow_persist;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
227
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
228
+	 * you got new information that somehow made you change your mind.
229
+	 *
230
+	 * @param boolean $allow_persist
231
+	 * @return boolean
232
+	 */
233
+	public function set_allow_persist($allow_persist)
234
+	{
235
+		return $this->_allow_persist = $allow_persist;
236
+	}
237
+
238
+
239
+	/**
240
+	 * Gets the field's original value when this object was constructed during this request.
241
+	 * This can be helpful when determining if a model object has changed or not
242
+	 *
243
+	 * @param string $field_name
244
+	 * @return mixed|null
245
+	 * @throws ReflectionException
246
+	 * @throws InvalidArgumentException
247
+	 * @throws InvalidInterfaceException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws EE_Error
250
+	 */
251
+	public function get_original($field_name)
252
+	{
253
+		if (
254
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
256
+		) {
257
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
+		}
259
+		return null;
260
+	}
261
+
262
+
263
+	/**
264
+	 * @param EE_Base_Class $obj
265
+	 * @return string
266
+	 */
267
+	public function get_class($obj)
268
+	{
269
+		return get_class($obj);
270
+	}
271
+
272
+
273
+	/**
274
+	 * Overrides parent because parent expects old models.
275
+	 * This also doesn't do any validation, and won't work for serialized arrays
276
+	 *
277
+	 * @param    string $field_name
278
+	 * @param    mixed  $field_value
279
+	 * @param bool      $use_default
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidInterfaceException
282
+	 * @throws InvalidDataTypeException
283
+	 * @throws EE_Error
284
+	 * @throws ReflectionException
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 */
288
+	public function set($field_name, $field_value, $use_default = false)
289
+	{
290
+		// if not using default and nothing has changed, and object has already been setup (has ID),
291
+		// then don't do anything
292
+		if (
293
+			! $use_default
294
+			&& $this->_fields[ $field_name ] === $field_value
295
+			&& $this->ID()
296
+		) {
297
+			return;
298
+		}
299
+		$model = $this->get_model();
300
+		$this->_has_changes = true;
301
+		$field_obj = $model->field_settings_for($field_name);
302
+		if ($field_obj instanceof EE_Model_Field_Base) {
303
+			// if ( method_exists( $field_obj, 'set_timezone' )) {
304
+			if ($field_obj instanceof EE_Datetime_Field) {
305
+				$field_obj->set_timezone($this->_timezone);
306
+				$field_obj->set_date_format($this->_dt_frmt);
307
+				$field_obj->set_time_format($this->_tm_frmt);
308
+			}
309
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
310
+			// should the value be null?
311
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
312
+				$this->_fields[ $field_name ] = $field_obj->get_default_value();
313
+				/**
314
+				 * To save having to refactor all the models, if a default value is used for a
315
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
316
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
317
+				 * object.
318
+				 *
319
+				 * @since 4.6.10+
320
+				 */
321
+				if (
322
+					$field_obj instanceof EE_Datetime_Field
323
+					&& $this->_fields[ $field_name ] !== null
324
+					&& ! $this->_fields[ $field_name ] instanceof DateTime
325
+				) {
326
+					empty($this->_fields[ $field_name ])
327
+						? $this->set($field_name, time())
328
+						: $this->set($field_name, $this->_fields[ $field_name ]);
329
+				}
330
+			} else {
331
+				$this->_fields[ $field_name ] = $holder_of_value;
332
+			}
333
+			// if we're not in the constructor...
334
+			// now check if what we set was a primary key
335
+			if (
336 336
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
337
-                $this->_props_n_values_provided_in_constructor
338
-                && $field_value
339
-                && $field_name === $model->primary_key_name()
340
-            ) {
341
-                // if so, we want all this object's fields to be filled either with
342
-                // what we've explicitly set on this model
343
-                // or what we have in the db
344
-                // echo "setting primary key!";
345
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
346
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
-                foreach ($fields_on_model as $field_obj) {
348
-                    if (
349
-                        ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
-                        && $field_obj->get_name() !== $field_name
351
-                    ) {
352
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
-                    }
354
-                }
355
-                // oh this model object has an ID? well make sure its in the entity mapper
356
-                $model->add_to_entity_map($this);
357
-            }
358
-            // let's unset any cache for this field_name from the $_cached_properties property.
359
-            $this->_clear_cached_property($field_name);
360
-        } else {
361
-            throw new EE_Error(
362
-                sprintf(
363
-                    esc_html__(
364
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
-                        'event_espresso'
366
-                    ),
367
-                    $field_name
368
-                )
369
-            );
370
-        }
371
-    }
372
-
373
-
374
-    /**
375
-     * Set custom select values for model.
376
-     *
377
-     * @param array $custom_select_values
378
-     */
379
-    public function setCustomSelectsValues(array $custom_select_values)
380
-    {
381
-        $this->custom_selection_results = $custom_select_values;
382
-    }
383
-
384
-
385
-    /**
386
-     * Returns the custom select value for the provided alias if its set.
387
-     * If not set, returns null.
388
-     *
389
-     * @param string $alias
390
-     * @return string|int|float|null
391
-     */
392
-    public function getCustomSelect($alias)
393
-    {
394
-        return isset($this->custom_selection_results[ $alias ])
395
-            ? $this->custom_selection_results[ $alias ]
396
-            : null;
397
-    }
398
-
399
-
400
-    /**
401
-     * This sets the field value on the db column if it exists for the given $column_name or
402
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
-     *
404
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
-     * @param string $field_name  Must be the exact column name.
406
-     * @param mixed  $field_value The value to set.
407
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
-     * @throws InvalidArgumentException
409
-     * @throws InvalidInterfaceException
410
-     * @throws InvalidDataTypeException
411
-     * @throws EE_Error
412
-     * @throws ReflectionException
413
-     */
414
-    public function set_field_or_extra_meta($field_name, $field_value)
415
-    {
416
-        if ($this->get_model()->has_field($field_name)) {
417
-            $this->set($field_name, $field_value);
418
-            return true;
419
-        }
420
-        // ensure this object is saved first so that extra meta can be properly related.
421
-        $this->save();
422
-        return $this->update_extra_meta($field_name, $field_value);
423
-    }
424
-
425
-
426
-    /**
427
-     * This retrieves the value of the db column set on this class or if that's not present
428
-     * it will attempt to retrieve from extra_meta if found.
429
-     * Example Usage:
430
-     * Via EE_Message child class:
431
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
434
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
-     * value for those extra fields dynamically via the EE_message object.
436
-     *
437
-     * @param  string $field_name expecting the fully qualified field name.
438
-     * @return mixed|null  value for the field if found.  null if not found.
439
-     * @throws ReflectionException
440
-     * @throws InvalidArgumentException
441
-     * @throws InvalidInterfaceException
442
-     * @throws InvalidDataTypeException
443
-     * @throws EE_Error
444
-     */
445
-    public function get_field_or_extra_meta($field_name)
446
-    {
447
-        if ($this->get_model()->has_field($field_name)) {
448
-            $column_value = $this->get($field_name);
449
-        } else {
450
-            // This isn't a column in the main table, let's see if it is in the extra meta.
451
-            $column_value = $this->get_extra_meta($field_name, true, null);
452
-        }
453
-        return $column_value;
454
-    }
455
-
456
-
457
-    /**
458
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
-     *
463
-     * @access public
464
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
-     * @return void
466
-     * @throws InvalidArgumentException
467
-     * @throws InvalidInterfaceException
468
-     * @throws InvalidDataTypeException
469
-     * @throws EE_Error
470
-     * @throws ReflectionException
471
-     */
472
-    public function set_timezone($timezone = '')
473
-    {
474
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
-        // make sure we clear all cached properties because they won't be relevant now
476
-        $this->_clear_cached_properties();
477
-        // make sure we update field settings and the date for all EE_Datetime_Fields
478
-        $model_fields = $this->get_model()->field_settings(false);
479
-        foreach ($model_fields as $field_name => $field_obj) {
480
-            if ($field_obj instanceof EE_Datetime_Field) {
481
-                $field_obj->set_timezone($this->_timezone);
482
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
-                }
485
-            }
486
-        }
487
-    }
488
-
489
-
490
-    /**
491
-     * This just returns whatever is set for the current timezone.
492
-     *
493
-     * @access public
494
-     * @return string timezone string
495
-     */
496
-    public function get_timezone()
497
-    {
498
-        return $this->_timezone;
499
-    }
500
-
501
-
502
-    /**
503
-     * This sets the internal date format to what is sent in to be used as the new default for the class
504
-     * internally instead of wp set date format options
505
-     *
506
-     * @since 4.6
507
-     * @param string $format should be a format recognizable by PHP date() functions.
508
-     */
509
-    public function set_date_format($format)
510
-    {
511
-        $this->_dt_frmt = $format;
512
-        // clear cached_properties because they won't be relevant now.
513
-        $this->_clear_cached_properties();
514
-    }
515
-
516
-
517
-    /**
518
-     * This sets the internal time format string to what is sent in to be used as the new default for the
519
-     * class internally instead of wp set time format options.
520
-     *
521
-     * @since 4.6
522
-     * @param string $format should be a format recognizable by PHP date() functions.
523
-     */
524
-    public function set_time_format($format)
525
-    {
526
-        $this->_tm_frmt = $format;
527
-        // clear cached_properties because they won't be relevant now.
528
-        $this->_clear_cached_properties();
529
-    }
530
-
531
-
532
-    /**
533
-     * This returns the current internal set format for the date and time formats.
534
-     *
535
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
-     *                             where the first value is the date format and the second value is the time format.
537
-     * @return mixed string|array
538
-     */
539
-    public function get_format($full = true)
540
-    {
541
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
-    }
543
-
544
-
545
-    /**
546
-     * cache
547
-     * stores the passed model object on the current model object.
548
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
-     *
550
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
-     *                                       'Registration' associated with this model object
552
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
-     *                                       that could be a payment or a registration)
554
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
-     *                                       items which will be stored in an array on this object
556
-     * @throws ReflectionException
557
-     * @throws InvalidArgumentException
558
-     * @throws InvalidInterfaceException
559
-     * @throws InvalidDataTypeException
560
-     * @throws EE_Error
561
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
-     *                                       related thing, no array)
563
-     */
564
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
-    {
566
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
-        if (! $object_to_cache instanceof EE_Base_Class) {
568
-            return false;
569
-        }
570
-        // also get "how" the object is related, or throw an error
571
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
-            throw new EE_Error(
573
-                sprintf(
574
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
-                    $relationName,
576
-                    get_class($this)
577
-                )
578
-            );
579
-        }
580
-        // how many things are related ?
581
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
-            // if it's a "belongs to" relationship, then there's only one related model object
583
-            // eg, if this is a registration, there's only 1 attendee for it
584
-            // so for these model objects just set it to be cached
585
-            $this->_model_relations[ $relationName ] = $object_to_cache;
586
-            $return = true;
587
-        } else {
588
-            // otherwise, this is the "many" side of a one to many relationship,
589
-            // so we'll add the object to the array of related objects for that type.
590
-            // eg: if this is an event, there are many registrations for that event,
591
-            // so we cache the registrations in an array
592
-            if (! is_array($this->_model_relations[ $relationName ])) {
593
-                // if for some reason, the cached item is a model object,
594
-                // then stick that in the array, otherwise start with an empty array
595
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
-                                                           instanceof
597
-                                                           EE_Base_Class
598
-                    ? array($this->_model_relations[ $relationName ]) : array();
599
-            }
600
-            // first check for a cache_id which is normally empty
601
-            if (! empty($cache_id)) {
602
-                // if the cache_id exists, then it means we are purposely trying to cache this
603
-                // with a known key that can then be used to retrieve the object later on
604
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
-                $return = $cache_id;
606
-            } elseif ($object_to_cache->ID()) {
607
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
608
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
-                $return = $object_to_cache->ID();
610
-            } else {
611
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
613
-                // move the internal pointer to the end of the array
614
-                end($this->_model_relations[ $relationName ]);
615
-                // and grab the key so that we can return it
616
-                $return = key($this->_model_relations[ $relationName ]);
617
-            }
618
-        }
619
-        return $return;
620
-    }
621
-
622
-
623
-    /**
624
-     * For adding an item to the cached_properties property.
625
-     *
626
-     * @access protected
627
-     * @param string      $fieldname the property item the corresponding value is for.
628
-     * @param mixed       $value     The value we are caching.
629
-     * @param string|null $cache_type
630
-     * @return void
631
-     * @throws ReflectionException
632
-     * @throws InvalidArgumentException
633
-     * @throws InvalidInterfaceException
634
-     * @throws InvalidDataTypeException
635
-     * @throws EE_Error
636
-     */
637
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
-    {
639
-        // first make sure this property exists
640
-        $this->get_model()->field_settings_for($fieldname);
641
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
-    }
644
-
645
-
646
-    /**
647
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
-     * This also SETS the cache if we return the actual property!
649
-     *
650
-     * @param string $fieldname        the name of the property we're trying to retrieve
651
-     * @param bool   $pretty
652
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
-     *                                 (in cases where the same property may be used for different outputs
654
-     *                                 - i.e. datetime, money etc.)
655
-     *                                 It can also accept certain pre-defined "schema" strings
656
-     *                                 to define how to output the property.
657
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
-     * @return mixed                   whatever the value for the property is we're retrieving
659
-     * @throws ReflectionException
660
-     * @throws InvalidArgumentException
661
-     * @throws InvalidInterfaceException
662
-     * @throws InvalidDataTypeException
663
-     * @throws EE_Error
664
-     */
665
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
-    {
667
-        // verify the field exists
668
-        $model = $this->get_model();
669
-        $model->field_settings_for($fieldname);
670
-        $cache_type = $pretty ? 'pretty' : 'standard';
671
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
-        }
675
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
-        $this->_set_cached_property($fieldname, $value, $cache_type);
677
-        return $value;
678
-    }
679
-
680
-
681
-    /**
682
-     * If the cache didn't fetch the needed item, this fetches it.
683
-     *
684
-     * @param string $fieldname
685
-     * @param bool   $pretty
686
-     * @param string $extra_cache_ref
687
-     * @return mixed
688
-     * @throws InvalidArgumentException
689
-     * @throws InvalidInterfaceException
690
-     * @throws InvalidDataTypeException
691
-     * @throws EE_Error
692
-     * @throws ReflectionException
693
-     */
694
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
-    {
696
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
697
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
-        if ($field_obj instanceof EE_Datetime_Field) {
699
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
-        }
701
-        if (! isset($this->_fields[ $fieldname ])) {
702
-            $this->_fields[ $fieldname ] = null;
703
-        }
704
-        return $pretty
705
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
-    }
708
-
709
-
710
-    /**
711
-     * set timezone, formats, and output for EE_Datetime_Field objects
712
-     *
713
-     * @param EE_Datetime_Field $datetime_field
714
-     * @param bool              $pretty
715
-     * @param null              $date_or_time
716
-     * @return void
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidInterfaceException
719
-     * @throws InvalidDataTypeException
720
-     */
721
-    protected function _prepare_datetime_field(
722
-        EE_Datetime_Field $datetime_field,
723
-        $pretty = false,
724
-        $date_or_time = null
725
-    ) {
726
-        $datetime_field->set_timezone($this->_timezone);
727
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
728
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
729
-        // set the output returned
730
-        switch ($date_or_time) {
731
-            case 'D':
732
-                $datetime_field->set_date_time_output('date');
733
-                break;
734
-            case 'T':
735
-                $datetime_field->set_date_time_output('time');
736
-                break;
737
-            default:
738
-                $datetime_field->set_date_time_output();
739
-        }
740
-    }
741
-
742
-
743
-    /**
744
-     * This just takes care of clearing out the cached_properties
745
-     *
746
-     * @return void
747
-     */
748
-    protected function _clear_cached_properties()
749
-    {
750
-        $this->_cached_properties = array();
751
-    }
752
-
753
-
754
-    /**
755
-     * This just clears out ONE property if it exists in the cache
756
-     *
757
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
758
-     * @return void
759
-     */
760
-    protected function _clear_cached_property($property_name)
761
-    {
762
-        if (isset($this->_cached_properties[ $property_name ])) {
763
-            unset($this->_cached_properties[ $property_name ]);
764
-        }
765
-    }
766
-
767
-
768
-    /**
769
-     * Ensures that this related thing is a model object.
770
-     *
771
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
772
-     * @param string $model_name   name of the related thing, eg 'Attendee',
773
-     * @return EE_Base_Class
774
-     * @throws ReflectionException
775
-     * @throws InvalidArgumentException
776
-     * @throws InvalidInterfaceException
777
-     * @throws InvalidDataTypeException
778
-     * @throws EE_Error
779
-     */
780
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
781
-    {
782
-        $other_model_instance = self::_get_model_instance_with_name(
783
-            self::_get_model_classname($model_name),
784
-            $this->_timezone
785
-        );
786
-        return $other_model_instance->ensure_is_obj($object_or_id);
787
-    }
788
-
789
-
790
-    /**
791
-     * Forgets the cached model of the given relation Name. So the next time we request it,
792
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
793
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
794
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
795
-     *
796
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
797
-     *                                                     Eg 'Registration'
798
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
799
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
800
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
801
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
802
-     *                                                     this is HasMany or HABTM.
803
-     * @throws ReflectionException
804
-     * @throws InvalidArgumentException
805
-     * @throws InvalidInterfaceException
806
-     * @throws InvalidDataTypeException
807
-     * @throws EE_Error
808
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
809
-     *                                                     relation from all
810
-     */
811
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
812
-    {
813
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
814
-        $index_in_cache = '';
815
-        if (! $relationship_to_model) {
816
-            throw new EE_Error(
817
-                sprintf(
818
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
819
-                    $relationName,
820
-                    get_class($this)
821
-                )
822
-            );
823
-        }
824
-        if ($clear_all) {
825
-            $obj_removed = true;
826
-            $this->_model_relations[ $relationName ] = null;
827
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
828
-            $obj_removed = $this->_model_relations[ $relationName ];
829
-            $this->_model_relations[ $relationName ] = null;
830
-        } else {
831
-            if (
832
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
833
-                && $object_to_remove_or_index_into_array->ID()
834
-            ) {
835
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
836
-                if (
837
-                    is_array($this->_model_relations[ $relationName ])
838
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
839
-                ) {
840
-                    $index_found_at = null;
841
-                    // find this object in the array even though it has a different key
842
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
843
-                        /** @noinspection TypeUnsafeComparisonInspection */
844
-                        if (
845
-                            $obj instanceof EE_Base_Class
846
-                            && (
847
-                                $obj == $object_to_remove_or_index_into_array
848
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
849
-                            )
850
-                        ) {
851
-                            $index_found_at = $index;
852
-                            break;
853
-                        }
854
-                    }
855
-                    if ($index_found_at) {
856
-                        $index_in_cache = $index_found_at;
857
-                    } else {
858
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
859
-                        // if it wasn't in it to begin with. So we're done
860
-                        return $object_to_remove_or_index_into_array;
861
-                    }
862
-                }
863
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
864
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
865
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
866
-                    /** @noinspection TypeUnsafeComparisonInspection */
867
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
868
-                        $index_in_cache = $index;
869
-                    }
870
-                }
871
-            } else {
872
-                $index_in_cache = $object_to_remove_or_index_into_array;
873
-            }
874
-            // supposedly we've found it. But it could just be that the client code
875
-            // provided a bad index/object
876
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
877
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
878
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
879
-            } else {
880
-                // that thing was never cached anyways.
881
-                $obj_removed = null;
882
-            }
883
-        }
884
-        return $obj_removed;
885
-    }
886
-
887
-
888
-    /**
889
-     * update_cache_after_object_save
890
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
891
-     * obtained after being saved to the db
892
-     *
893
-     * @param string        $relationName       - the type of object that is cached
894
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
895
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
896
-     * @return boolean TRUE on success, FALSE on fail
897
-     * @throws ReflectionException
898
-     * @throws InvalidArgumentException
899
-     * @throws InvalidInterfaceException
900
-     * @throws InvalidDataTypeException
901
-     * @throws EE_Error
902
-     */
903
-    public function update_cache_after_object_save(
904
-        $relationName,
905
-        EE_Base_Class $newly_saved_object,
906
-        $current_cache_id = ''
907
-    ) {
908
-        // verify that incoming object is of the correct type
909
-        $obj_class = 'EE_' . $relationName;
910
-        if ($newly_saved_object instanceof $obj_class) {
911
-            /* @type EE_Base_Class $newly_saved_object */
912
-            // now get the type of relation
913
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
914
-            // if this is a 1:1 relationship
915
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
916
-                // then just replace the cached object with the newly saved object
917
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
918
-                return true;
919
-                // or if it's some kind of sordid feral polyamorous relationship...
920
-            }
921
-            if (
922
-                is_array($this->_model_relations[ $relationName ])
923
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
924
-            ) {
925
-                // then remove the current cached item
926
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
927
-                // and cache the newly saved object using it's new ID
928
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
929
-                return true;
930
-            }
931
-        }
932
-        return false;
933
-    }
934
-
935
-
936
-    /**
937
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
938
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
939
-     *
940
-     * @param string $relationName
941
-     * @return EE_Base_Class
942
-     */
943
-    public function get_one_from_cache($relationName)
944
-    {
945
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
946
-            ? $this->_model_relations[ $relationName ]
947
-            : null;
948
-        if (is_array($cached_array_or_object)) {
949
-            return array_shift($cached_array_or_object);
950
-        }
951
-        return $cached_array_or_object;
952
-    }
953
-
954
-
955
-    /**
956
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
957
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
958
-     *
959
-     * @param string $relationName
960
-     * @throws ReflectionException
961
-     * @throws InvalidArgumentException
962
-     * @throws InvalidInterfaceException
963
-     * @throws InvalidDataTypeException
964
-     * @throws EE_Error
965
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
966
-     */
967
-    public function get_all_from_cache($relationName)
968
-    {
969
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
970
-        // if the result is not an array, but exists, make it an array
971
-        $objects = is_array($objects) ? $objects : array($objects);
972
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
973
-        // basically, if this model object was stored in the session, and these cached model objects
974
-        // already have IDs, let's make sure they're in their model's entity mapper
975
-        // otherwise we will have duplicates next time we call
976
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
977
-        $model = EE_Registry::instance()->load_model($relationName);
978
-        foreach ($objects as $model_object) {
979
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
980
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
981
-                if ($model_object->ID()) {
982
-                    $model->add_to_entity_map($model_object);
983
-                }
984
-            } else {
985
-                throw new EE_Error(
986
-                    sprintf(
987
-                        esc_html__(
988
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
989
-                            'event_espresso'
990
-                        ),
991
-                        $relationName,
992
-                        gettype($model_object)
993
-                    )
994
-                );
995
-            }
996
-        }
997
-        return $objects;
998
-    }
999
-
1000
-
1001
-    /**
1002
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1003
-     * matching the given query conditions.
1004
-     *
1005
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1006
-     * @param int   $limit              How many objects to return.
1007
-     * @param array $query_params       Any additional conditions on the query.
1008
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1009
-     *                                  you can indicate just the columns you want returned
1010
-     * @return array|EE_Base_Class[]
1011
-     * @throws ReflectionException
1012
-     * @throws InvalidArgumentException
1013
-     * @throws InvalidInterfaceException
1014
-     * @throws InvalidDataTypeException
1015
-     * @throws EE_Error
1016
-     */
1017
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1018
-    {
1019
-        $model = $this->get_model();
1020
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1021
-            ? $model->get_primary_key_field()->get_name()
1022
-            : $field_to_order_by;
1023
-        $current_value = ! empty($field) ? $this->get($field) : null;
1024
-        if (empty($field) || empty($current_value)) {
1025
-            return array();
1026
-        }
1027
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1028
-    }
1029
-
1030
-
1031
-    /**
1032
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1033
-     * matching the given query conditions.
1034
-     *
1035
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1036
-     * @param int   $limit              How many objects to return.
1037
-     * @param array $query_params       Any additional conditions on the query.
1038
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1039
-     *                                  you can indicate just the columns you want returned
1040
-     * @return array|EE_Base_Class[]
1041
-     * @throws ReflectionException
1042
-     * @throws InvalidArgumentException
1043
-     * @throws InvalidInterfaceException
1044
-     * @throws InvalidDataTypeException
1045
-     * @throws EE_Error
1046
-     */
1047
-    public function previous_x(
1048
-        $field_to_order_by = null,
1049
-        $limit = 1,
1050
-        $query_params = array(),
1051
-        $columns_to_select = null
1052
-    ) {
1053
-        $model = $this->get_model();
1054
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1055
-            ? $model->get_primary_key_field()->get_name()
1056
-            : $field_to_order_by;
1057
-        $current_value = ! empty($field) ? $this->get($field) : null;
1058
-        if (empty($field) || empty($current_value)) {
1059
-            return array();
1060
-        }
1061
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1062
-    }
1063
-
1064
-
1065
-    /**
1066
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1067
-     * matching the given query conditions.
1068
-     *
1069
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1070
-     * @param array $query_params       Any additional conditions on the query.
1071
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1072
-     *                                  you can indicate just the columns you want returned
1073
-     * @return array|EE_Base_Class
1074
-     * @throws ReflectionException
1075
-     * @throws InvalidArgumentException
1076
-     * @throws InvalidInterfaceException
1077
-     * @throws InvalidDataTypeException
1078
-     * @throws EE_Error
1079
-     */
1080
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1081
-    {
1082
-        $model = $this->get_model();
1083
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1084
-            ? $model->get_primary_key_field()->get_name()
1085
-            : $field_to_order_by;
1086
-        $current_value = ! empty($field) ? $this->get($field) : null;
1087
-        if (empty($field) || empty($current_value)) {
1088
-            return array();
1089
-        }
1090
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1096
-     * matching the given query conditions.
1097
-     *
1098
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1099
-     * @param array $query_params       Any additional conditions on the query.
1100
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1101
-     *                                  you can indicate just the column you want returned
1102
-     * @return array|EE_Base_Class
1103
-     * @throws ReflectionException
1104
-     * @throws InvalidArgumentException
1105
-     * @throws InvalidInterfaceException
1106
-     * @throws InvalidDataTypeException
1107
-     * @throws EE_Error
1108
-     */
1109
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1110
-    {
1111
-        $model = $this->get_model();
1112
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1113
-            ? $model->get_primary_key_field()->get_name()
1114
-            : $field_to_order_by;
1115
-        $current_value = ! empty($field) ? $this->get($field) : null;
1116
-        if (empty($field) || empty($current_value)) {
1117
-            return array();
1118
-        }
1119
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1120
-    }
1121
-
1122
-
1123
-    /**
1124
-     * Overrides parent because parent expects old models.
1125
-     * This also doesn't do any validation, and won't work for serialized arrays
1126
-     *
1127
-     * @param string $field_name
1128
-     * @param mixed  $field_value_from_db
1129
-     * @throws ReflectionException
1130
-     * @throws InvalidArgumentException
1131
-     * @throws InvalidInterfaceException
1132
-     * @throws InvalidDataTypeException
1133
-     * @throws EE_Error
1134
-     */
1135
-    public function set_from_db($field_name, $field_value_from_db)
1136
-    {
1137
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1138
-        if ($field_obj instanceof EE_Model_Field_Base) {
1139
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
1140
-            // eg, a CPT model object could have an entry in the posts table, but no
1141
-            // entry in the meta table. Meaning that all its columns in the meta table
1142
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
1143
-            if ($field_value_from_db === null) {
1144
-                if ($field_obj->is_nullable()) {
1145
-                    // if the field allows nulls, then let it be null
1146
-                    $field_value = null;
1147
-                } else {
1148
-                    $field_value = $field_obj->get_default_value();
1149
-                }
1150
-            } else {
1151
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1152
-            }
1153
-            $this->_fields[ $field_name ] = $field_value;
1154
-            $this->_clear_cached_property($field_name);
1155
-        }
1156
-    }
1157
-
1158
-
1159
-    /**
1160
-     * verifies that the specified field is of the correct type
1161
-     *
1162
-     * @param string $field_name
1163
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1164
-     *                                (in cases where the same property may be used for different outputs
1165
-     *                                - i.e. datetime, money etc.)
1166
-     * @return mixed
1167
-     * @throws ReflectionException
1168
-     * @throws InvalidArgumentException
1169
-     * @throws InvalidInterfaceException
1170
-     * @throws InvalidDataTypeException
1171
-     * @throws EE_Error
1172
-     */
1173
-    public function get($field_name, $extra_cache_ref = null)
1174
-    {
1175
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1176
-    }
1177
-
1178
-
1179
-    /**
1180
-     * This method simply returns the RAW unprocessed value for the given property in this class
1181
-     *
1182
-     * @param  string $field_name A valid fieldname
1183
-     * @return mixed              Whatever the raw value stored on the property is.
1184
-     * @throws ReflectionException
1185
-     * @throws InvalidArgumentException
1186
-     * @throws InvalidInterfaceException
1187
-     * @throws InvalidDataTypeException
1188
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1189
-     */
1190
-    public function get_raw($field_name)
1191
-    {
1192
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1193
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1194
-            ? $this->_fields[ $field_name ]->format('U')
1195
-            : $this->_fields[ $field_name ];
1196
-    }
1197
-
1198
-
1199
-    /**
1200
-     * This is used to return the internal DateTime object used for a field that is a
1201
-     * EE_Datetime_Field.
1202
-     *
1203
-     * @param string $field_name               The field name retrieving the DateTime object.
1204
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1205
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1206
-     *                                         EE_Datetime_Field and but the field value is null, then
1207
-     *                                         just null is returned (because that indicates that likely
1208
-     *                                         this field is nullable).
1209
-     * @throws InvalidArgumentException
1210
-     * @throws InvalidDataTypeException
1211
-     * @throws InvalidInterfaceException
1212
-     * @throws ReflectionException
1213
-     */
1214
-    public function get_DateTime_object($field_name)
1215
-    {
1216
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1217
-        if (! $field_settings instanceof EE_Datetime_Field) {
1218
-            EE_Error::add_error(
1219
-                sprintf(
1220
-                    esc_html__(
1221
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1222
-                        'event_espresso'
1223
-                    ),
1224
-                    $field_name
1225
-                ),
1226
-                __FILE__,
1227
-                __FUNCTION__,
1228
-                __LINE__
1229
-            );
1230
-            return false;
1231
-        }
1232
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1233
-            ? clone $this->_fields[ $field_name ]
1234
-            : null;
1235
-    }
1236
-
1237
-
1238
-    /**
1239
-     * To be used in template to immediately echo out the value, and format it for output.
1240
-     * Eg, should call stripslashes and whatnot before echoing
1241
-     *
1242
-     * @param string $field_name      the name of the field as it appears in the DB
1243
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1244
-     *                                (in cases where the same property may be used for different outputs
1245
-     *                                - i.e. datetime, money etc.)
1246
-     * @return void
1247
-     * @throws ReflectionException
1248
-     * @throws InvalidArgumentException
1249
-     * @throws InvalidInterfaceException
1250
-     * @throws InvalidDataTypeException
1251
-     * @throws EE_Error
1252
-     */
1253
-    public function e($field_name, $extra_cache_ref = null)
1254
-    {
1255
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1256
-    }
1257
-
1258
-
1259
-    /**
1260
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1261
-     * can be easily used as the value of form input.
1262
-     *
1263
-     * @param string $field_name
1264
-     * @return void
1265
-     * @throws ReflectionException
1266
-     * @throws InvalidArgumentException
1267
-     * @throws InvalidInterfaceException
1268
-     * @throws InvalidDataTypeException
1269
-     * @throws EE_Error
1270
-     */
1271
-    public function f($field_name)
1272
-    {
1273
-        $this->e($field_name, 'form_input');
1274
-    }
1275
-
1276
-
1277
-    /**
1278
-     * Same as `f()` but just returns the value instead of echoing it
1279
-     *
1280
-     * @param string $field_name
1281
-     * @return string
1282
-     * @throws ReflectionException
1283
-     * @throws InvalidArgumentException
1284
-     * @throws InvalidInterfaceException
1285
-     * @throws InvalidDataTypeException
1286
-     * @throws EE_Error
1287
-     */
1288
-    public function get_f($field_name)
1289
-    {
1290
-        return (string) $this->get_pretty($field_name, 'form_input');
1291
-    }
1292
-
1293
-
1294
-    /**
1295
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1296
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1297
-     * to see what options are available.
1298
-     *
1299
-     * @param string $field_name
1300
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1301
-     *                                (in cases where the same property may be used for different outputs
1302
-     *                                - i.e. datetime, money etc.)
1303
-     * @return mixed
1304
-     * @throws ReflectionException
1305
-     * @throws InvalidArgumentException
1306
-     * @throws InvalidInterfaceException
1307
-     * @throws InvalidDataTypeException
1308
-     * @throws EE_Error
1309
-     */
1310
-    public function get_pretty($field_name, $extra_cache_ref = null)
1311
-    {
1312
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1313
-    }
1314
-
1315
-
1316
-    /**
1317
-     * This simply returns the datetime for the given field name
1318
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1319
-     * (and the equivalent e_date, e_time, e_datetime).
1320
-     *
1321
-     * @access   protected
1322
-     * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1323
-     * @param string|null $date_format  valid datetime format used for date
1324
-     *                                  (if '' then we just use the default on the field,
1325
-     *                                  if NULL we use the last-used format)
1326
-     * @param string|null $time_format  Same as above except this is for time format
1327
-     * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1328
-     * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1329
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1330
-     *                                  if field is not a valid dtt field, or void if echoing
1331
-     * @throws EE_Error
1332
-     * @throws ReflectionException
1333
-     */
1334
-    protected function _get_datetime(
1335
-        string $field_name,
1336
-        ?string $date_format = '',
1337
-        ?string $time_format = '',
1338
-        ?string $date_or_time = '',
1339
-        ?bool $echo = false
1340
-    ) {
1341
-        // clear cached property
1342
-        $this->_clear_cached_property($field_name);
1343
-        // reset format properties because they are used in get()
1344
-        $this->_dt_frmt = $date_format !== '' ? $date_format : $this->_dt_frmt;
1345
-        $this->_tm_frmt = $time_format !== '' ? $time_format : $this->_tm_frmt;
1346
-        if ($echo) {
1347
-            $this->e($field_name, $date_or_time);
1348
-            return '';
1349
-        }
1350
-        return $this->get($field_name, $date_or_time);
1351
-    }
1352
-
1353
-
1354
-    /**
1355
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
-     * other echoes the pretty value for dtt)
1358
-     *
1359
-     * @param  string $field_name name of model object datetime field holding the value
1360
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
-     * @return string            datetime value formatted
1362
-     * @throws ReflectionException
1363
-     * @throws InvalidArgumentException
1364
-     * @throws InvalidInterfaceException
1365
-     * @throws InvalidDataTypeException
1366
-     * @throws EE_Error
1367
-     */
1368
-    public function get_date($field_name, $format = '')
1369
-    {
1370
-        return $this->_get_datetime($field_name, $format, null, 'D');
1371
-    }
1372
-
1373
-
1374
-    /**
1375
-     * @param        $field_name
1376
-     * @param string $format
1377
-     * @throws ReflectionException
1378
-     * @throws InvalidArgumentException
1379
-     * @throws InvalidInterfaceException
1380
-     * @throws InvalidDataTypeException
1381
-     * @throws EE_Error
1382
-     */
1383
-    public function e_date($field_name, $format = '')
1384
-    {
1385
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1386
-    }
1387
-
1388
-
1389
-    /**
1390
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
-     * other echoes the pretty value for dtt)
1393
-     *
1394
-     * @param  string $field_name name of model object datetime field holding the value
1395
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
-     * @return string             datetime value formatted
1397
-     * @throws ReflectionException
1398
-     * @throws InvalidArgumentException
1399
-     * @throws InvalidInterfaceException
1400
-     * @throws InvalidDataTypeException
1401
-     * @throws EE_Error
1402
-     */
1403
-    public function get_time($field_name, $format = '')
1404
-    {
1405
-        return $this->_get_datetime($field_name, null, $format, 'T');
1406
-    }
1407
-
1408
-
1409
-    /**
1410
-     * @param        $field_name
1411
-     * @param string $format
1412
-     * @throws ReflectionException
1413
-     * @throws InvalidArgumentException
1414
-     * @throws InvalidInterfaceException
1415
-     * @throws InvalidDataTypeException
1416
-     * @throws EE_Error
1417
-     */
1418
-    public function e_time($field_name, $format = '')
1419
-    {
1420
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1421
-    }
1422
-
1423
-
1424
-    /**
1425
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
-     * other echoes the pretty value for dtt)
1428
-     *
1429
-     * @param  string $field_name name of model object datetime field holding the value
1430
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
-     * @return string             datetime value formatted
1433
-     * @throws ReflectionException
1434
-     * @throws InvalidArgumentException
1435
-     * @throws InvalidInterfaceException
1436
-     * @throws InvalidDataTypeException
1437
-     * @throws EE_Error
1438
-     */
1439
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
-    {
1441
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
-    }
1443
-
1444
-
1445
-    /**
1446
-     * @param string $field_name
1447
-     * @param string $dt_frmt
1448
-     * @param string $tm_frmt
1449
-     * @throws ReflectionException
1450
-     * @throws InvalidArgumentException
1451
-     * @throws InvalidInterfaceException
1452
-     * @throws InvalidDataTypeException
1453
-     * @throws EE_Error
1454
-     */
1455
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
-    {
1457
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
-    }
1459
-
1460
-
1461
-    /**
1462
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
-     *
1464
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
-     *                           on the object will be used.
1467
-     * @return string Date and time string in set locale or false if no field exists for the given
1468
-     * @throws ReflectionException
1469
-     * @throws InvalidArgumentException
1470
-     * @throws InvalidInterfaceException
1471
-     * @throws InvalidDataTypeException
1472
-     * @throws EE_Error
1473
-     *                           field name.
1474
-     */
1475
-    public function get_i18n_datetime($field_name, $format = '')
1476
-    {
1477
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
-        return date_i18n(
1479
-            $format,
1480
-            EEH_DTT_Helper::get_timestamp_with_offset(
1481
-                $this->get_raw($field_name),
1482
-                $this->_timezone
1483
-            )
1484
-        );
1485
-    }
1486
-
1487
-
1488
-    /**
1489
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
-     * thrown.
1492
-     *
1493
-     * @param  string $field_name The field name being checked
1494
-     * @throws ReflectionException
1495
-     * @throws InvalidArgumentException
1496
-     * @throws InvalidInterfaceException
1497
-     * @throws InvalidDataTypeException
1498
-     * @throws EE_Error
1499
-     * @return EE_Datetime_Field
1500
-     */
1501
-    protected function _get_dtt_field_settings($field_name)
1502
-    {
1503
-        $field = $this->get_model()->field_settings_for($field_name);
1504
-        // check if field is dtt
1505
-        if ($field instanceof EE_Datetime_Field) {
1506
-            return $field;
1507
-        }
1508
-        throw new EE_Error(
1509
-            sprintf(
1510
-                esc_html__(
1511
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1512
-                    'event_espresso'
1513
-                ),
1514
-                $field_name,
1515
-                self::_get_model_classname(get_class($this))
1516
-            )
1517
-        );
1518
-    }
1519
-
1520
-
1521
-
1522
-
1523
-    /**
1524
-     * NOTE ABOUT BELOW:
1525
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
-     * method and make sure you send the entire datetime value for setting.
1529
-     */
1530
-    /**
1531
-     * sets the time on a datetime property
1532
-     *
1533
-     * @access protected
1534
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
-     * @throws ReflectionException
1537
-     * @throws InvalidArgumentException
1538
-     * @throws InvalidInterfaceException
1539
-     * @throws InvalidDataTypeException
1540
-     * @throws EE_Error
1541
-     */
1542
-    protected function _set_time_for($time, $fieldname)
1543
-    {
1544
-        $this->_set_date_time('T', $time, $fieldname);
1545
-    }
1546
-
1547
-
1548
-    /**
1549
-     * sets the date on a datetime property
1550
-     *
1551
-     * @access protected
1552
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
-     * @throws ReflectionException
1555
-     * @throws InvalidArgumentException
1556
-     * @throws InvalidInterfaceException
1557
-     * @throws InvalidDataTypeException
1558
-     * @throws EE_Error
1559
-     */
1560
-    protected function _set_date_for($date, $fieldname)
1561
-    {
1562
-        $this->_set_date_time('D', $date, $fieldname);
1563
-    }
1564
-
1565
-
1566
-    /**
1567
-     * This takes care of setting a date or time independently on a given model object property. This method also
1568
-     * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1569
-     *
1570
-     * @access protected
1571
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
-     * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1574
-     *                                        EE_Datetime_Field property)
1575
-     * @throws ReflectionException
1576
-     * @throws InvalidArgumentException
1577
-     * @throws InvalidInterfaceException
1578
-     * @throws InvalidDataTypeException
1579
-     * @throws EE_Error
1580
-     */
1581
-    protected function _set_date_time(string $what, $datetime_value, string $field_name)
1582
-    {
1583
-        $field = $this->_get_dtt_field_settings($field_name);
1584
-        $field->set_timezone($this->_timezone);
1585
-        $field->set_date_format($this->_dt_frmt);
1586
-        $field->set_time_format($this->_tm_frmt);
1587
-        switch ($what) {
1588
-            case 'T':
1589
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1590
-                    $datetime_value,
1591
-                    $this->_fields[ $field_name ]
1592
-                );
1593
-                $this->_has_changes = true;
1594
-                break;
1595
-            case 'D':
1596
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1597
-                    $datetime_value,
1598
-                    $this->_fields[ $field_name ]
1599
-                );
1600
-                $this->_has_changes = true;
1601
-                break;
1602
-            case 'B':
1603
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1604
-                $this->_has_changes = true;
1605
-                break;
1606
-        }
1607
-        $this->_clear_cached_property($field_name);
1608
-    }
1609
-
1610
-
1611
-    /**
1612
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
-     * that could lead to some unexpected results!
1616
-     *
1617
-     * @access public
1618
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
-     *                                         value being returned.
1620
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
-     * @param string $prepend                  You can include something to prepend on the timestamp
1623
-     * @param string $append                   You can include something to append on the timestamp
1624
-     * @throws ReflectionException
1625
-     * @throws InvalidArgumentException
1626
-     * @throws InvalidInterfaceException
1627
-     * @throws InvalidDataTypeException
1628
-     * @throws EE_Error
1629
-     * @return string timestamp
1630
-     */
1631
-    public function display_in_my_timezone(
1632
-        $field_name,
1633
-        $callback = 'get_datetime',
1634
-        $args = null,
1635
-        $prepend = '',
1636
-        $append = ''
1637
-    ) {
1638
-        $timezone = EEH_DTT_Helper::get_timezone();
1639
-        if ($timezone === $this->_timezone) {
1640
-            return '';
1641
-        }
1642
-        $original_timezone = $this->_timezone;
1643
-        $this->set_timezone($timezone);
1644
-        $fn = (array) $field_name;
1645
-        $args = array_merge($fn, (array) $args);
1646
-        if (! method_exists($this, $callback)) {
1647
-            throw new EE_Error(
1648
-                sprintf(
1649
-                    esc_html__(
1650
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
-                        'event_espresso'
1652
-                    ),
1653
-                    $callback
1654
-                )
1655
-            );
1656
-        }
1657
-        $args = (array) $args;
1658
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
-        $this->set_timezone($original_timezone);
1660
-        return $return;
1661
-    }
1662
-
1663
-
1664
-    /**
1665
-     * Deletes this model object.
1666
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
-     * override
1668
-     * `EE_Base_Class::_delete` NOT this class.
1669
-     *
1670
-     * @return boolean | int
1671
-     * @throws ReflectionException
1672
-     * @throws InvalidArgumentException
1673
-     * @throws InvalidInterfaceException
1674
-     * @throws InvalidDataTypeException
1675
-     * @throws EE_Error
1676
-     */
1677
-    public function delete()
1678
-    {
1679
-        /**
1680
-         * Called just before the `EE_Base_Class::_delete` method call.
1681
-         * Note:
1682
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
-         * should be aware that `_delete` may not always result in a permanent delete.
1684
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
-         * soft deletes (trash) the object and does not permanently delete it.
1686
-         *
1687
-         * @param EE_Base_Class $model_object about to be 'deleted'
1688
-         */
1689
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
-        $result = $this->_delete();
1691
-        /**
1692
-         * Called just after the `EE_Base_Class::_delete` method call.
1693
-         * Note:
1694
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
-         * should be aware that `_delete` may not always result in a permanent delete.
1696
-         * For example `EE_Soft_Base_Class::_delete`
1697
-         * soft deletes (trash) the object and does not permanently delete it.
1698
-         *
1699
-         * @param EE_Base_Class $model_object that was just 'deleted'
1700
-         * @param boolean       $result
1701
-         */
1702
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
-        return $result;
1704
-    }
1705
-
1706
-
1707
-    /**
1708
-     * Calls the specific delete method for the instantiated class.
1709
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
-     * `EE_Base_Class::delete`
1712
-     *
1713
-     * @return bool|int
1714
-     * @throws ReflectionException
1715
-     * @throws InvalidArgumentException
1716
-     * @throws InvalidInterfaceException
1717
-     * @throws InvalidDataTypeException
1718
-     * @throws EE_Error
1719
-     */
1720
-    protected function _delete()
1721
-    {
1722
-        return $this->delete_permanently();
1723
-    }
1724
-
1725
-
1726
-    /**
1727
-     * Deletes this model object permanently from db
1728
-     * (but keep in mind related models may block the delete and return an error)
1729
-     *
1730
-     * @return bool | int
1731
-     * @throws ReflectionException
1732
-     * @throws InvalidArgumentException
1733
-     * @throws InvalidInterfaceException
1734
-     * @throws InvalidDataTypeException
1735
-     * @throws EE_Error
1736
-     */
1737
-    public function delete_permanently()
1738
-    {
1739
-        /**
1740
-         * Called just before HARD deleting a model object
1741
-         *
1742
-         * @param EE_Base_Class $model_object about to be 'deleted'
1743
-         */
1744
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
-        $model = $this->get_model();
1746
-        $result = $model->delete_permanently_by_ID($this->ID());
1747
-        $this->refresh_cache_of_related_objects();
1748
-        /**
1749
-         * Called just after HARD deleting a model object
1750
-         *
1751
-         * @param EE_Base_Class $model_object that was just 'deleted'
1752
-         * @param boolean       $result
1753
-         */
1754
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
-        return $result;
1756
-    }
1757
-
1758
-
1759
-    /**
1760
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
-     * related model objects
1762
-     *
1763
-     * @throws ReflectionException
1764
-     * @throws InvalidArgumentException
1765
-     * @throws InvalidInterfaceException
1766
-     * @throws InvalidDataTypeException
1767
-     * @throws EE_Error
1768
-     */
1769
-    public function refresh_cache_of_related_objects()
1770
-    {
1771
-        $model = $this->get_model();
1772
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
-            if (! empty($this->_model_relations[ $relation_name ])) {
1774
-                $related_objects = $this->_model_relations[ $relation_name ];
1775
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
-                    // this relation only stores a single model object, not an array
1777
-                    // but let's make it consistent
1778
-                    $related_objects = array($related_objects);
1779
-                }
1780
-                foreach ($related_objects as $related_object) {
1781
-                    // only refresh their cache if they're in memory
1782
-                    if ($related_object instanceof EE_Base_Class) {
1783
-                        $related_object->clear_cache(
1784
-                            $model->get_this_model_name(),
1785
-                            $this
1786
-                        );
1787
-                    }
1788
-                }
1789
-            }
1790
-        }
1791
-    }
1792
-
1793
-
1794
-    /**
1795
-     *        Saves this object to the database. An array may be supplied to set some values on this
1796
-     * object just before saving.
1797
-     *
1798
-     * @access public
1799
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1800
-     *                                 if provided during the save() method (often client code will change the fields'
1801
-     *                                 values before calling save)
1802
-     * @return bool|int|string         1 on a successful update
1803
-     *                                 the ID of the new entry on insert
1804
-     *                                 0 on failure or if the model object isn't allowed to persist
1805
-     *                                 (as determined by EE_Base_Class::allow_persist())
1806
-     * @throws InvalidInterfaceException
1807
-     * @throws InvalidDataTypeException
1808
-     * @throws EE_Error
1809
-     * @throws InvalidArgumentException
1810
-     * @throws ReflectionException
1811
-     * @throws ReflectionException
1812
-     * @throws ReflectionException
1813
-     */
1814
-    public function save($set_cols_n_values = array())
1815
-    {
1816
-        $model = $this->get_model();
1817
-        /**
1818
-         * Filters the fields we're about to save on the model object
1819
-         *
1820
-         * @param array         $set_cols_n_values
1821
-         * @param EE_Base_Class $model_object
1822
-         */
1823
-        $set_cols_n_values = (array) apply_filters(
1824
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
-            $set_cols_n_values,
1826
-            $this
1827
-        );
1828
-        // set attributes as provided in $set_cols_n_values
1829
-        foreach ($set_cols_n_values as $column => $value) {
1830
-            $this->set($column, $value);
1831
-        }
1832
-        // no changes ? then don't do anything
1833
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
-            return 0;
1835
-        }
1836
-        /**
1837
-         * Saving a model object.
1838
-         * Before we perform a save, this action is fired.
1839
-         *
1840
-         * @param EE_Base_Class $model_object the model object about to be saved.
1841
-         */
1842
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
-        if (! $this->allow_persist()) {
1844
-            return 0;
1845
-        }
1846
-        // now get current attribute values
1847
-        $save_cols_n_values = $this->_fields;
1848
-        // if the object already has an ID, update it. Otherwise, insert it
1849
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
-        // They have been
1851
-        $old_assumption_concerning_value_preparation = $model
1852
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1853
-        $model->assume_values_already_prepared_by_model_object(true);
1854
-        // does this model have an autoincrement PK?
1855
-        if ($model->has_primary_key_field()) {
1856
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1857
-                // ok check if it's set, if so: update; if not, insert
1858
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
-                } else {
1861
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
-                    $results = $model->insert($save_cols_n_values);
1863
-                    if ($results) {
1864
-                        // if successful, set the primary key
1865
-                        // but don't use the normal SET method, because it will check if
1866
-                        // an item with the same ID exists in the mapper & db, then
1867
-                        // will find it in the db (because we just added it) and THAT object
1868
-                        // will get added to the mapper before we can add this one!
1869
-                        // but if we just avoid using the SET method, all that headache can be avoided
1870
-                        $pk_field_name = $model->primary_key_name();
1871
-                        $this->_fields[ $pk_field_name ] = $results;
1872
-                        $this->_clear_cached_property($pk_field_name);
1873
-                        $model->add_to_entity_map($this);
1874
-                        $this->_update_cached_related_model_objs_fks();
1875
-                    }
1876
-                }
1877
-            } else {// PK is NOT auto-increment
1878
-                // so check if one like it already exists in the db
1879
-                if ($model->exists_by_ID($this->ID())) {
1880
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1881
-                        throw new EE_Error(
1882
-                            sprintf(
1883
-                                esc_html__(
1884
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1885
-                                    'event_espresso'
1886
-                                ),
1887
-                                get_class($this),
1888
-                                get_class($model) . '::instance()->add_to_entity_map()',
1889
-                                get_class($model) . '::instance()->get_one_by_ID()',
1890
-                                '<br />'
1891
-                            )
1892
-                        );
1893
-                    }
1894
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
-                } else {
1896
-                    $results = $model->insert($save_cols_n_values);
1897
-                    $this->_update_cached_related_model_objs_fks();
1898
-                }
1899
-            }
1900
-        } else {// there is NO primary key
1901
-            $already_in_db = false;
1902
-            foreach ($model->unique_indexes() as $index) {
1903
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
-                if ($model->exists(array($uniqueness_where_params))) {
1905
-                    $already_in_db = true;
1906
-                }
1907
-            }
1908
-            if ($already_in_db) {
1909
-                $combined_pk_fields_n_values = array_intersect_key(
1910
-                    $save_cols_n_values,
1911
-                    $model->get_combined_primary_key_fields()
1912
-                );
1913
-                $results = $model->update(
1914
-                    $save_cols_n_values,
1915
-                    $combined_pk_fields_n_values
1916
-                );
1917
-            } else {
1918
-                $results = $model->insert($save_cols_n_values);
1919
-            }
1920
-        }
1921
-        // restore the old assumption about values being prepared by the model object
1922
-        $model->assume_values_already_prepared_by_model_object(
1923
-            $old_assumption_concerning_value_preparation
1924
-        );
1925
-        /**
1926
-         * After saving the model object this action is called
1927
-         *
1928
-         * @param EE_Base_Class $model_object which was just saved
1929
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
-         */
1932
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
-        $this->_has_changes = false;
1934
-        return $results;
1935
-    }
1936
-
1937
-
1938
-    /**
1939
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1944
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
-     *
1947
-     * @return void
1948
-     * @throws ReflectionException
1949
-     * @throws InvalidArgumentException
1950
-     * @throws InvalidInterfaceException
1951
-     * @throws InvalidDataTypeException
1952
-     * @throws EE_Error
1953
-     */
1954
-    protected function _update_cached_related_model_objs_fks()
1955
-    {
1956
-        $model = $this->get_model();
1957
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
-                        $model->get_this_model_name()
1962
-                    );
1963
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
-                    if ($related_model_obj_in_cache->ID()) {
1965
-                        $related_model_obj_in_cache->save();
1966
-                    }
1967
-                }
1968
-            }
1969
-        }
1970
-    }
1971
-
1972
-
1973
-    /**
1974
-     * Saves this model object and its NEW cached relations to the database.
1975
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1977
-     * because otherwise, there's a potential for infinite looping of saving
1978
-     * Saves the cached related model objects, and ensures the relation between them
1979
-     * and this object and properly setup
1980
-     *
1981
-     * @return int ID of new model object on save; 0 on failure+
1982
-     * @throws ReflectionException
1983
-     * @throws InvalidArgumentException
1984
-     * @throws InvalidInterfaceException
1985
-     * @throws InvalidDataTypeException
1986
-     * @throws EE_Error
1987
-     */
1988
-    public function save_new_cached_related_model_objs()
1989
-    {
1990
-        // make sure this has been saved
1991
-        if (! $this->ID()) {
1992
-            $id = $this->save();
1993
-        } else {
1994
-            $id = $this->ID();
1995
-        }
1996
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
-            if ($this->_model_relations[ $relationName ]) {
1999
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
-                /* @var $related_model_obj EE_Base_Class */
2002
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2004
-                    // but ONLY if it DOES NOT exist in the DB
2005
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2006
-                    // if( ! $related_model_obj->ID()){
2007
-                    $this->_add_relation_to($related_model_obj, $relationName);
2008
-                    $related_model_obj->save_new_cached_related_model_objs();
2009
-                    // }
2010
-                } else {
2011
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2013
-                        // but ONLY if it DOES NOT exist in the DB
2014
-                        // if( ! $related_model_obj->ID()){
2015
-                        $this->_add_relation_to($related_model_obj, $relationName);
2016
-                        $related_model_obj->save_new_cached_related_model_objs();
2017
-                        // }
2018
-                    }
2019
-                }
2020
-            }
2021
-        }
2022
-        return $id;
2023
-    }
2024
-
2025
-
2026
-    /**
2027
-     * for getting a model while instantiated.
2028
-     *
2029
-     * @return EEM_Base | EEM_CPT_Base
2030
-     * @throws ReflectionException
2031
-     * @throws InvalidArgumentException
2032
-     * @throws InvalidInterfaceException
2033
-     * @throws InvalidDataTypeException
2034
-     * @throws EE_Error
2035
-     */
2036
-    public function get_model()
2037
-    {
2038
-        if (! $this->_model) {
2039
-            $modelName = self::_get_model_classname(get_class($this));
2040
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
-        } else {
2042
-            $this->_model->set_timezone($this->_timezone);
2043
-        }
2044
-        return $this->_model;
2045
-    }
2046
-
2047
-
2048
-    /**
2049
-     * @param $props_n_values
2050
-     * @param $classname
2051
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
-     * @throws ReflectionException
2053
-     * @throws InvalidArgumentException
2054
-     * @throws InvalidInterfaceException
2055
-     * @throws InvalidDataTypeException
2056
-     * @throws EE_Error
2057
-     */
2058
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
-    {
2060
-        // TODO: will not work for Term_Relationships because they have no PK!
2061
-        $primary_id_ref = self::_get_primary_key_name($classname);
2062
-        if (
2063
-            array_key_exists($primary_id_ref, $props_n_values)
2064
-            && ! empty($props_n_values[ $primary_id_ref ])
2065
-        ) {
2066
-            $id = $props_n_values[ $primary_id_ref ];
2067
-            return self::_get_model($classname)->get_from_entity_map($id);
2068
-        }
2069
-        return false;
2070
-    }
2071
-
2072
-
2073
-    /**
2074
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2077
-     * we return false.
2078
-     *
2079
-     * @param  array  $props_n_values   incoming array of properties and their values
2080
-     * @param  string $classname        the classname of the child class
2081
-     * @param null    $timezone
2082
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
-     *                                  date_format and the second value is the time format
2084
-     * @return mixed (EE_Base_Class|bool)
2085
-     * @throws InvalidArgumentException
2086
-     * @throws InvalidInterfaceException
2087
-     * @throws InvalidDataTypeException
2088
-     * @throws EE_Error
2089
-     * @throws ReflectionException
2090
-     * @throws ReflectionException
2091
-     * @throws ReflectionException
2092
-     */
2093
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
-    {
2095
-        $existing = null;
2096
-        $model = self::_get_model($classname, $timezone);
2097
-        if ($model->has_primary_key_field()) {
2098
-            $primary_id_ref = self::_get_primary_key_name($classname);
2099
-            if (
2100
-                array_key_exists($primary_id_ref, $props_n_values)
2101
-                && ! empty($props_n_values[ $primary_id_ref ])
2102
-            ) {
2103
-                $existing = $model->get_one_by_ID(
2104
-                    $props_n_values[ $primary_id_ref ]
2105
-                );
2106
-            }
2107
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
-            // no primary key on this model, but there's still a matching item in the DB
2109
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
-                self::_get_model($classname, $timezone)
2111
-                    ->get_index_primary_key_string($props_n_values)
2112
-            );
2113
-        }
2114
-        if ($existing) {
2115
-            // set date formats if present before setting values
2116
-            if (! empty($date_formats) && is_array($date_formats)) {
2117
-                $existing->set_date_format($date_formats[0]);
2118
-                $existing->set_time_format($date_formats[1]);
2119
-            } else {
2120
-                // set default formats for date and time
2121
-                $existing->set_date_format(get_option('date_format'));
2122
-                $existing->set_time_format(get_option('time_format'));
2123
-            }
2124
-            foreach ($props_n_values as $property => $field_value) {
2125
-                $existing->set($property, $field_value);
2126
-            }
2127
-            return $existing;
2128
-        }
2129
-        return false;
2130
-    }
2131
-
2132
-
2133
-    /**
2134
-     * Gets the EEM_*_Model for this class
2135
-     *
2136
-     * @access public now, as this is more convenient
2137
-     * @param      $classname
2138
-     * @param null $timezone
2139
-     * @throws ReflectionException
2140
-     * @throws InvalidArgumentException
2141
-     * @throws InvalidInterfaceException
2142
-     * @throws InvalidDataTypeException
2143
-     * @throws EE_Error
2144
-     * @return EEM_Base
2145
-     */
2146
-    protected static function _get_model($classname, $timezone = null)
2147
-    {
2148
-        // find model for this class
2149
-        if (! $classname) {
2150
-            throw new EE_Error(
2151
-                sprintf(
2152
-                    esc_html__(
2153
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
-                        'event_espresso'
2155
-                    ),
2156
-                    $classname
2157
-                )
2158
-            );
2159
-        }
2160
-        $modelName = self::_get_model_classname($classname);
2161
-        return self::_get_model_instance_with_name($modelName, $timezone);
2162
-    }
2163
-
2164
-
2165
-    /**
2166
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
-     *
2168
-     * @param string $model_classname
2169
-     * @param null   $timezone
2170
-     * @return EEM_Base
2171
-     * @throws ReflectionException
2172
-     * @throws InvalidArgumentException
2173
-     * @throws InvalidInterfaceException
2174
-     * @throws InvalidDataTypeException
2175
-     * @throws EE_Error
2176
-     */
2177
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
-    {
2179
-        $model_classname = str_replace('EEM_', '', $model_classname);
2180
-        $model = EE_Registry::instance()->load_model($model_classname);
2181
-        $model->set_timezone($timezone);
2182
-        return $model;
2183
-    }
2184
-
2185
-
2186
-    /**
2187
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2188
-     * Also works if a model class's classname is provided (eg EE_Registration).
2189
-     *
2190
-     * @param string|null $model_name
2191
-     * @return string like EEM_Attendee
2192
-     */
2193
-    private static function _get_model_classname($model_name = '')
2194
-    {
2195
-        return strpos((string) $model_name, 'EE_') === 0
2196
-            ? str_replace('EE_', 'EEM_', $model_name)
2197
-            : 'EEM_' . $model_name;
2198
-    }
2199
-
2200
-
2201
-    /**
2202
-     * returns the name of the primary key attribute
2203
-     *
2204
-     * @param null $classname
2205
-     * @throws ReflectionException
2206
-     * @throws InvalidArgumentException
2207
-     * @throws InvalidInterfaceException
2208
-     * @throws InvalidDataTypeException
2209
-     * @throws EE_Error
2210
-     * @return string
2211
-     */
2212
-    protected static function _get_primary_key_name($classname = null)
2213
-    {
2214
-        if (! $classname) {
2215
-            throw new EE_Error(
2216
-                sprintf(
2217
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2218
-                    $classname
2219
-                )
2220
-            );
2221
-        }
2222
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2223
-    }
2224
-
2225
-
2226
-    /**
2227
-     * Gets the value of the primary key.
2228
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2229
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2230
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2231
-     *
2232
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2233
-     * @throws ReflectionException
2234
-     * @throws InvalidArgumentException
2235
-     * @throws InvalidInterfaceException
2236
-     * @throws InvalidDataTypeException
2237
-     * @throws EE_Error
2238
-     */
2239
-    public function ID()
2240
-    {
2241
-        $model = $this->get_model();
2242
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2243
-        if ($model->has_primary_key_field()) {
2244
-            return $this->_fields[ $model->primary_key_name() ];
2245
-        }
2246
-        return $model->get_index_primary_key_string($this->_fields);
2247
-    }
2248
-
2249
-
2250
-    /**
2251
-     * @param EE_Base_Class|int|string $otherModelObjectOrID
2252
-     * @param string                   $relationName
2253
-     * @return bool
2254
-     * @throws EE_Error
2255
-     * @throws ReflectionException
2256
-     * @since   5.0.0.p
2257
-     */
2258
-    public function hasRelation($otherModelObjectOrID, string $relationName): bool
2259
-    {
2260
-        $other_model = self::_get_model_instance_with_name(
2261
-            self::_get_model_classname($relationName),
2262
-            $this->_timezone
2263
-        );
2264
-        $primary_key = $other_model->primary_key_name();
2265
-        /** @var EE_Base_Class $otherModelObject */
2266
-        $otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2267
-        return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2268
-    }
2269
-
2270
-
2271
-    /**
2272
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2273
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2274
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2275
-     *
2276
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2277
-     * @param string $relationName                     eg 'Events','Question',etc.
2278
-     *                                                 an attendee to a group, you also want to specify which role they
2279
-     *                                                 will have in that group. So you would use this parameter to
2280
-     *                                                 specify array('role-column-name'=>'role-id')
2281
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2282
-     *                                                 allow you to further constrict the relation to being added.
2283
-     *                                                 However, keep in mind that the columns (keys) given must match a
2284
-     *                                                 column on the JOIN table and currently only the HABTM models
2285
-     *                                                 accept these additional conditions.  Also remember that if an
2286
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2287
-     *                                                 NEW row is created in the join table.
2288
-     * @param null   $cache_id
2289
-     * @throws ReflectionException
2290
-     * @throws InvalidArgumentException
2291
-     * @throws InvalidInterfaceException
2292
-     * @throws InvalidDataTypeException
2293
-     * @throws EE_Error
2294
-     * @return EE_Base_Class the object the relation was added to
2295
-     */
2296
-    public function _add_relation_to(
2297
-        $otherObjectModelObjectOrID,
2298
-        $relationName,
2299
-        $extra_join_model_fields_n_values = array(),
2300
-        $cache_id = null
2301
-    ) {
2302
-        $model = $this->get_model();
2303
-        // if this thing exists in the DB, save the relation to the DB
2304
-        if ($this->ID()) {
2305
-            $otherObject = $model->add_relationship_to(
2306
-                $this,
2307
-                $otherObjectModelObjectOrID,
2308
-                $relationName,
2309
-                $extra_join_model_fields_n_values
2310
-            );
2311
-            // clear cache so future get_many_related and get_first_related() return new results.
2312
-            $this->clear_cache($relationName, $otherObject, true);
2313
-            if ($otherObject instanceof EE_Base_Class) {
2314
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2315
-            }
2316
-        } else {
2317
-            // this thing doesn't exist in the DB,  so just cache it
2318
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2319
-                throw new EE_Error(
2320
-                    sprintf(
2321
-                        esc_html__(
2322
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2323
-                            'event_espresso'
2324
-                        ),
2325
-                        $otherObjectModelObjectOrID,
2326
-                        get_class($this)
2327
-                    )
2328
-                );
2329
-            }
2330
-            $otherObject = $otherObjectModelObjectOrID;
2331
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2332
-        }
2333
-        if ($otherObject instanceof EE_Base_Class) {
2334
-            // fix the reciprocal relation too
2335
-            if ($otherObject->ID()) {
2336
-                // its saved so assumed relations exist in the DB, so we can just
2337
-                // clear the cache so future queries use the updated info in the DB
2338
-                $otherObject->clear_cache(
2339
-                    $model->get_this_model_name(),
2340
-                    null,
2341
-                    true
2342
-                );
2343
-            } else {
2344
-                // it's not saved, so it caches relations like this
2345
-                $otherObject->cache($model->get_this_model_name(), $this);
2346
-            }
2347
-        }
2348
-        return $otherObject;
2349
-    }
2350
-
2351
-
2352
-    /**
2353
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2354
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2355
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2356
-     * from the cache
2357
-     *
2358
-     * @param mixed  $otherObjectModelObjectOrID
2359
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2360
-     *                to the DB yet
2361
-     * @param string $relationName
2362
-     * @param array  $where_query
2363
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2364
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2365
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2366
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2367
-     *                deleted.
2368
-     * @return EE_Base_Class the relation was removed from
2369
-     * @throws ReflectionException
2370
-     * @throws InvalidArgumentException
2371
-     * @throws InvalidInterfaceException
2372
-     * @throws InvalidDataTypeException
2373
-     * @throws EE_Error
2374
-     */
2375
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2376
-    {
2377
-        if ($this->ID()) {
2378
-            // if this exists in the DB, save the relation change to the DB too
2379
-            $otherObject = $this->get_model()->remove_relationship_to(
2380
-                $this,
2381
-                $otherObjectModelObjectOrID,
2382
-                $relationName,
2383
-                $where_query
2384
-            );
2385
-            $this->clear_cache(
2386
-                $relationName,
2387
-                $otherObject
2388
-            );
2389
-        } else {
2390
-            // this doesn't exist in the DB, just remove it from the cache
2391
-            $otherObject = $this->clear_cache(
2392
-                $relationName,
2393
-                $otherObjectModelObjectOrID
2394
-            );
2395
-        }
2396
-        if ($otherObject instanceof EE_Base_Class) {
2397
-            $otherObject->clear_cache(
2398
-                $this->get_model()->get_this_model_name(),
2399
-                $this
2400
-            );
2401
-        }
2402
-        return $otherObject;
2403
-    }
2404
-
2405
-
2406
-    /**
2407
-     * Removes ALL the related things for the $relationName.
2408
-     *
2409
-     * @param string $relationName
2410
-     * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2411
-     * @return EE_Base_Class
2412
-     * @throws ReflectionException
2413
-     * @throws InvalidArgumentException
2414
-     * @throws InvalidInterfaceException
2415
-     * @throws InvalidDataTypeException
2416
-     * @throws EE_Error
2417
-     */
2418
-    public function _remove_relations($relationName, $where_query_params = array())
2419
-    {
2420
-        if ($this->ID()) {
2421
-            // if this exists in the DB, save the relation change to the DB too
2422
-            $otherObjects = $this->get_model()->remove_relations(
2423
-                $this,
2424
-                $relationName,
2425
-                $where_query_params
2426
-            );
2427
-            $this->clear_cache(
2428
-                $relationName,
2429
-                null,
2430
-                true
2431
-            );
2432
-        } else {
2433
-            // this doesn't exist in the DB, just remove it from the cache
2434
-            $otherObjects = $this->clear_cache(
2435
-                $relationName,
2436
-                null,
2437
-                true
2438
-            );
2439
-        }
2440
-        if (is_array($otherObjects)) {
2441
-            foreach ($otherObjects as $otherObject) {
2442
-                $otherObject->clear_cache(
2443
-                    $this->get_model()->get_this_model_name(),
2444
-                    $this
2445
-                );
2446
-            }
2447
-        }
2448
-        return $otherObjects;
2449
-    }
2450
-
2451
-
2452
-    /**
2453
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2454
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2455
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2456
-     * because we want to get even deleted items etc.
2457
-     *
2458
-     * @param string $relationName key in the model's _model_relations array
2459
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2460
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2461
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2462
-     *                             results if you want IDs
2463
-     * @throws ReflectionException
2464
-     * @throws InvalidArgumentException
2465
-     * @throws InvalidInterfaceException
2466
-     * @throws InvalidDataTypeException
2467
-     * @throws EE_Error
2468
-     */
2469
-    public function get_many_related($relationName, $query_params = array())
2470
-    {
2471
-        if ($this->ID()) {
2472
-            // this exists in the DB, so get the related things from either the cache or the DB
2473
-            // if there are query parameters, forget about caching the related model objects.
2474
-            if ($query_params) {
2475
-                $related_model_objects = $this->get_model()->get_all_related(
2476
-                    $this,
2477
-                    $relationName,
2478
-                    $query_params
2479
-                );
2480
-            } else {
2481
-                // did we already cache the result of this query?
2482
-                $cached_results = $this->get_all_from_cache($relationName);
2483
-                if (! $cached_results) {
2484
-                    $related_model_objects = $this->get_model()->get_all_related(
2485
-                        $this,
2486
-                        $relationName,
2487
-                        $query_params
2488
-                    );
2489
-                    // if no query parameters were passed, then we got all the related model objects
2490
-                    // for that relation. We can cache them then.
2491
-                    foreach ($related_model_objects as $related_model_object) {
2492
-                        $this->cache($relationName, $related_model_object);
2493
-                    }
2494
-                } else {
2495
-                    $related_model_objects = $cached_results;
2496
-                }
2497
-            }
2498
-        } else {
2499
-            // this doesn't exist in the DB, so just get the related things from the cache
2500
-            $related_model_objects = $this->get_all_from_cache($relationName);
2501
-        }
2502
-        return $related_model_objects;
2503
-    }
2504
-
2505
-
2506
-    /**
2507
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2508
-     * unless otherwise specified in the $query_params
2509
-     *
2510
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2511
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2512
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2513
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2514
-     *                               that by the setting $distinct to TRUE;
2515
-     * @return int
2516
-     * @throws ReflectionException
2517
-     * @throws InvalidArgumentException
2518
-     * @throws InvalidInterfaceException
2519
-     * @throws InvalidDataTypeException
2520
-     * @throws EE_Error
2521
-     */
2522
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2523
-    {
2524
-        return $this->get_model()->count_related(
2525
-            $this,
2526
-            $relation_name,
2527
-            $query_params,
2528
-            $field_to_count,
2529
-            $distinct
2530
-        );
2531
-    }
2532
-
2533
-
2534
-    /**
2535
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2536
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2537
-     *
2538
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2539
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2540
-     * @param string $field_to_sum  name of field to count by.
2541
-     *                              By default, uses primary key
2542
-     *                              (which doesn't make much sense, so you should probably change it)
2543
-     * @return int
2544
-     * @throws ReflectionException
2545
-     * @throws InvalidArgumentException
2546
-     * @throws InvalidInterfaceException
2547
-     * @throws InvalidDataTypeException
2548
-     * @throws EE_Error
2549
-     */
2550
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2551
-    {
2552
-        return $this->get_model()->sum_related(
2553
-            $this,
2554
-            $relation_name,
2555
-            $query_params,
2556
-            $field_to_sum
2557
-        );
2558
-    }
2559
-
2560
-
2561
-    /**
2562
-     * Gets the first (ie, one) related model object of the specified type.
2563
-     *
2564
-     * @param string $relationName key in the model's _model_relations array
2565
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2566
-     * @return EE_Base_Class (not an array, a single object)
2567
-     * @throws ReflectionException
2568
-     * @throws InvalidArgumentException
2569
-     * @throws InvalidInterfaceException
2570
-     * @throws InvalidDataTypeException
2571
-     * @throws EE_Error
2572
-     */
2573
-    public function get_first_related($relationName, $query_params = array())
2574
-    {
2575
-        $model = $this->get_model();
2576
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2577
-            // if they've provided some query parameters, don't bother trying to cache the result
2578
-            // also make sure we're not caching the result of get_first_related
2579
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2580
-            if (
2581
-                $query_params
2582
-                || ! $model->related_settings_for($relationName)
2583
-                     instanceof
2584
-                     EE_Belongs_To_Relation
2585
-            ) {
2586
-                $related_model_object = $model->get_first_related(
2587
-                    $this,
2588
-                    $relationName,
2589
-                    $query_params
2590
-                );
2591
-            } else {
2592
-                // first, check if we've already cached the result of this query
2593
-                $cached_result = $this->get_one_from_cache($relationName);
2594
-                if (! $cached_result) {
2595
-                    $related_model_object = $model->get_first_related(
2596
-                        $this,
2597
-                        $relationName,
2598
-                        $query_params
2599
-                    );
2600
-                    $this->cache($relationName, $related_model_object);
2601
-                } else {
2602
-                    $related_model_object = $cached_result;
2603
-                }
2604
-            }
2605
-        } else {
2606
-            $related_model_object = null;
2607
-            // this doesn't exist in the Db,
2608
-            // but maybe the relation is of type belongs to, and so the related thing might
2609
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2610
-                $related_model_object = $model->get_first_related(
2611
-                    $this,
2612
-                    $relationName,
2613
-                    $query_params
2614
-                );
2615
-            }
2616
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2617
-            // just get what's cached on this object
2618
-            if (! $related_model_object) {
2619
-                $related_model_object = $this->get_one_from_cache($relationName);
2620
-            }
2621
-        }
2622
-        return $related_model_object;
2623
-    }
2624
-
2625
-
2626
-    /**
2627
-     * Does a delete on all related objects of type $relationName and removes
2628
-     * the current model object's relation to them. If they can't be deleted (because
2629
-     * of blocking related model objects) does nothing. If the related model objects are
2630
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2631
-     * If this model object doesn't exist yet in the DB, just removes its related things
2632
-     *
2633
-     * @param string $relationName
2634
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2635
-     * @return int how many deleted
2636
-     * @throws ReflectionException
2637
-     * @throws InvalidArgumentException
2638
-     * @throws InvalidInterfaceException
2639
-     * @throws InvalidDataTypeException
2640
-     * @throws EE_Error
2641
-     */
2642
-    public function delete_related($relationName, $query_params = array())
2643
-    {
2644
-        if ($this->ID()) {
2645
-            $count = $this->get_model()->delete_related(
2646
-                $this,
2647
-                $relationName,
2648
-                $query_params
2649
-            );
2650
-        } else {
2651
-            $count = count($this->get_all_from_cache($relationName));
2652
-            $this->clear_cache($relationName, null, true);
2653
-        }
2654
-        return $count;
2655
-    }
2656
-
2657
-
2658
-    /**
2659
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2660
-     * the current model object's relation to them. If they can't be deleted (because
2661
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2662
-     * If the related thing isn't a soft-deletable model object, this function is identical
2663
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2664
-     *
2665
-     * @param string $relationName
2666
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2667
-     * @return int how many deleted (including those soft deleted)
2668
-     * @throws ReflectionException
2669
-     * @throws InvalidArgumentException
2670
-     * @throws InvalidInterfaceException
2671
-     * @throws InvalidDataTypeException
2672
-     * @throws EE_Error
2673
-     */
2674
-    public function delete_related_permanently($relationName, $query_params = array())
2675
-    {
2676
-        if ($this->ID()) {
2677
-            $count = $this->get_model()->delete_related_permanently(
2678
-                $this,
2679
-                $relationName,
2680
-                $query_params
2681
-            );
2682
-        } else {
2683
-            $count = count($this->get_all_from_cache($relationName));
2684
-        }
2685
-        $this->clear_cache($relationName, null, true);
2686
-        return $count;
2687
-    }
2688
-
2689
-
2690
-    /**
2691
-     * is_set
2692
-     * Just a simple utility function children can use for checking if property exists
2693
-     *
2694
-     * @access  public
2695
-     * @param  string $field_name property to check
2696
-     * @return bool                              TRUE if existing,FALSE if not.
2697
-     */
2698
-    public function is_set($field_name)
2699
-    {
2700
-        return isset($this->_fields[ $field_name ]);
2701
-    }
2702
-
2703
-
2704
-    /**
2705
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2706
-     * EE_Error exception if they don't
2707
-     *
2708
-     * @param  mixed (string|array) $properties properties to check
2709
-     * @throws EE_Error
2710
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2711
-     */
2712
-    protected function _property_exists($properties)
2713
-    {
2714
-        foreach ((array) $properties as $property_name) {
2715
-            // first make sure this property exists
2716
-            if (! $this->_fields[ $property_name ]) {
2717
-                throw new EE_Error(
2718
-                    sprintf(
2719
-                        esc_html__(
2720
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2721
-                            'event_espresso'
2722
-                        ),
2723
-                        $property_name
2724
-                    )
2725
-                );
2726
-            }
2727
-        }
2728
-        return true;
2729
-    }
2730
-
2731
-
2732
-    /**
2733
-     * This simply returns an array of model fields for this object
2734
-     *
2735
-     * @return array
2736
-     * @throws ReflectionException
2737
-     * @throws InvalidArgumentException
2738
-     * @throws InvalidInterfaceException
2739
-     * @throws InvalidDataTypeException
2740
-     * @throws EE_Error
2741
-     */
2742
-    public function model_field_array()
2743
-    {
2744
-        $fields = $this->get_model()->field_settings(false);
2745
-        $properties = array();
2746
-        // remove prepended underscore
2747
-        foreach ($fields as $field_name => $settings) {
2748
-            $properties[ $field_name ] = $this->get($field_name);
2749
-        }
2750
-        return $properties;
2751
-    }
2752
-
2753
-
2754
-    /**
2755
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2756
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2757
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2758
-     * Instead of requiring a plugin to extend the EE_Base_Class
2759
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2760
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2761
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2762
-     * and accepts 2 arguments: the object on which the function was called,
2763
-     * and an array of the original arguments passed to the function.
2764
-     * Whatever their callback function returns will be returned by this function.
2765
-     * Example: in functions.php (or in a plugin):
2766
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2767
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2768
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2769
-     *          return $previousReturnValue.$returnString;
2770
-     *      }
2771
-     * require('EE_Answer.class.php');
2772
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2773
-     *      ->my_callback('monkeys',100);
2774
-     * // will output "you called my_callback! and passed args:monkeys,100"
2775
-     *
2776
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2777
-     * @param array  $args       array of original arguments passed to the function
2778
-     * @throws EE_Error
2779
-     * @return mixed whatever the plugin which calls add_filter decides
2780
-     */
2781
-    public function __call($methodName, $args)
2782
-    {
2783
-        $className = get_class($this);
2784
-        $tagName = "FHEE__{$className}__{$methodName}";
2785
-        if (! has_filter($tagName)) {
2786
-            throw new EE_Error(
2787
-                sprintf(
2788
-                    esc_html__(
2789
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2790
-                        'event_espresso'
2791
-                    ),
2792
-                    $methodName,
2793
-                    $className,
2794
-                    $tagName
2795
-                )
2796
-            );
2797
-        }
2798
-        return apply_filters($tagName, null, $this, $args);
2799
-    }
2800
-
2801
-
2802
-    /**
2803
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2804
-     * A $previous_value can be specified in case there are many meta rows with the same key
2805
-     *
2806
-     * @param string $meta_key
2807
-     * @param mixed  $meta_value
2808
-     * @param mixed  $previous_value
2809
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2810
-     *                  NOTE: if the values haven't changed, returns 0
2811
-     * @throws InvalidArgumentException
2812
-     * @throws InvalidInterfaceException
2813
-     * @throws InvalidDataTypeException
2814
-     * @throws EE_Error
2815
-     * @throws ReflectionException
2816
-     */
2817
-    public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2818
-    {
2819
-        $query_params = [
2820
-            [
2821
-                'EXM_key'  => $meta_key,
2822
-                'OBJ_ID'   => $this->ID(),
2823
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2824
-            ],
2825
-        ];
2826
-        if ($previous_value !== null) {
2827
-            $query_params[0]['EXM_value'] = $meta_value;
2828
-        }
2829
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2830
-        if (! $existing_rows_like_that) {
2831
-            return $this->add_extra_meta($meta_key, $meta_value);
2832
-        }
2833
-        foreach ($existing_rows_like_that as $existing_row) {
2834
-            $existing_row->save(['EXM_value' => $meta_value]);
2835
-        }
2836
-        return count($existing_rows_like_that);
2837
-    }
2838
-
2839
-
2840
-    /**
2841
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2842
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2843
-     * extra meta row was entered, false if not
2844
-     *
2845
-     * @param string $meta_key
2846
-     * @param mixed  $meta_value
2847
-     * @param bool   $unique
2848
-     * @return bool
2849
-     * @throws InvalidArgumentException
2850
-     * @throws InvalidInterfaceException
2851
-     * @throws InvalidDataTypeException
2852
-     * @throws EE_Error
2853
-     * @throws ReflectionException
2854
-     * @throws ReflectionException
2855
-     */
2856
-    public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2857
-    {
2858
-        if ($unique) {
2859
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2860
-                [
2861
-                    [
2862
-                        'EXM_key'  => $meta_key,
2863
-                        'OBJ_ID'   => $this->ID(),
2864
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2865
-                    ],
2866
-                ]
2867
-            );
2868
-            if ($existing_extra_meta) {
2869
-                return false;
2870
-            }
2871
-        }
2872
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2873
-            [
2874
-                'EXM_key'   => $meta_key,
2875
-                'EXM_value' => $meta_value,
2876
-                'OBJ_ID'    => $this->ID(),
2877
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2878
-            ]
2879
-        );
2880
-        $new_extra_meta->save();
2881
-        return true;
2882
-    }
2883
-
2884
-
2885
-    /**
2886
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2887
-     * is specified, only deletes extra meta records with that value.
2888
-     *
2889
-     * @param string $meta_key
2890
-     * @param mixed  $meta_value
2891
-     * @return int|bool number of extra meta rows deleted
2892
-     * @throws InvalidArgumentException
2893
-     * @throws InvalidInterfaceException
2894
-     * @throws InvalidDataTypeException
2895
-     * @throws EE_Error
2896
-     * @throws ReflectionException
2897
-     */
2898
-    public function delete_extra_meta(string $meta_key, $meta_value = null)
2899
-    {
2900
-        $query_params = [
2901
-            [
2902
-                'EXM_key'  => $meta_key,
2903
-                'OBJ_ID'   => $this->ID(),
2904
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2905
-            ],
2906
-        ];
2907
-        if ($meta_value !== null) {
2908
-            $query_params[0]['EXM_value'] = $meta_value;
2909
-        }
2910
-        return EEM_Extra_Meta::instance()->delete($query_params);
2911
-    }
2912
-
2913
-
2914
-    /**
2915
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2916
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2917
-     * You can specify $default is case you haven't found the extra meta
2918
-     *
2919
-     * @param string     $meta_key
2920
-     * @param bool       $single
2921
-     * @param mixed      $default if we don't find anything, what should we return?
2922
-     * @param array|null $extra_where
2923
-     * @return mixed single value if $single; array if ! $single
2924
-     * @throws ReflectionException
2925
-     * @throws EE_Error
2926
-     */
2927
-    public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2928
-    {
2929
-        $query_params = [ $extra_where + ['EXM_key' => $meta_key] ];
2930
-        if ($single) {
2931
-            $result = $this->get_first_related('Extra_Meta', $query_params);
2932
-            if ($result instanceof EE_Extra_Meta) {
2933
-                return $result->value();
2934
-            }
2935
-        } else {
2936
-            $results = $this->get_many_related('Extra_Meta', $query_params);
2937
-            if ($results) {
2938
-                $values = [];
2939
-                foreach ($results as $result) {
2940
-                    if ($result instanceof EE_Extra_Meta) {
2941
-                        $values[ $result->ID() ] = $result->value();
2942
-                    }
2943
-                }
2944
-                return $values;
2945
-            }
2946
-        }
2947
-        // if nothing discovered yet return default.
2948
-        return apply_filters(
2949
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2950
-            $default,
2951
-            $meta_key,
2952
-            $single,
2953
-            $this
2954
-        );
2955
-    }
2956
-
2957
-
2958
-    /**
2959
-     * Returns a simple array of all the extra meta associated with this model object.
2960
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2961
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2962
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2963
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2964
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2965
-     * finally the extra meta's value as each sub-value. (eg
2966
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2967
-     *
2968
-     * @param bool $one_of_each_key
2969
-     * @return array
2970
-     * @throws ReflectionException
2971
-     * @throws InvalidArgumentException
2972
-     * @throws InvalidInterfaceException
2973
-     * @throws InvalidDataTypeException
2974
-     * @throws EE_Error
2975
-     */
2976
-    public function all_extra_meta_array(bool $one_of_each_key = true): array
2977
-    {
2978
-        $return_array = [];
2979
-        if ($one_of_each_key) {
2980
-            $extra_meta_objs = $this->get_many_related(
2981
-                'Extra_Meta',
2982
-                ['group_by' => 'EXM_key']
2983
-            );
2984
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2985
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2986
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2987
-                }
2988
-            }
2989
-        } else {
2990
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2991
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2992
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2993
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2994
-                        $return_array[ $extra_meta_obj->key() ] = [];
2995
-                    }
2996
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2997
-                }
2998
-            }
2999
-        }
3000
-        return $return_array;
3001
-    }
3002
-
3003
-
3004
-    /**
3005
-     * Gets a pretty nice displayable nice for this model object. Often overridden
3006
-     *
3007
-     * @return string
3008
-     * @throws ReflectionException
3009
-     * @throws InvalidArgumentException
3010
-     * @throws InvalidInterfaceException
3011
-     * @throws InvalidDataTypeException
3012
-     * @throws EE_Error
3013
-     */
3014
-    public function name()
3015
-    {
3016
-        // find a field that's not a text field
3017
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3018
-        if ($field_we_can_use) {
3019
-            return $this->get($field_we_can_use->get_name());
3020
-        }
3021
-        $first_few_properties = $this->model_field_array();
3022
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3023
-        $name_parts = array();
3024
-        foreach ($first_few_properties as $name => $value) {
3025
-            $name_parts[] = "$name:$value";
3026
-        }
3027
-        return implode(',', $name_parts);
3028
-    }
3029
-
3030
-
3031
-    /**
3032
-     * in_entity_map
3033
-     * Checks if this model object has been proven to already be in the entity map
3034
-     *
3035
-     * @return boolean
3036
-     * @throws ReflectionException
3037
-     * @throws InvalidArgumentException
3038
-     * @throws InvalidInterfaceException
3039
-     * @throws InvalidDataTypeException
3040
-     * @throws EE_Error
3041
-     */
3042
-    public function in_entity_map()
3043
-    {
3044
-        // well, if we looked, did we find it in the entity map?
3045
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3046
-    }
3047
-
3048
-
3049
-    /**
3050
-     * refresh_from_db
3051
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3052
-     *
3053
-     * @throws ReflectionException
3054
-     * @throws InvalidArgumentException
3055
-     * @throws InvalidInterfaceException
3056
-     * @throws InvalidDataTypeException
3057
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3058
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3059
-     */
3060
-    public function refresh_from_db()
3061
-    {
3062
-        if ($this->ID() && $this->in_entity_map()) {
3063
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3064
-        } else {
3065
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3066
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3067
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3068
-            // absolutely nothing in it for this ID
3069
-            if (WP_DEBUG) {
3070
-                throw new EE_Error(
3071
-                    sprintf(
3072
-                        esc_html__(
3073
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3074
-                            'event_espresso'
3075
-                        ),
3076
-                        $this->ID(),
3077
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3078
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3079
-                    )
3080
-                );
3081
-            }
3082
-        }
3083
-    }
3084
-
3085
-
3086
-    /**
3087
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3088
-     *
3089
-     * @since 4.9.80.p
3090
-     * @param EE_Model_Field_Base[] $fields
3091
-     * @param string $new_value_sql
3092
-     *      example: 'column_name=123',
3093
-     *      or 'column_name=column_name+1',
3094
-     *      or 'column_name= CASE
3095
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3096
-     *          THEN `column_name` + 5
3097
-     *          ELSE `column_name`
3098
-     *      END'
3099
-     *      Also updates $field on this model object with the latest value from the database.
3100
-     * @return bool
3101
-     * @throws EE_Error
3102
-     * @throws InvalidArgumentException
3103
-     * @throws InvalidDataTypeException
3104
-     * @throws InvalidInterfaceException
3105
-     * @throws ReflectionException
3106
-     */
3107
-    protected function updateFieldsInDB($fields, $new_value_sql)
3108
-    {
3109
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3110
-        // if it wasn't even there to start off.
3111
-        if (! $this->ID()) {
3112
-            $this->save();
3113
-        }
3114
-        global $wpdb;
3115
-        if (empty($fields)) {
3116
-            throw new InvalidArgumentException(
3117
-                esc_html__(
3118
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3119
-                    'event_espresso'
3120
-                )
3121
-            );
3122
-        }
3123
-        $first_field = reset($fields);
3124
-        $table_alias = $first_field->get_table_alias();
3125
-        foreach ($fields as $field) {
3126
-            if ($table_alias !== $field->get_table_alias()) {
3127
-                throw new InvalidArgumentException(
3128
-                    sprintf(
3129
-                        esc_html__(
3130
-                            // @codingStandardsIgnoreStart
3131
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3132
-                            // @codingStandardsIgnoreEnd
3133
-                            'event_espresso'
3134
-                        ),
3135
-                        $table_alias,
3136
-                        $field->get_table_alias()
3137
-                    )
3138
-                );
3139
-            }
3140
-        }
3141
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3142
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3143
-        $table_pk_value = $this->ID();
3144
-        $table_name = $table_obj->get_table_name();
3145
-        if ($table_obj instanceof EE_Secondary_Table) {
3146
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3147
-        } else {
3148
-            $table_pk_field_name = $table_obj->get_pk_column();
3149
-        }
3150
-
3151
-        $query =
3152
-            "UPDATE `{$table_name}`
337
+				$this->_props_n_values_provided_in_constructor
338
+				&& $field_value
339
+				&& $field_name === $model->primary_key_name()
340
+			) {
341
+				// if so, we want all this object's fields to be filled either with
342
+				// what we've explicitly set on this model
343
+				// or what we have in the db
344
+				// echo "setting primary key!";
345
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
346
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
347
+				foreach ($fields_on_model as $field_obj) {
348
+					if (
349
+						! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
350
+						&& $field_obj->get_name() !== $field_name
351
+					) {
352
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
353
+					}
354
+				}
355
+				// oh this model object has an ID? well make sure its in the entity mapper
356
+				$model->add_to_entity_map($this);
357
+			}
358
+			// let's unset any cache for this field_name from the $_cached_properties property.
359
+			$this->_clear_cached_property($field_name);
360
+		} else {
361
+			throw new EE_Error(
362
+				sprintf(
363
+					esc_html__(
364
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
365
+						'event_espresso'
366
+					),
367
+					$field_name
368
+				)
369
+			);
370
+		}
371
+	}
372
+
373
+
374
+	/**
375
+	 * Set custom select values for model.
376
+	 *
377
+	 * @param array $custom_select_values
378
+	 */
379
+	public function setCustomSelectsValues(array $custom_select_values)
380
+	{
381
+		$this->custom_selection_results = $custom_select_values;
382
+	}
383
+
384
+
385
+	/**
386
+	 * Returns the custom select value for the provided alias if its set.
387
+	 * If not set, returns null.
388
+	 *
389
+	 * @param string $alias
390
+	 * @return string|int|float|null
391
+	 */
392
+	public function getCustomSelect($alias)
393
+	{
394
+		return isset($this->custom_selection_results[ $alias ])
395
+			? $this->custom_selection_results[ $alias ]
396
+			: null;
397
+	}
398
+
399
+
400
+	/**
401
+	 * This sets the field value on the db column if it exists for the given $column_name or
402
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
403
+	 *
404
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
405
+	 * @param string $field_name  Must be the exact column name.
406
+	 * @param mixed  $field_value The value to set.
407
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
408
+	 * @throws InvalidArgumentException
409
+	 * @throws InvalidInterfaceException
410
+	 * @throws InvalidDataTypeException
411
+	 * @throws EE_Error
412
+	 * @throws ReflectionException
413
+	 */
414
+	public function set_field_or_extra_meta($field_name, $field_value)
415
+	{
416
+		if ($this->get_model()->has_field($field_name)) {
417
+			$this->set($field_name, $field_value);
418
+			return true;
419
+		}
420
+		// ensure this object is saved first so that extra meta can be properly related.
421
+		$this->save();
422
+		return $this->update_extra_meta($field_name, $field_value);
423
+	}
424
+
425
+
426
+	/**
427
+	 * This retrieves the value of the db column set on this class or if that's not present
428
+	 * it will attempt to retrieve from extra_meta if found.
429
+	 * Example Usage:
430
+	 * Via EE_Message child class:
431
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
432
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
433
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
434
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
435
+	 * value for those extra fields dynamically via the EE_message object.
436
+	 *
437
+	 * @param  string $field_name expecting the fully qualified field name.
438
+	 * @return mixed|null  value for the field if found.  null if not found.
439
+	 * @throws ReflectionException
440
+	 * @throws InvalidArgumentException
441
+	 * @throws InvalidInterfaceException
442
+	 * @throws InvalidDataTypeException
443
+	 * @throws EE_Error
444
+	 */
445
+	public function get_field_or_extra_meta($field_name)
446
+	{
447
+		if ($this->get_model()->has_field($field_name)) {
448
+			$column_value = $this->get($field_name);
449
+		} else {
450
+			// This isn't a column in the main table, let's see if it is in the extra meta.
451
+			$column_value = $this->get_extra_meta($field_name, true, null);
452
+		}
453
+		return $column_value;
454
+	}
455
+
456
+
457
+	/**
458
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
459
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
460
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
461
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
462
+	 *
463
+	 * @access public
464
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
465
+	 * @return void
466
+	 * @throws InvalidArgumentException
467
+	 * @throws InvalidInterfaceException
468
+	 * @throws InvalidDataTypeException
469
+	 * @throws EE_Error
470
+	 * @throws ReflectionException
471
+	 */
472
+	public function set_timezone($timezone = '')
473
+	{
474
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
475
+		// make sure we clear all cached properties because they won't be relevant now
476
+		$this->_clear_cached_properties();
477
+		// make sure we update field settings and the date for all EE_Datetime_Fields
478
+		$model_fields = $this->get_model()->field_settings(false);
479
+		foreach ($model_fields as $field_name => $field_obj) {
480
+			if ($field_obj instanceof EE_Datetime_Field) {
481
+				$field_obj->set_timezone($this->_timezone);
482
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
483
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
+				}
485
+			}
486
+		}
487
+	}
488
+
489
+
490
+	/**
491
+	 * This just returns whatever is set for the current timezone.
492
+	 *
493
+	 * @access public
494
+	 * @return string timezone string
495
+	 */
496
+	public function get_timezone()
497
+	{
498
+		return $this->_timezone;
499
+	}
500
+
501
+
502
+	/**
503
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
504
+	 * internally instead of wp set date format options
505
+	 *
506
+	 * @since 4.6
507
+	 * @param string $format should be a format recognizable by PHP date() functions.
508
+	 */
509
+	public function set_date_format($format)
510
+	{
511
+		$this->_dt_frmt = $format;
512
+		// clear cached_properties because they won't be relevant now.
513
+		$this->_clear_cached_properties();
514
+	}
515
+
516
+
517
+	/**
518
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
519
+	 * class internally instead of wp set time format options.
520
+	 *
521
+	 * @since 4.6
522
+	 * @param string $format should be a format recognizable by PHP date() functions.
523
+	 */
524
+	public function set_time_format($format)
525
+	{
526
+		$this->_tm_frmt = $format;
527
+		// clear cached_properties because they won't be relevant now.
528
+		$this->_clear_cached_properties();
529
+	}
530
+
531
+
532
+	/**
533
+	 * This returns the current internal set format for the date and time formats.
534
+	 *
535
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
536
+	 *                             where the first value is the date format and the second value is the time format.
537
+	 * @return mixed string|array
538
+	 */
539
+	public function get_format($full = true)
540
+	{
541
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
542
+	}
543
+
544
+
545
+	/**
546
+	 * cache
547
+	 * stores the passed model object on the current model object.
548
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
549
+	 *
550
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
551
+	 *                                       'Registration' associated with this model object
552
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
553
+	 *                                       that could be a payment or a registration)
554
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
555
+	 *                                       items which will be stored in an array on this object
556
+	 * @throws ReflectionException
557
+	 * @throws InvalidArgumentException
558
+	 * @throws InvalidInterfaceException
559
+	 * @throws InvalidDataTypeException
560
+	 * @throws EE_Error
561
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
562
+	 *                                       related thing, no array)
563
+	 */
564
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
565
+	{
566
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
567
+		if (! $object_to_cache instanceof EE_Base_Class) {
568
+			return false;
569
+		}
570
+		// also get "how" the object is related, or throw an error
571
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
572
+			throw new EE_Error(
573
+				sprintf(
574
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
575
+					$relationName,
576
+					get_class($this)
577
+				)
578
+			);
579
+		}
580
+		// how many things are related ?
581
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
582
+			// if it's a "belongs to" relationship, then there's only one related model object
583
+			// eg, if this is a registration, there's only 1 attendee for it
584
+			// so for these model objects just set it to be cached
585
+			$this->_model_relations[ $relationName ] = $object_to_cache;
586
+			$return = true;
587
+		} else {
588
+			// otherwise, this is the "many" side of a one to many relationship,
589
+			// so we'll add the object to the array of related objects for that type.
590
+			// eg: if this is an event, there are many registrations for that event,
591
+			// so we cache the registrations in an array
592
+			if (! is_array($this->_model_relations[ $relationName ])) {
593
+				// if for some reason, the cached item is a model object,
594
+				// then stick that in the array, otherwise start with an empty array
595
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
596
+														   instanceof
597
+														   EE_Base_Class
598
+					? array($this->_model_relations[ $relationName ]) : array();
599
+			}
600
+			// first check for a cache_id which is normally empty
601
+			if (! empty($cache_id)) {
602
+				// if the cache_id exists, then it means we are purposely trying to cache this
603
+				// with a known key that can then be used to retrieve the object later on
604
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
605
+				$return = $cache_id;
606
+			} elseif ($object_to_cache->ID()) {
607
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
608
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
609
+				$return = $object_to_cache->ID();
610
+			} else {
611
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
612
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
613
+				// move the internal pointer to the end of the array
614
+				end($this->_model_relations[ $relationName ]);
615
+				// and grab the key so that we can return it
616
+				$return = key($this->_model_relations[ $relationName ]);
617
+			}
618
+		}
619
+		return $return;
620
+	}
621
+
622
+
623
+	/**
624
+	 * For adding an item to the cached_properties property.
625
+	 *
626
+	 * @access protected
627
+	 * @param string      $fieldname the property item the corresponding value is for.
628
+	 * @param mixed       $value     The value we are caching.
629
+	 * @param string|null $cache_type
630
+	 * @return void
631
+	 * @throws ReflectionException
632
+	 * @throws InvalidArgumentException
633
+	 * @throws InvalidInterfaceException
634
+	 * @throws InvalidDataTypeException
635
+	 * @throws EE_Error
636
+	 */
637
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
638
+	{
639
+		// first make sure this property exists
640
+		$this->get_model()->field_settings_for($fieldname);
641
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
642
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
643
+	}
644
+
645
+
646
+	/**
647
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
648
+	 * This also SETS the cache if we return the actual property!
649
+	 *
650
+	 * @param string $fieldname        the name of the property we're trying to retrieve
651
+	 * @param bool   $pretty
652
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
653
+	 *                                 (in cases where the same property may be used for different outputs
654
+	 *                                 - i.e. datetime, money etc.)
655
+	 *                                 It can also accept certain pre-defined "schema" strings
656
+	 *                                 to define how to output the property.
657
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
658
+	 * @return mixed                   whatever the value for the property is we're retrieving
659
+	 * @throws ReflectionException
660
+	 * @throws InvalidArgumentException
661
+	 * @throws InvalidInterfaceException
662
+	 * @throws InvalidDataTypeException
663
+	 * @throws EE_Error
664
+	 */
665
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
666
+	{
667
+		// verify the field exists
668
+		$model = $this->get_model();
669
+		$model->field_settings_for($fieldname);
670
+		$cache_type = $pretty ? 'pretty' : 'standard';
671
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
672
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
673
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
+		}
675
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
676
+		$this->_set_cached_property($fieldname, $value, $cache_type);
677
+		return $value;
678
+	}
679
+
680
+
681
+	/**
682
+	 * If the cache didn't fetch the needed item, this fetches it.
683
+	 *
684
+	 * @param string $fieldname
685
+	 * @param bool   $pretty
686
+	 * @param string $extra_cache_ref
687
+	 * @return mixed
688
+	 * @throws InvalidArgumentException
689
+	 * @throws InvalidInterfaceException
690
+	 * @throws InvalidDataTypeException
691
+	 * @throws EE_Error
692
+	 * @throws ReflectionException
693
+	 */
694
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
695
+	{
696
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
697
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
698
+		if ($field_obj instanceof EE_Datetime_Field) {
699
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
700
+		}
701
+		if (! isset($this->_fields[ $fieldname ])) {
702
+			$this->_fields[ $fieldname ] = null;
703
+		}
704
+		return $pretty
705
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
706
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
707
+	}
708
+
709
+
710
+	/**
711
+	 * set timezone, formats, and output for EE_Datetime_Field objects
712
+	 *
713
+	 * @param EE_Datetime_Field $datetime_field
714
+	 * @param bool              $pretty
715
+	 * @param null              $date_or_time
716
+	 * @return void
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidInterfaceException
719
+	 * @throws InvalidDataTypeException
720
+	 */
721
+	protected function _prepare_datetime_field(
722
+		EE_Datetime_Field $datetime_field,
723
+		$pretty = false,
724
+		$date_or_time = null
725
+	) {
726
+		$datetime_field->set_timezone($this->_timezone);
727
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
728
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
729
+		// set the output returned
730
+		switch ($date_or_time) {
731
+			case 'D':
732
+				$datetime_field->set_date_time_output('date');
733
+				break;
734
+			case 'T':
735
+				$datetime_field->set_date_time_output('time');
736
+				break;
737
+			default:
738
+				$datetime_field->set_date_time_output();
739
+		}
740
+	}
741
+
742
+
743
+	/**
744
+	 * This just takes care of clearing out the cached_properties
745
+	 *
746
+	 * @return void
747
+	 */
748
+	protected function _clear_cached_properties()
749
+	{
750
+		$this->_cached_properties = array();
751
+	}
752
+
753
+
754
+	/**
755
+	 * This just clears out ONE property if it exists in the cache
756
+	 *
757
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
758
+	 * @return void
759
+	 */
760
+	protected function _clear_cached_property($property_name)
761
+	{
762
+		if (isset($this->_cached_properties[ $property_name ])) {
763
+			unset($this->_cached_properties[ $property_name ]);
764
+		}
765
+	}
766
+
767
+
768
+	/**
769
+	 * Ensures that this related thing is a model object.
770
+	 *
771
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
772
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
773
+	 * @return EE_Base_Class
774
+	 * @throws ReflectionException
775
+	 * @throws InvalidArgumentException
776
+	 * @throws InvalidInterfaceException
777
+	 * @throws InvalidDataTypeException
778
+	 * @throws EE_Error
779
+	 */
780
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
781
+	{
782
+		$other_model_instance = self::_get_model_instance_with_name(
783
+			self::_get_model_classname($model_name),
784
+			$this->_timezone
785
+		);
786
+		return $other_model_instance->ensure_is_obj($object_or_id);
787
+	}
788
+
789
+
790
+	/**
791
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
792
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
793
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
794
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
795
+	 *
796
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
797
+	 *                                                     Eg 'Registration'
798
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
799
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
800
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
801
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
802
+	 *                                                     this is HasMany or HABTM.
803
+	 * @throws ReflectionException
804
+	 * @throws InvalidArgumentException
805
+	 * @throws InvalidInterfaceException
806
+	 * @throws InvalidDataTypeException
807
+	 * @throws EE_Error
808
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
809
+	 *                                                     relation from all
810
+	 */
811
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
812
+	{
813
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
814
+		$index_in_cache = '';
815
+		if (! $relationship_to_model) {
816
+			throw new EE_Error(
817
+				sprintf(
818
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
819
+					$relationName,
820
+					get_class($this)
821
+				)
822
+			);
823
+		}
824
+		if ($clear_all) {
825
+			$obj_removed = true;
826
+			$this->_model_relations[ $relationName ] = null;
827
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
828
+			$obj_removed = $this->_model_relations[ $relationName ];
829
+			$this->_model_relations[ $relationName ] = null;
830
+		} else {
831
+			if (
832
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
833
+				&& $object_to_remove_or_index_into_array->ID()
834
+			) {
835
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
836
+				if (
837
+					is_array($this->_model_relations[ $relationName ])
838
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
839
+				) {
840
+					$index_found_at = null;
841
+					// find this object in the array even though it has a different key
842
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
843
+						/** @noinspection TypeUnsafeComparisonInspection */
844
+						if (
845
+							$obj instanceof EE_Base_Class
846
+							&& (
847
+								$obj == $object_to_remove_or_index_into_array
848
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
849
+							)
850
+						) {
851
+							$index_found_at = $index;
852
+							break;
853
+						}
854
+					}
855
+					if ($index_found_at) {
856
+						$index_in_cache = $index_found_at;
857
+					} else {
858
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
859
+						// if it wasn't in it to begin with. So we're done
860
+						return $object_to_remove_or_index_into_array;
861
+					}
862
+				}
863
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
864
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
865
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
866
+					/** @noinspection TypeUnsafeComparisonInspection */
867
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
868
+						$index_in_cache = $index;
869
+					}
870
+				}
871
+			} else {
872
+				$index_in_cache = $object_to_remove_or_index_into_array;
873
+			}
874
+			// supposedly we've found it. But it could just be that the client code
875
+			// provided a bad index/object
876
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
877
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
878
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
879
+			} else {
880
+				// that thing was never cached anyways.
881
+				$obj_removed = null;
882
+			}
883
+		}
884
+		return $obj_removed;
885
+	}
886
+
887
+
888
+	/**
889
+	 * update_cache_after_object_save
890
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
891
+	 * obtained after being saved to the db
892
+	 *
893
+	 * @param string        $relationName       - the type of object that is cached
894
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
895
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
896
+	 * @return boolean TRUE on success, FALSE on fail
897
+	 * @throws ReflectionException
898
+	 * @throws InvalidArgumentException
899
+	 * @throws InvalidInterfaceException
900
+	 * @throws InvalidDataTypeException
901
+	 * @throws EE_Error
902
+	 */
903
+	public function update_cache_after_object_save(
904
+		$relationName,
905
+		EE_Base_Class $newly_saved_object,
906
+		$current_cache_id = ''
907
+	) {
908
+		// verify that incoming object is of the correct type
909
+		$obj_class = 'EE_' . $relationName;
910
+		if ($newly_saved_object instanceof $obj_class) {
911
+			/* @type EE_Base_Class $newly_saved_object */
912
+			// now get the type of relation
913
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
914
+			// if this is a 1:1 relationship
915
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
916
+				// then just replace the cached object with the newly saved object
917
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
918
+				return true;
919
+				// or if it's some kind of sordid feral polyamorous relationship...
920
+			}
921
+			if (
922
+				is_array($this->_model_relations[ $relationName ])
923
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
924
+			) {
925
+				// then remove the current cached item
926
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
927
+				// and cache the newly saved object using it's new ID
928
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
929
+				return true;
930
+			}
931
+		}
932
+		return false;
933
+	}
934
+
935
+
936
+	/**
937
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
938
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
939
+	 *
940
+	 * @param string $relationName
941
+	 * @return EE_Base_Class
942
+	 */
943
+	public function get_one_from_cache($relationName)
944
+	{
945
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
946
+			? $this->_model_relations[ $relationName ]
947
+			: null;
948
+		if (is_array($cached_array_or_object)) {
949
+			return array_shift($cached_array_or_object);
950
+		}
951
+		return $cached_array_or_object;
952
+	}
953
+
954
+
955
+	/**
956
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
957
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
958
+	 *
959
+	 * @param string $relationName
960
+	 * @throws ReflectionException
961
+	 * @throws InvalidArgumentException
962
+	 * @throws InvalidInterfaceException
963
+	 * @throws InvalidDataTypeException
964
+	 * @throws EE_Error
965
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
966
+	 */
967
+	public function get_all_from_cache($relationName)
968
+	{
969
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
970
+		// if the result is not an array, but exists, make it an array
971
+		$objects = is_array($objects) ? $objects : array($objects);
972
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
973
+		// basically, if this model object was stored in the session, and these cached model objects
974
+		// already have IDs, let's make sure they're in their model's entity mapper
975
+		// otherwise we will have duplicates next time we call
976
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
977
+		$model = EE_Registry::instance()->load_model($relationName);
978
+		foreach ($objects as $model_object) {
979
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
980
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
981
+				if ($model_object->ID()) {
982
+					$model->add_to_entity_map($model_object);
983
+				}
984
+			} else {
985
+				throw new EE_Error(
986
+					sprintf(
987
+						esc_html__(
988
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
989
+							'event_espresso'
990
+						),
991
+						$relationName,
992
+						gettype($model_object)
993
+					)
994
+				);
995
+			}
996
+		}
997
+		return $objects;
998
+	}
999
+
1000
+
1001
+	/**
1002
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1003
+	 * matching the given query conditions.
1004
+	 *
1005
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1006
+	 * @param int   $limit              How many objects to return.
1007
+	 * @param array $query_params       Any additional conditions on the query.
1008
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1009
+	 *                                  you can indicate just the columns you want returned
1010
+	 * @return array|EE_Base_Class[]
1011
+	 * @throws ReflectionException
1012
+	 * @throws InvalidArgumentException
1013
+	 * @throws InvalidInterfaceException
1014
+	 * @throws InvalidDataTypeException
1015
+	 * @throws EE_Error
1016
+	 */
1017
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1018
+	{
1019
+		$model = $this->get_model();
1020
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1021
+			? $model->get_primary_key_field()->get_name()
1022
+			: $field_to_order_by;
1023
+		$current_value = ! empty($field) ? $this->get($field) : null;
1024
+		if (empty($field) || empty($current_value)) {
1025
+			return array();
1026
+		}
1027
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1028
+	}
1029
+
1030
+
1031
+	/**
1032
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1033
+	 * matching the given query conditions.
1034
+	 *
1035
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1036
+	 * @param int   $limit              How many objects to return.
1037
+	 * @param array $query_params       Any additional conditions on the query.
1038
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1039
+	 *                                  you can indicate just the columns you want returned
1040
+	 * @return array|EE_Base_Class[]
1041
+	 * @throws ReflectionException
1042
+	 * @throws InvalidArgumentException
1043
+	 * @throws InvalidInterfaceException
1044
+	 * @throws InvalidDataTypeException
1045
+	 * @throws EE_Error
1046
+	 */
1047
+	public function previous_x(
1048
+		$field_to_order_by = null,
1049
+		$limit = 1,
1050
+		$query_params = array(),
1051
+		$columns_to_select = null
1052
+	) {
1053
+		$model = $this->get_model();
1054
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1055
+			? $model->get_primary_key_field()->get_name()
1056
+			: $field_to_order_by;
1057
+		$current_value = ! empty($field) ? $this->get($field) : null;
1058
+		if (empty($field) || empty($current_value)) {
1059
+			return array();
1060
+		}
1061
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1062
+	}
1063
+
1064
+
1065
+	/**
1066
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1067
+	 * matching the given query conditions.
1068
+	 *
1069
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1070
+	 * @param array $query_params       Any additional conditions on the query.
1071
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1072
+	 *                                  you can indicate just the columns you want returned
1073
+	 * @return array|EE_Base_Class
1074
+	 * @throws ReflectionException
1075
+	 * @throws InvalidArgumentException
1076
+	 * @throws InvalidInterfaceException
1077
+	 * @throws InvalidDataTypeException
1078
+	 * @throws EE_Error
1079
+	 */
1080
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1081
+	{
1082
+		$model = $this->get_model();
1083
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1084
+			? $model->get_primary_key_field()->get_name()
1085
+			: $field_to_order_by;
1086
+		$current_value = ! empty($field) ? $this->get($field) : null;
1087
+		if (empty($field) || empty($current_value)) {
1088
+			return array();
1089
+		}
1090
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1096
+	 * matching the given query conditions.
1097
+	 *
1098
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1099
+	 * @param array $query_params       Any additional conditions on the query.
1100
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1101
+	 *                                  you can indicate just the column you want returned
1102
+	 * @return array|EE_Base_Class
1103
+	 * @throws ReflectionException
1104
+	 * @throws InvalidArgumentException
1105
+	 * @throws InvalidInterfaceException
1106
+	 * @throws InvalidDataTypeException
1107
+	 * @throws EE_Error
1108
+	 */
1109
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1110
+	{
1111
+		$model = $this->get_model();
1112
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1113
+			? $model->get_primary_key_field()->get_name()
1114
+			: $field_to_order_by;
1115
+		$current_value = ! empty($field) ? $this->get($field) : null;
1116
+		if (empty($field) || empty($current_value)) {
1117
+			return array();
1118
+		}
1119
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1120
+	}
1121
+
1122
+
1123
+	/**
1124
+	 * Overrides parent because parent expects old models.
1125
+	 * This also doesn't do any validation, and won't work for serialized arrays
1126
+	 *
1127
+	 * @param string $field_name
1128
+	 * @param mixed  $field_value_from_db
1129
+	 * @throws ReflectionException
1130
+	 * @throws InvalidArgumentException
1131
+	 * @throws InvalidInterfaceException
1132
+	 * @throws InvalidDataTypeException
1133
+	 * @throws EE_Error
1134
+	 */
1135
+	public function set_from_db($field_name, $field_value_from_db)
1136
+	{
1137
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1138
+		if ($field_obj instanceof EE_Model_Field_Base) {
1139
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
1140
+			// eg, a CPT model object could have an entry in the posts table, but no
1141
+			// entry in the meta table. Meaning that all its columns in the meta table
1142
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
1143
+			if ($field_value_from_db === null) {
1144
+				if ($field_obj->is_nullable()) {
1145
+					// if the field allows nulls, then let it be null
1146
+					$field_value = null;
1147
+				} else {
1148
+					$field_value = $field_obj->get_default_value();
1149
+				}
1150
+			} else {
1151
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1152
+			}
1153
+			$this->_fields[ $field_name ] = $field_value;
1154
+			$this->_clear_cached_property($field_name);
1155
+		}
1156
+	}
1157
+
1158
+
1159
+	/**
1160
+	 * verifies that the specified field is of the correct type
1161
+	 *
1162
+	 * @param string $field_name
1163
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1164
+	 *                                (in cases where the same property may be used for different outputs
1165
+	 *                                - i.e. datetime, money etc.)
1166
+	 * @return mixed
1167
+	 * @throws ReflectionException
1168
+	 * @throws InvalidArgumentException
1169
+	 * @throws InvalidInterfaceException
1170
+	 * @throws InvalidDataTypeException
1171
+	 * @throws EE_Error
1172
+	 */
1173
+	public function get($field_name, $extra_cache_ref = null)
1174
+	{
1175
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1176
+	}
1177
+
1178
+
1179
+	/**
1180
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1181
+	 *
1182
+	 * @param  string $field_name A valid fieldname
1183
+	 * @return mixed              Whatever the raw value stored on the property is.
1184
+	 * @throws ReflectionException
1185
+	 * @throws InvalidArgumentException
1186
+	 * @throws InvalidInterfaceException
1187
+	 * @throws InvalidDataTypeException
1188
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1189
+	 */
1190
+	public function get_raw($field_name)
1191
+	{
1192
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1193
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1194
+			? $this->_fields[ $field_name ]->format('U')
1195
+			: $this->_fields[ $field_name ];
1196
+	}
1197
+
1198
+
1199
+	/**
1200
+	 * This is used to return the internal DateTime object used for a field that is a
1201
+	 * EE_Datetime_Field.
1202
+	 *
1203
+	 * @param string $field_name               The field name retrieving the DateTime object.
1204
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1205
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1206
+	 *                                         EE_Datetime_Field and but the field value is null, then
1207
+	 *                                         just null is returned (because that indicates that likely
1208
+	 *                                         this field is nullable).
1209
+	 * @throws InvalidArgumentException
1210
+	 * @throws InvalidDataTypeException
1211
+	 * @throws InvalidInterfaceException
1212
+	 * @throws ReflectionException
1213
+	 */
1214
+	public function get_DateTime_object($field_name)
1215
+	{
1216
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1217
+		if (! $field_settings instanceof EE_Datetime_Field) {
1218
+			EE_Error::add_error(
1219
+				sprintf(
1220
+					esc_html__(
1221
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1222
+						'event_espresso'
1223
+					),
1224
+					$field_name
1225
+				),
1226
+				__FILE__,
1227
+				__FUNCTION__,
1228
+				__LINE__
1229
+			);
1230
+			return false;
1231
+		}
1232
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1233
+			? clone $this->_fields[ $field_name ]
1234
+			: null;
1235
+	}
1236
+
1237
+
1238
+	/**
1239
+	 * To be used in template to immediately echo out the value, and format it for output.
1240
+	 * Eg, should call stripslashes and whatnot before echoing
1241
+	 *
1242
+	 * @param string $field_name      the name of the field as it appears in the DB
1243
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1244
+	 *                                (in cases where the same property may be used for different outputs
1245
+	 *                                - i.e. datetime, money etc.)
1246
+	 * @return void
1247
+	 * @throws ReflectionException
1248
+	 * @throws InvalidArgumentException
1249
+	 * @throws InvalidInterfaceException
1250
+	 * @throws InvalidDataTypeException
1251
+	 * @throws EE_Error
1252
+	 */
1253
+	public function e($field_name, $extra_cache_ref = null)
1254
+	{
1255
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1256
+	}
1257
+
1258
+
1259
+	/**
1260
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1261
+	 * can be easily used as the value of form input.
1262
+	 *
1263
+	 * @param string $field_name
1264
+	 * @return void
1265
+	 * @throws ReflectionException
1266
+	 * @throws InvalidArgumentException
1267
+	 * @throws InvalidInterfaceException
1268
+	 * @throws InvalidDataTypeException
1269
+	 * @throws EE_Error
1270
+	 */
1271
+	public function f($field_name)
1272
+	{
1273
+		$this->e($field_name, 'form_input');
1274
+	}
1275
+
1276
+
1277
+	/**
1278
+	 * Same as `f()` but just returns the value instead of echoing it
1279
+	 *
1280
+	 * @param string $field_name
1281
+	 * @return string
1282
+	 * @throws ReflectionException
1283
+	 * @throws InvalidArgumentException
1284
+	 * @throws InvalidInterfaceException
1285
+	 * @throws InvalidDataTypeException
1286
+	 * @throws EE_Error
1287
+	 */
1288
+	public function get_f($field_name)
1289
+	{
1290
+		return (string) $this->get_pretty($field_name, 'form_input');
1291
+	}
1292
+
1293
+
1294
+	/**
1295
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1296
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1297
+	 * to see what options are available.
1298
+	 *
1299
+	 * @param string $field_name
1300
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1301
+	 *                                (in cases where the same property may be used for different outputs
1302
+	 *                                - i.e. datetime, money etc.)
1303
+	 * @return mixed
1304
+	 * @throws ReflectionException
1305
+	 * @throws InvalidArgumentException
1306
+	 * @throws InvalidInterfaceException
1307
+	 * @throws InvalidDataTypeException
1308
+	 * @throws EE_Error
1309
+	 */
1310
+	public function get_pretty($field_name, $extra_cache_ref = null)
1311
+	{
1312
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1313
+	}
1314
+
1315
+
1316
+	/**
1317
+	 * This simply returns the datetime for the given field name
1318
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1319
+	 * (and the equivalent e_date, e_time, e_datetime).
1320
+	 *
1321
+	 * @access   protected
1322
+	 * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1323
+	 * @param string|null $date_format  valid datetime format used for date
1324
+	 *                                  (if '' then we just use the default on the field,
1325
+	 *                                  if NULL we use the last-used format)
1326
+	 * @param string|null $time_format  Same as above except this is for time format
1327
+	 * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1328
+	 * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1329
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1330
+	 *                                  if field is not a valid dtt field, or void if echoing
1331
+	 * @throws EE_Error
1332
+	 * @throws ReflectionException
1333
+	 */
1334
+	protected function _get_datetime(
1335
+		string $field_name,
1336
+		?string $date_format = '',
1337
+		?string $time_format = '',
1338
+		?string $date_or_time = '',
1339
+		?bool $echo = false
1340
+	) {
1341
+		// clear cached property
1342
+		$this->_clear_cached_property($field_name);
1343
+		// reset format properties because they are used in get()
1344
+		$this->_dt_frmt = $date_format !== '' ? $date_format : $this->_dt_frmt;
1345
+		$this->_tm_frmt = $time_format !== '' ? $time_format : $this->_tm_frmt;
1346
+		if ($echo) {
1347
+			$this->e($field_name, $date_or_time);
1348
+			return '';
1349
+		}
1350
+		return $this->get($field_name, $date_or_time);
1351
+	}
1352
+
1353
+
1354
+	/**
1355
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1356
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1357
+	 * other echoes the pretty value for dtt)
1358
+	 *
1359
+	 * @param  string $field_name name of model object datetime field holding the value
1360
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1361
+	 * @return string            datetime value formatted
1362
+	 * @throws ReflectionException
1363
+	 * @throws InvalidArgumentException
1364
+	 * @throws InvalidInterfaceException
1365
+	 * @throws InvalidDataTypeException
1366
+	 * @throws EE_Error
1367
+	 */
1368
+	public function get_date($field_name, $format = '')
1369
+	{
1370
+		return $this->_get_datetime($field_name, $format, null, 'D');
1371
+	}
1372
+
1373
+
1374
+	/**
1375
+	 * @param        $field_name
1376
+	 * @param string $format
1377
+	 * @throws ReflectionException
1378
+	 * @throws InvalidArgumentException
1379
+	 * @throws InvalidInterfaceException
1380
+	 * @throws InvalidDataTypeException
1381
+	 * @throws EE_Error
1382
+	 */
1383
+	public function e_date($field_name, $format = '')
1384
+	{
1385
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1386
+	}
1387
+
1388
+
1389
+	/**
1390
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1391
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1392
+	 * other echoes the pretty value for dtt)
1393
+	 *
1394
+	 * @param  string $field_name name of model object datetime field holding the value
1395
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1396
+	 * @return string             datetime value formatted
1397
+	 * @throws ReflectionException
1398
+	 * @throws InvalidArgumentException
1399
+	 * @throws InvalidInterfaceException
1400
+	 * @throws InvalidDataTypeException
1401
+	 * @throws EE_Error
1402
+	 */
1403
+	public function get_time($field_name, $format = '')
1404
+	{
1405
+		return $this->_get_datetime($field_name, null, $format, 'T');
1406
+	}
1407
+
1408
+
1409
+	/**
1410
+	 * @param        $field_name
1411
+	 * @param string $format
1412
+	 * @throws ReflectionException
1413
+	 * @throws InvalidArgumentException
1414
+	 * @throws InvalidInterfaceException
1415
+	 * @throws InvalidDataTypeException
1416
+	 * @throws EE_Error
1417
+	 */
1418
+	public function e_time($field_name, $format = '')
1419
+	{
1420
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1421
+	}
1422
+
1423
+
1424
+	/**
1425
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1426
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1427
+	 * other echoes the pretty value for dtt)
1428
+	 *
1429
+	 * @param  string $field_name name of model object datetime field holding the value
1430
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1431
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1432
+	 * @return string             datetime value formatted
1433
+	 * @throws ReflectionException
1434
+	 * @throws InvalidArgumentException
1435
+	 * @throws InvalidInterfaceException
1436
+	 * @throws InvalidDataTypeException
1437
+	 * @throws EE_Error
1438
+	 */
1439
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1440
+	{
1441
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1442
+	}
1443
+
1444
+
1445
+	/**
1446
+	 * @param string $field_name
1447
+	 * @param string $dt_frmt
1448
+	 * @param string $tm_frmt
1449
+	 * @throws ReflectionException
1450
+	 * @throws InvalidArgumentException
1451
+	 * @throws InvalidInterfaceException
1452
+	 * @throws InvalidDataTypeException
1453
+	 * @throws EE_Error
1454
+	 */
1455
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1456
+	{
1457
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1458
+	}
1459
+
1460
+
1461
+	/**
1462
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1463
+	 *
1464
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1465
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1466
+	 *                           on the object will be used.
1467
+	 * @return string Date and time string in set locale or false if no field exists for the given
1468
+	 * @throws ReflectionException
1469
+	 * @throws InvalidArgumentException
1470
+	 * @throws InvalidInterfaceException
1471
+	 * @throws InvalidDataTypeException
1472
+	 * @throws EE_Error
1473
+	 *                           field name.
1474
+	 */
1475
+	public function get_i18n_datetime($field_name, $format = '')
1476
+	{
1477
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1478
+		return date_i18n(
1479
+			$format,
1480
+			EEH_DTT_Helper::get_timestamp_with_offset(
1481
+				$this->get_raw($field_name),
1482
+				$this->_timezone
1483
+			)
1484
+		);
1485
+	}
1486
+
1487
+
1488
+	/**
1489
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1490
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1491
+	 * thrown.
1492
+	 *
1493
+	 * @param  string $field_name The field name being checked
1494
+	 * @throws ReflectionException
1495
+	 * @throws InvalidArgumentException
1496
+	 * @throws InvalidInterfaceException
1497
+	 * @throws InvalidDataTypeException
1498
+	 * @throws EE_Error
1499
+	 * @return EE_Datetime_Field
1500
+	 */
1501
+	protected function _get_dtt_field_settings($field_name)
1502
+	{
1503
+		$field = $this->get_model()->field_settings_for($field_name);
1504
+		// check if field is dtt
1505
+		if ($field instanceof EE_Datetime_Field) {
1506
+			return $field;
1507
+		}
1508
+		throw new EE_Error(
1509
+			sprintf(
1510
+				esc_html__(
1511
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1512
+					'event_espresso'
1513
+				),
1514
+				$field_name,
1515
+				self::_get_model_classname(get_class($this))
1516
+			)
1517
+		);
1518
+	}
1519
+
1520
+
1521
+
1522
+
1523
+	/**
1524
+	 * NOTE ABOUT BELOW:
1525
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1526
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1527
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1528
+	 * method and make sure you send the entire datetime value for setting.
1529
+	 */
1530
+	/**
1531
+	 * sets the time on a datetime property
1532
+	 *
1533
+	 * @access protected
1534
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1535
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1536
+	 * @throws ReflectionException
1537
+	 * @throws InvalidArgumentException
1538
+	 * @throws InvalidInterfaceException
1539
+	 * @throws InvalidDataTypeException
1540
+	 * @throws EE_Error
1541
+	 */
1542
+	protected function _set_time_for($time, $fieldname)
1543
+	{
1544
+		$this->_set_date_time('T', $time, $fieldname);
1545
+	}
1546
+
1547
+
1548
+	/**
1549
+	 * sets the date on a datetime property
1550
+	 *
1551
+	 * @access protected
1552
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1553
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1554
+	 * @throws ReflectionException
1555
+	 * @throws InvalidArgumentException
1556
+	 * @throws InvalidInterfaceException
1557
+	 * @throws InvalidDataTypeException
1558
+	 * @throws EE_Error
1559
+	 */
1560
+	protected function _set_date_for($date, $fieldname)
1561
+	{
1562
+		$this->_set_date_time('D', $date, $fieldname);
1563
+	}
1564
+
1565
+
1566
+	/**
1567
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1568
+	 * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1569
+	 *
1570
+	 * @access protected
1571
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1572
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1573
+	 * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1574
+	 *                                        EE_Datetime_Field property)
1575
+	 * @throws ReflectionException
1576
+	 * @throws InvalidArgumentException
1577
+	 * @throws InvalidInterfaceException
1578
+	 * @throws InvalidDataTypeException
1579
+	 * @throws EE_Error
1580
+	 */
1581
+	protected function _set_date_time(string $what, $datetime_value, string $field_name)
1582
+	{
1583
+		$field = $this->_get_dtt_field_settings($field_name);
1584
+		$field->set_timezone($this->_timezone);
1585
+		$field->set_date_format($this->_dt_frmt);
1586
+		$field->set_time_format($this->_tm_frmt);
1587
+		switch ($what) {
1588
+			case 'T':
1589
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1590
+					$datetime_value,
1591
+					$this->_fields[ $field_name ]
1592
+				);
1593
+				$this->_has_changes = true;
1594
+				break;
1595
+			case 'D':
1596
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1597
+					$datetime_value,
1598
+					$this->_fields[ $field_name ]
1599
+				);
1600
+				$this->_has_changes = true;
1601
+				break;
1602
+			case 'B':
1603
+				$this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1604
+				$this->_has_changes = true;
1605
+				break;
1606
+		}
1607
+		$this->_clear_cached_property($field_name);
1608
+	}
1609
+
1610
+
1611
+	/**
1612
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1613
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1614
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1615
+	 * that could lead to some unexpected results!
1616
+	 *
1617
+	 * @access public
1618
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1619
+	 *                                         value being returned.
1620
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1621
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1622
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1623
+	 * @param string $append                   You can include something to append on the timestamp
1624
+	 * @throws ReflectionException
1625
+	 * @throws InvalidArgumentException
1626
+	 * @throws InvalidInterfaceException
1627
+	 * @throws InvalidDataTypeException
1628
+	 * @throws EE_Error
1629
+	 * @return string timestamp
1630
+	 */
1631
+	public function display_in_my_timezone(
1632
+		$field_name,
1633
+		$callback = 'get_datetime',
1634
+		$args = null,
1635
+		$prepend = '',
1636
+		$append = ''
1637
+	) {
1638
+		$timezone = EEH_DTT_Helper::get_timezone();
1639
+		if ($timezone === $this->_timezone) {
1640
+			return '';
1641
+		}
1642
+		$original_timezone = $this->_timezone;
1643
+		$this->set_timezone($timezone);
1644
+		$fn = (array) $field_name;
1645
+		$args = array_merge($fn, (array) $args);
1646
+		if (! method_exists($this, $callback)) {
1647
+			throw new EE_Error(
1648
+				sprintf(
1649
+					esc_html__(
1650
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1651
+						'event_espresso'
1652
+					),
1653
+					$callback
1654
+				)
1655
+			);
1656
+		}
1657
+		$args = (array) $args;
1658
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1659
+		$this->set_timezone($original_timezone);
1660
+		return $return;
1661
+	}
1662
+
1663
+
1664
+	/**
1665
+	 * Deletes this model object.
1666
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1667
+	 * override
1668
+	 * `EE_Base_Class::_delete` NOT this class.
1669
+	 *
1670
+	 * @return boolean | int
1671
+	 * @throws ReflectionException
1672
+	 * @throws InvalidArgumentException
1673
+	 * @throws InvalidInterfaceException
1674
+	 * @throws InvalidDataTypeException
1675
+	 * @throws EE_Error
1676
+	 */
1677
+	public function delete()
1678
+	{
1679
+		/**
1680
+		 * Called just before the `EE_Base_Class::_delete` method call.
1681
+		 * Note:
1682
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1683
+		 * should be aware that `_delete` may not always result in a permanent delete.
1684
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1685
+		 * soft deletes (trash) the object and does not permanently delete it.
1686
+		 *
1687
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1688
+		 */
1689
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1690
+		$result = $this->_delete();
1691
+		/**
1692
+		 * Called just after the `EE_Base_Class::_delete` method call.
1693
+		 * Note:
1694
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1695
+		 * should be aware that `_delete` may not always result in a permanent delete.
1696
+		 * For example `EE_Soft_Base_Class::_delete`
1697
+		 * soft deletes (trash) the object and does not permanently delete it.
1698
+		 *
1699
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1700
+		 * @param boolean       $result
1701
+		 */
1702
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1703
+		return $result;
1704
+	}
1705
+
1706
+
1707
+	/**
1708
+	 * Calls the specific delete method for the instantiated class.
1709
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1710
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1711
+	 * `EE_Base_Class::delete`
1712
+	 *
1713
+	 * @return bool|int
1714
+	 * @throws ReflectionException
1715
+	 * @throws InvalidArgumentException
1716
+	 * @throws InvalidInterfaceException
1717
+	 * @throws InvalidDataTypeException
1718
+	 * @throws EE_Error
1719
+	 */
1720
+	protected function _delete()
1721
+	{
1722
+		return $this->delete_permanently();
1723
+	}
1724
+
1725
+
1726
+	/**
1727
+	 * Deletes this model object permanently from db
1728
+	 * (but keep in mind related models may block the delete and return an error)
1729
+	 *
1730
+	 * @return bool | int
1731
+	 * @throws ReflectionException
1732
+	 * @throws InvalidArgumentException
1733
+	 * @throws InvalidInterfaceException
1734
+	 * @throws InvalidDataTypeException
1735
+	 * @throws EE_Error
1736
+	 */
1737
+	public function delete_permanently()
1738
+	{
1739
+		/**
1740
+		 * Called just before HARD deleting a model object
1741
+		 *
1742
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1743
+		 */
1744
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1745
+		$model = $this->get_model();
1746
+		$result = $model->delete_permanently_by_ID($this->ID());
1747
+		$this->refresh_cache_of_related_objects();
1748
+		/**
1749
+		 * Called just after HARD deleting a model object
1750
+		 *
1751
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1752
+		 * @param boolean       $result
1753
+		 */
1754
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1755
+		return $result;
1756
+	}
1757
+
1758
+
1759
+	/**
1760
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1761
+	 * related model objects
1762
+	 *
1763
+	 * @throws ReflectionException
1764
+	 * @throws InvalidArgumentException
1765
+	 * @throws InvalidInterfaceException
1766
+	 * @throws InvalidDataTypeException
1767
+	 * @throws EE_Error
1768
+	 */
1769
+	public function refresh_cache_of_related_objects()
1770
+	{
1771
+		$model = $this->get_model();
1772
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1773
+			if (! empty($this->_model_relations[ $relation_name ])) {
1774
+				$related_objects = $this->_model_relations[ $relation_name ];
1775
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1776
+					// this relation only stores a single model object, not an array
1777
+					// but let's make it consistent
1778
+					$related_objects = array($related_objects);
1779
+				}
1780
+				foreach ($related_objects as $related_object) {
1781
+					// only refresh their cache if they're in memory
1782
+					if ($related_object instanceof EE_Base_Class) {
1783
+						$related_object->clear_cache(
1784
+							$model->get_this_model_name(),
1785
+							$this
1786
+						);
1787
+					}
1788
+				}
1789
+			}
1790
+		}
1791
+	}
1792
+
1793
+
1794
+	/**
1795
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1796
+	 * object just before saving.
1797
+	 *
1798
+	 * @access public
1799
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1800
+	 *                                 if provided during the save() method (often client code will change the fields'
1801
+	 *                                 values before calling save)
1802
+	 * @return bool|int|string         1 on a successful update
1803
+	 *                                 the ID of the new entry on insert
1804
+	 *                                 0 on failure or if the model object isn't allowed to persist
1805
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1806
+	 * @throws InvalidInterfaceException
1807
+	 * @throws InvalidDataTypeException
1808
+	 * @throws EE_Error
1809
+	 * @throws InvalidArgumentException
1810
+	 * @throws ReflectionException
1811
+	 * @throws ReflectionException
1812
+	 * @throws ReflectionException
1813
+	 */
1814
+	public function save($set_cols_n_values = array())
1815
+	{
1816
+		$model = $this->get_model();
1817
+		/**
1818
+		 * Filters the fields we're about to save on the model object
1819
+		 *
1820
+		 * @param array         $set_cols_n_values
1821
+		 * @param EE_Base_Class $model_object
1822
+		 */
1823
+		$set_cols_n_values = (array) apply_filters(
1824
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1825
+			$set_cols_n_values,
1826
+			$this
1827
+		);
1828
+		// set attributes as provided in $set_cols_n_values
1829
+		foreach ($set_cols_n_values as $column => $value) {
1830
+			$this->set($column, $value);
1831
+		}
1832
+		// no changes ? then don't do anything
1833
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1834
+			return 0;
1835
+		}
1836
+		/**
1837
+		 * Saving a model object.
1838
+		 * Before we perform a save, this action is fired.
1839
+		 *
1840
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1841
+		 */
1842
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1843
+		if (! $this->allow_persist()) {
1844
+			return 0;
1845
+		}
1846
+		// now get current attribute values
1847
+		$save_cols_n_values = $this->_fields;
1848
+		// if the object already has an ID, update it. Otherwise, insert it
1849
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1850
+		// They have been
1851
+		$old_assumption_concerning_value_preparation = $model
1852
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1853
+		$model->assume_values_already_prepared_by_model_object(true);
1854
+		// does this model have an autoincrement PK?
1855
+		if ($model->has_primary_key_field()) {
1856
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1857
+				// ok check if it's set, if so: update; if not, insert
1858
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1859
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1860
+				} else {
1861
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1862
+					$results = $model->insert($save_cols_n_values);
1863
+					if ($results) {
1864
+						// if successful, set the primary key
1865
+						// but don't use the normal SET method, because it will check if
1866
+						// an item with the same ID exists in the mapper & db, then
1867
+						// will find it in the db (because we just added it) and THAT object
1868
+						// will get added to the mapper before we can add this one!
1869
+						// but if we just avoid using the SET method, all that headache can be avoided
1870
+						$pk_field_name = $model->primary_key_name();
1871
+						$this->_fields[ $pk_field_name ] = $results;
1872
+						$this->_clear_cached_property($pk_field_name);
1873
+						$model->add_to_entity_map($this);
1874
+						$this->_update_cached_related_model_objs_fks();
1875
+					}
1876
+				}
1877
+			} else {// PK is NOT auto-increment
1878
+				// so check if one like it already exists in the db
1879
+				if ($model->exists_by_ID($this->ID())) {
1880
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1881
+						throw new EE_Error(
1882
+							sprintf(
1883
+								esc_html__(
1884
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1885
+									'event_espresso'
1886
+								),
1887
+								get_class($this),
1888
+								get_class($model) . '::instance()->add_to_entity_map()',
1889
+								get_class($model) . '::instance()->get_one_by_ID()',
1890
+								'<br />'
1891
+							)
1892
+						);
1893
+					}
1894
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1895
+				} else {
1896
+					$results = $model->insert($save_cols_n_values);
1897
+					$this->_update_cached_related_model_objs_fks();
1898
+				}
1899
+			}
1900
+		} else {// there is NO primary key
1901
+			$already_in_db = false;
1902
+			foreach ($model->unique_indexes() as $index) {
1903
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1904
+				if ($model->exists(array($uniqueness_where_params))) {
1905
+					$already_in_db = true;
1906
+				}
1907
+			}
1908
+			if ($already_in_db) {
1909
+				$combined_pk_fields_n_values = array_intersect_key(
1910
+					$save_cols_n_values,
1911
+					$model->get_combined_primary_key_fields()
1912
+				);
1913
+				$results = $model->update(
1914
+					$save_cols_n_values,
1915
+					$combined_pk_fields_n_values
1916
+				);
1917
+			} else {
1918
+				$results = $model->insert($save_cols_n_values);
1919
+			}
1920
+		}
1921
+		// restore the old assumption about values being prepared by the model object
1922
+		$model->assume_values_already_prepared_by_model_object(
1923
+			$old_assumption_concerning_value_preparation
1924
+		);
1925
+		/**
1926
+		 * After saving the model object this action is called
1927
+		 *
1928
+		 * @param EE_Base_Class $model_object which was just saved
1929
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1930
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1931
+		 */
1932
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1933
+		$this->_has_changes = false;
1934
+		return $results;
1935
+	}
1936
+
1937
+
1938
+	/**
1939
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1940
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1941
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1942
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1943
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1944
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1945
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1946
+	 *
1947
+	 * @return void
1948
+	 * @throws ReflectionException
1949
+	 * @throws InvalidArgumentException
1950
+	 * @throws InvalidInterfaceException
1951
+	 * @throws InvalidDataTypeException
1952
+	 * @throws EE_Error
1953
+	 */
1954
+	protected function _update_cached_related_model_objs_fks()
1955
+	{
1956
+		$model = $this->get_model();
1957
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1958
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1959
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1960
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1961
+						$model->get_this_model_name()
1962
+					);
1963
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1964
+					if ($related_model_obj_in_cache->ID()) {
1965
+						$related_model_obj_in_cache->save();
1966
+					}
1967
+				}
1968
+			}
1969
+		}
1970
+	}
1971
+
1972
+
1973
+	/**
1974
+	 * Saves this model object and its NEW cached relations to the database.
1975
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1976
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1977
+	 * because otherwise, there's a potential for infinite looping of saving
1978
+	 * Saves the cached related model objects, and ensures the relation between them
1979
+	 * and this object and properly setup
1980
+	 *
1981
+	 * @return int ID of new model object on save; 0 on failure+
1982
+	 * @throws ReflectionException
1983
+	 * @throws InvalidArgumentException
1984
+	 * @throws InvalidInterfaceException
1985
+	 * @throws InvalidDataTypeException
1986
+	 * @throws EE_Error
1987
+	 */
1988
+	public function save_new_cached_related_model_objs()
1989
+	{
1990
+		// make sure this has been saved
1991
+		if (! $this->ID()) {
1992
+			$id = $this->save();
1993
+		} else {
1994
+			$id = $this->ID();
1995
+		}
1996
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1997
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1998
+			if ($this->_model_relations[ $relationName ]) {
1999
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2000
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2001
+				/* @var $related_model_obj EE_Base_Class */
2002
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2003
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2004
+					// but ONLY if it DOES NOT exist in the DB
2005
+					$related_model_obj = $this->_model_relations[ $relationName ];
2006
+					// if( ! $related_model_obj->ID()){
2007
+					$this->_add_relation_to($related_model_obj, $relationName);
2008
+					$related_model_obj->save_new_cached_related_model_objs();
2009
+					// }
2010
+				} else {
2011
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2012
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2013
+						// but ONLY if it DOES NOT exist in the DB
2014
+						// if( ! $related_model_obj->ID()){
2015
+						$this->_add_relation_to($related_model_obj, $relationName);
2016
+						$related_model_obj->save_new_cached_related_model_objs();
2017
+						// }
2018
+					}
2019
+				}
2020
+			}
2021
+		}
2022
+		return $id;
2023
+	}
2024
+
2025
+
2026
+	/**
2027
+	 * for getting a model while instantiated.
2028
+	 *
2029
+	 * @return EEM_Base | EEM_CPT_Base
2030
+	 * @throws ReflectionException
2031
+	 * @throws InvalidArgumentException
2032
+	 * @throws InvalidInterfaceException
2033
+	 * @throws InvalidDataTypeException
2034
+	 * @throws EE_Error
2035
+	 */
2036
+	public function get_model()
2037
+	{
2038
+		if (! $this->_model) {
2039
+			$modelName = self::_get_model_classname(get_class($this));
2040
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2041
+		} else {
2042
+			$this->_model->set_timezone($this->_timezone);
2043
+		}
2044
+		return $this->_model;
2045
+	}
2046
+
2047
+
2048
+	/**
2049
+	 * @param $props_n_values
2050
+	 * @param $classname
2051
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2052
+	 * @throws ReflectionException
2053
+	 * @throws InvalidArgumentException
2054
+	 * @throws InvalidInterfaceException
2055
+	 * @throws InvalidDataTypeException
2056
+	 * @throws EE_Error
2057
+	 */
2058
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2059
+	{
2060
+		// TODO: will not work for Term_Relationships because they have no PK!
2061
+		$primary_id_ref = self::_get_primary_key_name($classname);
2062
+		if (
2063
+			array_key_exists($primary_id_ref, $props_n_values)
2064
+			&& ! empty($props_n_values[ $primary_id_ref ])
2065
+		) {
2066
+			$id = $props_n_values[ $primary_id_ref ];
2067
+			return self::_get_model($classname)->get_from_entity_map($id);
2068
+		}
2069
+		return false;
2070
+	}
2071
+
2072
+
2073
+	/**
2074
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2075
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2076
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2077
+	 * we return false.
2078
+	 *
2079
+	 * @param  array  $props_n_values   incoming array of properties and their values
2080
+	 * @param  string $classname        the classname of the child class
2081
+	 * @param null    $timezone
2082
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2083
+	 *                                  date_format and the second value is the time format
2084
+	 * @return mixed (EE_Base_Class|bool)
2085
+	 * @throws InvalidArgumentException
2086
+	 * @throws InvalidInterfaceException
2087
+	 * @throws InvalidDataTypeException
2088
+	 * @throws EE_Error
2089
+	 * @throws ReflectionException
2090
+	 * @throws ReflectionException
2091
+	 * @throws ReflectionException
2092
+	 */
2093
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2094
+	{
2095
+		$existing = null;
2096
+		$model = self::_get_model($classname, $timezone);
2097
+		if ($model->has_primary_key_field()) {
2098
+			$primary_id_ref = self::_get_primary_key_name($classname);
2099
+			if (
2100
+				array_key_exists($primary_id_ref, $props_n_values)
2101
+				&& ! empty($props_n_values[ $primary_id_ref ])
2102
+			) {
2103
+				$existing = $model->get_one_by_ID(
2104
+					$props_n_values[ $primary_id_ref ]
2105
+				);
2106
+			}
2107
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2108
+			// no primary key on this model, but there's still a matching item in the DB
2109
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2110
+				self::_get_model($classname, $timezone)
2111
+					->get_index_primary_key_string($props_n_values)
2112
+			);
2113
+		}
2114
+		if ($existing) {
2115
+			// set date formats if present before setting values
2116
+			if (! empty($date_formats) && is_array($date_formats)) {
2117
+				$existing->set_date_format($date_formats[0]);
2118
+				$existing->set_time_format($date_formats[1]);
2119
+			} else {
2120
+				// set default formats for date and time
2121
+				$existing->set_date_format(get_option('date_format'));
2122
+				$existing->set_time_format(get_option('time_format'));
2123
+			}
2124
+			foreach ($props_n_values as $property => $field_value) {
2125
+				$existing->set($property, $field_value);
2126
+			}
2127
+			return $existing;
2128
+		}
2129
+		return false;
2130
+	}
2131
+
2132
+
2133
+	/**
2134
+	 * Gets the EEM_*_Model for this class
2135
+	 *
2136
+	 * @access public now, as this is more convenient
2137
+	 * @param      $classname
2138
+	 * @param null $timezone
2139
+	 * @throws ReflectionException
2140
+	 * @throws InvalidArgumentException
2141
+	 * @throws InvalidInterfaceException
2142
+	 * @throws InvalidDataTypeException
2143
+	 * @throws EE_Error
2144
+	 * @return EEM_Base
2145
+	 */
2146
+	protected static function _get_model($classname, $timezone = null)
2147
+	{
2148
+		// find model for this class
2149
+		if (! $classname) {
2150
+			throw new EE_Error(
2151
+				sprintf(
2152
+					esc_html__(
2153
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2154
+						'event_espresso'
2155
+					),
2156
+					$classname
2157
+				)
2158
+			);
2159
+		}
2160
+		$modelName = self::_get_model_classname($classname);
2161
+		return self::_get_model_instance_with_name($modelName, $timezone);
2162
+	}
2163
+
2164
+
2165
+	/**
2166
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2167
+	 *
2168
+	 * @param string $model_classname
2169
+	 * @param null   $timezone
2170
+	 * @return EEM_Base
2171
+	 * @throws ReflectionException
2172
+	 * @throws InvalidArgumentException
2173
+	 * @throws InvalidInterfaceException
2174
+	 * @throws InvalidDataTypeException
2175
+	 * @throws EE_Error
2176
+	 */
2177
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2178
+	{
2179
+		$model_classname = str_replace('EEM_', '', $model_classname);
2180
+		$model = EE_Registry::instance()->load_model($model_classname);
2181
+		$model->set_timezone($timezone);
2182
+		return $model;
2183
+	}
2184
+
2185
+
2186
+	/**
2187
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2188
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2189
+	 *
2190
+	 * @param string|null $model_name
2191
+	 * @return string like EEM_Attendee
2192
+	 */
2193
+	private static function _get_model_classname($model_name = '')
2194
+	{
2195
+		return strpos((string) $model_name, 'EE_') === 0
2196
+			? str_replace('EE_', 'EEM_', $model_name)
2197
+			: 'EEM_' . $model_name;
2198
+	}
2199
+
2200
+
2201
+	/**
2202
+	 * returns the name of the primary key attribute
2203
+	 *
2204
+	 * @param null $classname
2205
+	 * @throws ReflectionException
2206
+	 * @throws InvalidArgumentException
2207
+	 * @throws InvalidInterfaceException
2208
+	 * @throws InvalidDataTypeException
2209
+	 * @throws EE_Error
2210
+	 * @return string
2211
+	 */
2212
+	protected static function _get_primary_key_name($classname = null)
2213
+	{
2214
+		if (! $classname) {
2215
+			throw new EE_Error(
2216
+				sprintf(
2217
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2218
+					$classname
2219
+				)
2220
+			);
2221
+		}
2222
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2223
+	}
2224
+
2225
+
2226
+	/**
2227
+	 * Gets the value of the primary key.
2228
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2229
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2230
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2231
+	 *
2232
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2233
+	 * @throws ReflectionException
2234
+	 * @throws InvalidArgumentException
2235
+	 * @throws InvalidInterfaceException
2236
+	 * @throws InvalidDataTypeException
2237
+	 * @throws EE_Error
2238
+	 */
2239
+	public function ID()
2240
+	{
2241
+		$model = $this->get_model();
2242
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2243
+		if ($model->has_primary_key_field()) {
2244
+			return $this->_fields[ $model->primary_key_name() ];
2245
+		}
2246
+		return $model->get_index_primary_key_string($this->_fields);
2247
+	}
2248
+
2249
+
2250
+	/**
2251
+	 * @param EE_Base_Class|int|string $otherModelObjectOrID
2252
+	 * @param string                   $relationName
2253
+	 * @return bool
2254
+	 * @throws EE_Error
2255
+	 * @throws ReflectionException
2256
+	 * @since   5.0.0.p
2257
+	 */
2258
+	public function hasRelation($otherModelObjectOrID, string $relationName): bool
2259
+	{
2260
+		$other_model = self::_get_model_instance_with_name(
2261
+			self::_get_model_classname($relationName),
2262
+			$this->_timezone
2263
+		);
2264
+		$primary_key = $other_model->primary_key_name();
2265
+		/** @var EE_Base_Class $otherModelObject */
2266
+		$otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2267
+		return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2268
+	}
2269
+
2270
+
2271
+	/**
2272
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2273
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2274
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2275
+	 *
2276
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2277
+	 * @param string $relationName                     eg 'Events','Question',etc.
2278
+	 *                                                 an attendee to a group, you also want to specify which role they
2279
+	 *                                                 will have in that group. So you would use this parameter to
2280
+	 *                                                 specify array('role-column-name'=>'role-id')
2281
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2282
+	 *                                                 allow you to further constrict the relation to being added.
2283
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2284
+	 *                                                 column on the JOIN table and currently only the HABTM models
2285
+	 *                                                 accept these additional conditions.  Also remember that if an
2286
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2287
+	 *                                                 NEW row is created in the join table.
2288
+	 * @param null   $cache_id
2289
+	 * @throws ReflectionException
2290
+	 * @throws InvalidArgumentException
2291
+	 * @throws InvalidInterfaceException
2292
+	 * @throws InvalidDataTypeException
2293
+	 * @throws EE_Error
2294
+	 * @return EE_Base_Class the object the relation was added to
2295
+	 */
2296
+	public function _add_relation_to(
2297
+		$otherObjectModelObjectOrID,
2298
+		$relationName,
2299
+		$extra_join_model_fields_n_values = array(),
2300
+		$cache_id = null
2301
+	) {
2302
+		$model = $this->get_model();
2303
+		// if this thing exists in the DB, save the relation to the DB
2304
+		if ($this->ID()) {
2305
+			$otherObject = $model->add_relationship_to(
2306
+				$this,
2307
+				$otherObjectModelObjectOrID,
2308
+				$relationName,
2309
+				$extra_join_model_fields_n_values
2310
+			);
2311
+			// clear cache so future get_many_related and get_first_related() return new results.
2312
+			$this->clear_cache($relationName, $otherObject, true);
2313
+			if ($otherObject instanceof EE_Base_Class) {
2314
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2315
+			}
2316
+		} else {
2317
+			// this thing doesn't exist in the DB,  so just cache it
2318
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2319
+				throw new EE_Error(
2320
+					sprintf(
2321
+						esc_html__(
2322
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2323
+							'event_espresso'
2324
+						),
2325
+						$otherObjectModelObjectOrID,
2326
+						get_class($this)
2327
+					)
2328
+				);
2329
+			}
2330
+			$otherObject = $otherObjectModelObjectOrID;
2331
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2332
+		}
2333
+		if ($otherObject instanceof EE_Base_Class) {
2334
+			// fix the reciprocal relation too
2335
+			if ($otherObject->ID()) {
2336
+				// its saved so assumed relations exist in the DB, so we can just
2337
+				// clear the cache so future queries use the updated info in the DB
2338
+				$otherObject->clear_cache(
2339
+					$model->get_this_model_name(),
2340
+					null,
2341
+					true
2342
+				);
2343
+			} else {
2344
+				// it's not saved, so it caches relations like this
2345
+				$otherObject->cache($model->get_this_model_name(), $this);
2346
+			}
2347
+		}
2348
+		return $otherObject;
2349
+	}
2350
+
2351
+
2352
+	/**
2353
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2354
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2355
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2356
+	 * from the cache
2357
+	 *
2358
+	 * @param mixed  $otherObjectModelObjectOrID
2359
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2360
+	 *                to the DB yet
2361
+	 * @param string $relationName
2362
+	 * @param array  $where_query
2363
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2364
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2365
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2366
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2367
+	 *                deleted.
2368
+	 * @return EE_Base_Class the relation was removed from
2369
+	 * @throws ReflectionException
2370
+	 * @throws InvalidArgumentException
2371
+	 * @throws InvalidInterfaceException
2372
+	 * @throws InvalidDataTypeException
2373
+	 * @throws EE_Error
2374
+	 */
2375
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2376
+	{
2377
+		if ($this->ID()) {
2378
+			// if this exists in the DB, save the relation change to the DB too
2379
+			$otherObject = $this->get_model()->remove_relationship_to(
2380
+				$this,
2381
+				$otherObjectModelObjectOrID,
2382
+				$relationName,
2383
+				$where_query
2384
+			);
2385
+			$this->clear_cache(
2386
+				$relationName,
2387
+				$otherObject
2388
+			);
2389
+		} else {
2390
+			// this doesn't exist in the DB, just remove it from the cache
2391
+			$otherObject = $this->clear_cache(
2392
+				$relationName,
2393
+				$otherObjectModelObjectOrID
2394
+			);
2395
+		}
2396
+		if ($otherObject instanceof EE_Base_Class) {
2397
+			$otherObject->clear_cache(
2398
+				$this->get_model()->get_this_model_name(),
2399
+				$this
2400
+			);
2401
+		}
2402
+		return $otherObject;
2403
+	}
2404
+
2405
+
2406
+	/**
2407
+	 * Removes ALL the related things for the $relationName.
2408
+	 *
2409
+	 * @param string $relationName
2410
+	 * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2411
+	 * @return EE_Base_Class
2412
+	 * @throws ReflectionException
2413
+	 * @throws InvalidArgumentException
2414
+	 * @throws InvalidInterfaceException
2415
+	 * @throws InvalidDataTypeException
2416
+	 * @throws EE_Error
2417
+	 */
2418
+	public function _remove_relations($relationName, $where_query_params = array())
2419
+	{
2420
+		if ($this->ID()) {
2421
+			// if this exists in the DB, save the relation change to the DB too
2422
+			$otherObjects = $this->get_model()->remove_relations(
2423
+				$this,
2424
+				$relationName,
2425
+				$where_query_params
2426
+			);
2427
+			$this->clear_cache(
2428
+				$relationName,
2429
+				null,
2430
+				true
2431
+			);
2432
+		} else {
2433
+			// this doesn't exist in the DB, just remove it from the cache
2434
+			$otherObjects = $this->clear_cache(
2435
+				$relationName,
2436
+				null,
2437
+				true
2438
+			);
2439
+		}
2440
+		if (is_array($otherObjects)) {
2441
+			foreach ($otherObjects as $otherObject) {
2442
+				$otherObject->clear_cache(
2443
+					$this->get_model()->get_this_model_name(),
2444
+					$this
2445
+				);
2446
+			}
2447
+		}
2448
+		return $otherObjects;
2449
+	}
2450
+
2451
+
2452
+	/**
2453
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2454
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2455
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2456
+	 * because we want to get even deleted items etc.
2457
+	 *
2458
+	 * @param string $relationName key in the model's _model_relations array
2459
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2460
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2461
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2462
+	 *                             results if you want IDs
2463
+	 * @throws ReflectionException
2464
+	 * @throws InvalidArgumentException
2465
+	 * @throws InvalidInterfaceException
2466
+	 * @throws InvalidDataTypeException
2467
+	 * @throws EE_Error
2468
+	 */
2469
+	public function get_many_related($relationName, $query_params = array())
2470
+	{
2471
+		if ($this->ID()) {
2472
+			// this exists in the DB, so get the related things from either the cache or the DB
2473
+			// if there are query parameters, forget about caching the related model objects.
2474
+			if ($query_params) {
2475
+				$related_model_objects = $this->get_model()->get_all_related(
2476
+					$this,
2477
+					$relationName,
2478
+					$query_params
2479
+				);
2480
+			} else {
2481
+				// did we already cache the result of this query?
2482
+				$cached_results = $this->get_all_from_cache($relationName);
2483
+				if (! $cached_results) {
2484
+					$related_model_objects = $this->get_model()->get_all_related(
2485
+						$this,
2486
+						$relationName,
2487
+						$query_params
2488
+					);
2489
+					// if no query parameters were passed, then we got all the related model objects
2490
+					// for that relation. We can cache them then.
2491
+					foreach ($related_model_objects as $related_model_object) {
2492
+						$this->cache($relationName, $related_model_object);
2493
+					}
2494
+				} else {
2495
+					$related_model_objects = $cached_results;
2496
+				}
2497
+			}
2498
+		} else {
2499
+			// this doesn't exist in the DB, so just get the related things from the cache
2500
+			$related_model_objects = $this->get_all_from_cache($relationName);
2501
+		}
2502
+		return $related_model_objects;
2503
+	}
2504
+
2505
+
2506
+	/**
2507
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2508
+	 * unless otherwise specified in the $query_params
2509
+	 *
2510
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2511
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2512
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2513
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2514
+	 *                               that by the setting $distinct to TRUE;
2515
+	 * @return int
2516
+	 * @throws ReflectionException
2517
+	 * @throws InvalidArgumentException
2518
+	 * @throws InvalidInterfaceException
2519
+	 * @throws InvalidDataTypeException
2520
+	 * @throws EE_Error
2521
+	 */
2522
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2523
+	{
2524
+		return $this->get_model()->count_related(
2525
+			$this,
2526
+			$relation_name,
2527
+			$query_params,
2528
+			$field_to_count,
2529
+			$distinct
2530
+		);
2531
+	}
2532
+
2533
+
2534
+	/**
2535
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2536
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2537
+	 *
2538
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2539
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2540
+	 * @param string $field_to_sum  name of field to count by.
2541
+	 *                              By default, uses primary key
2542
+	 *                              (which doesn't make much sense, so you should probably change it)
2543
+	 * @return int
2544
+	 * @throws ReflectionException
2545
+	 * @throws InvalidArgumentException
2546
+	 * @throws InvalidInterfaceException
2547
+	 * @throws InvalidDataTypeException
2548
+	 * @throws EE_Error
2549
+	 */
2550
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2551
+	{
2552
+		return $this->get_model()->sum_related(
2553
+			$this,
2554
+			$relation_name,
2555
+			$query_params,
2556
+			$field_to_sum
2557
+		);
2558
+	}
2559
+
2560
+
2561
+	/**
2562
+	 * Gets the first (ie, one) related model object of the specified type.
2563
+	 *
2564
+	 * @param string $relationName key in the model's _model_relations array
2565
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2566
+	 * @return EE_Base_Class (not an array, a single object)
2567
+	 * @throws ReflectionException
2568
+	 * @throws InvalidArgumentException
2569
+	 * @throws InvalidInterfaceException
2570
+	 * @throws InvalidDataTypeException
2571
+	 * @throws EE_Error
2572
+	 */
2573
+	public function get_first_related($relationName, $query_params = array())
2574
+	{
2575
+		$model = $this->get_model();
2576
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2577
+			// if they've provided some query parameters, don't bother trying to cache the result
2578
+			// also make sure we're not caching the result of get_first_related
2579
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2580
+			if (
2581
+				$query_params
2582
+				|| ! $model->related_settings_for($relationName)
2583
+					 instanceof
2584
+					 EE_Belongs_To_Relation
2585
+			) {
2586
+				$related_model_object = $model->get_first_related(
2587
+					$this,
2588
+					$relationName,
2589
+					$query_params
2590
+				);
2591
+			} else {
2592
+				// first, check if we've already cached the result of this query
2593
+				$cached_result = $this->get_one_from_cache($relationName);
2594
+				if (! $cached_result) {
2595
+					$related_model_object = $model->get_first_related(
2596
+						$this,
2597
+						$relationName,
2598
+						$query_params
2599
+					);
2600
+					$this->cache($relationName, $related_model_object);
2601
+				} else {
2602
+					$related_model_object = $cached_result;
2603
+				}
2604
+			}
2605
+		} else {
2606
+			$related_model_object = null;
2607
+			// this doesn't exist in the Db,
2608
+			// but maybe the relation is of type belongs to, and so the related thing might
2609
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2610
+				$related_model_object = $model->get_first_related(
2611
+					$this,
2612
+					$relationName,
2613
+					$query_params
2614
+				);
2615
+			}
2616
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2617
+			// just get what's cached on this object
2618
+			if (! $related_model_object) {
2619
+				$related_model_object = $this->get_one_from_cache($relationName);
2620
+			}
2621
+		}
2622
+		return $related_model_object;
2623
+	}
2624
+
2625
+
2626
+	/**
2627
+	 * Does a delete on all related objects of type $relationName and removes
2628
+	 * the current model object's relation to them. If they can't be deleted (because
2629
+	 * of blocking related model objects) does nothing. If the related model objects are
2630
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2631
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2632
+	 *
2633
+	 * @param string $relationName
2634
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2635
+	 * @return int how many deleted
2636
+	 * @throws ReflectionException
2637
+	 * @throws InvalidArgumentException
2638
+	 * @throws InvalidInterfaceException
2639
+	 * @throws InvalidDataTypeException
2640
+	 * @throws EE_Error
2641
+	 */
2642
+	public function delete_related($relationName, $query_params = array())
2643
+	{
2644
+		if ($this->ID()) {
2645
+			$count = $this->get_model()->delete_related(
2646
+				$this,
2647
+				$relationName,
2648
+				$query_params
2649
+			);
2650
+		} else {
2651
+			$count = count($this->get_all_from_cache($relationName));
2652
+			$this->clear_cache($relationName, null, true);
2653
+		}
2654
+		return $count;
2655
+	}
2656
+
2657
+
2658
+	/**
2659
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2660
+	 * the current model object's relation to them. If they can't be deleted (because
2661
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2662
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2663
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2664
+	 *
2665
+	 * @param string $relationName
2666
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2667
+	 * @return int how many deleted (including those soft deleted)
2668
+	 * @throws ReflectionException
2669
+	 * @throws InvalidArgumentException
2670
+	 * @throws InvalidInterfaceException
2671
+	 * @throws InvalidDataTypeException
2672
+	 * @throws EE_Error
2673
+	 */
2674
+	public function delete_related_permanently($relationName, $query_params = array())
2675
+	{
2676
+		if ($this->ID()) {
2677
+			$count = $this->get_model()->delete_related_permanently(
2678
+				$this,
2679
+				$relationName,
2680
+				$query_params
2681
+			);
2682
+		} else {
2683
+			$count = count($this->get_all_from_cache($relationName));
2684
+		}
2685
+		$this->clear_cache($relationName, null, true);
2686
+		return $count;
2687
+	}
2688
+
2689
+
2690
+	/**
2691
+	 * is_set
2692
+	 * Just a simple utility function children can use for checking if property exists
2693
+	 *
2694
+	 * @access  public
2695
+	 * @param  string $field_name property to check
2696
+	 * @return bool                              TRUE if existing,FALSE if not.
2697
+	 */
2698
+	public function is_set($field_name)
2699
+	{
2700
+		return isset($this->_fields[ $field_name ]);
2701
+	}
2702
+
2703
+
2704
+	/**
2705
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2706
+	 * EE_Error exception if they don't
2707
+	 *
2708
+	 * @param  mixed (string|array) $properties properties to check
2709
+	 * @throws EE_Error
2710
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2711
+	 */
2712
+	protected function _property_exists($properties)
2713
+	{
2714
+		foreach ((array) $properties as $property_name) {
2715
+			// first make sure this property exists
2716
+			if (! $this->_fields[ $property_name ]) {
2717
+				throw new EE_Error(
2718
+					sprintf(
2719
+						esc_html__(
2720
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2721
+							'event_espresso'
2722
+						),
2723
+						$property_name
2724
+					)
2725
+				);
2726
+			}
2727
+		}
2728
+		return true;
2729
+	}
2730
+
2731
+
2732
+	/**
2733
+	 * This simply returns an array of model fields for this object
2734
+	 *
2735
+	 * @return array
2736
+	 * @throws ReflectionException
2737
+	 * @throws InvalidArgumentException
2738
+	 * @throws InvalidInterfaceException
2739
+	 * @throws InvalidDataTypeException
2740
+	 * @throws EE_Error
2741
+	 */
2742
+	public function model_field_array()
2743
+	{
2744
+		$fields = $this->get_model()->field_settings(false);
2745
+		$properties = array();
2746
+		// remove prepended underscore
2747
+		foreach ($fields as $field_name => $settings) {
2748
+			$properties[ $field_name ] = $this->get($field_name);
2749
+		}
2750
+		return $properties;
2751
+	}
2752
+
2753
+
2754
+	/**
2755
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2756
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2757
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2758
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2759
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2760
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2761
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2762
+	 * and accepts 2 arguments: the object on which the function was called,
2763
+	 * and an array of the original arguments passed to the function.
2764
+	 * Whatever their callback function returns will be returned by this function.
2765
+	 * Example: in functions.php (or in a plugin):
2766
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2767
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2768
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2769
+	 *          return $previousReturnValue.$returnString;
2770
+	 *      }
2771
+	 * require('EE_Answer.class.php');
2772
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2773
+	 *      ->my_callback('monkeys',100);
2774
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2775
+	 *
2776
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2777
+	 * @param array  $args       array of original arguments passed to the function
2778
+	 * @throws EE_Error
2779
+	 * @return mixed whatever the plugin which calls add_filter decides
2780
+	 */
2781
+	public function __call($methodName, $args)
2782
+	{
2783
+		$className = get_class($this);
2784
+		$tagName = "FHEE__{$className}__{$methodName}";
2785
+		if (! has_filter($tagName)) {
2786
+			throw new EE_Error(
2787
+				sprintf(
2788
+					esc_html__(
2789
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2790
+						'event_espresso'
2791
+					),
2792
+					$methodName,
2793
+					$className,
2794
+					$tagName
2795
+				)
2796
+			);
2797
+		}
2798
+		return apply_filters($tagName, null, $this, $args);
2799
+	}
2800
+
2801
+
2802
+	/**
2803
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2804
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2805
+	 *
2806
+	 * @param string $meta_key
2807
+	 * @param mixed  $meta_value
2808
+	 * @param mixed  $previous_value
2809
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2810
+	 *                  NOTE: if the values haven't changed, returns 0
2811
+	 * @throws InvalidArgumentException
2812
+	 * @throws InvalidInterfaceException
2813
+	 * @throws InvalidDataTypeException
2814
+	 * @throws EE_Error
2815
+	 * @throws ReflectionException
2816
+	 */
2817
+	public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2818
+	{
2819
+		$query_params = [
2820
+			[
2821
+				'EXM_key'  => $meta_key,
2822
+				'OBJ_ID'   => $this->ID(),
2823
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2824
+			],
2825
+		];
2826
+		if ($previous_value !== null) {
2827
+			$query_params[0]['EXM_value'] = $meta_value;
2828
+		}
2829
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2830
+		if (! $existing_rows_like_that) {
2831
+			return $this->add_extra_meta($meta_key, $meta_value);
2832
+		}
2833
+		foreach ($existing_rows_like_that as $existing_row) {
2834
+			$existing_row->save(['EXM_value' => $meta_value]);
2835
+		}
2836
+		return count($existing_rows_like_that);
2837
+	}
2838
+
2839
+
2840
+	/**
2841
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2842
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2843
+	 * extra meta row was entered, false if not
2844
+	 *
2845
+	 * @param string $meta_key
2846
+	 * @param mixed  $meta_value
2847
+	 * @param bool   $unique
2848
+	 * @return bool
2849
+	 * @throws InvalidArgumentException
2850
+	 * @throws InvalidInterfaceException
2851
+	 * @throws InvalidDataTypeException
2852
+	 * @throws EE_Error
2853
+	 * @throws ReflectionException
2854
+	 * @throws ReflectionException
2855
+	 */
2856
+	public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2857
+	{
2858
+		if ($unique) {
2859
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2860
+				[
2861
+					[
2862
+						'EXM_key'  => $meta_key,
2863
+						'OBJ_ID'   => $this->ID(),
2864
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2865
+					],
2866
+				]
2867
+			);
2868
+			if ($existing_extra_meta) {
2869
+				return false;
2870
+			}
2871
+		}
2872
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2873
+			[
2874
+				'EXM_key'   => $meta_key,
2875
+				'EXM_value' => $meta_value,
2876
+				'OBJ_ID'    => $this->ID(),
2877
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2878
+			]
2879
+		);
2880
+		$new_extra_meta->save();
2881
+		return true;
2882
+	}
2883
+
2884
+
2885
+	/**
2886
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2887
+	 * is specified, only deletes extra meta records with that value.
2888
+	 *
2889
+	 * @param string $meta_key
2890
+	 * @param mixed  $meta_value
2891
+	 * @return int|bool number of extra meta rows deleted
2892
+	 * @throws InvalidArgumentException
2893
+	 * @throws InvalidInterfaceException
2894
+	 * @throws InvalidDataTypeException
2895
+	 * @throws EE_Error
2896
+	 * @throws ReflectionException
2897
+	 */
2898
+	public function delete_extra_meta(string $meta_key, $meta_value = null)
2899
+	{
2900
+		$query_params = [
2901
+			[
2902
+				'EXM_key'  => $meta_key,
2903
+				'OBJ_ID'   => $this->ID(),
2904
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2905
+			],
2906
+		];
2907
+		if ($meta_value !== null) {
2908
+			$query_params[0]['EXM_value'] = $meta_value;
2909
+		}
2910
+		return EEM_Extra_Meta::instance()->delete($query_params);
2911
+	}
2912
+
2913
+
2914
+	/**
2915
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2916
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2917
+	 * You can specify $default is case you haven't found the extra meta
2918
+	 *
2919
+	 * @param string     $meta_key
2920
+	 * @param bool       $single
2921
+	 * @param mixed      $default if we don't find anything, what should we return?
2922
+	 * @param array|null $extra_where
2923
+	 * @return mixed single value if $single; array if ! $single
2924
+	 * @throws ReflectionException
2925
+	 * @throws EE_Error
2926
+	 */
2927
+	public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2928
+	{
2929
+		$query_params = [ $extra_where + ['EXM_key' => $meta_key] ];
2930
+		if ($single) {
2931
+			$result = $this->get_first_related('Extra_Meta', $query_params);
2932
+			if ($result instanceof EE_Extra_Meta) {
2933
+				return $result->value();
2934
+			}
2935
+		} else {
2936
+			$results = $this->get_many_related('Extra_Meta', $query_params);
2937
+			if ($results) {
2938
+				$values = [];
2939
+				foreach ($results as $result) {
2940
+					if ($result instanceof EE_Extra_Meta) {
2941
+						$values[ $result->ID() ] = $result->value();
2942
+					}
2943
+				}
2944
+				return $values;
2945
+			}
2946
+		}
2947
+		// if nothing discovered yet return default.
2948
+		return apply_filters(
2949
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2950
+			$default,
2951
+			$meta_key,
2952
+			$single,
2953
+			$this
2954
+		);
2955
+	}
2956
+
2957
+
2958
+	/**
2959
+	 * Returns a simple array of all the extra meta associated with this model object.
2960
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2961
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2962
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2963
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2964
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2965
+	 * finally the extra meta's value as each sub-value. (eg
2966
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2967
+	 *
2968
+	 * @param bool $one_of_each_key
2969
+	 * @return array
2970
+	 * @throws ReflectionException
2971
+	 * @throws InvalidArgumentException
2972
+	 * @throws InvalidInterfaceException
2973
+	 * @throws InvalidDataTypeException
2974
+	 * @throws EE_Error
2975
+	 */
2976
+	public function all_extra_meta_array(bool $one_of_each_key = true): array
2977
+	{
2978
+		$return_array = [];
2979
+		if ($one_of_each_key) {
2980
+			$extra_meta_objs = $this->get_many_related(
2981
+				'Extra_Meta',
2982
+				['group_by' => 'EXM_key']
2983
+			);
2984
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2985
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2986
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2987
+				}
2988
+			}
2989
+		} else {
2990
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2991
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2992
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2993
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2994
+						$return_array[ $extra_meta_obj->key() ] = [];
2995
+					}
2996
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2997
+				}
2998
+			}
2999
+		}
3000
+		return $return_array;
3001
+	}
3002
+
3003
+
3004
+	/**
3005
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
3006
+	 *
3007
+	 * @return string
3008
+	 * @throws ReflectionException
3009
+	 * @throws InvalidArgumentException
3010
+	 * @throws InvalidInterfaceException
3011
+	 * @throws InvalidDataTypeException
3012
+	 * @throws EE_Error
3013
+	 */
3014
+	public function name()
3015
+	{
3016
+		// find a field that's not a text field
3017
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3018
+		if ($field_we_can_use) {
3019
+			return $this->get($field_we_can_use->get_name());
3020
+		}
3021
+		$first_few_properties = $this->model_field_array();
3022
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3023
+		$name_parts = array();
3024
+		foreach ($first_few_properties as $name => $value) {
3025
+			$name_parts[] = "$name:$value";
3026
+		}
3027
+		return implode(',', $name_parts);
3028
+	}
3029
+
3030
+
3031
+	/**
3032
+	 * in_entity_map
3033
+	 * Checks if this model object has been proven to already be in the entity map
3034
+	 *
3035
+	 * @return boolean
3036
+	 * @throws ReflectionException
3037
+	 * @throws InvalidArgumentException
3038
+	 * @throws InvalidInterfaceException
3039
+	 * @throws InvalidDataTypeException
3040
+	 * @throws EE_Error
3041
+	 */
3042
+	public function in_entity_map()
3043
+	{
3044
+		// well, if we looked, did we find it in the entity map?
3045
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3046
+	}
3047
+
3048
+
3049
+	/**
3050
+	 * refresh_from_db
3051
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3052
+	 *
3053
+	 * @throws ReflectionException
3054
+	 * @throws InvalidArgumentException
3055
+	 * @throws InvalidInterfaceException
3056
+	 * @throws InvalidDataTypeException
3057
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3058
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3059
+	 */
3060
+	public function refresh_from_db()
3061
+	{
3062
+		if ($this->ID() && $this->in_entity_map()) {
3063
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3064
+		} else {
3065
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3066
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3067
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3068
+			// absolutely nothing in it for this ID
3069
+			if (WP_DEBUG) {
3070
+				throw new EE_Error(
3071
+					sprintf(
3072
+						esc_html__(
3073
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3074
+							'event_espresso'
3075
+						),
3076
+						$this->ID(),
3077
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3078
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3079
+					)
3080
+				);
3081
+			}
3082
+		}
3083
+	}
3084
+
3085
+
3086
+	/**
3087
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3088
+	 *
3089
+	 * @since 4.9.80.p
3090
+	 * @param EE_Model_Field_Base[] $fields
3091
+	 * @param string $new_value_sql
3092
+	 *      example: 'column_name=123',
3093
+	 *      or 'column_name=column_name+1',
3094
+	 *      or 'column_name= CASE
3095
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3096
+	 *          THEN `column_name` + 5
3097
+	 *          ELSE `column_name`
3098
+	 *      END'
3099
+	 *      Also updates $field on this model object with the latest value from the database.
3100
+	 * @return bool
3101
+	 * @throws EE_Error
3102
+	 * @throws InvalidArgumentException
3103
+	 * @throws InvalidDataTypeException
3104
+	 * @throws InvalidInterfaceException
3105
+	 * @throws ReflectionException
3106
+	 */
3107
+	protected function updateFieldsInDB($fields, $new_value_sql)
3108
+	{
3109
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3110
+		// if it wasn't even there to start off.
3111
+		if (! $this->ID()) {
3112
+			$this->save();
3113
+		}
3114
+		global $wpdb;
3115
+		if (empty($fields)) {
3116
+			throw new InvalidArgumentException(
3117
+				esc_html__(
3118
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3119
+					'event_espresso'
3120
+				)
3121
+			);
3122
+		}
3123
+		$first_field = reset($fields);
3124
+		$table_alias = $first_field->get_table_alias();
3125
+		foreach ($fields as $field) {
3126
+			if ($table_alias !== $field->get_table_alias()) {
3127
+				throw new InvalidArgumentException(
3128
+					sprintf(
3129
+						esc_html__(
3130
+							// @codingStandardsIgnoreStart
3131
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3132
+							// @codingStandardsIgnoreEnd
3133
+							'event_espresso'
3134
+						),
3135
+						$table_alias,
3136
+						$field->get_table_alias()
3137
+					)
3138
+				);
3139
+			}
3140
+		}
3141
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3142
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3143
+		$table_pk_value = $this->ID();
3144
+		$table_name = $table_obj->get_table_name();
3145
+		if ($table_obj instanceof EE_Secondary_Table) {
3146
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3147
+		} else {
3148
+			$table_pk_field_name = $table_obj->get_pk_column();
3149
+		}
3150
+
3151
+		$query =
3152
+			"UPDATE `{$table_name}`
3153 3153
             SET "
3154
-            . $new_value_sql
3155
-            . $wpdb->prepare(
3156
-                "
3154
+			. $new_value_sql
3155
+			. $wpdb->prepare(
3156
+				"
3157 3157
             WHERE `{$table_pk_field_name}` = %d;",
3158
-                $table_pk_value
3159
-            );
3160
-        $result = $wpdb->query($query);
3161
-        foreach ($fields as $field) {
3162
-            // If it was successful, we'd like to know the new value.
3163
-            // If it failed, we'd also like to know the new value.
3164
-            $new_value = $this->get_model()->get_var(
3165
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3166
-                    $this->get_model()->get_index_primary_key_string(
3167
-                        $this->model_field_array()
3168
-                    ),
3169
-                    array(
3170
-                        'default_where_conditions' => 'minimum',
3171
-                    )
3172
-                ),
3173
-                $field->get_name()
3174
-            );
3175
-            $this->set_from_db(
3176
-                $field->get_name(),
3177
-                $new_value
3178
-            );
3179
-        }
3180
-        return (bool) $result;
3181
-    }
3182
-
3183
-
3184
-    /**
3185
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3186
-     * Does not allow negative values, however.
3187
-     *
3188
-     * @since 4.9.80.p
3189
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3190
-     *                                   (positive or negative). One important gotcha: all these values must be
3191
-     *                                   on the same table (eg don't pass in one field for the posts table and
3192
-     *                                   another for the event meta table.)
3193
-     * @return bool
3194
-     * @throws EE_Error
3195
-     * @throws InvalidArgumentException
3196
-     * @throws InvalidDataTypeException
3197
-     * @throws InvalidInterfaceException
3198
-     * @throws ReflectionException
3199
-     */
3200
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3201
-    {
3202
-        global $wpdb;
3203
-        if (empty($fields_n_quantities)) {
3204
-            // No fields to update? Well sure, we updated them to that value just fine.
3205
-            return true;
3206
-        }
3207
-        $fields = [];
3208
-        $set_sql_statements = [];
3209
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3210
-            $field = $this->get_model()->field_settings_for($field_name, true);
3211
-            $fields[] = $field;
3212
-            $column_name = $field->get_table_column();
3213
-
3214
-            $abs_qty = absint($quantity);
3215
-            if ($quantity > 0) {
3216
-                // don't let the value be negative as often these fields are unsigned
3217
-                $set_sql_statements[] = $wpdb->prepare(
3218
-                    "`{$column_name}` = `{$column_name}` + %d",
3219
-                    $abs_qty
3220
-                );
3221
-            } else {
3222
-                $set_sql_statements[] = $wpdb->prepare(
3223
-                    "`{$column_name}` = CASE
3158
+				$table_pk_value
3159
+			);
3160
+		$result = $wpdb->query($query);
3161
+		foreach ($fields as $field) {
3162
+			// If it was successful, we'd like to know the new value.
3163
+			// If it failed, we'd also like to know the new value.
3164
+			$new_value = $this->get_model()->get_var(
3165
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3166
+					$this->get_model()->get_index_primary_key_string(
3167
+						$this->model_field_array()
3168
+					),
3169
+					array(
3170
+						'default_where_conditions' => 'minimum',
3171
+					)
3172
+				),
3173
+				$field->get_name()
3174
+			);
3175
+			$this->set_from_db(
3176
+				$field->get_name(),
3177
+				$new_value
3178
+			);
3179
+		}
3180
+		return (bool) $result;
3181
+	}
3182
+
3183
+
3184
+	/**
3185
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3186
+	 * Does not allow negative values, however.
3187
+	 *
3188
+	 * @since 4.9.80.p
3189
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3190
+	 *                                   (positive or negative). One important gotcha: all these values must be
3191
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3192
+	 *                                   another for the event meta table.)
3193
+	 * @return bool
3194
+	 * @throws EE_Error
3195
+	 * @throws InvalidArgumentException
3196
+	 * @throws InvalidDataTypeException
3197
+	 * @throws InvalidInterfaceException
3198
+	 * @throws ReflectionException
3199
+	 */
3200
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3201
+	{
3202
+		global $wpdb;
3203
+		if (empty($fields_n_quantities)) {
3204
+			// No fields to update? Well sure, we updated them to that value just fine.
3205
+			return true;
3206
+		}
3207
+		$fields = [];
3208
+		$set_sql_statements = [];
3209
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3210
+			$field = $this->get_model()->field_settings_for($field_name, true);
3211
+			$fields[] = $field;
3212
+			$column_name = $field->get_table_column();
3213
+
3214
+			$abs_qty = absint($quantity);
3215
+			if ($quantity > 0) {
3216
+				// don't let the value be negative as often these fields are unsigned
3217
+				$set_sql_statements[] = $wpdb->prepare(
3218
+					"`{$column_name}` = `{$column_name}` + %d",
3219
+					$abs_qty
3220
+				);
3221
+			} else {
3222
+				$set_sql_statements[] = $wpdb->prepare(
3223
+					"`{$column_name}` = CASE
3224 3224
                        WHEN (`{$column_name}` >= %d)
3225 3225
                        THEN `{$column_name}` - %d
3226 3226
                        ELSE 0
3227 3227
                     END",
3228
-                    $abs_qty,
3229
-                    $abs_qty
3230
-                );
3231
-            }
3232
-        }
3233
-        return $this->updateFieldsInDB(
3234
-            $fields,
3235
-            implode(', ', $set_sql_statements)
3236
-        );
3237
-    }
3238
-
3239
-
3240
-    /**
3241
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3242
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3243
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3244
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3245
-     * Otherwise returns false.
3246
-     *
3247
-     * @since 4.9.80.p
3248
-     * @param string $field_name_to_bump
3249
-     * @param string $field_name_affecting_total
3250
-     * @param string $limit_field_name
3251
-     * @param int    $quantity
3252
-     * @return bool
3253
-     * @throws EE_Error
3254
-     * @throws InvalidArgumentException
3255
-     * @throws InvalidDataTypeException
3256
-     * @throws InvalidInterfaceException
3257
-     * @throws ReflectionException
3258
-     */
3259
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3260
-    {
3261
-        global $wpdb;
3262
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3263
-        $column_name = $field->get_table_column();
3264
-
3265
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3266
-        $column_affecting_total = $field_affecting_total->get_table_column();
3267
-
3268
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3269
-        $limiting_column = $limiting_field->get_table_column();
3270
-        return $this->updateFieldsInDB(
3271
-            [$field],
3272
-            $wpdb->prepare(
3273
-                "`{$column_name}` =
3228
+					$abs_qty,
3229
+					$abs_qty
3230
+				);
3231
+			}
3232
+		}
3233
+		return $this->updateFieldsInDB(
3234
+			$fields,
3235
+			implode(', ', $set_sql_statements)
3236
+		);
3237
+	}
3238
+
3239
+
3240
+	/**
3241
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3242
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3243
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3244
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3245
+	 * Otherwise returns false.
3246
+	 *
3247
+	 * @since 4.9.80.p
3248
+	 * @param string $field_name_to_bump
3249
+	 * @param string $field_name_affecting_total
3250
+	 * @param string $limit_field_name
3251
+	 * @param int    $quantity
3252
+	 * @return bool
3253
+	 * @throws EE_Error
3254
+	 * @throws InvalidArgumentException
3255
+	 * @throws InvalidDataTypeException
3256
+	 * @throws InvalidInterfaceException
3257
+	 * @throws ReflectionException
3258
+	 */
3259
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3260
+	{
3261
+		global $wpdb;
3262
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3263
+		$column_name = $field->get_table_column();
3264
+
3265
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3266
+		$column_affecting_total = $field_affecting_total->get_table_column();
3267
+
3268
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3269
+		$limiting_column = $limiting_field->get_table_column();
3270
+		return $this->updateFieldsInDB(
3271
+			[$field],
3272
+			$wpdb->prepare(
3273
+				"`{$column_name}` =
3274 3274
             CASE
3275 3275
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3276 3276
                THEN `{$column_name}` + %d
3277 3277
                ELSE `{$column_name}`
3278 3278
             END",
3279
-                $quantity,
3280
-                EE_INF_IN_DB,
3281
-                $quantity
3282
-            )
3283
-        );
3284
-    }
3285
-
3286
-
3287
-    /**
3288
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3289
-     * (probably a bad assumption they have made, oh well)
3290
-     *
3291
-     * @return string
3292
-     */
3293
-    public function __toString()
3294
-    {
3295
-        try {
3296
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3297
-        } catch (Exception $e) {
3298
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3299
-            return '';
3300
-        }
3301
-    }
3302
-
3303
-
3304
-    /**
3305
-     * Clear related model objects if they're already in the DB, because otherwise when we
3306
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3307
-     * This means if we have made changes to those related model objects, and want to unserialize
3308
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3309
-     * Instead, those related model objects should be directly serialized and stored.
3310
-     * Eg, the following won't work:
3311
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3312
-     * $att = $reg->attendee();
3313
-     * $att->set( 'ATT_fname', 'Dirk' );
3314
-     * update_option( 'my_option', serialize( $reg ) );
3315
-     * //END REQUEST
3316
-     * //START NEXT REQUEST
3317
-     * $reg = get_option( 'my_option' );
3318
-     * $reg->attendee()->save();
3319
-     * And would need to be replace with:
3320
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3321
-     * $att = $reg->attendee();
3322
-     * $att->set( 'ATT_fname', 'Dirk' );
3323
-     * update_option( 'my_option', serialize( $reg ) );
3324
-     * //END REQUEST
3325
-     * //START NEXT REQUEST
3326
-     * $att = get_option( 'my_option' );
3327
-     * $att->save();
3328
-     *
3329
-     * @return array
3330
-     * @throws ReflectionException
3331
-     * @throws InvalidArgumentException
3332
-     * @throws InvalidInterfaceException
3333
-     * @throws InvalidDataTypeException
3334
-     * @throws EE_Error
3335
-     */
3336
-    public function __sleep()
3337
-    {
3338
-        $model = $this->get_model();
3339
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3340
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3341
-                $classname = 'EE_' . $model->get_this_model_name();
3342
-                if (
3343
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3344
-                    && $this->get_one_from_cache($relation_name)->ID()
3345
-                ) {
3346
-                    $this->clear_cache(
3347
-                        $relation_name,
3348
-                        $this->get_one_from_cache($relation_name)->ID()
3349
-                    );
3350
-                }
3351
-            }
3352
-        }
3353
-        $this->_props_n_values_provided_in_constructor = array();
3354
-        $properties_to_serialize = get_object_vars($this);
3355
-        // don't serialize the model. It's big and that risks recursion
3356
-        unset($properties_to_serialize['_model']);
3357
-        return array_keys($properties_to_serialize);
3358
-    }
3359
-
3360
-
3361
-    /**
3362
-     * restore _props_n_values_provided_in_constructor
3363
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3364
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3365
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3366
-     */
3367
-    public function __wakeup()
3368
-    {
3369
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3370
-    }
3371
-
3372
-
3373
-    /**
3374
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3375
-     * distinct with the clone host instance are also cloned.
3376
-     */
3377
-    public function __clone()
3378
-    {
3379
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3380
-        foreach ($this->_fields as $field => $value) {
3381
-            if ($value instanceof DateTime) {
3382
-                $this->_fields[ $field ] = clone $value;
3383
-            }
3384
-        }
3385
-    }
3279
+				$quantity,
3280
+				EE_INF_IN_DB,
3281
+				$quantity
3282
+			)
3283
+		);
3284
+	}
3285
+
3286
+
3287
+	/**
3288
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3289
+	 * (probably a bad assumption they have made, oh well)
3290
+	 *
3291
+	 * @return string
3292
+	 */
3293
+	public function __toString()
3294
+	{
3295
+		try {
3296
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3297
+		} catch (Exception $e) {
3298
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3299
+			return '';
3300
+		}
3301
+	}
3302
+
3303
+
3304
+	/**
3305
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3306
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3307
+	 * This means if we have made changes to those related model objects, and want to unserialize
3308
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3309
+	 * Instead, those related model objects should be directly serialized and stored.
3310
+	 * Eg, the following won't work:
3311
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3312
+	 * $att = $reg->attendee();
3313
+	 * $att->set( 'ATT_fname', 'Dirk' );
3314
+	 * update_option( 'my_option', serialize( $reg ) );
3315
+	 * //END REQUEST
3316
+	 * //START NEXT REQUEST
3317
+	 * $reg = get_option( 'my_option' );
3318
+	 * $reg->attendee()->save();
3319
+	 * And would need to be replace with:
3320
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3321
+	 * $att = $reg->attendee();
3322
+	 * $att->set( 'ATT_fname', 'Dirk' );
3323
+	 * update_option( 'my_option', serialize( $reg ) );
3324
+	 * //END REQUEST
3325
+	 * //START NEXT REQUEST
3326
+	 * $att = get_option( 'my_option' );
3327
+	 * $att->save();
3328
+	 *
3329
+	 * @return array
3330
+	 * @throws ReflectionException
3331
+	 * @throws InvalidArgumentException
3332
+	 * @throws InvalidInterfaceException
3333
+	 * @throws InvalidDataTypeException
3334
+	 * @throws EE_Error
3335
+	 */
3336
+	public function __sleep()
3337
+	{
3338
+		$model = $this->get_model();
3339
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3340
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3341
+				$classname = 'EE_' . $model->get_this_model_name();
3342
+				if (
3343
+					$this->get_one_from_cache($relation_name) instanceof $classname
3344
+					&& $this->get_one_from_cache($relation_name)->ID()
3345
+				) {
3346
+					$this->clear_cache(
3347
+						$relation_name,
3348
+						$this->get_one_from_cache($relation_name)->ID()
3349
+					);
3350
+				}
3351
+			}
3352
+		}
3353
+		$this->_props_n_values_provided_in_constructor = array();
3354
+		$properties_to_serialize = get_object_vars($this);
3355
+		// don't serialize the model. It's big and that risks recursion
3356
+		unset($properties_to_serialize['_model']);
3357
+		return array_keys($properties_to_serialize);
3358
+	}
3359
+
3360
+
3361
+	/**
3362
+	 * restore _props_n_values_provided_in_constructor
3363
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3364
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3365
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3366
+	 */
3367
+	public function __wakeup()
3368
+	{
3369
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3370
+	}
3371
+
3372
+
3373
+	/**
3374
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3375
+	 * distinct with the clone host instance are also cloned.
3376
+	 */
3377
+	public function __clone()
3378
+	{
3379
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3380
+		foreach ($this->_fields as $field => $value) {
3381
+			if ($value instanceof DateTime) {
3382
+				$this->_fields[ $field ] = clone $value;
3383
+			}
3384
+		}
3385
+	}
3386 3386
 }
Please login to merge, or discard this patch.
core/db_classes/EE_CPT_Base.class.php 1 patch
Indentation   +440 added lines, -440 removed lines patch added patch discarded remove patch
@@ -13,444 +13,444 @@
 block discarded – undo
13 13
  */
14 14
 abstract class EE_CPT_Base extends EE_Soft_Delete_Base_Class
15 15
 {
16
-    /**
17
-     * @var stdClass
18
-     * @since 5.0.0.p
19
-     */
20
-    public $labels;
21
-
22
-    /**
23
-     * @var string
24
-     * @since 5.0.0.p
25
-     */
26
-    public $name;
27
-
28
-    /**
29
-     * This is a property for holding cached feature images on CPT objects.  Cache's are set on the first
30
-     * "feature_image()" method call.  Each key in the array corresponds to the requested size.
31
-     *
32
-     * @var array
33
-     */
34
-    protected $_feature_image = array();
35
-
36
-    /**
37
-     * @var WP_Post the WP_Post that corresponds with this CPT model object
38
-     */
39
-    protected $_wp_post;
40
-
41
-
42
-    abstract public function wp_user();
43
-
44
-
45
-    /**
46
-     * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
47
-     * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
48
-     *
49
-     * @return WP_Post
50
-     */
51
-    public function wp_post()
52
-    {
53
-        global $wpdb;
54
-        if (! $this->_wp_post instanceof WP_Post) {
55
-            if ($this->ID()) {
56
-                $this->_wp_post = get_post($this->ID());
57
-            } else {
58
-                $simulated_db_result = new stdClass();
59
-                foreach ($this->get_model()->field_settings(true) as $field_name => $field_obj) {
60
-                    if (
61
-                        $this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name()
62
-                        === $wpdb->posts
63
-                    ) {
64
-                        $column = $field_obj->get_table_column();
65
-
66
-                        if ($field_obj instanceof EE_Datetime_Field) {
67
-                            $value_on_model_obj = $this->get_DateTime_object($field_name);
68
-                        } elseif ($field_obj->is_db_only_field()) {
69
-                            $value_on_model_obj = $field_obj->get_default_value();
70
-                        } else {
71
-                            $value_on_model_obj = $this->get_raw($field_name);
72
-                        }
73
-                        $simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
74
-                    }
75
-                }
76
-                $this->_wp_post = new WP_Post($simulated_db_result);
77
-            }
78
-            // and let's make retrieving the EE CPT object easy too
79
-            $classname = get_class($this);
80
-            if (! isset($this->_wp_post->{$classname})) {
81
-                $this->_wp_post->{$classname} = $this;
82
-            }
83
-        }
84
-        return $this->_wp_post;
85
-    }
86
-
87
-    /**
88
-     * When fetching a new value for a post field that uses the global $post for rendering,
89
-     * set the global $post temporarily to be this model object; and afterwards restore it
90
-     *
91
-     * @param string $fieldname
92
-     * @param bool   $pretty
93
-     * @param string $extra_cache_ref
94
-     * @return mixed
95
-     */
96
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
97
-    {
98
-        global $post;
99
-
100
-        if (
101
-            $pretty
102
-            && (
103
-                ! (
104
-                    $post instanceof WP_Post
105
-                    && $post->ID
106
-                )
107
-                || (int) $post->ID !== $this->ID()
108
-            )
109
-            && $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field
110
-        ) {
111
-            $old_post = $post;
112
-            $post = $this->wp_post();
113
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
114
-            $post = $old_post;
115
-        } else {
116
-            $return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
117
-        }
118
-        return $return_value;
119
-    }
120
-
121
-    /**
122
-     * Adds to the specified event category. If it category doesn't exist, creates it.
123
-     *
124
-     * @param string $category_name
125
-     * @param string $category_description    optional
126
-     * @param int    $parent_term_taxonomy_id optional
127
-     * @return EE_Term_Taxonomy
128
-     */
129
-    public function add_event_category($category_name, $category_description = null, $parent_term_taxonomy_id = null)
130
-    {
131
-        return $this->get_model()->add_event_category(
132
-            $this,
133
-            $category_name,
134
-            $category_description,
135
-            $parent_term_taxonomy_id
136
-        );
137
-    }
138
-
139
-
140
-    /**
141
-     * Removes the event category by specified name from being related ot this event
142
-     *
143
-     * @param string $category_name
144
-     * @return bool
145
-     */
146
-    public function remove_event_category($category_name)
147
-    {
148
-        return $this->get_model()->remove_event_category($this, $category_name);
149
-    }
150
-
151
-
152
-    /**
153
-     * Removes the relation to the specified term taxonomy, and maintains the
154
-     * data integrity of the term taxonomy provided
155
-     *
156
-     * @param EE_Term_Taxonomy $term_taxonomy
157
-     * @return EE_Base_Class the relation was removed from
158
-     */
159
-    public function remove_relation_to_term_taxonomy($term_taxonomy)
160
-    {
161
-        if (! $term_taxonomy) {
162
-            EE_Error::add_error(
163
-                sprintf(
164
-                    esc_html__(
165
-                        "No Term_Taxonomy provided which to remove from model object of type %s and id %d",
166
-                        "event_espresso"
167
-                    ),
168
-                    get_class($this),
169
-                    $this->ID()
170
-                ),
171
-                __FILE__,
172
-                __FUNCTION__,
173
-                __LINE__
174
-            );
175
-            return null;
176
-        }
177
-        $term_taxonomy->set_count($term_taxonomy->count() - 1);
178
-        $term_taxonomy->save();
179
-        return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
180
-    }
181
-
182
-
183
-    /**
184
-     * The main purpose of this method is to return the post type for the model object
185
-     *
186
-     * @access public
187
-     * @return string
188
-     */
189
-    public function post_type()
190
-    {
191
-        return $this->get_model()->post_type();
192
-    }
193
-
194
-
195
-    /**
196
-     * The main purpose of this method is to return the parent for the model object
197
-     *
198
-     * @access public
199
-     * @return int
200
-     */
201
-    public function parent()
202
-    {
203
-        return $this->get('parent');
204
-    }
205
-
206
-
207
-    /**
208
-     * return the _status property
209
-     *
210
-     * @return string
211
-     */
212
-    public function status()
213
-    {
214
-        return $this->get('status');
215
-    }
216
-
217
-
218
-    /**
219
-     * @param string $status
220
-     */
221
-    public function set_status($status)
222
-    {
223
-        $this->set('status', $status);
224
-    }
225
-
226
-
227
-    /**
228
-     * This calls the equivalent model method for retrieving the feature image which in turn is a wrapper for
229
-     * WordPress' get_the_post_thumbnail() function.
230
-     *
231
-     * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
232
-     * @access protected
233
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
234
-     *                           representing width and height in pixels (i.e. array(32,32) ).
235
-     * @param string|array $attr Optional. Query string or array of attributes.
236
-     * @return string HTML image element
237
-     */
238
-    protected function _get_feature_image($size, $attr)
239
-    {
240
-        // first let's see if we already have the _feature_image property set AND if it has a cached element on it FOR the given size
241
-        $attr_key = is_array($attr) ? implode('_', $attr) : $attr;
242
-        $cache_key = is_array($size) ? implode('_', $size) . $attr_key : $size . $attr_key;
243
-        $this->_feature_image[ $cache_key ] = isset($this->_feature_image[ $cache_key ])
244
-            ? $this->_feature_image[ $cache_key ] : $this->get_model()->get_feature_image($this->ID(), $size, $attr);
245
-        return $this->_feature_image[ $cache_key ];
246
-    }
247
-
248
-
249
-    /**
250
-     * See _get_feature_image. Returns the HTML to display a featured image
251
-     *
252
-     * @param string       $size
253
-     * @param string|array $attr
254
-     * @return string of html
255
-     */
256
-    public function feature_image($size = 'thumbnail', $attr = '')
257
-    {
258
-        return $this->_get_feature_image($size, $attr);
259
-    }
260
-
261
-
262
-    /**
263
-     * This uses the wp "wp_get_attachment_image_src()" function to return the feature image for the current class
264
-     * using the given size params.
265
-     *
266
-     * @param  string|array $size can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array
267
-     *                            representing width and height in pixels eg. array(32,32).
268
-     * @return string|boolean          the url of the image or false if not found
269
-     */
270
-    public function feature_image_url($size = 'thumbnail')
271
-    {
272
-        $attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
273
-        return ! empty($attachment) ? $attachment[0] : false;
274
-    }
275
-
276
-
277
-    /**
278
-     * This is a method for restoring this_obj using details from the given $revision_id
279
-     *
280
-     * @param int   $revision_id       ID of the revision we're getting data from
281
-     * @param array $related_obj_names if included this will be used to restore for related obj
282
-     *                                 if not included then we just do restore on the meta.
283
-     *                                 We will accept an array of related_obj_names for restoration here.
284
-     * @param array $where_query       You can optionally include an array of key=>value pairs
285
-     *                                 that allow you to further constrict the relation to being added.
286
-     *                                 However, keep in mind that the columns (keys) given
287
-     *                                 must match a column on the JOIN table and currently
288
-     *                                 only the HABTM models accept these additional conditions.
289
-     *                                 Also remember that if an exact match isn't found for these extra cols/val pairs,
290
-     *                                 then a NEW row is created in the join table.
291
-     *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names
292
-     *                                 sent);
293
-     * @return void
294
-     */
295
-    public function restore_revision($revision_id, $related_obj_names = array(), $where_query = array())
296
-    {
297
-        // get revision object
298
-        $revision_obj = $this->get_model()->get_one_by_ID($revision_id);
299
-        if ($revision_obj instanceof EE_CPT_Base) {
300
-            // no related_obj_name so we assume we're saving a revision on this object.
301
-            if (empty($related_obj_names)) {
302
-                $fields = $this->get_model()->get_meta_table_fields();
303
-                foreach ($fields as $field) {
304
-                    $this->set($field, $revision_obj->get($field));
305
-                }
306
-                $this->save();
307
-            }
308
-            $related_obj_names = (array) $related_obj_names;
309
-            foreach ($related_obj_names as $related_name) {
310
-                // related_obj_name so we're saving a revision on an object related to this object
311
-                // do we have $where_query params for this related object?  If we do then we include that.
312
-                $cols_n_values = isset($where_query[ $related_name ]) ? $where_query[ $related_name ] : array();
313
-                $where_params = ! empty($cols_n_values) ? array($cols_n_values) : array();
314
-                $related_objs = $this->get_many_related($related_name, $where_params);
315
-                $revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
316
-                // load helper
317
-                // remove related objs from this object that are not in revision
318
-                // array_diff *should* work cause I think objects are indexed by ID?
319
-                $related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
320
-                foreach ($related_to_remove as $rr) {
321
-                    $this->_remove_relation_to($rr, $related_name, $cols_n_values);
322
-                }
323
-                // add all related objs attached to revision to this object
324
-                foreach ($revision_related_objs as $r_obj) {
325
-                    $this->_add_relation_to($r_obj, $related_name, $cols_n_values);
326
-                }
327
-            }
328
-        }
329
-    }
330
-
331
-
332
-    /**
333
-     * Wrapper for get_post_meta, http://codex.wordpress.org/Function_Reference/get_post_meta
334
-     *
335
-     * @param string  $meta_key
336
-     * @param boolean $single
337
-     * @return mixed <ul><li>If only $id is set it will return all meta values in an associative array.</li>
338
-     * <li>If $single is set to false, or left blank, the function returns an array containing all values of the
339
-     * specified key.</li>
340
-     * <li>If $single is set to true, the function returns the first value of the specified key (not in an
341
-     * array</li></ul>
342
-     */
343
-    public function get_post_meta($meta_key = null, $single = false)
344
-    {
345
-        return get_post_meta($this->ID(), $meta_key, $single);
346
-    }
347
-
348
-
349
-    /**
350
-     * Wrapper for update_post_meta, http://codex.wordpress.org/Function_Reference/update_post_meta
351
-     *
352
-     * @param string $meta_key
353
-     * @param mixed  $meta_value
354
-     * @param mixed  $prev_value
355
-     * @return mixed Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure.
356
-     *               NOTE: If the meta_value passed to this function is the same as the value that is already in the
357
-     *               database, this function returns false.
358
-     */
359
-    public function update_post_meta($meta_key, $meta_value, $prev_value = null)
360
-    {
361
-        if (! $this->ID()) {
362
-            $this->save();
363
-        }
364
-        return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
365
-    }
366
-
367
-
368
-    /**
369
-     * Wrapper for add_post_meta, http://codex.wordpress.org/Function_Reference/add_post_meta
370
-     *
371
-     * @param mixed $meta_key
372
-     * @param mixed $meta_value
373
-     * @param bool  $unique . If postmeta for this $meta_key already exists, whether to add an additional item or not
374
-     * @return boolean Boolean true, except if the $unique argument was set to true and a custom field with the given
375
-     *                 key already exists, in which case false is returned.
376
-     */
377
-    public function add_post_meta($meta_key, $meta_value, $unique = false)
378
-    {
379
-        if ($this->ID()) {
380
-            $this->save();
381
-        }
382
-        return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
383
-    }
384
-
385
-
386
-    /**
387
-     * Wrapper for delete_post_meta, http://codex.wordpress.org/Function_Reference/delete_post_meta
388
-     *
389
-     * @param mixed $meta_key
390
-     * @param mixed $meta_value
391
-     * @return boolean False for failure. True for success.
392
-     */
393
-    public function delete_post_meta($meta_key, $meta_value = '')
394
-    {
395
-        if (! $this->ID()) {
396
-            // there are obviously no postmetas for this if it's not saved
397
-            // so let's just report this as a success
398
-            return true;
399
-        }
400
-        return delete_post_meta($this->ID(), $meta_key, $meta_value);
401
-    }
402
-
403
-
404
-    /**
405
-     * Gets the URL for viewing this event on the front-end
406
-     *
407
-     * @return string
408
-     */
409
-    public function get_permalink()
410
-    {
411
-        return get_permalink($this->ID());
412
-    }
413
-
414
-
415
-    /**
416
-     * Gets all the term-taxonomies for this CPT
417
-     *
418
-     * @param array $query_params
419
-     * @return EE_Term_Taxonomy
420
-     */
421
-    public function term_taxonomies($query_params = array())
422
-    {
423
-        return $this->get_many_related('Term_Taxonomy', $query_params);
424
-    }
425
-
426
-
427
-    /**
428
-     * @return mixed
429
-     */
430
-    public function get_custom_post_statuses()
431
-    {
432
-        return $this->get_model()->get_custom_post_statuses();
433
-    }
434
-
435
-
436
-    /**
437
-     * @return mixed
438
-     */
439
-    public function get_all_post_statuses()
440
-    {
441
-        return $this->get_model()->get_status_array();
442
-    }
443
-
444
-
445
-    /**
446
-     * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
447
-     *
448
-     * @return array
449
-     */
450
-    public function __sleep()
451
-    {
452
-        $properties_to_serialize = parent::__sleep();
453
-        $properties_to_serialize = array_diff($properties_to_serialize, array('_wp_post'));
454
-        return $properties_to_serialize;
455
-    }
16
+	/**
17
+	 * @var stdClass
18
+	 * @since 5.0.0.p
19
+	 */
20
+	public $labels;
21
+
22
+	/**
23
+	 * @var string
24
+	 * @since 5.0.0.p
25
+	 */
26
+	public $name;
27
+
28
+	/**
29
+	 * This is a property for holding cached feature images on CPT objects.  Cache's are set on the first
30
+	 * "feature_image()" method call.  Each key in the array corresponds to the requested size.
31
+	 *
32
+	 * @var array
33
+	 */
34
+	protected $_feature_image = array();
35
+
36
+	/**
37
+	 * @var WP_Post the WP_Post that corresponds with this CPT model object
38
+	 */
39
+	protected $_wp_post;
40
+
41
+
42
+	abstract public function wp_user();
43
+
44
+
45
+	/**
46
+	 * Returns the WP post associated with this CPT model object. If this CPT is saved, fetches it
47
+	 * from the DB. Otherwise, create an unsaved WP_POst object. Caches the post internally.
48
+	 *
49
+	 * @return WP_Post
50
+	 */
51
+	public function wp_post()
52
+	{
53
+		global $wpdb;
54
+		if (! $this->_wp_post instanceof WP_Post) {
55
+			if ($this->ID()) {
56
+				$this->_wp_post = get_post($this->ID());
57
+			} else {
58
+				$simulated_db_result = new stdClass();
59
+				foreach ($this->get_model()->field_settings(true) as $field_name => $field_obj) {
60
+					if (
61
+						$this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())->get_table_name()
62
+						=== $wpdb->posts
63
+					) {
64
+						$column = $field_obj->get_table_column();
65
+
66
+						if ($field_obj instanceof EE_Datetime_Field) {
67
+							$value_on_model_obj = $this->get_DateTime_object($field_name);
68
+						} elseif ($field_obj->is_db_only_field()) {
69
+							$value_on_model_obj = $field_obj->get_default_value();
70
+						} else {
71
+							$value_on_model_obj = $this->get_raw($field_name);
72
+						}
73
+						$simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
74
+					}
75
+				}
76
+				$this->_wp_post = new WP_Post($simulated_db_result);
77
+			}
78
+			// and let's make retrieving the EE CPT object easy too
79
+			$classname = get_class($this);
80
+			if (! isset($this->_wp_post->{$classname})) {
81
+				$this->_wp_post->{$classname} = $this;
82
+			}
83
+		}
84
+		return $this->_wp_post;
85
+	}
86
+
87
+	/**
88
+	 * When fetching a new value for a post field that uses the global $post for rendering,
89
+	 * set the global $post temporarily to be this model object; and afterwards restore it
90
+	 *
91
+	 * @param string $fieldname
92
+	 * @param bool   $pretty
93
+	 * @param string $extra_cache_ref
94
+	 * @return mixed
95
+	 */
96
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
97
+	{
98
+		global $post;
99
+
100
+		if (
101
+			$pretty
102
+			&& (
103
+				! (
104
+					$post instanceof WP_Post
105
+					&& $post->ID
106
+				)
107
+				|| (int) $post->ID !== $this->ID()
108
+			)
109
+			&& $this->get_model()->field_settings_for($fieldname) instanceof EE_Post_Content_Field
110
+		) {
111
+			$old_post = $post;
112
+			$post = $this->wp_post();
113
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
114
+			$post = $old_post;
115
+		} else {
116
+			$return_value = parent::_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
117
+		}
118
+		return $return_value;
119
+	}
120
+
121
+	/**
122
+	 * Adds to the specified event category. If it category doesn't exist, creates it.
123
+	 *
124
+	 * @param string $category_name
125
+	 * @param string $category_description    optional
126
+	 * @param int    $parent_term_taxonomy_id optional
127
+	 * @return EE_Term_Taxonomy
128
+	 */
129
+	public function add_event_category($category_name, $category_description = null, $parent_term_taxonomy_id = null)
130
+	{
131
+		return $this->get_model()->add_event_category(
132
+			$this,
133
+			$category_name,
134
+			$category_description,
135
+			$parent_term_taxonomy_id
136
+		);
137
+	}
138
+
139
+
140
+	/**
141
+	 * Removes the event category by specified name from being related ot this event
142
+	 *
143
+	 * @param string $category_name
144
+	 * @return bool
145
+	 */
146
+	public function remove_event_category($category_name)
147
+	{
148
+		return $this->get_model()->remove_event_category($this, $category_name);
149
+	}
150
+
151
+
152
+	/**
153
+	 * Removes the relation to the specified term taxonomy, and maintains the
154
+	 * data integrity of the term taxonomy provided
155
+	 *
156
+	 * @param EE_Term_Taxonomy $term_taxonomy
157
+	 * @return EE_Base_Class the relation was removed from
158
+	 */
159
+	public function remove_relation_to_term_taxonomy($term_taxonomy)
160
+	{
161
+		if (! $term_taxonomy) {
162
+			EE_Error::add_error(
163
+				sprintf(
164
+					esc_html__(
165
+						"No Term_Taxonomy provided which to remove from model object of type %s and id %d",
166
+						"event_espresso"
167
+					),
168
+					get_class($this),
169
+					$this->ID()
170
+				),
171
+				__FILE__,
172
+				__FUNCTION__,
173
+				__LINE__
174
+			);
175
+			return null;
176
+		}
177
+		$term_taxonomy->set_count($term_taxonomy->count() - 1);
178
+		$term_taxonomy->save();
179
+		return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
180
+	}
181
+
182
+
183
+	/**
184
+	 * The main purpose of this method is to return the post type for the model object
185
+	 *
186
+	 * @access public
187
+	 * @return string
188
+	 */
189
+	public function post_type()
190
+	{
191
+		return $this->get_model()->post_type();
192
+	}
193
+
194
+
195
+	/**
196
+	 * The main purpose of this method is to return the parent for the model object
197
+	 *
198
+	 * @access public
199
+	 * @return int
200
+	 */
201
+	public function parent()
202
+	{
203
+		return $this->get('parent');
204
+	}
205
+
206
+
207
+	/**
208
+	 * return the _status property
209
+	 *
210
+	 * @return string
211
+	 */
212
+	public function status()
213
+	{
214
+		return $this->get('status');
215
+	}
216
+
217
+
218
+	/**
219
+	 * @param string $status
220
+	 */
221
+	public function set_status($status)
222
+	{
223
+		$this->set('status', $status);
224
+	}
225
+
226
+
227
+	/**
228
+	 * This calls the equivalent model method for retrieving the feature image which in turn is a wrapper for
229
+	 * WordPress' get_the_post_thumbnail() function.
230
+	 *
231
+	 * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
232
+	 * @access protected
233
+	 * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
234
+	 *                           representing width and height in pixels (i.e. array(32,32) ).
235
+	 * @param string|array $attr Optional. Query string or array of attributes.
236
+	 * @return string HTML image element
237
+	 */
238
+	protected function _get_feature_image($size, $attr)
239
+	{
240
+		// first let's see if we already have the _feature_image property set AND if it has a cached element on it FOR the given size
241
+		$attr_key = is_array($attr) ? implode('_', $attr) : $attr;
242
+		$cache_key = is_array($size) ? implode('_', $size) . $attr_key : $size . $attr_key;
243
+		$this->_feature_image[ $cache_key ] = isset($this->_feature_image[ $cache_key ])
244
+			? $this->_feature_image[ $cache_key ] : $this->get_model()->get_feature_image($this->ID(), $size, $attr);
245
+		return $this->_feature_image[ $cache_key ];
246
+	}
247
+
248
+
249
+	/**
250
+	 * See _get_feature_image. Returns the HTML to display a featured image
251
+	 *
252
+	 * @param string       $size
253
+	 * @param string|array $attr
254
+	 * @return string of html
255
+	 */
256
+	public function feature_image($size = 'thumbnail', $attr = '')
257
+	{
258
+		return $this->_get_feature_image($size, $attr);
259
+	}
260
+
261
+
262
+	/**
263
+	 * This uses the wp "wp_get_attachment_image_src()" function to return the feature image for the current class
264
+	 * using the given size params.
265
+	 *
266
+	 * @param  string|array $size can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array
267
+	 *                            representing width and height in pixels eg. array(32,32).
268
+	 * @return string|boolean          the url of the image or false if not found
269
+	 */
270
+	public function feature_image_url($size = 'thumbnail')
271
+	{
272
+		$attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
273
+		return ! empty($attachment) ? $attachment[0] : false;
274
+	}
275
+
276
+
277
+	/**
278
+	 * This is a method for restoring this_obj using details from the given $revision_id
279
+	 *
280
+	 * @param int   $revision_id       ID of the revision we're getting data from
281
+	 * @param array $related_obj_names if included this will be used to restore for related obj
282
+	 *                                 if not included then we just do restore on the meta.
283
+	 *                                 We will accept an array of related_obj_names for restoration here.
284
+	 * @param array $where_query       You can optionally include an array of key=>value pairs
285
+	 *                                 that allow you to further constrict the relation to being added.
286
+	 *                                 However, keep in mind that the columns (keys) given
287
+	 *                                 must match a column on the JOIN table and currently
288
+	 *                                 only the HABTM models accept these additional conditions.
289
+	 *                                 Also remember that if an exact match isn't found for these extra cols/val pairs,
290
+	 *                                 then a NEW row is created in the join table.
291
+	 *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names
292
+	 *                                 sent);
293
+	 * @return void
294
+	 */
295
+	public function restore_revision($revision_id, $related_obj_names = array(), $where_query = array())
296
+	{
297
+		// get revision object
298
+		$revision_obj = $this->get_model()->get_one_by_ID($revision_id);
299
+		if ($revision_obj instanceof EE_CPT_Base) {
300
+			// no related_obj_name so we assume we're saving a revision on this object.
301
+			if (empty($related_obj_names)) {
302
+				$fields = $this->get_model()->get_meta_table_fields();
303
+				foreach ($fields as $field) {
304
+					$this->set($field, $revision_obj->get($field));
305
+				}
306
+				$this->save();
307
+			}
308
+			$related_obj_names = (array) $related_obj_names;
309
+			foreach ($related_obj_names as $related_name) {
310
+				// related_obj_name so we're saving a revision on an object related to this object
311
+				// do we have $where_query params for this related object?  If we do then we include that.
312
+				$cols_n_values = isset($where_query[ $related_name ]) ? $where_query[ $related_name ] : array();
313
+				$where_params = ! empty($cols_n_values) ? array($cols_n_values) : array();
314
+				$related_objs = $this->get_many_related($related_name, $where_params);
315
+				$revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
316
+				// load helper
317
+				// remove related objs from this object that are not in revision
318
+				// array_diff *should* work cause I think objects are indexed by ID?
319
+				$related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
320
+				foreach ($related_to_remove as $rr) {
321
+					$this->_remove_relation_to($rr, $related_name, $cols_n_values);
322
+				}
323
+				// add all related objs attached to revision to this object
324
+				foreach ($revision_related_objs as $r_obj) {
325
+					$this->_add_relation_to($r_obj, $related_name, $cols_n_values);
326
+				}
327
+			}
328
+		}
329
+	}
330
+
331
+
332
+	/**
333
+	 * Wrapper for get_post_meta, http://codex.wordpress.org/Function_Reference/get_post_meta
334
+	 *
335
+	 * @param string  $meta_key
336
+	 * @param boolean $single
337
+	 * @return mixed <ul><li>If only $id is set it will return all meta values in an associative array.</li>
338
+	 * <li>If $single is set to false, or left blank, the function returns an array containing all values of the
339
+	 * specified key.</li>
340
+	 * <li>If $single is set to true, the function returns the first value of the specified key (not in an
341
+	 * array</li></ul>
342
+	 */
343
+	public function get_post_meta($meta_key = null, $single = false)
344
+	{
345
+		return get_post_meta($this->ID(), $meta_key, $single);
346
+	}
347
+
348
+
349
+	/**
350
+	 * Wrapper for update_post_meta, http://codex.wordpress.org/Function_Reference/update_post_meta
351
+	 *
352
+	 * @param string $meta_key
353
+	 * @param mixed  $meta_value
354
+	 * @param mixed  $prev_value
355
+	 * @return mixed Returns meta_id if the meta doesn't exist, otherwise returns true on success and false on failure.
356
+	 *               NOTE: If the meta_value passed to this function is the same as the value that is already in the
357
+	 *               database, this function returns false.
358
+	 */
359
+	public function update_post_meta($meta_key, $meta_value, $prev_value = null)
360
+	{
361
+		if (! $this->ID()) {
362
+			$this->save();
363
+		}
364
+		return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
365
+	}
366
+
367
+
368
+	/**
369
+	 * Wrapper for add_post_meta, http://codex.wordpress.org/Function_Reference/add_post_meta
370
+	 *
371
+	 * @param mixed $meta_key
372
+	 * @param mixed $meta_value
373
+	 * @param bool  $unique . If postmeta for this $meta_key already exists, whether to add an additional item or not
374
+	 * @return boolean Boolean true, except if the $unique argument was set to true and a custom field with the given
375
+	 *                 key already exists, in which case false is returned.
376
+	 */
377
+	public function add_post_meta($meta_key, $meta_value, $unique = false)
378
+	{
379
+		if ($this->ID()) {
380
+			$this->save();
381
+		}
382
+		return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
383
+	}
384
+
385
+
386
+	/**
387
+	 * Wrapper for delete_post_meta, http://codex.wordpress.org/Function_Reference/delete_post_meta
388
+	 *
389
+	 * @param mixed $meta_key
390
+	 * @param mixed $meta_value
391
+	 * @return boolean False for failure. True for success.
392
+	 */
393
+	public function delete_post_meta($meta_key, $meta_value = '')
394
+	{
395
+		if (! $this->ID()) {
396
+			// there are obviously no postmetas for this if it's not saved
397
+			// so let's just report this as a success
398
+			return true;
399
+		}
400
+		return delete_post_meta($this->ID(), $meta_key, $meta_value);
401
+	}
402
+
403
+
404
+	/**
405
+	 * Gets the URL for viewing this event on the front-end
406
+	 *
407
+	 * @return string
408
+	 */
409
+	public function get_permalink()
410
+	{
411
+		return get_permalink($this->ID());
412
+	}
413
+
414
+
415
+	/**
416
+	 * Gets all the term-taxonomies for this CPT
417
+	 *
418
+	 * @param array $query_params
419
+	 * @return EE_Term_Taxonomy
420
+	 */
421
+	public function term_taxonomies($query_params = array())
422
+	{
423
+		return $this->get_many_related('Term_Taxonomy', $query_params);
424
+	}
425
+
426
+
427
+	/**
428
+	 * @return mixed
429
+	 */
430
+	public function get_custom_post_statuses()
431
+	{
432
+		return $this->get_model()->get_custom_post_statuses();
433
+	}
434
+
435
+
436
+	/**
437
+	 * @return mixed
438
+	 */
439
+	public function get_all_post_statuses()
440
+	{
441
+		return $this->get_model()->get_status_array();
442
+	}
443
+
444
+
445
+	/**
446
+	 * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
447
+	 *
448
+	 * @return array
449
+	 */
450
+	public function __sleep()
451
+	{
452
+		$properties_to_serialize = parent::__sleep();
453
+		$properties_to_serialize = array_diff($properties_to_serialize, array('_wp_post'));
454
+		return $properties_to_serialize;
455
+	}
456 456
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Event.class.php 1 patch
Indentation   +1633 added lines, -1633 removed lines patch added patch discarded remove patch
@@ -16,1640 +16,1640 @@
 block discarded – undo
16 16
  */
17 17
 class EE_Event extends EE_CPT_Base implements EEI_Line_Item_Object, EEI_Admin_Links, EEI_Has_Icon, EEI_Event
18 18
 {
19
-    /**
20
-     * cached value for the the logical active status for the event
21
-     *
22
-     * @see get_active_status()
23
-     * @var string
24
-     */
25
-    protected $_active_status = '';
26
-
27
-    /**
28
-     * This is just used for caching the Primary Datetime for the Event on initial retrieval
29
-     *
30
-     * @var EE_Datetime
31
-     */
32
-    protected $_Primary_Datetime;
33
-
34
-    /**
35
-     * @var EventSpacesCalculator $available_spaces_calculator
36
-     */
37
-    protected $available_spaces_calculator;
38
-
39
-
40
-    /**
41
-     * @param array  $props_n_values          incoming values
42
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
43
-     *                                        used.)
44
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
45
-     *                                        date_format and the second value is the time format
46
-     * @return EE_Event
47
-     * @throws EE_Error
48
-     * @throws ReflectionException
49
-     */
50
-    public static function new_instance($props_n_values = [], $timezone = null, $date_formats = []): EE_Event
51
-    {
52
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
53
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
54
-    }
55
-
56
-
57
-    /**
58
-     * @param array  $props_n_values  incoming values from the database
59
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
60
-     *                                the website will be used.
61
-     * @return EE_Event
62
-     * @throws EE_Error
63
-     * @throws ReflectionException
64
-     */
65
-    public static function new_instance_from_db($props_n_values = [], $timezone = null): EE_Event
66
-    {
67
-        return new self($props_n_values, true, $timezone);
68
-    }
69
-
70
-
71
-    /**
72
-     * @return EventSpacesCalculator
73
-     * @throws EE_Error
74
-     * @throws ReflectionException
75
-     */
76
-    public function getAvailableSpacesCalculator(): EventSpacesCalculator
77
-    {
78
-        if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79
-            $this->available_spaces_calculator = new EventSpacesCalculator($this);
80
-        }
81
-        return $this->available_spaces_calculator;
82
-    }
83
-
84
-
85
-    /**
86
-     * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
87
-     *
88
-     * @param string $field_name
89
-     * @param mixed  $field_value
90
-     * @param bool   $use_default
91
-     * @throws EE_Error
92
-     * @throws ReflectionException
93
-     */
94
-    public function set($field_name, $field_value, $use_default = false)
95
-    {
96
-        switch ($field_name) {
97
-            case 'status':
98
-                $this->set_status($field_value, $use_default);
99
-                break;
100
-            default:
101
-                parent::set($field_name, $field_value, $use_default);
102
-        }
103
-    }
104
-
105
-
106
-    /**
107
-     *    set_status
108
-     * Checks if event status is being changed to SOLD OUT
109
-     * and updates event meta data with previous event status
110
-     * so that we can revert things if/when the event is no longer sold out
111
-     *
112
-     * @param string $status
113
-     * @param bool   $use_default
114
-     * @return void
115
-     * @throws EE_Error
116
-     * @throws ReflectionException
117
-     */
118
-    public function set_status($status = '', $use_default = false)
119
-    {
120
-        // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($status) && ! $use_default) {
122
-            return;
123
-        }
124
-        // get current Event status
125
-        $old_status = $this->status();
126
-        // if status has changed
127
-        if ($old_status !== $status) {
128
-            // TO sold_out
129
-            if ($status === EEM_Event::sold_out) {
130
-                // save the previous event status so that we can revert if the event is no longer sold out
131
-                $this->add_post_meta('_previous_event_status', $old_status);
132
-                do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $status);
133
-                // OR FROM  sold_out
134
-            } elseif ($old_status === EEM_Event::sold_out) {
135
-                $this->delete_post_meta('_previous_event_status');
136
-                do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $status);
137
-            }
138
-            // clear out the active status so that it gets reset the next time it is requested
139
-            $this->_active_status = null;
140
-            // update status
141
-            parent::set('status', $status, $use_default);
142
-            do_action('AHEE__EE_Event__set_status__after_update', $this);
143
-            return;
144
-        }
145
-        // even though the old value matches the new value, it's still good to
146
-        // allow the parent set method to have a say
147
-        parent::set('status', $status, $use_default);
148
-    }
149
-
150
-
151
-    /**
152
-     * Gets all the datetimes for this event
153
-     *
154
-     * @param array|null $query_params
155
-     * @return EE_Base_Class[]|EE_Datetime[]
156
-     * @throws EE_Error
157
-     * @throws ReflectionException
158
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
159
-     */
160
-    public function datetimes(?array $query_params = []): array
161
-    {
162
-        return $this->get_many_related('Datetime', $query_params);
163
-    }
164
-
165
-
166
-    /**
167
-     * Gets all the datetimes for this event that are currently ACTIVE,
168
-     * meaning the datetime has started and has not yet ended.
169
-     *
170
-     * @param int|null   $start_date   timestamp to use for event date start time, defaults to NOW unless set to 0
171
-     * @param array|null $query_params will recursively replace default values
172
-     * @throws EE_Error
173
-     * @throws ReflectionException
174
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
175
-     */
176
-    public function activeDatetimes(?int $start_date, ?array $query_params = []): array
177
-    {
178
-        // if start date is null, then use current time
179
-        $start_date = $start_date ?? time();
180
-        $where      = [];
181
-        if ($start_date) {
182
-            $where['DTT_EVT_start'] = ['<', $start_date];
183
-            $where['DTT_EVT_end']   = ['>', time()];
184
-        }
185
-        $query_params = array_replace_recursive(
186
-            [
187
-                $where,
188
-                'order_by' => ['DTT_EVT_start' => 'ASC'],
189
-            ],
190
-            $query_params
191
-        );
192
-        return $this->get_many_related('Datetime', $query_params);
193
-    }
194
-
195
-
196
-    /**
197
-     * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
198
-     *
199
-     * @return EE_Base_Class[]|EE_Datetime[]
200
-     * @throws EE_Error
201
-     * @throws ReflectionException
202
-     */
203
-    public function datetimes_in_chronological_order(): array
204
-    {
205
-        return $this->get_many_related('Datetime', ['order_by' => ['DTT_EVT_start' => 'ASC']]);
206
-    }
207
-
208
-
209
-    /**
210
-     * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
211
-     * @darren, we should probably UNSET timezone on the EEM_Datetime model
212
-     * after running our query, so that this timezone isn't set for EVERY query
213
-     * on EEM_Datetime for the rest of the request, no?
214
-     *
215
-     * @param bool     $show_expired whether or not to include expired events
216
-     * @param bool     $show_deleted whether or not to include deleted events
217
-     * @param int|null $limit
218
-     * @return EE_Datetime[]
219
-     * @throws EE_Error
220
-     * @throws ReflectionException
221
-     */
222
-    public function datetimes_ordered(bool $show_expired = true, bool $show_deleted = false, ?int $limit = null): array
223
-    {
224
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
225
-            $this->ID(),
226
-            $show_expired,
227
-            $show_deleted,
228
-            $limit
229
-        );
230
-    }
231
-
232
-
233
-    /**
234
-     * Returns one related datetime. Mostly only used by some legacy code.
235
-     *
236
-     * @return EE_Base_Class|EE_Datetime
237
-     * @throws EE_Error
238
-     * @throws ReflectionException
239
-     */
240
-    public function first_datetime(): EE_Datetime
241
-    {
242
-        return $this->get_first_related('Datetime');
243
-    }
244
-
245
-
246
-    /**
247
-     * Returns the 'primary' datetime for the event
248
-     *
249
-     * @param bool $try_to_exclude_expired
250
-     * @param bool $try_to_exclude_deleted
251
-     * @return EE_Datetime|null
252
-     * @throws EE_Error
253
-     * @throws ReflectionException
254
-     */
255
-    public function primary_datetime(
256
-        bool $try_to_exclude_expired = true,
257
-        bool $try_to_exclude_deleted = true
258
-    ): ?EE_Datetime {
259
-        if (! empty($this->_Primary_Datetime)) {
260
-            return $this->_Primary_Datetime;
261
-        }
262
-        $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
263
-            $this->ID(),
264
-            $try_to_exclude_expired,
265
-            $try_to_exclude_deleted
266
-        );
267
-        return $this->_Primary_Datetime;
268
-    }
269
-
270
-
271
-    /**
272
-     * Gets all the tickets available for purchase of this event
273
-     *
274
-     * @param array|null $query_params
275
-     * @return EE_Base_Class[]|EE_Ticket[]
276
-     * @throws EE_Error
277
-     * @throws ReflectionException
278
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
279
-     */
280
-    public function tickets(?array $query_params = []): array
281
-    {
282
-        // first get all datetimes
283
-        $datetimes = $this->datetimes_ordered();
284
-        if (! $datetimes) {
285
-            return [];
286
-        }
287
-        $datetime_ids = [];
288
-        foreach ($datetimes as $datetime) {
289
-            $datetime_ids[] = $datetime->ID();
290
-        }
291
-        $where_params = ['Datetime.DTT_ID' => ['IN', $datetime_ids]];
292
-        // if incoming $query_params has where conditions let's merge but not override existing.
293
-        if (is_array($query_params) && isset($query_params[0])) {
294
-            $where_params = array_merge($query_params[0], $where_params);
295
-            unset($query_params[0]);
296
-        }
297
-        // now add $where_params to $query_params
298
-        $query_params[0] = $where_params;
299
-        return EEM_Ticket::instance()->get_all($query_params);
300
-    }
301
-
302
-
303
-    /**
304
-     * get all unexpired not-trashed tickets
305
-     *
306
-     * @return EE_Ticket[]
307
-     * @throws EE_Error
308
-     * @throws ReflectionException
309
-     */
310
-    public function active_tickets(): array
311
-    {
312
-        return $this->tickets(
313
-            [
314
-                [
315
-                    'TKT_end_date' => ['>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')],
316
-                    'TKT_deleted'  => false,
317
-                ],
318
-            ]
319
-        );
320
-    }
321
-
322
-
323
-    /**
324
-     * @return int
325
-     * @throws EE_Error
326
-     * @throws ReflectionException
327
-     */
328
-    public function additional_limit(): int
329
-    {
330
-        return $this->get('EVT_additional_limit');
331
-    }
332
-
333
-
334
-    /**
335
-     * @return bool
336
-     * @throws EE_Error
337
-     * @throws ReflectionException
338
-     */
339
-    public function allow_overflow(): bool
340
-    {
341
-        return $this->get('EVT_allow_overflow');
342
-    }
343
-
344
-
345
-    /**
346
-     * @return string
347
-     * @throws EE_Error
348
-     * @throws ReflectionException
349
-     */
350
-    public function created(): string
351
-    {
352
-        return $this->get('EVT_created');
353
-    }
354
-
355
-
356
-    /**
357
-     * @return string
358
-     * @throws EE_Error
359
-     * @throws ReflectionException
360
-     */
361
-    public function description(): string
362
-    {
363
-        return $this->get('EVT_desc');
364
-    }
365
-
366
-
367
-    /**
368
-     * Runs do_shortcode and wpautop on the description
369
-     *
370
-     * @return string of html
371
-     * @throws EE_Error
372
-     * @throws ReflectionException
373
-     */
374
-    public function description_filtered(): string
375
-    {
376
-        return $this->get_pretty('EVT_desc');
377
-    }
378
-
379
-
380
-    /**
381
-     * @return bool
382
-     * @throws EE_Error
383
-     * @throws ReflectionException
384
-     */
385
-    public function display_description(): bool
386
-    {
387
-        return $this->get('EVT_display_desc');
388
-    }
389
-
390
-
391
-    /**
392
-     * @return bool
393
-     * @throws EE_Error
394
-     * @throws ReflectionException
395
-     */
396
-    public function display_ticket_selector(): bool
397
-    {
398
-        return (bool) $this->get('EVT_display_ticket_selector');
399
-    }
400
-
401
-
402
-    /**
403
-     * @return string
404
-     * @throws EE_Error
405
-     * @throws ReflectionException
406
-     */
407
-    public function external_url(): ?string
408
-    {
409
-        return $this->get('EVT_external_URL') ?? '';
410
-    }
411
-
412
-
413
-    /**
414
-     * @return bool
415
-     * @throws EE_Error
416
-     * @throws ReflectionException
417
-     */
418
-    public function member_only(): bool
419
-    {
420
-        return $this->get('EVT_member_only');
421
-    }
422
-
423
-
424
-    /**
425
-     * @return string
426
-     * @throws EE_Error
427
-     * @throws ReflectionException
428
-     */
429
-    public function phone(): string
430
-    {
431
-        return $this->get('EVT_phone');
432
-    }
433
-
434
-
435
-    /**
436
-     * @return string
437
-     * @throws EE_Error
438
-     * @throws ReflectionException
439
-     */
440
-    public function modified(): string
441
-    {
442
-        return $this->get('EVT_modified');
443
-    }
444
-
445
-
446
-    /**
447
-     * @return string
448
-     * @throws EE_Error
449
-     * @throws ReflectionException
450
-     */
451
-    public function name(): string
452
-    {
453
-        return $this->get('EVT_name');
454
-    }
455
-
456
-
457
-    /**
458
-     * @return int
459
-     * @throws EE_Error
460
-     * @throws ReflectionException
461
-     */
462
-    public function order(): int
463
-    {
464
-        return $this->get('EVT_order');
465
-    }
466
-
467
-
468
-    /**
469
-     * @return string
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     */
473
-    public function default_registration_status(): string
474
-    {
475
-        $event_default_registration_status = $this->get('EVT_default_registration_status');
476
-        return ! empty($event_default_registration_status)
477
-            ? $event_default_registration_status
478
-            : EE_Registry::instance()->CFG->registration->default_STS_ID;
479
-    }
480
-
481
-
482
-    /**
483
-     * @param int|null    $num_words
484
-     * @param string|null $more
485
-     * @param bool        $not_full_desc
486
-     * @return string
487
-     * @throws EE_Error
488
-     * @throws ReflectionException
489
-     */
490
-    public function short_description(?int $num_words = 55, string $more = null, bool $not_full_desc = false): string
491
-    {
492
-        $short_desc = $this->get('EVT_short_desc');
493
-        if (! empty($short_desc) || $not_full_desc) {
494
-            return $short_desc;
495
-        }
496
-        $full_desc = $this->get('EVT_desc');
497
-        return wp_trim_words($full_desc, $num_words, $more);
498
-    }
499
-
500
-
501
-    /**
502
-     * @return string
503
-     * @throws EE_Error
504
-     * @throws ReflectionException
505
-     */
506
-    public function slug(): string
507
-    {
508
-        return $this->get('EVT_slug');
509
-    }
510
-
511
-
512
-    /**
513
-     * @return string
514
-     * @throws EE_Error
515
-     * @throws ReflectionException
516
-     */
517
-    public function timezone_string(): string
518
-    {
519
-        return $this->get('EVT_timezone_string');
520
-    }
521
-
522
-
523
-    /**
524
-     * @return string
525
-     * @throws EE_Error
526
-     * @throws ReflectionException
527
-     * @deprecated
528
-     */
529
-    public function visible_on(): string
530
-    {
531
-        EE_Error::doing_it_wrong(
532
-            __METHOD__,
533
-            esc_html__(
534
-                'This method has been deprecated and there is no replacement for it.',
535
-                'event_espresso'
536
-            ),
537
-            '5.0.0.rc.002'
538
-        );
539
-        return $this->get('EVT_visible_on');
540
-    }
541
-
542
-
543
-    /**
544
-     * @return int
545
-     * @throws EE_Error
546
-     * @throws ReflectionException
547
-     */
548
-    public function wp_user(): int
549
-    {
550
-        return $this->get('EVT_wp_user');
551
-    }
552
-
553
-
554
-    /**
555
-     * @return bool
556
-     * @throws EE_Error
557
-     * @throws ReflectionException
558
-     */
559
-    public function donations(): bool
560
-    {
561
-        return $this->get('EVT_donations');
562
-    }
563
-
564
-
565
-    /**
566
-     * @param int $limit
567
-     * @throws EE_Error
568
-     * @throws ReflectionException
569
-     */
570
-    public function set_additional_limit(int $limit)
571
-    {
572
-        $this->set('EVT_additional_limit', $limit);
573
-    }
574
-
575
-
576
-    /**
577
-     * @param $created
578
-     * @throws EE_Error
579
-     * @throws ReflectionException
580
-     */
581
-    public function set_created($created)
582
-    {
583
-        $this->set('EVT_created', $created);
584
-    }
585
-
586
-
587
-    /**
588
-     * @param $desc
589
-     * @throws EE_Error
590
-     * @throws ReflectionException
591
-     */
592
-    public function set_description($desc)
593
-    {
594
-        $this->set('EVT_desc', $desc);
595
-    }
596
-
597
-
598
-    /**
599
-     * @param $display_desc
600
-     * @throws EE_Error
601
-     * @throws ReflectionException
602
-     */
603
-    public function set_display_description($display_desc)
604
-    {
605
-        $this->set('EVT_display_desc', $display_desc);
606
-    }
607
-
608
-
609
-    /**
610
-     * @param $display_ticket_selector
611
-     * @throws EE_Error
612
-     * @throws ReflectionException
613
-     */
614
-    public function set_display_ticket_selector($display_ticket_selector)
615
-    {
616
-        $this->set('EVT_display_ticket_selector', $display_ticket_selector);
617
-    }
618
-
619
-
620
-    /**
621
-     * @param $external_url
622
-     * @throws EE_Error
623
-     * @throws ReflectionException
624
-     */
625
-    public function set_external_url($external_url)
626
-    {
627
-        $this->set('EVT_external_URL', $external_url);
628
-    }
629
-
630
-
631
-    /**
632
-     * @param $member_only
633
-     * @throws EE_Error
634
-     * @throws ReflectionException
635
-     */
636
-    public function set_member_only($member_only)
637
-    {
638
-        $this->set('EVT_member_only', $member_only);
639
-    }
640
-
641
-
642
-    /**
643
-     * @param $event_phone
644
-     * @throws EE_Error
645
-     * @throws ReflectionException
646
-     */
647
-    public function set_event_phone($event_phone)
648
-    {
649
-        $this->set('EVT_phone', $event_phone);
650
-    }
651
-
652
-
653
-    /**
654
-     * @param $modified
655
-     * @throws EE_Error
656
-     * @throws ReflectionException
657
-     */
658
-    public function set_modified($modified)
659
-    {
660
-        $this->set('EVT_modified', $modified);
661
-    }
662
-
663
-
664
-    /**
665
-     * @param $name
666
-     * @throws EE_Error
667
-     * @throws ReflectionException
668
-     */
669
-    public function set_name($name)
670
-    {
671
-        $this->set('EVT_name', $name);
672
-    }
673
-
674
-
675
-    /**
676
-     * @param $order
677
-     * @throws EE_Error
678
-     * @throws ReflectionException
679
-     */
680
-    public function set_order($order)
681
-    {
682
-        $this->set('EVT_order', $order);
683
-    }
684
-
685
-
686
-    /**
687
-     * @param $short_desc
688
-     * @throws EE_Error
689
-     * @throws ReflectionException
690
-     */
691
-    public function set_short_description($short_desc)
692
-    {
693
-        $this->set('EVT_short_desc', $short_desc);
694
-    }
695
-
696
-
697
-    /**
698
-     * @param $slug
699
-     * @throws EE_Error
700
-     * @throws ReflectionException
701
-     */
702
-    public function set_slug($slug)
703
-    {
704
-        $this->set('EVT_slug', $slug);
705
-    }
706
-
707
-
708
-    /**
709
-     * @param $timezone_string
710
-     * @throws EE_Error
711
-     * @throws ReflectionException
712
-     */
713
-    public function set_timezone_string($timezone_string)
714
-    {
715
-        $this->set('EVT_timezone_string', $timezone_string);
716
-    }
717
-
718
-
719
-    /**
720
-     * @param $visible_on
721
-     * @throws EE_Error
722
-     * @throws ReflectionException
723
-     * @deprecated
724
-     */
725
-    public function set_visible_on($visible_on)
726
-    {
727
-        EE_Error::doing_it_wrong(
728
-            __METHOD__,
729
-            esc_html__(
730
-                'This method has been deprecated and there is no replacement for it.',
731
-                'event_espresso'
732
-            ),
733
-            '5.0.0.rc.002'
734
-        );
735
-        $this->set('EVT_visible_on', $visible_on);
736
-    }
737
-
738
-
739
-    /**
740
-     * @param $wp_user
741
-     * @throws EE_Error
742
-     * @throws ReflectionException
743
-     */
744
-    public function set_wp_user($wp_user)
745
-    {
746
-        $this->set('EVT_wp_user', $wp_user);
747
-    }
748
-
749
-
750
-    /**
751
-     * @param $default_registration_status
752
-     * @throws EE_Error
753
-     * @throws ReflectionException
754
-     */
755
-    public function set_default_registration_status($default_registration_status)
756
-    {
757
-        $this->set('EVT_default_registration_status', $default_registration_status);
758
-    }
759
-
760
-
761
-    /**
762
-     * @param $donations
763
-     * @throws EE_Error
764
-     * @throws ReflectionException
765
-     */
766
-    public function set_donations($donations)
767
-    {
768
-        $this->set('EVT_donations', $donations);
769
-    }
770
-
771
-
772
-    /**
773
-     * Adds a venue to this event
774
-     *
775
-     * @param int|EE_Venue /int $venue_id_or_obj
776
-     * @return EE_Base_Class|EE_Venue
777
-     * @throws EE_Error
778
-     * @throws ReflectionException
779
-     */
780
-    public function add_venue($venue_id_or_obj): EE_Venue
781
-    {
782
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
783
-    }
784
-
785
-
786
-    /**
787
-     * Removes a venue from the event
788
-     *
789
-     * @param EE_Venue /int $venue_id_or_obj
790
-     * @return EE_Base_Class|EE_Venue
791
-     * @throws EE_Error
792
-     * @throws ReflectionException
793
-     */
794
-    public function remove_venue($venue_id_or_obj): EE_Venue
795
-    {
796
-        $venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
797
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
798
-    }
799
-
800
-
801
-    /**
802
-     * Gets the venue related to the event. May provide additional $query_params if desired
803
-     *
804
-     * @param array $query_params
805
-     * @return int
806
-     * @throws EE_Error
807
-     * @throws ReflectionException
808
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
809
-     */
810
-    public function venue_ID(array $query_params = []): int
811
-    {
812
-        $venue = $this->get_first_related('Venue', $query_params);
813
-        return $venue instanceof EE_Venue ? $venue->ID() : 0;
814
-    }
815
-
816
-
817
-    /**
818
-     * Gets the venue related to the event. May provide additional $query_params if desired
819
-     *
820
-     * @param array $query_params
821
-     * @return EE_Base_Class|EE_Venue|null
822
-     * @throws EE_Error
823
-     * @throws ReflectionException
824
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
825
-     */
826
-    public function venue(array $query_params = []): ?EE_Venue
827
-    {
828
-        return $this->get_first_related('Venue', $query_params);
829
-    }
830
-
831
-
832
-    /**
833
-     * @param array $query_params
834
-     * @return EE_Base_Class[]|EE_Venue[]
835
-     * @throws EE_Error
836
-     * @throws ReflectionException
837
-     * @deprecated 5.0.0.p
838
-     */
839
-    public function venues(array $query_params = []): array
840
-    {
841
-        return [$this->venue($query_params)];
842
-    }
843
-
844
-
845
-    /**
846
-     * check if event id is present and if event is published
847
-     *
848
-     * @return boolean true yes, false no
849
-     * @throws EE_Error
850
-     * @throws ReflectionException
851
-     */
852
-    private function _has_ID_and_is_published(): bool
853
-    {
854
-        // first check if event id is present and not NULL,
855
-        // then check if this event is published (or any of the equivalent "published" statuses)
856
-        return
857
-            $this->ID() && $this->ID() !== null
858
-            && (
859
-                $this->status() === 'publish'
860
-                || $this->status() === EEM_Event::sold_out
861
-                || $this->status() === EEM_Event::postponed
862
-                || $this->status() === EEM_Event::cancelled
863
-            );
864
-    }
865
-
866
-
867
-    /**
868
-     * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
869
-     *
870
-     * @return boolean true yes, false no
871
-     * @throws EE_Error
872
-     * @throws ReflectionException
873
-     */
874
-    public function is_upcoming(): bool
875
-    {
876
-        // check if event id is present and if this event is published
877
-        if ($this->is_inactive()) {
878
-            return false;
879
-        }
880
-        // set initial value
881
-        $upcoming = false;
882
-        // next let's get all datetimes and loop through them
883
-        $datetimes = $this->datetimes_in_chronological_order();
884
-        foreach ($datetimes as $datetime) {
885
-            if ($datetime instanceof EE_Datetime) {
886
-                // if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
887
-                if ($datetime->is_expired()) {
888
-                    continue;
889
-                }
890
-                // if this dtt is active then we return false.
891
-                if ($datetime->is_active()) {
892
-                    return false;
893
-                }
894
-                // otherwise let's check upcoming status
895
-                $upcoming = $datetime->is_upcoming();
896
-            }
897
-        }
898
-        return $upcoming;
899
-    }
900
-
901
-
902
-    /**
903
-     * @return bool
904
-     * @throws EE_Error
905
-     * @throws ReflectionException
906
-     */
907
-    public function is_active(): bool
908
-    {
909
-        // check if event id is present and if this event is published
910
-        if ($this->is_inactive()) {
911
-            return false;
912
-        }
913
-        // set initial value
914
-        $active = false;
915
-        // next let's get all datetimes and loop through them
916
-        $datetimes = $this->datetimes_in_chronological_order();
917
-        foreach ($datetimes as $datetime) {
918
-            if ($datetime instanceof EE_Datetime) {
919
-                // if this dtt is expired then we continue cause one of the other datetimes might be active.
920
-                if ($datetime->is_expired()) {
921
-                    continue;
922
-                }
923
-                // if this dtt is upcoming then we return false.
924
-                if ($datetime->is_upcoming()) {
925
-                    return false;
926
-                }
927
-                // otherwise let's check active status
928
-                $active = $datetime->is_active();
929
-            }
930
-        }
931
-        return $active;
932
-    }
933
-
934
-
935
-    /**
936
-     * @return bool
937
-     * @throws EE_Error
938
-     * @throws ReflectionException
939
-     */
940
-    public function is_expired(): bool
941
-    {
942
-        // check if event id is present and if this event is published
943
-        if ($this->is_inactive()) {
944
-            return false;
945
-        }
946
-        // set initial value
947
-        $expired = false;
948
-        // first let's get all datetimes and loop through them
949
-        $datetimes = $this->datetimes_in_chronological_order();
950
-        foreach ($datetimes as $datetime) {
951
-            if ($datetime instanceof EE_Datetime) {
952
-                // if this dtt is upcoming or active then we return false.
953
-                if ($datetime->is_upcoming() || $datetime->is_active()) {
954
-                    return false;
955
-                }
956
-                // otherwise let's check active status
957
-                $expired = $datetime->is_expired();
958
-            }
959
-        }
960
-        return $expired;
961
-    }
962
-
963
-
964
-    /**
965
-     * @return bool
966
-     * @throws EE_Error
967
-     * @throws ReflectionException
968
-     */
969
-    public function is_inactive(): bool
970
-    {
971
-        // check if event id is present and if this event is published
972
-        if ($this->_has_ID_and_is_published()) {
973
-            return false;
974
-        }
975
-        return true;
976
-    }
977
-
978
-
979
-    /**
980
-     * calculate spaces remaining based on "saleable" tickets
981
-     *
982
-     * @param array|null $tickets
983
-     * @param bool       $filtered
984
-     * @return int|float
985
-     * @throws EE_Error
986
-     * @throws DomainException
987
-     * @throws UnexpectedEntityException
988
-     * @throws ReflectionException
989
-     */
990
-    public function spaces_remaining(?array $tickets = [], ?bool $filtered = true)
991
-    {
992
-        $this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
993
-        $spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
994
-        return $filtered
995
-            ? apply_filters(
996
-                'FHEE_EE_Event__spaces_remaining',
997
-                $spaces_remaining,
998
-                $this,
999
-                $tickets
1000
-            )
1001
-            : $spaces_remaining;
1002
-    }
1003
-
1004
-
1005
-    /**
1006
-     *    perform_sold_out_status_check
1007
-     *    checks all of this event's datetime  reg_limit - sold values to determine if ANY datetimes have spaces
1008
-     *    available... if NOT, then the event status will get toggled to 'sold_out'
1009
-     *
1010
-     * @return bool    return the ACTUAL sold out state.
1011
-     * @throws EE_Error
1012
-     * @throws DomainException
1013
-     * @throws UnexpectedEntityException
1014
-     * @throws ReflectionException
1015
-     */
1016
-    public function perform_sold_out_status_check(): bool
1017
-    {
1018
-        // get all tickets
1019
-        $tickets     = $this->tickets(
1020
-            [
1021
-                'default_where_conditions' => 'none',
1022
-                'order_by'                 => ['TKT_qty' => 'ASC'],
1023
-            ]
1024
-        );
1025
-        $all_expired = true;
1026
-        foreach ($tickets as $ticket) {
1027
-            if (! $ticket->is_expired()) {
1028
-                $all_expired = false;
1029
-                break;
1030
-            }
1031
-        }
1032
-        // if all the tickets are just expired, then don't update the event status to sold out
1033
-        if ($all_expired) {
1034
-            return true;
1035
-        }
1036
-        $spaces_remaining = $this->spaces_remaining($tickets);
1037
-        if ($spaces_remaining < 1) {
1038
-            if ($this->status() !== EEM_CPT_Base::post_status_private) {
1039
-                $this->set_status(EEM_Event::sold_out);
1040
-                $this->save();
1041
-            }
1042
-            $sold_out = true;
1043
-        } else {
1044
-            $sold_out = false;
1045
-            // was event previously marked as sold out ?
1046
-            if ($this->status() === EEM_Event::sold_out) {
1047
-                // revert status to previous value, if it was set
1048
-                $previous_event_status = $this->get_post_meta('_previous_event_status', true);
1049
-                if ($previous_event_status) {
1050
-                    $this->set_status($previous_event_status);
1051
-                    $this->save();
1052
-                }
1053
-            }
1054
-        }
1055
-        do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
1056
-        return $sold_out;
1057
-    }
1058
-
1059
-
1060
-    /**
1061
-     * This returns the total remaining spaces for sale on this event.
1062
-     *
1063
-     * @return int|float
1064
-     * @throws EE_Error
1065
-     * @throws DomainException
1066
-     * @throws UnexpectedEntityException
1067
-     * @throws ReflectionException
1068
-     * @uses EE_Event::total_available_spaces()
1069
-     */
1070
-    public function spaces_remaining_for_sale()
1071
-    {
1072
-        return $this->total_available_spaces(true);
1073
-    }
1074
-
1075
-
1076
-    /**
1077
-     * This returns the total spaces available for an event
1078
-     * while considering all the quantities on the tickets and the reg limits
1079
-     * on the datetimes attached to this event.
1080
-     *
1081
-     * @param bool $consider_sold   Whether to consider any tickets that have already sold in our calculation.
1082
-     *                              If this is false, then we return the most tickets that could ever be sold
1083
-     *                              for this event with the datetime and tickets setup on the event under optimal
1084
-     *                              selling conditions.  Otherwise we return a live calculation of spaces available
1085
-     *                              based on tickets sold.  Depending on setup and stage of sales, this
1086
-     *                              may appear to equal remaining tickets.  However, the more tickets are
1087
-     *                              sold out, the more accurate the "live" total is.
1088
-     * @return int|float
1089
-     * @throws EE_Error
1090
-     * @throws DomainException
1091
-     * @throws UnexpectedEntityException
1092
-     * @throws ReflectionException
1093
-     */
1094
-    public function total_available_spaces(bool $consider_sold = false)
1095
-    {
1096
-        $spaces_available = $consider_sold
1097
-            ? $this->getAvailableSpacesCalculator()->spacesRemaining()
1098
-            : $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
1099
-        return apply_filters(
1100
-            'FHEE_EE_Event__total_available_spaces__spaces_available',
1101
-            $spaces_available,
1102
-            $this,
1103
-            $this->getAvailableSpacesCalculator()->getDatetimes(),
1104
-            $this->getAvailableSpacesCalculator()->getActiveTickets()
1105
-        );
1106
-    }
1107
-
1108
-
1109
-    /**
1110
-     * Checks if the event is set to sold out
1111
-     *
1112
-     * @param bool $actual  whether or not to perform calculations to not only figure the
1113
-     *                      actual status but also to flip the status if necessary to sold
1114
-     *                      out If false, we just check the existing status of the event
1115
-     * @return boolean
1116
-     * @throws EE_Error
1117
-     * @throws ReflectionException
1118
-     */
1119
-    public function is_sold_out(bool $actual = false): bool
1120
-    {
1121
-        if (! $actual) {
1122
-            return $this->status() === EEM_Event::sold_out;
1123
-        }
1124
-        return $this->perform_sold_out_status_check();
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * Checks if the event is marked as postponed
1130
-     *
1131
-     * @return boolean
1132
-     */
1133
-    public function is_postponed(): bool
1134
-    {
1135
-        return $this->status() === EEM_Event::postponed;
1136
-    }
1137
-
1138
-
1139
-    /**
1140
-     * Checks if the event is marked as cancelled
1141
-     *
1142
-     * @return boolean
1143
-     */
1144
-    public function is_cancelled(): bool
1145
-    {
1146
-        return $this->status() === EEM_Event::cancelled;
1147
-    }
1148
-
1149
-
1150
-    /**
1151
-     * Get the logical active status in a hierarchical order for all the datetimes.  Note
1152
-     * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1153
-     * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1154
-     * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1155
-     * the event is considered expired.
1156
-     * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a
1157
-     * status set on the EVENT when it is not published and thus is done
1158
-     *
1159
-     * @param bool $reset
1160
-     * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1161
-     * @throws EE_Error
1162
-     * @throws ReflectionException
1163
-     */
1164
-    public function get_active_status(bool $reset = false)
1165
-    {
1166
-        // if the active status has already been set, then just use that value (unless we are resetting it)
1167
-        if (! empty($this->_active_status) && ! $reset) {
1168
-            return $this->_active_status;
1169
-        }
1170
-        // first check if event id is present on this object
1171
-        if (! $this->ID()) {
1172
-            return false;
1173
-        }
1174
-        $where_params_for_event = [['EVT_ID' => $this->ID()]];
1175
-        // if event is published:
1176
-        if (
1177
-            $this->status() === EEM_CPT_Base::post_status_publish
1178
-            || $this->status() === EEM_CPT_Base::post_status_private
1179
-        ) {
1180
-            // active?
1181
-            if (
1182
-                EEM_Datetime::instance()->get_datetime_count_for_status(
1183
-                    EE_Datetime::active,
1184
-                    $where_params_for_event
1185
-                ) > 0
1186
-            ) {
1187
-                $this->_active_status = EE_Datetime::active;
1188
-            } else {
1189
-                // upcoming?
1190
-                if (
1191
-                    EEM_Datetime::instance()->get_datetime_count_for_status(
1192
-                        EE_Datetime::upcoming,
1193
-                        $where_params_for_event
1194
-                    ) > 0
1195
-                ) {
1196
-                    $this->_active_status = EE_Datetime::upcoming;
1197
-                } else {
1198
-                    // expired?
1199
-                    if (
1200
-                        EEM_Datetime::instance()->get_datetime_count_for_status(
1201
-                            EE_Datetime::expired,
1202
-                            $where_params_for_event
1203
-                        ) > 0
1204
-                    ) {
1205
-                        $this->_active_status = EE_Datetime::expired;
1206
-                    } else {
1207
-                        // it would be odd if things make it this far
1208
-                        // because it basically means there are no datetimes attached to the event.
1209
-                        // So in this case it will just be considered inactive.
1210
-                        $this->_active_status = EE_Datetime::inactive;
1211
-                    }
1212
-                }
1213
-            }
1214
-        } else {
1215
-            // the event is not published, so let's just set it's active status according to its' post status
1216
-            switch ($this->status()) {
1217
-                case EEM_Event::sold_out:
1218
-                    $this->_active_status = EE_Datetime::sold_out;
1219
-                    break;
1220
-                case EEM_Event::cancelled:
1221
-                    $this->_active_status = EE_Datetime::cancelled;
1222
-                    break;
1223
-                case EEM_Event::postponed:
1224
-                    $this->_active_status = EE_Datetime::postponed;
1225
-                    break;
1226
-                default:
1227
-                    $this->_active_status = EE_Datetime::inactive;
1228
-            }
1229
-        }
1230
-        return $this->_active_status;
1231
-    }
1232
-
1233
-
1234
-    /**
1235
-     *    pretty_active_status
1236
-     *
1237
-     * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1238
-     * @return string
1239
-     * @throws EE_Error
1240
-     * @throws ReflectionException
1241
-     */
1242
-    public function pretty_active_status(bool $echo = true): string
1243
-    {
1244
-        $active_status = $this->get_active_status();
1245
-        $status        = "
19
+	/**
20
+	 * cached value for the the logical active status for the event
21
+	 *
22
+	 * @see get_active_status()
23
+	 * @var string
24
+	 */
25
+	protected $_active_status = '';
26
+
27
+	/**
28
+	 * This is just used for caching the Primary Datetime for the Event on initial retrieval
29
+	 *
30
+	 * @var EE_Datetime
31
+	 */
32
+	protected $_Primary_Datetime;
33
+
34
+	/**
35
+	 * @var EventSpacesCalculator $available_spaces_calculator
36
+	 */
37
+	protected $available_spaces_calculator;
38
+
39
+
40
+	/**
41
+	 * @param array  $props_n_values          incoming values
42
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
43
+	 *                                        used.)
44
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
45
+	 *                                        date_format and the second value is the time format
46
+	 * @return EE_Event
47
+	 * @throws EE_Error
48
+	 * @throws ReflectionException
49
+	 */
50
+	public static function new_instance($props_n_values = [], $timezone = null, $date_formats = []): EE_Event
51
+	{
52
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
53
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
54
+	}
55
+
56
+
57
+	/**
58
+	 * @param array  $props_n_values  incoming values from the database
59
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
60
+	 *                                the website will be used.
61
+	 * @return EE_Event
62
+	 * @throws EE_Error
63
+	 * @throws ReflectionException
64
+	 */
65
+	public static function new_instance_from_db($props_n_values = [], $timezone = null): EE_Event
66
+	{
67
+		return new self($props_n_values, true, $timezone);
68
+	}
69
+
70
+
71
+	/**
72
+	 * @return EventSpacesCalculator
73
+	 * @throws EE_Error
74
+	 * @throws ReflectionException
75
+	 */
76
+	public function getAvailableSpacesCalculator(): EventSpacesCalculator
77
+	{
78
+		if (! $this->available_spaces_calculator instanceof EventSpacesCalculator) {
79
+			$this->available_spaces_calculator = new EventSpacesCalculator($this);
80
+		}
81
+		return $this->available_spaces_calculator;
82
+	}
83
+
84
+
85
+	/**
86
+	 * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
87
+	 *
88
+	 * @param string $field_name
89
+	 * @param mixed  $field_value
90
+	 * @param bool   $use_default
91
+	 * @throws EE_Error
92
+	 * @throws ReflectionException
93
+	 */
94
+	public function set($field_name, $field_value, $use_default = false)
95
+	{
96
+		switch ($field_name) {
97
+			case 'status':
98
+				$this->set_status($field_value, $use_default);
99
+				break;
100
+			default:
101
+				parent::set($field_name, $field_value, $use_default);
102
+		}
103
+	}
104
+
105
+
106
+	/**
107
+	 *    set_status
108
+	 * Checks if event status is being changed to SOLD OUT
109
+	 * and updates event meta data with previous event status
110
+	 * so that we can revert things if/when the event is no longer sold out
111
+	 *
112
+	 * @param string $status
113
+	 * @param bool   $use_default
114
+	 * @return void
115
+	 * @throws EE_Error
116
+	 * @throws ReflectionException
117
+	 */
118
+	public function set_status($status = '', $use_default = false)
119
+	{
120
+		// if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
+		if (empty($status) && ! $use_default) {
122
+			return;
123
+		}
124
+		// get current Event status
125
+		$old_status = $this->status();
126
+		// if status has changed
127
+		if ($old_status !== $status) {
128
+			// TO sold_out
129
+			if ($status === EEM_Event::sold_out) {
130
+				// save the previous event status so that we can revert if the event is no longer sold out
131
+				$this->add_post_meta('_previous_event_status', $old_status);
132
+				do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $status);
133
+				// OR FROM  sold_out
134
+			} elseif ($old_status === EEM_Event::sold_out) {
135
+				$this->delete_post_meta('_previous_event_status');
136
+				do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $status);
137
+			}
138
+			// clear out the active status so that it gets reset the next time it is requested
139
+			$this->_active_status = null;
140
+			// update status
141
+			parent::set('status', $status, $use_default);
142
+			do_action('AHEE__EE_Event__set_status__after_update', $this);
143
+			return;
144
+		}
145
+		// even though the old value matches the new value, it's still good to
146
+		// allow the parent set method to have a say
147
+		parent::set('status', $status, $use_default);
148
+	}
149
+
150
+
151
+	/**
152
+	 * Gets all the datetimes for this event
153
+	 *
154
+	 * @param array|null $query_params
155
+	 * @return EE_Base_Class[]|EE_Datetime[]
156
+	 * @throws EE_Error
157
+	 * @throws ReflectionException
158
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
159
+	 */
160
+	public function datetimes(?array $query_params = []): array
161
+	{
162
+		return $this->get_many_related('Datetime', $query_params);
163
+	}
164
+
165
+
166
+	/**
167
+	 * Gets all the datetimes for this event that are currently ACTIVE,
168
+	 * meaning the datetime has started and has not yet ended.
169
+	 *
170
+	 * @param int|null   $start_date   timestamp to use for event date start time, defaults to NOW unless set to 0
171
+	 * @param array|null $query_params will recursively replace default values
172
+	 * @throws EE_Error
173
+	 * @throws ReflectionException
174
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
175
+	 */
176
+	public function activeDatetimes(?int $start_date, ?array $query_params = []): array
177
+	{
178
+		// if start date is null, then use current time
179
+		$start_date = $start_date ?? time();
180
+		$where      = [];
181
+		if ($start_date) {
182
+			$where['DTT_EVT_start'] = ['<', $start_date];
183
+			$where['DTT_EVT_end']   = ['>', time()];
184
+		}
185
+		$query_params = array_replace_recursive(
186
+			[
187
+				$where,
188
+				'order_by' => ['DTT_EVT_start' => 'ASC'],
189
+			],
190
+			$query_params
191
+		);
192
+		return $this->get_many_related('Datetime', $query_params);
193
+	}
194
+
195
+
196
+	/**
197
+	 * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
198
+	 *
199
+	 * @return EE_Base_Class[]|EE_Datetime[]
200
+	 * @throws EE_Error
201
+	 * @throws ReflectionException
202
+	 */
203
+	public function datetimes_in_chronological_order(): array
204
+	{
205
+		return $this->get_many_related('Datetime', ['order_by' => ['DTT_EVT_start' => 'ASC']]);
206
+	}
207
+
208
+
209
+	/**
210
+	 * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
211
+	 * @darren, we should probably UNSET timezone on the EEM_Datetime model
212
+	 * after running our query, so that this timezone isn't set for EVERY query
213
+	 * on EEM_Datetime for the rest of the request, no?
214
+	 *
215
+	 * @param bool     $show_expired whether or not to include expired events
216
+	 * @param bool     $show_deleted whether or not to include deleted events
217
+	 * @param int|null $limit
218
+	 * @return EE_Datetime[]
219
+	 * @throws EE_Error
220
+	 * @throws ReflectionException
221
+	 */
222
+	public function datetimes_ordered(bool $show_expired = true, bool $show_deleted = false, ?int $limit = null): array
223
+	{
224
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
225
+			$this->ID(),
226
+			$show_expired,
227
+			$show_deleted,
228
+			$limit
229
+		);
230
+	}
231
+
232
+
233
+	/**
234
+	 * Returns one related datetime. Mostly only used by some legacy code.
235
+	 *
236
+	 * @return EE_Base_Class|EE_Datetime
237
+	 * @throws EE_Error
238
+	 * @throws ReflectionException
239
+	 */
240
+	public function first_datetime(): EE_Datetime
241
+	{
242
+		return $this->get_first_related('Datetime');
243
+	}
244
+
245
+
246
+	/**
247
+	 * Returns the 'primary' datetime for the event
248
+	 *
249
+	 * @param bool $try_to_exclude_expired
250
+	 * @param bool $try_to_exclude_deleted
251
+	 * @return EE_Datetime|null
252
+	 * @throws EE_Error
253
+	 * @throws ReflectionException
254
+	 */
255
+	public function primary_datetime(
256
+		bool $try_to_exclude_expired = true,
257
+		bool $try_to_exclude_deleted = true
258
+	): ?EE_Datetime {
259
+		if (! empty($this->_Primary_Datetime)) {
260
+			return $this->_Primary_Datetime;
261
+		}
262
+		$this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
263
+			$this->ID(),
264
+			$try_to_exclude_expired,
265
+			$try_to_exclude_deleted
266
+		);
267
+		return $this->_Primary_Datetime;
268
+	}
269
+
270
+
271
+	/**
272
+	 * Gets all the tickets available for purchase of this event
273
+	 *
274
+	 * @param array|null $query_params
275
+	 * @return EE_Base_Class[]|EE_Ticket[]
276
+	 * @throws EE_Error
277
+	 * @throws ReflectionException
278
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
279
+	 */
280
+	public function tickets(?array $query_params = []): array
281
+	{
282
+		// first get all datetimes
283
+		$datetimes = $this->datetimes_ordered();
284
+		if (! $datetimes) {
285
+			return [];
286
+		}
287
+		$datetime_ids = [];
288
+		foreach ($datetimes as $datetime) {
289
+			$datetime_ids[] = $datetime->ID();
290
+		}
291
+		$where_params = ['Datetime.DTT_ID' => ['IN', $datetime_ids]];
292
+		// if incoming $query_params has where conditions let's merge but not override existing.
293
+		if (is_array($query_params) && isset($query_params[0])) {
294
+			$where_params = array_merge($query_params[0], $where_params);
295
+			unset($query_params[0]);
296
+		}
297
+		// now add $where_params to $query_params
298
+		$query_params[0] = $where_params;
299
+		return EEM_Ticket::instance()->get_all($query_params);
300
+	}
301
+
302
+
303
+	/**
304
+	 * get all unexpired not-trashed tickets
305
+	 *
306
+	 * @return EE_Ticket[]
307
+	 * @throws EE_Error
308
+	 * @throws ReflectionException
309
+	 */
310
+	public function active_tickets(): array
311
+	{
312
+		return $this->tickets(
313
+			[
314
+				[
315
+					'TKT_end_date' => ['>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')],
316
+					'TKT_deleted'  => false,
317
+				],
318
+			]
319
+		);
320
+	}
321
+
322
+
323
+	/**
324
+	 * @return int
325
+	 * @throws EE_Error
326
+	 * @throws ReflectionException
327
+	 */
328
+	public function additional_limit(): int
329
+	{
330
+		return $this->get('EVT_additional_limit');
331
+	}
332
+
333
+
334
+	/**
335
+	 * @return bool
336
+	 * @throws EE_Error
337
+	 * @throws ReflectionException
338
+	 */
339
+	public function allow_overflow(): bool
340
+	{
341
+		return $this->get('EVT_allow_overflow');
342
+	}
343
+
344
+
345
+	/**
346
+	 * @return string
347
+	 * @throws EE_Error
348
+	 * @throws ReflectionException
349
+	 */
350
+	public function created(): string
351
+	{
352
+		return $this->get('EVT_created');
353
+	}
354
+
355
+
356
+	/**
357
+	 * @return string
358
+	 * @throws EE_Error
359
+	 * @throws ReflectionException
360
+	 */
361
+	public function description(): string
362
+	{
363
+		return $this->get('EVT_desc');
364
+	}
365
+
366
+
367
+	/**
368
+	 * Runs do_shortcode and wpautop on the description
369
+	 *
370
+	 * @return string of html
371
+	 * @throws EE_Error
372
+	 * @throws ReflectionException
373
+	 */
374
+	public function description_filtered(): string
375
+	{
376
+		return $this->get_pretty('EVT_desc');
377
+	}
378
+
379
+
380
+	/**
381
+	 * @return bool
382
+	 * @throws EE_Error
383
+	 * @throws ReflectionException
384
+	 */
385
+	public function display_description(): bool
386
+	{
387
+		return $this->get('EVT_display_desc');
388
+	}
389
+
390
+
391
+	/**
392
+	 * @return bool
393
+	 * @throws EE_Error
394
+	 * @throws ReflectionException
395
+	 */
396
+	public function display_ticket_selector(): bool
397
+	{
398
+		return (bool) $this->get('EVT_display_ticket_selector');
399
+	}
400
+
401
+
402
+	/**
403
+	 * @return string
404
+	 * @throws EE_Error
405
+	 * @throws ReflectionException
406
+	 */
407
+	public function external_url(): ?string
408
+	{
409
+		return $this->get('EVT_external_URL') ?? '';
410
+	}
411
+
412
+
413
+	/**
414
+	 * @return bool
415
+	 * @throws EE_Error
416
+	 * @throws ReflectionException
417
+	 */
418
+	public function member_only(): bool
419
+	{
420
+		return $this->get('EVT_member_only');
421
+	}
422
+
423
+
424
+	/**
425
+	 * @return string
426
+	 * @throws EE_Error
427
+	 * @throws ReflectionException
428
+	 */
429
+	public function phone(): string
430
+	{
431
+		return $this->get('EVT_phone');
432
+	}
433
+
434
+
435
+	/**
436
+	 * @return string
437
+	 * @throws EE_Error
438
+	 * @throws ReflectionException
439
+	 */
440
+	public function modified(): string
441
+	{
442
+		return $this->get('EVT_modified');
443
+	}
444
+
445
+
446
+	/**
447
+	 * @return string
448
+	 * @throws EE_Error
449
+	 * @throws ReflectionException
450
+	 */
451
+	public function name(): string
452
+	{
453
+		return $this->get('EVT_name');
454
+	}
455
+
456
+
457
+	/**
458
+	 * @return int
459
+	 * @throws EE_Error
460
+	 * @throws ReflectionException
461
+	 */
462
+	public function order(): int
463
+	{
464
+		return $this->get('EVT_order');
465
+	}
466
+
467
+
468
+	/**
469
+	 * @return string
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 */
473
+	public function default_registration_status(): string
474
+	{
475
+		$event_default_registration_status = $this->get('EVT_default_registration_status');
476
+		return ! empty($event_default_registration_status)
477
+			? $event_default_registration_status
478
+			: EE_Registry::instance()->CFG->registration->default_STS_ID;
479
+	}
480
+
481
+
482
+	/**
483
+	 * @param int|null    $num_words
484
+	 * @param string|null $more
485
+	 * @param bool        $not_full_desc
486
+	 * @return string
487
+	 * @throws EE_Error
488
+	 * @throws ReflectionException
489
+	 */
490
+	public function short_description(?int $num_words = 55, string $more = null, bool $not_full_desc = false): string
491
+	{
492
+		$short_desc = $this->get('EVT_short_desc');
493
+		if (! empty($short_desc) || $not_full_desc) {
494
+			return $short_desc;
495
+		}
496
+		$full_desc = $this->get('EVT_desc');
497
+		return wp_trim_words($full_desc, $num_words, $more);
498
+	}
499
+
500
+
501
+	/**
502
+	 * @return string
503
+	 * @throws EE_Error
504
+	 * @throws ReflectionException
505
+	 */
506
+	public function slug(): string
507
+	{
508
+		return $this->get('EVT_slug');
509
+	}
510
+
511
+
512
+	/**
513
+	 * @return string
514
+	 * @throws EE_Error
515
+	 * @throws ReflectionException
516
+	 */
517
+	public function timezone_string(): string
518
+	{
519
+		return $this->get('EVT_timezone_string');
520
+	}
521
+
522
+
523
+	/**
524
+	 * @return string
525
+	 * @throws EE_Error
526
+	 * @throws ReflectionException
527
+	 * @deprecated
528
+	 */
529
+	public function visible_on(): string
530
+	{
531
+		EE_Error::doing_it_wrong(
532
+			__METHOD__,
533
+			esc_html__(
534
+				'This method has been deprecated and there is no replacement for it.',
535
+				'event_espresso'
536
+			),
537
+			'5.0.0.rc.002'
538
+		);
539
+		return $this->get('EVT_visible_on');
540
+	}
541
+
542
+
543
+	/**
544
+	 * @return int
545
+	 * @throws EE_Error
546
+	 * @throws ReflectionException
547
+	 */
548
+	public function wp_user(): int
549
+	{
550
+		return $this->get('EVT_wp_user');
551
+	}
552
+
553
+
554
+	/**
555
+	 * @return bool
556
+	 * @throws EE_Error
557
+	 * @throws ReflectionException
558
+	 */
559
+	public function donations(): bool
560
+	{
561
+		return $this->get('EVT_donations');
562
+	}
563
+
564
+
565
+	/**
566
+	 * @param int $limit
567
+	 * @throws EE_Error
568
+	 * @throws ReflectionException
569
+	 */
570
+	public function set_additional_limit(int $limit)
571
+	{
572
+		$this->set('EVT_additional_limit', $limit);
573
+	}
574
+
575
+
576
+	/**
577
+	 * @param $created
578
+	 * @throws EE_Error
579
+	 * @throws ReflectionException
580
+	 */
581
+	public function set_created($created)
582
+	{
583
+		$this->set('EVT_created', $created);
584
+	}
585
+
586
+
587
+	/**
588
+	 * @param $desc
589
+	 * @throws EE_Error
590
+	 * @throws ReflectionException
591
+	 */
592
+	public function set_description($desc)
593
+	{
594
+		$this->set('EVT_desc', $desc);
595
+	}
596
+
597
+
598
+	/**
599
+	 * @param $display_desc
600
+	 * @throws EE_Error
601
+	 * @throws ReflectionException
602
+	 */
603
+	public function set_display_description($display_desc)
604
+	{
605
+		$this->set('EVT_display_desc', $display_desc);
606
+	}
607
+
608
+
609
+	/**
610
+	 * @param $display_ticket_selector
611
+	 * @throws EE_Error
612
+	 * @throws ReflectionException
613
+	 */
614
+	public function set_display_ticket_selector($display_ticket_selector)
615
+	{
616
+		$this->set('EVT_display_ticket_selector', $display_ticket_selector);
617
+	}
618
+
619
+
620
+	/**
621
+	 * @param $external_url
622
+	 * @throws EE_Error
623
+	 * @throws ReflectionException
624
+	 */
625
+	public function set_external_url($external_url)
626
+	{
627
+		$this->set('EVT_external_URL', $external_url);
628
+	}
629
+
630
+
631
+	/**
632
+	 * @param $member_only
633
+	 * @throws EE_Error
634
+	 * @throws ReflectionException
635
+	 */
636
+	public function set_member_only($member_only)
637
+	{
638
+		$this->set('EVT_member_only', $member_only);
639
+	}
640
+
641
+
642
+	/**
643
+	 * @param $event_phone
644
+	 * @throws EE_Error
645
+	 * @throws ReflectionException
646
+	 */
647
+	public function set_event_phone($event_phone)
648
+	{
649
+		$this->set('EVT_phone', $event_phone);
650
+	}
651
+
652
+
653
+	/**
654
+	 * @param $modified
655
+	 * @throws EE_Error
656
+	 * @throws ReflectionException
657
+	 */
658
+	public function set_modified($modified)
659
+	{
660
+		$this->set('EVT_modified', $modified);
661
+	}
662
+
663
+
664
+	/**
665
+	 * @param $name
666
+	 * @throws EE_Error
667
+	 * @throws ReflectionException
668
+	 */
669
+	public function set_name($name)
670
+	{
671
+		$this->set('EVT_name', $name);
672
+	}
673
+
674
+
675
+	/**
676
+	 * @param $order
677
+	 * @throws EE_Error
678
+	 * @throws ReflectionException
679
+	 */
680
+	public function set_order($order)
681
+	{
682
+		$this->set('EVT_order', $order);
683
+	}
684
+
685
+
686
+	/**
687
+	 * @param $short_desc
688
+	 * @throws EE_Error
689
+	 * @throws ReflectionException
690
+	 */
691
+	public function set_short_description($short_desc)
692
+	{
693
+		$this->set('EVT_short_desc', $short_desc);
694
+	}
695
+
696
+
697
+	/**
698
+	 * @param $slug
699
+	 * @throws EE_Error
700
+	 * @throws ReflectionException
701
+	 */
702
+	public function set_slug($slug)
703
+	{
704
+		$this->set('EVT_slug', $slug);
705
+	}
706
+
707
+
708
+	/**
709
+	 * @param $timezone_string
710
+	 * @throws EE_Error
711
+	 * @throws ReflectionException
712
+	 */
713
+	public function set_timezone_string($timezone_string)
714
+	{
715
+		$this->set('EVT_timezone_string', $timezone_string);
716
+	}
717
+
718
+
719
+	/**
720
+	 * @param $visible_on
721
+	 * @throws EE_Error
722
+	 * @throws ReflectionException
723
+	 * @deprecated
724
+	 */
725
+	public function set_visible_on($visible_on)
726
+	{
727
+		EE_Error::doing_it_wrong(
728
+			__METHOD__,
729
+			esc_html__(
730
+				'This method has been deprecated and there is no replacement for it.',
731
+				'event_espresso'
732
+			),
733
+			'5.0.0.rc.002'
734
+		);
735
+		$this->set('EVT_visible_on', $visible_on);
736
+	}
737
+
738
+
739
+	/**
740
+	 * @param $wp_user
741
+	 * @throws EE_Error
742
+	 * @throws ReflectionException
743
+	 */
744
+	public function set_wp_user($wp_user)
745
+	{
746
+		$this->set('EVT_wp_user', $wp_user);
747
+	}
748
+
749
+
750
+	/**
751
+	 * @param $default_registration_status
752
+	 * @throws EE_Error
753
+	 * @throws ReflectionException
754
+	 */
755
+	public function set_default_registration_status($default_registration_status)
756
+	{
757
+		$this->set('EVT_default_registration_status', $default_registration_status);
758
+	}
759
+
760
+
761
+	/**
762
+	 * @param $donations
763
+	 * @throws EE_Error
764
+	 * @throws ReflectionException
765
+	 */
766
+	public function set_donations($donations)
767
+	{
768
+		$this->set('EVT_donations', $donations);
769
+	}
770
+
771
+
772
+	/**
773
+	 * Adds a venue to this event
774
+	 *
775
+	 * @param int|EE_Venue /int $venue_id_or_obj
776
+	 * @return EE_Base_Class|EE_Venue
777
+	 * @throws EE_Error
778
+	 * @throws ReflectionException
779
+	 */
780
+	public function add_venue($venue_id_or_obj): EE_Venue
781
+	{
782
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
783
+	}
784
+
785
+
786
+	/**
787
+	 * Removes a venue from the event
788
+	 *
789
+	 * @param EE_Venue /int $venue_id_or_obj
790
+	 * @return EE_Base_Class|EE_Venue
791
+	 * @throws EE_Error
792
+	 * @throws ReflectionException
793
+	 */
794
+	public function remove_venue($venue_id_or_obj): EE_Venue
795
+	{
796
+		$venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
797
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
798
+	}
799
+
800
+
801
+	/**
802
+	 * Gets the venue related to the event. May provide additional $query_params if desired
803
+	 *
804
+	 * @param array $query_params
805
+	 * @return int
806
+	 * @throws EE_Error
807
+	 * @throws ReflectionException
808
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
809
+	 */
810
+	public function venue_ID(array $query_params = []): int
811
+	{
812
+		$venue = $this->get_first_related('Venue', $query_params);
813
+		return $venue instanceof EE_Venue ? $venue->ID() : 0;
814
+	}
815
+
816
+
817
+	/**
818
+	 * Gets the venue related to the event. May provide additional $query_params if desired
819
+	 *
820
+	 * @param array $query_params
821
+	 * @return EE_Base_Class|EE_Venue|null
822
+	 * @throws EE_Error
823
+	 * @throws ReflectionException
824
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
825
+	 */
826
+	public function venue(array $query_params = []): ?EE_Venue
827
+	{
828
+		return $this->get_first_related('Venue', $query_params);
829
+	}
830
+
831
+
832
+	/**
833
+	 * @param array $query_params
834
+	 * @return EE_Base_Class[]|EE_Venue[]
835
+	 * @throws EE_Error
836
+	 * @throws ReflectionException
837
+	 * @deprecated 5.0.0.p
838
+	 */
839
+	public function venues(array $query_params = []): array
840
+	{
841
+		return [$this->venue($query_params)];
842
+	}
843
+
844
+
845
+	/**
846
+	 * check if event id is present and if event is published
847
+	 *
848
+	 * @return boolean true yes, false no
849
+	 * @throws EE_Error
850
+	 * @throws ReflectionException
851
+	 */
852
+	private function _has_ID_and_is_published(): bool
853
+	{
854
+		// first check if event id is present and not NULL,
855
+		// then check if this event is published (or any of the equivalent "published" statuses)
856
+		return
857
+			$this->ID() && $this->ID() !== null
858
+			&& (
859
+				$this->status() === 'publish'
860
+				|| $this->status() === EEM_Event::sold_out
861
+				|| $this->status() === EEM_Event::postponed
862
+				|| $this->status() === EEM_Event::cancelled
863
+			);
864
+	}
865
+
866
+
867
+	/**
868
+	 * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
869
+	 *
870
+	 * @return boolean true yes, false no
871
+	 * @throws EE_Error
872
+	 * @throws ReflectionException
873
+	 */
874
+	public function is_upcoming(): bool
875
+	{
876
+		// check if event id is present and if this event is published
877
+		if ($this->is_inactive()) {
878
+			return false;
879
+		}
880
+		// set initial value
881
+		$upcoming = false;
882
+		// next let's get all datetimes and loop through them
883
+		$datetimes = $this->datetimes_in_chronological_order();
884
+		foreach ($datetimes as $datetime) {
885
+			if ($datetime instanceof EE_Datetime) {
886
+				// if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
887
+				if ($datetime->is_expired()) {
888
+					continue;
889
+				}
890
+				// if this dtt is active then we return false.
891
+				if ($datetime->is_active()) {
892
+					return false;
893
+				}
894
+				// otherwise let's check upcoming status
895
+				$upcoming = $datetime->is_upcoming();
896
+			}
897
+		}
898
+		return $upcoming;
899
+	}
900
+
901
+
902
+	/**
903
+	 * @return bool
904
+	 * @throws EE_Error
905
+	 * @throws ReflectionException
906
+	 */
907
+	public function is_active(): bool
908
+	{
909
+		// check if event id is present and if this event is published
910
+		if ($this->is_inactive()) {
911
+			return false;
912
+		}
913
+		// set initial value
914
+		$active = false;
915
+		// next let's get all datetimes and loop through them
916
+		$datetimes = $this->datetimes_in_chronological_order();
917
+		foreach ($datetimes as $datetime) {
918
+			if ($datetime instanceof EE_Datetime) {
919
+				// if this dtt is expired then we continue cause one of the other datetimes might be active.
920
+				if ($datetime->is_expired()) {
921
+					continue;
922
+				}
923
+				// if this dtt is upcoming then we return false.
924
+				if ($datetime->is_upcoming()) {
925
+					return false;
926
+				}
927
+				// otherwise let's check active status
928
+				$active = $datetime->is_active();
929
+			}
930
+		}
931
+		return $active;
932
+	}
933
+
934
+
935
+	/**
936
+	 * @return bool
937
+	 * @throws EE_Error
938
+	 * @throws ReflectionException
939
+	 */
940
+	public function is_expired(): bool
941
+	{
942
+		// check if event id is present and if this event is published
943
+		if ($this->is_inactive()) {
944
+			return false;
945
+		}
946
+		// set initial value
947
+		$expired = false;
948
+		// first let's get all datetimes and loop through them
949
+		$datetimes = $this->datetimes_in_chronological_order();
950
+		foreach ($datetimes as $datetime) {
951
+			if ($datetime instanceof EE_Datetime) {
952
+				// if this dtt is upcoming or active then we return false.
953
+				if ($datetime->is_upcoming() || $datetime->is_active()) {
954
+					return false;
955
+				}
956
+				// otherwise let's check active status
957
+				$expired = $datetime->is_expired();
958
+			}
959
+		}
960
+		return $expired;
961
+	}
962
+
963
+
964
+	/**
965
+	 * @return bool
966
+	 * @throws EE_Error
967
+	 * @throws ReflectionException
968
+	 */
969
+	public function is_inactive(): bool
970
+	{
971
+		// check if event id is present and if this event is published
972
+		if ($this->_has_ID_and_is_published()) {
973
+			return false;
974
+		}
975
+		return true;
976
+	}
977
+
978
+
979
+	/**
980
+	 * calculate spaces remaining based on "saleable" tickets
981
+	 *
982
+	 * @param array|null $tickets
983
+	 * @param bool       $filtered
984
+	 * @return int|float
985
+	 * @throws EE_Error
986
+	 * @throws DomainException
987
+	 * @throws UnexpectedEntityException
988
+	 * @throws ReflectionException
989
+	 */
990
+	public function spaces_remaining(?array $tickets = [], ?bool $filtered = true)
991
+	{
992
+		$this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
993
+		$spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
994
+		return $filtered
995
+			? apply_filters(
996
+				'FHEE_EE_Event__spaces_remaining',
997
+				$spaces_remaining,
998
+				$this,
999
+				$tickets
1000
+			)
1001
+			: $spaces_remaining;
1002
+	}
1003
+
1004
+
1005
+	/**
1006
+	 *    perform_sold_out_status_check
1007
+	 *    checks all of this event's datetime  reg_limit - sold values to determine if ANY datetimes have spaces
1008
+	 *    available... if NOT, then the event status will get toggled to 'sold_out'
1009
+	 *
1010
+	 * @return bool    return the ACTUAL sold out state.
1011
+	 * @throws EE_Error
1012
+	 * @throws DomainException
1013
+	 * @throws UnexpectedEntityException
1014
+	 * @throws ReflectionException
1015
+	 */
1016
+	public function perform_sold_out_status_check(): bool
1017
+	{
1018
+		// get all tickets
1019
+		$tickets     = $this->tickets(
1020
+			[
1021
+				'default_where_conditions' => 'none',
1022
+				'order_by'                 => ['TKT_qty' => 'ASC'],
1023
+			]
1024
+		);
1025
+		$all_expired = true;
1026
+		foreach ($tickets as $ticket) {
1027
+			if (! $ticket->is_expired()) {
1028
+				$all_expired = false;
1029
+				break;
1030
+			}
1031
+		}
1032
+		// if all the tickets are just expired, then don't update the event status to sold out
1033
+		if ($all_expired) {
1034
+			return true;
1035
+		}
1036
+		$spaces_remaining = $this->spaces_remaining($tickets);
1037
+		if ($spaces_remaining < 1) {
1038
+			if ($this->status() !== EEM_CPT_Base::post_status_private) {
1039
+				$this->set_status(EEM_Event::sold_out);
1040
+				$this->save();
1041
+			}
1042
+			$sold_out = true;
1043
+		} else {
1044
+			$sold_out = false;
1045
+			// was event previously marked as sold out ?
1046
+			if ($this->status() === EEM_Event::sold_out) {
1047
+				// revert status to previous value, if it was set
1048
+				$previous_event_status = $this->get_post_meta('_previous_event_status', true);
1049
+				if ($previous_event_status) {
1050
+					$this->set_status($previous_event_status);
1051
+					$this->save();
1052
+				}
1053
+			}
1054
+		}
1055
+		do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
1056
+		return $sold_out;
1057
+	}
1058
+
1059
+
1060
+	/**
1061
+	 * This returns the total remaining spaces for sale on this event.
1062
+	 *
1063
+	 * @return int|float
1064
+	 * @throws EE_Error
1065
+	 * @throws DomainException
1066
+	 * @throws UnexpectedEntityException
1067
+	 * @throws ReflectionException
1068
+	 * @uses EE_Event::total_available_spaces()
1069
+	 */
1070
+	public function spaces_remaining_for_sale()
1071
+	{
1072
+		return $this->total_available_spaces(true);
1073
+	}
1074
+
1075
+
1076
+	/**
1077
+	 * This returns the total spaces available for an event
1078
+	 * while considering all the quantities on the tickets and the reg limits
1079
+	 * on the datetimes attached to this event.
1080
+	 *
1081
+	 * @param bool $consider_sold   Whether to consider any tickets that have already sold in our calculation.
1082
+	 *                              If this is false, then we return the most tickets that could ever be sold
1083
+	 *                              for this event with the datetime and tickets setup on the event under optimal
1084
+	 *                              selling conditions.  Otherwise we return a live calculation of spaces available
1085
+	 *                              based on tickets sold.  Depending on setup and stage of sales, this
1086
+	 *                              may appear to equal remaining tickets.  However, the more tickets are
1087
+	 *                              sold out, the more accurate the "live" total is.
1088
+	 * @return int|float
1089
+	 * @throws EE_Error
1090
+	 * @throws DomainException
1091
+	 * @throws UnexpectedEntityException
1092
+	 * @throws ReflectionException
1093
+	 */
1094
+	public function total_available_spaces(bool $consider_sold = false)
1095
+	{
1096
+		$spaces_available = $consider_sold
1097
+			? $this->getAvailableSpacesCalculator()->spacesRemaining()
1098
+			: $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
1099
+		return apply_filters(
1100
+			'FHEE_EE_Event__total_available_spaces__spaces_available',
1101
+			$spaces_available,
1102
+			$this,
1103
+			$this->getAvailableSpacesCalculator()->getDatetimes(),
1104
+			$this->getAvailableSpacesCalculator()->getActiveTickets()
1105
+		);
1106
+	}
1107
+
1108
+
1109
+	/**
1110
+	 * Checks if the event is set to sold out
1111
+	 *
1112
+	 * @param bool $actual  whether or not to perform calculations to not only figure the
1113
+	 *                      actual status but also to flip the status if necessary to sold
1114
+	 *                      out If false, we just check the existing status of the event
1115
+	 * @return boolean
1116
+	 * @throws EE_Error
1117
+	 * @throws ReflectionException
1118
+	 */
1119
+	public function is_sold_out(bool $actual = false): bool
1120
+	{
1121
+		if (! $actual) {
1122
+			return $this->status() === EEM_Event::sold_out;
1123
+		}
1124
+		return $this->perform_sold_out_status_check();
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * Checks if the event is marked as postponed
1130
+	 *
1131
+	 * @return boolean
1132
+	 */
1133
+	public function is_postponed(): bool
1134
+	{
1135
+		return $this->status() === EEM_Event::postponed;
1136
+	}
1137
+
1138
+
1139
+	/**
1140
+	 * Checks if the event is marked as cancelled
1141
+	 *
1142
+	 * @return boolean
1143
+	 */
1144
+	public function is_cancelled(): bool
1145
+	{
1146
+		return $this->status() === EEM_Event::cancelled;
1147
+	}
1148
+
1149
+
1150
+	/**
1151
+	 * Get the logical active status in a hierarchical order for all the datetimes.  Note
1152
+	 * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1153
+	 * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1154
+	 * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1155
+	 * the event is considered expired.
1156
+	 * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a
1157
+	 * status set on the EVENT when it is not published and thus is done
1158
+	 *
1159
+	 * @param bool $reset
1160
+	 * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1161
+	 * @throws EE_Error
1162
+	 * @throws ReflectionException
1163
+	 */
1164
+	public function get_active_status(bool $reset = false)
1165
+	{
1166
+		// if the active status has already been set, then just use that value (unless we are resetting it)
1167
+		if (! empty($this->_active_status) && ! $reset) {
1168
+			return $this->_active_status;
1169
+		}
1170
+		// first check if event id is present on this object
1171
+		if (! $this->ID()) {
1172
+			return false;
1173
+		}
1174
+		$where_params_for_event = [['EVT_ID' => $this->ID()]];
1175
+		// if event is published:
1176
+		if (
1177
+			$this->status() === EEM_CPT_Base::post_status_publish
1178
+			|| $this->status() === EEM_CPT_Base::post_status_private
1179
+		) {
1180
+			// active?
1181
+			if (
1182
+				EEM_Datetime::instance()->get_datetime_count_for_status(
1183
+					EE_Datetime::active,
1184
+					$where_params_for_event
1185
+				) > 0
1186
+			) {
1187
+				$this->_active_status = EE_Datetime::active;
1188
+			} else {
1189
+				// upcoming?
1190
+				if (
1191
+					EEM_Datetime::instance()->get_datetime_count_for_status(
1192
+						EE_Datetime::upcoming,
1193
+						$where_params_for_event
1194
+					) > 0
1195
+				) {
1196
+					$this->_active_status = EE_Datetime::upcoming;
1197
+				} else {
1198
+					// expired?
1199
+					if (
1200
+						EEM_Datetime::instance()->get_datetime_count_for_status(
1201
+							EE_Datetime::expired,
1202
+							$where_params_for_event
1203
+						) > 0
1204
+					) {
1205
+						$this->_active_status = EE_Datetime::expired;
1206
+					} else {
1207
+						// it would be odd if things make it this far
1208
+						// because it basically means there are no datetimes attached to the event.
1209
+						// So in this case it will just be considered inactive.
1210
+						$this->_active_status = EE_Datetime::inactive;
1211
+					}
1212
+				}
1213
+			}
1214
+		} else {
1215
+			// the event is not published, so let's just set it's active status according to its' post status
1216
+			switch ($this->status()) {
1217
+				case EEM_Event::sold_out:
1218
+					$this->_active_status = EE_Datetime::sold_out;
1219
+					break;
1220
+				case EEM_Event::cancelled:
1221
+					$this->_active_status = EE_Datetime::cancelled;
1222
+					break;
1223
+				case EEM_Event::postponed:
1224
+					$this->_active_status = EE_Datetime::postponed;
1225
+					break;
1226
+				default:
1227
+					$this->_active_status = EE_Datetime::inactive;
1228
+			}
1229
+		}
1230
+		return $this->_active_status;
1231
+	}
1232
+
1233
+
1234
+	/**
1235
+	 *    pretty_active_status
1236
+	 *
1237
+	 * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1238
+	 * @return string
1239
+	 * @throws EE_Error
1240
+	 * @throws ReflectionException
1241
+	 */
1242
+	public function pretty_active_status(bool $echo = true): string
1243
+	{
1244
+		$active_status = $this->get_active_status();
1245
+		$status        = "
1246 1246
         <span class='ee-status ee-status-bg--$active_status event-active-status-$active_status'>
1247 1247
             " . EEH_Template::pretty_status($active_status, false, 'sentence') . "
1248 1248
         </span >";
1249
-        if ($echo) {
1250
-            echo wp_kses($status, AllowedTags::getAllowedTags());
1251
-            return '';
1252
-        }
1253
-        return $status;
1254
-    }
1255
-
1256
-
1257
-    /**
1258
-     * @return bool|int
1259
-     * @throws EE_Error
1260
-     * @throws ReflectionException
1261
-     */
1262
-    public function get_number_of_tickets_sold()
1263
-    {
1264
-        $tkt_sold = 0;
1265
-        if (! $this->ID()) {
1266
-            return 0;
1267
-        }
1268
-        $datetimes = $this->datetimes();
1269
-        foreach ($datetimes as $datetime) {
1270
-            if ($datetime instanceof EE_Datetime) {
1271
-                $tkt_sold += $datetime->sold();
1272
-            }
1273
-        }
1274
-        return $tkt_sold;
1275
-    }
1276
-
1277
-
1278
-    /**
1279
-     * This just returns a count of all the registrations for this event
1280
-     *
1281
-     * @return int
1282
-     * @throws EE_Error
1283
-     * @throws ReflectionException
1284
-     */
1285
-    public function get_count_of_all_registrations(): int
1286
-    {
1287
-        return EEM_Event::instance()->count_related($this, 'Registration');
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     * This returns the ticket with the earliest start time that is
1293
-     * available for this event (across all datetimes attached to the event)
1294
-     *
1295
-     * @return EE_Base_Class|EE_Ticket|null
1296
-     * @throws EE_Error
1297
-     * @throws ReflectionException
1298
-     */
1299
-    public function get_ticket_with_earliest_start_time()
1300
-    {
1301
-        $where['Datetime.EVT_ID'] = $this->ID();
1302
-        $query_params             = [$where, 'order_by' => ['TKT_start_date' => 'ASC']];
1303
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1304
-    }
1305
-
1306
-
1307
-    /**
1308
-     * This returns the ticket with the latest end time that is available
1309
-     * for this event (across all datetimes attached to the event)
1310
-     *
1311
-     * @return EE_Base_Class|EE_Ticket|null
1312
-     * @throws EE_Error
1313
-     * @throws ReflectionException
1314
-     */
1315
-    public function get_ticket_with_latest_end_time()
1316
-    {
1317
-        $where['Datetime.EVT_ID'] = $this->ID();
1318
-        $query_params             = [$where, 'order_by' => ['TKT_end_date' => 'DESC']];
1319
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * This returns the number of different ticket types currently on sale for this event.
1325
-     *
1326
-     * @return int
1327
-     * @throws EE_Error
1328
-     * @throws ReflectionException
1329
-     */
1330
-    public function countTicketsOnSale(): int
1331
-    {
1332
-        $where = [
1333
-            'Datetime.EVT_ID' => $this->ID(),
1334
-            'TKT_start_date'  => ['<', time()],
1335
-            'TKT_end_date'    => ['>', time()],
1336
-        ];
1337
-        return EEM_Ticket::instance()->count([$where]);
1338
-    }
1339
-
1340
-
1341
-    /**
1342
-     * This returns whether there are any tickets on sale for this event.
1343
-     *
1344
-     * @return bool true = YES tickets on sale.
1345
-     * @throws EE_Error
1346
-     * @throws ReflectionException
1347
-     */
1348
-    public function tickets_on_sale(): bool
1349
-    {
1350
-        return $this->countTicketsOnSale() > 0;
1351
-    }
1352
-
1353
-
1354
-    /**
1355
-     * Gets the URL for viewing this event on the front-end. Overrides parent
1356
-     * to check for an external URL first
1357
-     *
1358
-     * @return string
1359
-     * @throws EE_Error
1360
-     * @throws ReflectionException
1361
-     */
1362
-    public function get_permalink(): string
1363
-    {
1364
-        if ($this->external_url()) {
1365
-            return $this->external_url();
1366
-        }
1367
-        return parent::get_permalink();
1368
-    }
1369
-
1370
-
1371
-    /**
1372
-     * Gets the first term for 'espresso_event_categories' we can find
1373
-     *
1374
-     * @param array $query_params
1375
-     * @return EE_Base_Class|EE_Term|null
1376
-     * @throws EE_Error
1377
-     * @throws ReflectionException
1378
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1379
-     */
1380
-    public function first_event_category(array $query_params = []): ?EE_Term
1381
-    {
1382
-        $query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1383
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1384
-        return EEM_Term::instance()->get_one($query_params);
1385
-    }
1386
-
1387
-
1388
-    /**
1389
-     * Gets all terms for 'espresso_event_categories' we can find
1390
-     *
1391
-     * @param array $query_params
1392
-     * @return EE_Base_Class[]|EE_Term[]
1393
-     * @throws EE_Error
1394
-     * @throws ReflectionException
1395
-     */
1396
-    public function get_all_event_categories(array $query_params = []): array
1397
-    {
1398
-        $query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1399
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1400
-        return EEM_Term::instance()->get_all($query_params);
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * Adds a question group to this event
1406
-     *
1407
-     * @param EE_Question_Group|int $question_group_id_or_obj
1408
-     * @param bool                  $for_primary if true, the question group will be added for the primary
1409
-     *                                           registrant, if false will be added for others. default: false
1410
-     * @return EE_Base_Class|EE_Question_Group
1411
-     * @throws EE_Error
1412
-     * @throws InvalidArgumentException
1413
-     * @throws InvalidDataTypeException
1414
-     * @throws InvalidInterfaceException
1415
-     * @throws ReflectionException
1416
-     */
1417
-    public function add_question_group($question_group_id_or_obj, bool $for_primary = false): EE_Question_Group
1418
-    {
1419
-        // If the row already exists, it will be updated. If it doesn't, it will be inserted.
1420
-        // That's in EE_HABTM_Relation::add_relation_to().
1421
-        return $this->_add_relation_to(
1422
-            $question_group_id_or_obj,
1423
-            'Question_Group',
1424
-            [
1425
-                EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary) => true,
1426
-            ]
1427
-        );
1428
-    }
1429
-
1430
-
1431
-    /**
1432
-     * Removes a question group from the event
1433
-     *
1434
-     * @param EE_Question_Group|int $question_group_id_or_obj
1435
-     * @param bool                  $for_primary if true, the question group will be removed from the primary
1436
-     *                                           registrant, if false will be removed from others. default: false
1437
-     * @return EE_Base_Class|EE_Question_Group|int
1438
-     * @throws EE_Error
1439
-     * @throws InvalidArgumentException
1440
-     * @throws ReflectionException
1441
-     * @throws InvalidDataTypeException
1442
-     * @throws InvalidInterfaceException
1443
-     */
1444
-    public function remove_question_group($question_group_id_or_obj, bool $for_primary = false)
1445
-    {
1446
-        // If the question group is used for the other type (primary or additional)
1447
-        // then just update it. If not, delete it outright.
1448
-        $existing_relation = $this->get_first_related(
1449
-            'Event_Question_Group',
1450
-            [
1451
-                [
1452
-                    'QSG_ID' => EEM_Question_Group::instance()->ensure_is_ID($question_group_id_or_obj),
1453
-                ],
1454
-            ]
1455
-        );
1456
-        $field_to_update   = EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary);
1457
-        $other_field       = EEM_Event_Question_Group::instance()->fieldNameForContext(! $for_primary);
1458
-        if ($existing_relation->get($other_field) === false) {
1459
-            // Delete it. It's now no longer for primary or additional question groups.
1460
-            return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group');
1461
-        }
1462
-        // Just update it. They'll still use this question group for the other category
1463
-        $existing_relation->save(
1464
-            [
1465
-                $field_to_update => false,
1466
-            ]
1467
-        );
1468
-        return $question_group_id_or_obj;
1469
-    }
1470
-
1471
-
1472
-    /**
1473
-     * Gets all the question groups, ordering them by QSG_order ascending
1474
-     *
1475
-     * @param array $query_params
1476
-     * @return EE_Base_Class[]|EE_Question_Group[]
1477
-     * @throws EE_Error
1478
-     * @throws ReflectionException
1479
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1480
-     */
1481
-    public function question_groups(array $query_params = []): array
1482
-    {
1483
-        $query_params = ! empty($query_params) ? $query_params : ['order_by' => ['QSG_order' => 'ASC']];
1484
-        return $this->get_many_related('Question_Group', $query_params);
1485
-    }
1486
-
1487
-
1488
-    /**
1489
-     * Implementation for EEI_Has_Icon interface method.
1490
-     *
1491
-     * @return string
1492
-     * @see EEI_Visual_Representation for comments
1493
-     */
1494
-    public function get_icon(): string
1495
-    {
1496
-        return '<span class="dashicons dashicons-flag"></span>';
1497
-    }
1498
-
1499
-
1500
-    /**
1501
-     * Implementation for EEI_Admin_Links interface method.
1502
-     *
1503
-     * @return string
1504
-     * @throws EE_Error
1505
-     * @throws ReflectionException
1506
-     * @see EEI_Admin_Links for comments
1507
-     */
1508
-    public function get_admin_details_link(): string
1509
-    {
1510
-        return $this->get_admin_edit_link();
1511
-    }
1512
-
1513
-
1514
-    /**
1515
-     * Implementation for EEI_Admin_Links interface method.
1516
-     *
1517
-     * @return string
1518
-     * @throws EE_Error
1519
-     * @throws ReflectionException
1520
-     * @see EEI_Admin_Links for comments
1521
-     */
1522
-    public function get_admin_edit_link(): string
1523
-    {
1524
-        return EEH_URL::add_query_args_and_nonce(
1525
-            [
1526
-                'page'   => 'espresso_events',
1527
-                'action' => 'edit',
1528
-                'post'   => $this->ID(),
1529
-            ],
1530
-            admin_url('admin.php')
1531
-        );
1532
-    }
1533
-
1534
-
1535
-    /**
1536
-     * Implementation for EEI_Admin_Links interface method.
1537
-     *
1538
-     * @return string
1539
-     * @see EEI_Admin_Links for comments
1540
-     */
1541
-    public function get_admin_settings_link(): string
1542
-    {
1543
-        return EEH_URL::add_query_args_and_nonce(
1544
-            [
1545
-                'page'   => 'espresso_events',
1546
-                'action' => 'default_event_settings',
1547
-            ],
1548
-            admin_url('admin.php')
1549
-        );
1550
-    }
1551
-
1552
-
1553
-    /**
1554
-     * Implementation for EEI_Admin_Links interface method.
1555
-     *
1556
-     * @return string
1557
-     * @see EEI_Admin_Links for comments
1558
-     */
1559
-    public function get_admin_overview_link(): string
1560
-    {
1561
-        return EEH_URL::add_query_args_and_nonce(
1562
-            [
1563
-                'page'   => 'espresso_events',
1564
-                'action' => 'default',
1565
-            ],
1566
-            admin_url('admin.php')
1567
-        );
1568
-    }
1569
-
1570
-
1571
-    /**
1572
-     * @return string|null
1573
-     * @throws EE_Error
1574
-     * @throws ReflectionException
1575
-     */
1576
-    public function registrationFormUuid(): ?string
1577
-    {
1578
-        return $this->get('FSC_UUID') ?? '';
1579
-    }
1580
-
1581
-
1582
-    /**
1583
-     * Gets all the form sections for this event
1584
-     *
1585
-     * @return EE_Base_Class[]|EE_Form_Section[]
1586
-     * @throws EE_Error
1587
-     * @throws ReflectionException
1588
-     */
1589
-    public function registrationForm(): array
1590
-    {
1591
-        $FSC_UUID = $this->registrationFormUuid();
1592
-
1593
-        if (empty($FSC_UUID)) {
1594
-            return [];
1595
-        }
1596
-
1597
-        return EEM_Form_Section::instance()->get_all(
1598
-            [
1599
-                [
1600
-                    'OR' => [
1601
-                        'FSC_UUID'      => $FSC_UUID, // top level form
1602
-                        'FSC_belongsTo' => $FSC_UUID, // child form sections
1603
-                    ],
1604
-                ],
1605
-                'order_by' => ['FSC_order' => 'ASC'],
1606
-            ]
1607
-        );
1608
-    }
1609
-
1610
-
1611
-    /**
1612
-     * @param string $UUID
1613
-     * @throws EE_Error
1614
-     * @throws ReflectionException
1615
-     */
1616
-    public function setRegistrationFormUuid(string $UUID): void
1617
-    {
1618
-        if (! Cuid::isCuid($UUID)) {
1619
-            throw new InvalidArgumentException(
1620
-                sprintf(
1621
-                /* translators: 1: UUID value, 2: UUID generator function. */
1622
-                    esc_html__(
1623
-                        'The supplied UUID "%1$s" is invalid or missing. Please use %2$s to generate a valid one.',
1624
-                        'event_espresso'
1625
-                    ),
1626
-                    $UUID,
1627
-                    '`Cuid::cuid()`'
1628
-                )
1629
-            );
1630
-        }
1631
-        $this->set('FSC_UUID', $UUID);
1632
-    }
1633
-
1634
-
1635
-    /**
1636
-     * Get visibility status of event
1637
-     *
1638
-     * @param bool $hide_public
1639
-     * @return string
1640
-     */
1641
-    public function get_visibility_status(bool $hide_public = true): string
1642
-    {
1643
-        if ($this->status() === 'private') {
1644
-            return esc_html__('Private', 'event_espresso');
1645
-        }
1646
-        if (! empty($this->wp_post()->post_password)) {
1647
-            return esc_html__('Password Protected', 'event_espresso');
1648
-        }
1649
-        if (! $hide_public) {
1650
-            return esc_html__('Public', 'event_espresso');
1651
-        }
1652
-
1653
-        return '';
1654
-    }
1249
+		if ($echo) {
1250
+			echo wp_kses($status, AllowedTags::getAllowedTags());
1251
+			return '';
1252
+		}
1253
+		return $status;
1254
+	}
1255
+
1256
+
1257
+	/**
1258
+	 * @return bool|int
1259
+	 * @throws EE_Error
1260
+	 * @throws ReflectionException
1261
+	 */
1262
+	public function get_number_of_tickets_sold()
1263
+	{
1264
+		$tkt_sold = 0;
1265
+		if (! $this->ID()) {
1266
+			return 0;
1267
+		}
1268
+		$datetimes = $this->datetimes();
1269
+		foreach ($datetimes as $datetime) {
1270
+			if ($datetime instanceof EE_Datetime) {
1271
+				$tkt_sold += $datetime->sold();
1272
+			}
1273
+		}
1274
+		return $tkt_sold;
1275
+	}
1276
+
1277
+
1278
+	/**
1279
+	 * This just returns a count of all the registrations for this event
1280
+	 *
1281
+	 * @return int
1282
+	 * @throws EE_Error
1283
+	 * @throws ReflectionException
1284
+	 */
1285
+	public function get_count_of_all_registrations(): int
1286
+	{
1287
+		return EEM_Event::instance()->count_related($this, 'Registration');
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 * This returns the ticket with the earliest start time that is
1293
+	 * available for this event (across all datetimes attached to the event)
1294
+	 *
1295
+	 * @return EE_Base_Class|EE_Ticket|null
1296
+	 * @throws EE_Error
1297
+	 * @throws ReflectionException
1298
+	 */
1299
+	public function get_ticket_with_earliest_start_time()
1300
+	{
1301
+		$where['Datetime.EVT_ID'] = $this->ID();
1302
+		$query_params             = [$where, 'order_by' => ['TKT_start_date' => 'ASC']];
1303
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1304
+	}
1305
+
1306
+
1307
+	/**
1308
+	 * This returns the ticket with the latest end time that is available
1309
+	 * for this event (across all datetimes attached to the event)
1310
+	 *
1311
+	 * @return EE_Base_Class|EE_Ticket|null
1312
+	 * @throws EE_Error
1313
+	 * @throws ReflectionException
1314
+	 */
1315
+	public function get_ticket_with_latest_end_time()
1316
+	{
1317
+		$where['Datetime.EVT_ID'] = $this->ID();
1318
+		$query_params             = [$where, 'order_by' => ['TKT_end_date' => 'DESC']];
1319
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * This returns the number of different ticket types currently on sale for this event.
1325
+	 *
1326
+	 * @return int
1327
+	 * @throws EE_Error
1328
+	 * @throws ReflectionException
1329
+	 */
1330
+	public function countTicketsOnSale(): int
1331
+	{
1332
+		$where = [
1333
+			'Datetime.EVT_ID' => $this->ID(),
1334
+			'TKT_start_date'  => ['<', time()],
1335
+			'TKT_end_date'    => ['>', time()],
1336
+		];
1337
+		return EEM_Ticket::instance()->count([$where]);
1338
+	}
1339
+
1340
+
1341
+	/**
1342
+	 * This returns whether there are any tickets on sale for this event.
1343
+	 *
1344
+	 * @return bool true = YES tickets on sale.
1345
+	 * @throws EE_Error
1346
+	 * @throws ReflectionException
1347
+	 */
1348
+	public function tickets_on_sale(): bool
1349
+	{
1350
+		return $this->countTicketsOnSale() > 0;
1351
+	}
1352
+
1353
+
1354
+	/**
1355
+	 * Gets the URL for viewing this event on the front-end. Overrides parent
1356
+	 * to check for an external URL first
1357
+	 *
1358
+	 * @return string
1359
+	 * @throws EE_Error
1360
+	 * @throws ReflectionException
1361
+	 */
1362
+	public function get_permalink(): string
1363
+	{
1364
+		if ($this->external_url()) {
1365
+			return $this->external_url();
1366
+		}
1367
+		return parent::get_permalink();
1368
+	}
1369
+
1370
+
1371
+	/**
1372
+	 * Gets the first term for 'espresso_event_categories' we can find
1373
+	 *
1374
+	 * @param array $query_params
1375
+	 * @return EE_Base_Class|EE_Term|null
1376
+	 * @throws EE_Error
1377
+	 * @throws ReflectionException
1378
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1379
+	 */
1380
+	public function first_event_category(array $query_params = []): ?EE_Term
1381
+	{
1382
+		$query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1383
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1384
+		return EEM_Term::instance()->get_one($query_params);
1385
+	}
1386
+
1387
+
1388
+	/**
1389
+	 * Gets all terms for 'espresso_event_categories' we can find
1390
+	 *
1391
+	 * @param array $query_params
1392
+	 * @return EE_Base_Class[]|EE_Term[]
1393
+	 * @throws EE_Error
1394
+	 * @throws ReflectionException
1395
+	 */
1396
+	public function get_all_event_categories(array $query_params = []): array
1397
+	{
1398
+		$query_params[0]['Term_Taxonomy.taxonomy']     = 'espresso_event_categories';
1399
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1400
+		return EEM_Term::instance()->get_all($query_params);
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * Adds a question group to this event
1406
+	 *
1407
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1408
+	 * @param bool                  $for_primary if true, the question group will be added for the primary
1409
+	 *                                           registrant, if false will be added for others. default: false
1410
+	 * @return EE_Base_Class|EE_Question_Group
1411
+	 * @throws EE_Error
1412
+	 * @throws InvalidArgumentException
1413
+	 * @throws InvalidDataTypeException
1414
+	 * @throws InvalidInterfaceException
1415
+	 * @throws ReflectionException
1416
+	 */
1417
+	public function add_question_group($question_group_id_or_obj, bool $for_primary = false): EE_Question_Group
1418
+	{
1419
+		// If the row already exists, it will be updated. If it doesn't, it will be inserted.
1420
+		// That's in EE_HABTM_Relation::add_relation_to().
1421
+		return $this->_add_relation_to(
1422
+			$question_group_id_or_obj,
1423
+			'Question_Group',
1424
+			[
1425
+				EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary) => true,
1426
+			]
1427
+		);
1428
+	}
1429
+
1430
+
1431
+	/**
1432
+	 * Removes a question group from the event
1433
+	 *
1434
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1435
+	 * @param bool                  $for_primary if true, the question group will be removed from the primary
1436
+	 *                                           registrant, if false will be removed from others. default: false
1437
+	 * @return EE_Base_Class|EE_Question_Group|int
1438
+	 * @throws EE_Error
1439
+	 * @throws InvalidArgumentException
1440
+	 * @throws ReflectionException
1441
+	 * @throws InvalidDataTypeException
1442
+	 * @throws InvalidInterfaceException
1443
+	 */
1444
+	public function remove_question_group($question_group_id_or_obj, bool $for_primary = false)
1445
+	{
1446
+		// If the question group is used for the other type (primary or additional)
1447
+		// then just update it. If not, delete it outright.
1448
+		$existing_relation = $this->get_first_related(
1449
+			'Event_Question_Group',
1450
+			[
1451
+				[
1452
+					'QSG_ID' => EEM_Question_Group::instance()->ensure_is_ID($question_group_id_or_obj),
1453
+				],
1454
+			]
1455
+		);
1456
+		$field_to_update   = EEM_Event_Question_Group::instance()->fieldNameForContext($for_primary);
1457
+		$other_field       = EEM_Event_Question_Group::instance()->fieldNameForContext(! $for_primary);
1458
+		if ($existing_relation->get($other_field) === false) {
1459
+			// Delete it. It's now no longer for primary or additional question groups.
1460
+			return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group');
1461
+		}
1462
+		// Just update it. They'll still use this question group for the other category
1463
+		$existing_relation->save(
1464
+			[
1465
+				$field_to_update => false,
1466
+			]
1467
+		);
1468
+		return $question_group_id_or_obj;
1469
+	}
1470
+
1471
+
1472
+	/**
1473
+	 * Gets all the question groups, ordering them by QSG_order ascending
1474
+	 *
1475
+	 * @param array $query_params
1476
+	 * @return EE_Base_Class[]|EE_Question_Group[]
1477
+	 * @throws EE_Error
1478
+	 * @throws ReflectionException
1479
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1480
+	 */
1481
+	public function question_groups(array $query_params = []): array
1482
+	{
1483
+		$query_params = ! empty($query_params) ? $query_params : ['order_by' => ['QSG_order' => 'ASC']];
1484
+		return $this->get_many_related('Question_Group', $query_params);
1485
+	}
1486
+
1487
+
1488
+	/**
1489
+	 * Implementation for EEI_Has_Icon interface method.
1490
+	 *
1491
+	 * @return string
1492
+	 * @see EEI_Visual_Representation for comments
1493
+	 */
1494
+	public function get_icon(): string
1495
+	{
1496
+		return '<span class="dashicons dashicons-flag"></span>';
1497
+	}
1498
+
1499
+
1500
+	/**
1501
+	 * Implementation for EEI_Admin_Links interface method.
1502
+	 *
1503
+	 * @return string
1504
+	 * @throws EE_Error
1505
+	 * @throws ReflectionException
1506
+	 * @see EEI_Admin_Links for comments
1507
+	 */
1508
+	public function get_admin_details_link(): string
1509
+	{
1510
+		return $this->get_admin_edit_link();
1511
+	}
1512
+
1513
+
1514
+	/**
1515
+	 * Implementation for EEI_Admin_Links interface method.
1516
+	 *
1517
+	 * @return string
1518
+	 * @throws EE_Error
1519
+	 * @throws ReflectionException
1520
+	 * @see EEI_Admin_Links for comments
1521
+	 */
1522
+	public function get_admin_edit_link(): string
1523
+	{
1524
+		return EEH_URL::add_query_args_and_nonce(
1525
+			[
1526
+				'page'   => 'espresso_events',
1527
+				'action' => 'edit',
1528
+				'post'   => $this->ID(),
1529
+			],
1530
+			admin_url('admin.php')
1531
+		);
1532
+	}
1533
+
1534
+
1535
+	/**
1536
+	 * Implementation for EEI_Admin_Links interface method.
1537
+	 *
1538
+	 * @return string
1539
+	 * @see EEI_Admin_Links for comments
1540
+	 */
1541
+	public function get_admin_settings_link(): string
1542
+	{
1543
+		return EEH_URL::add_query_args_and_nonce(
1544
+			[
1545
+				'page'   => 'espresso_events',
1546
+				'action' => 'default_event_settings',
1547
+			],
1548
+			admin_url('admin.php')
1549
+		);
1550
+	}
1551
+
1552
+
1553
+	/**
1554
+	 * Implementation for EEI_Admin_Links interface method.
1555
+	 *
1556
+	 * @return string
1557
+	 * @see EEI_Admin_Links for comments
1558
+	 */
1559
+	public function get_admin_overview_link(): string
1560
+	{
1561
+		return EEH_URL::add_query_args_and_nonce(
1562
+			[
1563
+				'page'   => 'espresso_events',
1564
+				'action' => 'default',
1565
+			],
1566
+			admin_url('admin.php')
1567
+		);
1568
+	}
1569
+
1570
+
1571
+	/**
1572
+	 * @return string|null
1573
+	 * @throws EE_Error
1574
+	 * @throws ReflectionException
1575
+	 */
1576
+	public function registrationFormUuid(): ?string
1577
+	{
1578
+		return $this->get('FSC_UUID') ?? '';
1579
+	}
1580
+
1581
+
1582
+	/**
1583
+	 * Gets all the form sections for this event
1584
+	 *
1585
+	 * @return EE_Base_Class[]|EE_Form_Section[]
1586
+	 * @throws EE_Error
1587
+	 * @throws ReflectionException
1588
+	 */
1589
+	public function registrationForm(): array
1590
+	{
1591
+		$FSC_UUID = $this->registrationFormUuid();
1592
+
1593
+		if (empty($FSC_UUID)) {
1594
+			return [];
1595
+		}
1596
+
1597
+		return EEM_Form_Section::instance()->get_all(
1598
+			[
1599
+				[
1600
+					'OR' => [
1601
+						'FSC_UUID'      => $FSC_UUID, // top level form
1602
+						'FSC_belongsTo' => $FSC_UUID, // child form sections
1603
+					],
1604
+				],
1605
+				'order_by' => ['FSC_order' => 'ASC'],
1606
+			]
1607
+		);
1608
+	}
1609
+
1610
+
1611
+	/**
1612
+	 * @param string $UUID
1613
+	 * @throws EE_Error
1614
+	 * @throws ReflectionException
1615
+	 */
1616
+	public function setRegistrationFormUuid(string $UUID): void
1617
+	{
1618
+		if (! Cuid::isCuid($UUID)) {
1619
+			throw new InvalidArgumentException(
1620
+				sprintf(
1621
+				/* translators: 1: UUID value, 2: UUID generator function. */
1622
+					esc_html__(
1623
+						'The supplied UUID "%1$s" is invalid or missing. Please use %2$s to generate a valid one.',
1624
+						'event_espresso'
1625
+					),
1626
+					$UUID,
1627
+					'`Cuid::cuid()`'
1628
+				)
1629
+			);
1630
+		}
1631
+		$this->set('FSC_UUID', $UUID);
1632
+	}
1633
+
1634
+
1635
+	/**
1636
+	 * Get visibility status of event
1637
+	 *
1638
+	 * @param bool $hide_public
1639
+	 * @return string
1640
+	 */
1641
+	public function get_visibility_status(bool $hide_public = true): string
1642
+	{
1643
+		if ($this->status() === 'private') {
1644
+			return esc_html__('Private', 'event_espresso');
1645
+		}
1646
+		if (! empty($this->wp_post()->post_password)) {
1647
+			return esc_html__('Password Protected', 'event_espresso');
1648
+		}
1649
+		if (! $hide_public) {
1650
+			return esc_html__('Public', 'event_espresso');
1651
+		}
1652
+
1653
+		return '';
1654
+	}
1655 1655
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Line_Item.class.php 1 patch
Indentation   +1659 added lines, -1659 removed lines patch added patch discarded remove patch
@@ -15,1663 +15,1663 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Line_Item extends EE_Base_Class implements EEI_Line_Item
17 17
 {
18
-    /**
19
-     * for children line items (currently not a normal relation)
20
-     *
21
-     * @type EE_Line_Item[]
22
-     */
23
-    protected $_children = array();
24
-
25
-    /**
26
-     * for the parent line item
27
-     *
28
-     * @var EE_Line_Item
29
-     */
30
-    protected $_parent;
31
-
32
-    /**
33
-     * @var LineItemCalculator
34
-     */
35
-    protected $calculator;
36
-
37
-
38
-    /**
39
-     * @param array  $props_n_values          incoming values
40
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
41
-     *                                        used.)
42
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
43
-     *                                        date_format and the second value is the time format
44
-     * @return EE_Line_Item
45
-     * @throws EE_Error
46
-     * @throws InvalidArgumentException
47
-     * @throws InvalidDataTypeException
48
-     * @throws InvalidInterfaceException
49
-     * @throws ReflectionException
50
-     */
51
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
-    {
53
-        $has_object = parent::_check_for_object(
54
-            $props_n_values,
55
-            __CLASS__,
56
-            $timezone,
57
-            $date_formats
58
-        );
59
-        return $has_object
60
-            ? $has_object
61
-            : new self($props_n_values, false, $timezone);
62
-    }
63
-
64
-
65
-    /**
66
-     * @param array  $props_n_values  incoming values from the database
67
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
68
-     *                                the website will be used.
69
-     * @return EE_Line_Item
70
-     * @throws EE_Error
71
-     * @throws InvalidArgumentException
72
-     * @throws InvalidDataTypeException
73
-     * @throws InvalidInterfaceException
74
-     * @throws ReflectionException
75
-     */
76
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
77
-    {
78
-        return new self($props_n_values, true, $timezone);
79
-    }
80
-
81
-
82
-    /**
83
-     * Adds some defaults if they're not specified
84
-     *
85
-     * @param array  $fieldValues
86
-     * @param bool   $bydb
87
-     * @param string $timezone
88
-     * @throws EE_Error
89
-     * @throws InvalidArgumentException
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     * @throws ReflectionException
93
-     */
94
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
95
-    {
96
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
97
-        parent::__construct($fieldValues, $bydb, $timezone);
98
-        if (! $this->get('LIN_code')) {
99
-            $this->set_code($this->generate_code());
100
-        }
101
-    }
102
-
103
-
104
-    public function __wakeup()
105
-    {
106
-        $this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
107
-        parent::__wakeup();
108
-    }
109
-
110
-
111
-    /**
112
-     * Gets ID
113
-     *
114
-     * @return int
115
-     * @throws EE_Error
116
-     * @throws InvalidArgumentException
117
-     * @throws InvalidDataTypeException
118
-     * @throws InvalidInterfaceException
119
-     * @throws ReflectionException
120
-     */
121
-    public function ID()
122
-    {
123
-        return $this->get('LIN_ID');
124
-    }
125
-
126
-
127
-    /**
128
-     * Gets TXN_ID
129
-     *
130
-     * @return int
131
-     * @throws EE_Error
132
-     * @throws InvalidArgumentException
133
-     * @throws InvalidDataTypeException
134
-     * @throws InvalidInterfaceException
135
-     * @throws ReflectionException
136
-     */
137
-    public function TXN_ID()
138
-    {
139
-        return $this->get('TXN_ID');
140
-    }
141
-
142
-
143
-    /**
144
-     * Sets TXN_ID
145
-     *
146
-     * @param int $TXN_ID
147
-     * @throws EE_Error
148
-     * @throws InvalidArgumentException
149
-     * @throws InvalidDataTypeException
150
-     * @throws InvalidInterfaceException
151
-     * @throws ReflectionException
152
-     */
153
-    public function set_TXN_ID($TXN_ID)
154
-    {
155
-        $this->set('TXN_ID', $TXN_ID);
156
-    }
157
-
158
-
159
-    /**
160
-     * Gets name
161
-     *
162
-     * @return string
163
-     * @throws EE_Error
164
-     * @throws InvalidArgumentException
165
-     * @throws InvalidDataTypeException
166
-     * @throws InvalidInterfaceException
167
-     * @throws ReflectionException
168
-     */
169
-    public function name()
170
-    {
171
-        $name = $this->get('LIN_name');
172
-        if (! $name) {
173
-            $name = ucwords(str_replace('-', ' ', $this->type()));
174
-        }
175
-        return $name;
176
-    }
177
-
178
-
179
-    /**
180
-     * Sets name
181
-     *
182
-     * @param string $name
183
-     * @throws EE_Error
184
-     * @throws InvalidArgumentException
185
-     * @throws InvalidDataTypeException
186
-     * @throws InvalidInterfaceException
187
-     * @throws ReflectionException
188
-     */
189
-    public function set_name($name)
190
-    {
191
-        $this->set('LIN_name', $name);
192
-    }
193
-
194
-
195
-    /**
196
-     * Gets desc
197
-     *
198
-     * @return string
199
-     * @throws EE_Error
200
-     * @throws InvalidArgumentException
201
-     * @throws InvalidDataTypeException
202
-     * @throws InvalidInterfaceException
203
-     * @throws ReflectionException
204
-     */
205
-    public function desc()
206
-    {
207
-        return $this->get('LIN_desc');
208
-    }
209
-
210
-
211
-    /**
212
-     * Sets desc
213
-     *
214
-     * @param string $desc
215
-     * @throws EE_Error
216
-     * @throws InvalidArgumentException
217
-     * @throws InvalidDataTypeException
218
-     * @throws InvalidInterfaceException
219
-     * @throws ReflectionException
220
-     */
221
-    public function set_desc($desc)
222
-    {
223
-        $this->set('LIN_desc', $desc);
224
-    }
225
-
226
-
227
-    /**
228
-     * Gets quantity
229
-     *
230
-     * @return int
231
-     * @throws EE_Error
232
-     * @throws InvalidArgumentException
233
-     * @throws InvalidDataTypeException
234
-     * @throws InvalidInterfaceException
235
-     * @throws ReflectionException
236
-     */
237
-    public function quantity(): int
238
-    {
239
-        return (int) $this->get('LIN_quantity');
240
-    }
241
-
242
-
243
-    /**
244
-     * Sets quantity
245
-     *
246
-     * @param int $quantity
247
-     * @throws EE_Error
248
-     * @throws InvalidArgumentException
249
-     * @throws InvalidDataTypeException
250
-     * @throws InvalidInterfaceException
251
-     * @throws ReflectionException
252
-     */
253
-    public function set_quantity($quantity)
254
-    {
255
-        $this->set('LIN_quantity', max($quantity, 0));
256
-    }
257
-
258
-
259
-    /**
260
-     * Gets item_id
261
-     *
262
-     * @return int
263
-     * @throws EE_Error
264
-     * @throws InvalidArgumentException
265
-     * @throws InvalidDataTypeException
266
-     * @throws InvalidInterfaceException
267
-     * @throws ReflectionException
268
-     */
269
-    public function OBJ_ID()
270
-    {
271
-        return $this->get('OBJ_ID');
272
-    }
273
-
274
-
275
-    /**
276
-     * Sets item_id
277
-     *
278
-     * @param int $item_id
279
-     * @throws EE_Error
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidDataTypeException
282
-     * @throws InvalidInterfaceException
283
-     * @throws ReflectionException
284
-     */
285
-    public function set_OBJ_ID($item_id)
286
-    {
287
-        $this->set('OBJ_ID', $item_id);
288
-    }
289
-
290
-
291
-    /**
292
-     * Gets item_type
293
-     *
294
-     * @return string
295
-     * @throws EE_Error
296
-     * @throws InvalidArgumentException
297
-     * @throws InvalidDataTypeException
298
-     * @throws InvalidInterfaceException
299
-     * @throws ReflectionException
300
-     */
301
-    public function OBJ_type()
302
-    {
303
-        return $this->get('OBJ_type');
304
-    }
305
-
306
-
307
-    /**
308
-     * Gets item_type
309
-     *
310
-     * @return string
311
-     * @throws EE_Error
312
-     * @throws InvalidArgumentException
313
-     * @throws InvalidDataTypeException
314
-     * @throws InvalidInterfaceException
315
-     * @throws ReflectionException
316
-     */
317
-    public function OBJ_type_i18n()
318
-    {
319
-        $obj_type = $this->OBJ_type();
320
-        switch ($obj_type) {
321
-            case EEM_Line_Item::OBJ_TYPE_EVENT:
322
-                $obj_type = esc_html__('Event', 'event_espresso');
323
-                break;
324
-            case EEM_Line_Item::OBJ_TYPE_PRICE:
325
-                $obj_type = esc_html__('Price', 'event_espresso');
326
-                break;
327
-            case EEM_Line_Item::OBJ_TYPE_PROMOTION:
328
-                $obj_type = esc_html__('Promotion', 'event_espresso');
329
-                break;
330
-            case EEM_Line_Item::OBJ_TYPE_TICKET:
331
-                $obj_type = esc_html__('Ticket', 'event_espresso');
332
-                break;
333
-            case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
334
-                $obj_type = esc_html__('Transaction', 'event_espresso');
335
-                break;
336
-        }
337
-        return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
338
-    }
339
-
340
-
341
-    /**
342
-     * Sets item_type
343
-     *
344
-     * @param string $OBJ_type
345
-     * @throws EE_Error
346
-     * @throws InvalidArgumentException
347
-     * @throws InvalidDataTypeException
348
-     * @throws InvalidInterfaceException
349
-     * @throws ReflectionException
350
-     */
351
-    public function set_OBJ_type($OBJ_type)
352
-    {
353
-        $this->set('OBJ_type', $OBJ_type);
354
-    }
355
-
356
-
357
-    /**
358
-     * Gets unit_price
359
-     *
360
-     * @return float
361
-     * @throws EE_Error
362
-     * @throws InvalidArgumentException
363
-     * @throws InvalidDataTypeException
364
-     * @throws InvalidInterfaceException
365
-     * @throws ReflectionException
366
-     */
367
-    public function unit_price()
368
-    {
369
-        return $this->get('LIN_unit_price');
370
-    }
371
-
372
-
373
-    /**
374
-     * Sets unit_price
375
-     *
376
-     * @param float $unit_price
377
-     * @throws EE_Error
378
-     * @throws InvalidArgumentException
379
-     * @throws InvalidDataTypeException
380
-     * @throws InvalidInterfaceException
381
-     * @throws ReflectionException
382
-     */
383
-    public function set_unit_price($unit_price)
384
-    {
385
-        $this->set('LIN_unit_price', $unit_price);
386
-    }
387
-
388
-
389
-    /**
390
-     * Checks if this item is a percentage modifier or not
391
-     *
392
-     * @return boolean
393
-     * @throws EE_Error
394
-     * @throws InvalidArgumentException
395
-     * @throws InvalidDataTypeException
396
-     * @throws InvalidInterfaceException
397
-     * @throws ReflectionException
398
-     */
399
-    public function is_percent()
400
-    {
401
-        if ($this->is_tax_sub_total()) {
402
-            // tax subtotals HAVE a percent on them, that percentage only applies
403
-            // to taxable items, so its' an exception. Treat it like a flat line item
404
-            return false;
405
-        }
406
-        $unit_price = abs($this->get('LIN_unit_price'));
407
-        $percent = abs($this->get('LIN_percent'));
408
-        if ($unit_price < .001 && $percent) {
409
-            return true;
410
-        }
411
-        if ($unit_price >= .001 && ! $percent) {
412
-            return false;
413
-        }
414
-        if ($unit_price >= .001 && $percent) {
415
-            throw new EE_Error(
416
-                sprintf(
417
-                    esc_html__(
418
-                        'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
419
-                        'event_espresso'
420
-                    ),
421
-                    $unit_price,
422
-                    $percent
423
-                )
424
-            );
425
-        }
426
-        // if they're both 0, assume its not a percent item
427
-        return false;
428
-    }
429
-
430
-
431
-    /**
432
-     * Gets percent (between 100-.001)
433
-     *
434
-     * @return float
435
-     * @throws EE_Error
436
-     * @throws InvalidArgumentException
437
-     * @throws InvalidDataTypeException
438
-     * @throws InvalidInterfaceException
439
-     * @throws ReflectionException
440
-     */
441
-    public function percent()
442
-    {
443
-        return $this->get('LIN_percent');
444
-    }
445
-
446
-
447
-    /**
448
-     * @return string
449
-     * @throws EE_Error
450
-     * @throws ReflectionException
451
-     * @since 5.0.0.p
452
-     */
453
-    public function prettyPercent(): string
454
-    {
455
-        return $this->get_pretty('LIN_percent');
456
-    }
457
-
458
-
459
-    /**
460
-     * Sets percent (between 100-0.01)
461
-     *
462
-     * @param float $percent
463
-     * @throws EE_Error
464
-     * @throws InvalidArgumentException
465
-     * @throws InvalidDataTypeException
466
-     * @throws InvalidInterfaceException
467
-     * @throws ReflectionException
468
-     */
469
-    public function set_percent($percent)
470
-    {
471
-        $this->set('LIN_percent', $percent);
472
-    }
473
-
474
-
475
-    /**
476
-     * Gets total
477
-     *
478
-     * @return float
479
-     * @throws EE_Error
480
-     * @throws InvalidArgumentException
481
-     * @throws InvalidDataTypeException
482
-     * @throws InvalidInterfaceException
483
-     * @throws ReflectionException
484
-     */
485
-    public function pretaxTotal(): float
486
-    {
487
-        return (float) $this->get('LIN_pretax');
488
-    }
489
-
490
-
491
-    /**
492
-     * Sets total
493
-     *
494
-     * @param float $pretax_total
495
-     * @throws EE_Error
496
-     * @throws InvalidArgumentException
497
-     * @throws InvalidDataTypeException
498
-     * @throws InvalidInterfaceException
499
-     * @throws ReflectionException
500
-     */
501
-    public function setPretaxTotal(float $pretax_total)
502
-    {
503
-        $this->set('LIN_pretax', $pretax_total);
504
-    }
505
-
506
-
507
-    /**
508
-     * @return float
509
-     * @throws EE_Error
510
-     * @throws ReflectionException
511
-     * @since  5.0.0.p
512
-     */
513
-    public function totalWithTax(): float
514
-    {
515
-        return (float) $this->get('LIN_total');
516
-    }
517
-
518
-
519
-    /**
520
-     * Sets total
521
-     *
522
-     * @param float $total
523
-     * @throws EE_Error
524
-     * @throws ReflectionException
525
-     * @since  5.0.0.p
526
-     */
527
-    public function setTotalWithTax(float $total)
528
-    {
529
-        $this->set('LIN_total', $total);
530
-    }
531
-
532
-
533
-    /**
534
-     * Gets total
535
-     *
536
-     * @return float
537
-     * @throws EE_Error
538
-     * @throws ReflectionException
539
-     * @deprecatd 5.0.0.p
540
-     */
541
-    public function total(): float
542
-    {
543
-        return $this->totalWithTax();
544
-    }
545
-
546
-
547
-    /**
548
-     * Sets total
549
-     *
550
-     * @param float $total
551
-     * @throws EE_Error
552
-     * @throws ReflectionException
553
-     * @deprecatd 5.0.0.p
554
-     */
555
-    public function set_total($total)
556
-    {
557
-        $this->setTotalWithTax($total);
558
-    }
559
-
560
-
561
-    /**
562
-     * Gets order
563
-     *
564
-     * @return int
565
-     * @throws EE_Error
566
-     * @throws InvalidArgumentException
567
-     * @throws InvalidDataTypeException
568
-     * @throws InvalidInterfaceException
569
-     * @throws ReflectionException
570
-     */
571
-    public function order()
572
-    {
573
-        return $this->get('LIN_order');
574
-    }
575
-
576
-
577
-    /**
578
-     * Sets order
579
-     *
580
-     * @param int $order
581
-     * @throws EE_Error
582
-     * @throws InvalidArgumentException
583
-     * @throws InvalidDataTypeException
584
-     * @throws InvalidInterfaceException
585
-     * @throws ReflectionException
586
-     */
587
-    public function set_order($order)
588
-    {
589
-        $this->set('LIN_order', $order);
590
-    }
591
-
592
-
593
-    /**
594
-     * Gets parent
595
-     *
596
-     * @return int
597
-     * @throws EE_Error
598
-     * @throws InvalidArgumentException
599
-     * @throws InvalidDataTypeException
600
-     * @throws InvalidInterfaceException
601
-     * @throws ReflectionException
602
-     */
603
-    public function parent_ID()
604
-    {
605
-        return $this->get('LIN_parent');
606
-    }
607
-
608
-
609
-    /**
610
-     * Sets parent
611
-     *
612
-     * @param int $parent
613
-     * @throws EE_Error
614
-     * @throws InvalidArgumentException
615
-     * @throws InvalidDataTypeException
616
-     * @throws InvalidInterfaceException
617
-     * @throws ReflectionException
618
-     */
619
-    public function set_parent_ID($parent)
620
-    {
621
-        $this->set('LIN_parent', $parent);
622
-    }
623
-
624
-
625
-    /**
626
-     * Gets type
627
-     *
628
-     * @return string
629
-     * @throws EE_Error
630
-     * @throws InvalidArgumentException
631
-     * @throws InvalidDataTypeException
632
-     * @throws InvalidInterfaceException
633
-     * @throws ReflectionException
634
-     */
635
-    public function type()
636
-    {
637
-        return $this->get('LIN_type');
638
-    }
639
-
640
-
641
-    /**
642
-     * Sets type
643
-     *
644
-     * @param string $type
645
-     * @throws EE_Error
646
-     * @throws InvalidArgumentException
647
-     * @throws InvalidDataTypeException
648
-     * @throws InvalidInterfaceException
649
-     * @throws ReflectionException
650
-     */
651
-    public function set_type($type)
652
-    {
653
-        $this->set('LIN_type', $type);
654
-    }
655
-
656
-
657
-    /**
658
-     * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
659
-     * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
660
-     * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
661
-     * or indirectly by `EE_Line_item::add_child_line_item()`)
662
-     *
663
-     * @return EE_Base_Class|EE_Line_Item
664
-     * @throws EE_Error
665
-     * @throws InvalidArgumentException
666
-     * @throws InvalidDataTypeException
667
-     * @throws InvalidInterfaceException
668
-     * @throws ReflectionException
669
-     */
670
-    public function parent()
671
-    {
672
-        return $this->ID()
673
-            ? $this->get_model()->get_one_by_ID($this->parent_ID())
674
-            : $this->_parent;
675
-    }
676
-
677
-
678
-    /**
679
-     * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
680
-     *
681
-     * @return EE_Line_Item[]
682
-     * @throws EE_Error
683
-     * @throws InvalidArgumentException
684
-     * @throws InvalidDataTypeException
685
-     * @throws InvalidInterfaceException
686
-     * @throws ReflectionException
687
-     */
688
-    public function children(array $query_params = []): array
689
-    {
690
-        if ($this->ID()) {
691
-            // ensure where params are an array
692
-            $query_params[0] = $query_params[0] ?? [];
693
-            // add defaults for line item parent and orderby
694
-            $query_params[0] += ['LIN_parent' => $this->ID()];
695
-            $query_params += ['order_by' => ['LIN_order' => 'ASC']];
696
-            return $this->get_model()->get_all($query_params);
697
-        }
698
-        if (! is_array($this->_children)) {
699
-            $this->_children = array();
700
-        }
701
-        return $this->_children;
702
-    }
703
-
704
-
705
-    /**
706
-     * Gets code
707
-     *
708
-     * @return string
709
-     * @throws EE_Error
710
-     * @throws InvalidArgumentException
711
-     * @throws InvalidDataTypeException
712
-     * @throws InvalidInterfaceException
713
-     * @throws ReflectionException
714
-     */
715
-    public function code()
716
-    {
717
-        return $this->get('LIN_code');
718
-    }
719
-
720
-
721
-    /**
722
-     * Sets code
723
-     *
724
-     * @param string $code
725
-     * @throws EE_Error
726
-     * @throws InvalidArgumentException
727
-     * @throws InvalidDataTypeException
728
-     * @throws InvalidInterfaceException
729
-     * @throws ReflectionException
730
-     */
731
-    public function set_code($code)
732
-    {
733
-        $this->set('LIN_code', $code);
734
-    }
735
-
736
-
737
-    /**
738
-     * Gets is_taxable
739
-     *
740
-     * @return boolean
741
-     * @throws EE_Error
742
-     * @throws InvalidArgumentException
743
-     * @throws InvalidDataTypeException
744
-     * @throws InvalidInterfaceException
745
-     * @throws ReflectionException
746
-     */
747
-    public function is_taxable()
748
-    {
749
-        return $this->get('LIN_is_taxable');
750
-    }
751
-
752
-
753
-    /**
754
-     * Sets is_taxable
755
-     *
756
-     * @param boolean $is_taxable
757
-     * @throws EE_Error
758
-     * @throws InvalidArgumentException
759
-     * @throws InvalidDataTypeException
760
-     * @throws InvalidInterfaceException
761
-     * @throws ReflectionException
762
-     */
763
-    public function set_is_taxable($is_taxable)
764
-    {
765
-        $this->set('LIN_is_taxable', $is_taxable);
766
-    }
767
-
768
-
769
-    /**
770
-     * @param int $timestamp
771
-     * @throws EE_Error
772
-     * @throws ReflectionException
773
-     * @since 5.0.0.p
774
-     */
775
-    public function setTimestamp(int $timestamp)
776
-    {
777
-        $this->set('LIN_timestamp', $timestamp);
778
-    }
779
-
780
-
781
-    /**
782
-     * Gets the object that this model-joins-to.
783
-     * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
784
-     * EEM_Promotion_Object
785
-     *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
786
-     *
787
-     * @return EE_Base_Class | NULL
788
-     * @throws EE_Error
789
-     * @throws InvalidArgumentException
790
-     * @throws InvalidDataTypeException
791
-     * @throws InvalidInterfaceException
792
-     * @throws ReflectionException
793
-     */
794
-    public function get_object()
795
-    {
796
-        $model_name_of_related_obj = $this->OBJ_type();
797
-        return $this->get_model()->has_relation($model_name_of_related_obj)
798
-            ? $this->get_first_related($model_name_of_related_obj)
799
-            : null;
800
-    }
801
-
802
-
803
-    /**
804
-     * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
805
-     * (IE, if this line item is for a price or something else, will return NULL)
806
-     *
807
-     * @param array $query_params
808
-     * @return EE_Base_Class|EE_Ticket
809
-     * @throws EE_Error
810
-     * @throws InvalidArgumentException
811
-     * @throws InvalidDataTypeException
812
-     * @throws InvalidInterfaceException
813
-     * @throws ReflectionException
814
-     */
815
-    public function ticket($query_params = array())
816
-    {
817
-        // we're going to assume that when this method is called
818
-        // we always want to receive the attached ticket EVEN if that ticket is archived.
819
-        // This can be overridden via the incoming $query_params argument
820
-        $remove_defaults = array('default_where_conditions' => 'none');
821
-        $query_params = array_merge($remove_defaults, $query_params);
822
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
823
-    }
824
-
825
-
826
-    /**
827
-     * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
828
-     *
829
-     * @return EE_Datetime | NULL
830
-     * @throws EE_Error
831
-     * @throws InvalidArgumentException
832
-     * @throws InvalidDataTypeException
833
-     * @throws InvalidInterfaceException
834
-     * @throws ReflectionException
835
-     */
836
-    public function get_ticket_datetime()
837
-    {
838
-        if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
839
-            $ticket = $this->ticket();
840
-            if ($ticket instanceof EE_Ticket) {
841
-                $datetime = $ticket->first_datetime();
842
-                if ($datetime instanceof EE_Datetime) {
843
-                    return $datetime;
844
-                }
845
-            }
846
-        }
847
-        return null;
848
-    }
849
-
850
-
851
-    /**
852
-     * Gets the event's name that's related to the ticket, if this is for
853
-     * a ticket
854
-     *
855
-     * @return string
856
-     * @throws EE_Error
857
-     * @throws InvalidArgumentException
858
-     * @throws InvalidDataTypeException
859
-     * @throws InvalidInterfaceException
860
-     * @throws ReflectionException
861
-     */
862
-    public function ticket_event_name()
863
-    {
864
-        $event_name = esc_html__('Unknown', 'event_espresso');
865
-        $event = $this->ticket_event();
866
-        if ($event instanceof EE_Event) {
867
-            $event_name = $event->name();
868
-        }
869
-        return $event_name;
870
-    }
871
-
872
-
873
-    /**
874
-     * Gets the event that's related to the ticket, if this line item represents a ticket.
875
-     *
876
-     * @return EE_Event|null
877
-     * @throws EE_Error
878
-     * @throws InvalidArgumentException
879
-     * @throws InvalidDataTypeException
880
-     * @throws InvalidInterfaceException
881
-     * @throws ReflectionException
882
-     */
883
-    public function ticket_event()
884
-    {
885
-        $event = null;
886
-        $ticket = $this->ticket();
887
-        if ($ticket instanceof EE_Ticket) {
888
-            $datetime = $ticket->first_datetime();
889
-            if ($datetime instanceof EE_Datetime) {
890
-                $event = $datetime->event();
891
-            }
892
-        }
893
-        return $event;
894
-    }
895
-
896
-
897
-    /**
898
-     * Gets the first datetime for this lien item, assuming it's for a ticket
899
-     *
900
-     * @param string $date_format
901
-     * @param string $time_format
902
-     * @return string
903
-     * @throws EE_Error
904
-     * @throws InvalidArgumentException
905
-     * @throws InvalidDataTypeException
906
-     * @throws InvalidInterfaceException
907
-     * @throws ReflectionException
908
-     */
909
-    public function ticket_datetime_start($date_format = '', $time_format = '')
910
-    {
911
-        $first_datetime_string = esc_html__('Unknown', 'event_espresso');
912
-        $datetime = $this->get_ticket_datetime();
913
-        if ($datetime) {
914
-            $first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
915
-        }
916
-        return $first_datetime_string;
917
-    }
918
-
919
-
920
-    /**
921
-     * Adds the line item as a child to this line item. If there is another child line
922
-     * item with the same LIN_code, it is overwritten by this new one
923
-     *
924
-     * @param EE_Line_Item $line_item
925
-     * @param bool          $set_order
926
-     * @return bool success
927
-     * @throws EE_Error
928
-     * @throws InvalidArgumentException
929
-     * @throws InvalidDataTypeException
930
-     * @throws InvalidInterfaceException
931
-     * @throws ReflectionException
932
-     */
933
-    public function add_child_line_item(EE_Line_Item $line_item, $set_order = true)
934
-    {
935
-        // should we calculate the LIN_order for this line item ?
936
-        if ($set_order || $line_item->order() === null) {
937
-            $line_item->set_order(count($this->children()));
938
-        }
939
-        if ($this->ID()) {
940
-            // check for any duplicate line items (with the same code), if so, this replaces it
941
-            $line_item_with_same_code = $this->get_child_line_item($line_item->code());
942
-            if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
943
-                $this->delete_child_line_item($line_item_with_same_code->code());
944
-            }
945
-            $line_item->set_parent_ID($this->ID());
946
-            if ($this->TXN_ID()) {
947
-                $line_item->set_TXN_ID($this->TXN_ID());
948
-            }
949
-            return $line_item->save();
950
-        }
951
-        $this->_children[ $line_item->code() ] = $line_item;
952
-        if ($line_item->parent() !== $this) {
953
-            $line_item->set_parent($this);
954
-        }
955
-        return true;
956
-    }
957
-
958
-
959
-    /**
960
-     * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
961
-     * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
962
-     * However, if this line item is NOT saved to the DB, this just caches the parent on
963
-     * the EE_Line_Item::_parent property.
964
-     *
965
-     * @param EE_Line_Item $line_item
966
-     * @throws EE_Error
967
-     * @throws InvalidArgumentException
968
-     * @throws InvalidDataTypeException
969
-     * @throws InvalidInterfaceException
970
-     * @throws ReflectionException
971
-     */
972
-    public function set_parent($line_item)
973
-    {
974
-        if ($this->ID()) {
975
-            if (! $line_item->ID()) {
976
-                $line_item->save();
977
-            }
978
-            $this->set_parent_ID($line_item->ID());
979
-            $this->save();
980
-        } else {
981
-            $this->_parent = $line_item;
982
-            $this->set_parent_ID($line_item->ID());
983
-        }
984
-    }
985
-
986
-
987
-    /**
988
-     * Gets the child line item as specified by its code. Because this returns an object (by reference)
989
-     * you can modify this child line item and the parent (this object) can know about them
990
-     * because it also has a reference to that line item
991
-     *
992
-     * @param string $code
993
-     * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
994
-     * @throws EE_Error
995
-     * @throws InvalidArgumentException
996
-     * @throws InvalidDataTypeException
997
-     * @throws InvalidInterfaceException
998
-     * @throws ReflectionException
999
-     */
1000
-    public function get_child_line_item($code)
1001
-    {
1002
-        if ($this->ID()) {
1003
-            return $this->get_model()->get_one(
1004
-                array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
1005
-            );
1006
-        }
1007
-        return isset($this->_children[ $code ])
1008
-            ? $this->_children[ $code ]
1009
-            : null;
1010
-    }
1011
-
1012
-
1013
-    /**
1014
-     * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1015
-     * cached on it)
1016
-     *
1017
-     * @return int
1018
-     * @throws EE_Error
1019
-     * @throws InvalidArgumentException
1020
-     * @throws InvalidDataTypeException
1021
-     * @throws InvalidInterfaceException
1022
-     * @throws ReflectionException
1023
-     */
1024
-    public function delete_children_line_items()
1025
-    {
1026
-        if ($this->ID()) {
1027
-            return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
1028
-        }
1029
-        $count = count($this->_children);
1030
-        $this->_children = array();
1031
-        return $count;
1032
-    }
1033
-
1034
-
1035
-    /**
1036
-     * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1037
-     * HAS NOT been saved to the DB, removes the child line item with index $code.
1038
-     * Also searches through the child's children for a matching line item. However, once a line item has been found
1039
-     * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1040
-     * deleted)
1041
-     *
1042
-     * @param string $code
1043
-     * @param bool   $stop_search_once_found
1044
-     * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1045
-     *             the DB yet)
1046
-     * @throws EE_Error
1047
-     * @throws InvalidArgumentException
1048
-     * @throws InvalidDataTypeException
1049
-     * @throws InvalidInterfaceException
1050
-     * @throws ReflectionException
1051
-     */
1052
-    public function delete_child_line_item($code, $stop_search_once_found = true)
1053
-    {
1054
-        if ($this->ID()) {
1055
-            $items_deleted = 0;
1056
-            if ($this->code() === $code) {
1057
-                $items_deleted += EEH_Line_Item::delete_all_child_items($this);
1058
-                $items_deleted += (int) $this->delete();
1059
-                if ($stop_search_once_found) {
1060
-                    return $items_deleted;
1061
-                }
1062
-            }
1063
-            foreach ($this->children() as $child_line_item) {
1064
-                $items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1065
-            }
1066
-            return $items_deleted;
1067
-        }
1068
-        if (isset($this->_children[ $code ])) {
1069
-            unset($this->_children[ $code ]);
1070
-            return 1;
1071
-        }
1072
-        return 0;
1073
-    }
1074
-
1075
-
1076
-    /**
1077
-     * If this line item is in the database, is of the type subtotal, and
1078
-     * has no children, why do we have it? It should be deleted so this function
1079
-     * does that
1080
-     *
1081
-     * @return boolean
1082
-     * @throws EE_Error
1083
-     * @throws InvalidArgumentException
1084
-     * @throws InvalidDataTypeException
1085
-     * @throws InvalidInterfaceException
1086
-     * @throws ReflectionException
1087
-     */
1088
-    public function delete_if_childless_subtotal()
1089
-    {
1090
-        if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1091
-            return $this->delete();
1092
-        }
1093
-        return false;
1094
-    }
1095
-
1096
-
1097
-    /**
1098
-     * Creates a code and returns a string. doesn't assign the code to this model object
1099
-     *
1100
-     * @return string
1101
-     * @throws EE_Error
1102
-     * @throws InvalidArgumentException
1103
-     * @throws InvalidDataTypeException
1104
-     * @throws InvalidInterfaceException
1105
-     * @throws ReflectionException
1106
-     */
1107
-    public function generate_code()
1108
-    {
1109
-        // each line item in the cart requires a unique identifier
1110
-        return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1111
-    }
1112
-
1113
-
1114
-    /**
1115
-     * @return bool
1116
-     * @throws EE_Error
1117
-     * @throws InvalidArgumentException
1118
-     * @throws InvalidDataTypeException
1119
-     * @throws InvalidInterfaceException
1120
-     * @throws ReflectionException
1121
-     */
1122
-    public function isGlobalTax(): bool
1123
-    {
1124
-        return $this->type() === EEM_Line_Item::type_tax;
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * @return bool
1130
-     * @throws EE_Error
1131
-     * @throws InvalidArgumentException
1132
-     * @throws InvalidDataTypeException
1133
-     * @throws InvalidInterfaceException
1134
-     * @throws ReflectionException
1135
-     */
1136
-    public function isSubTax(): bool
1137
-    {
1138
-        return $this->type() === EEM_Line_Item::type_sub_tax;
1139
-    }
1140
-
1141
-
1142
-    /**
1143
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1144
-     *
1145
-     * @return array
1146
-     * @throws EE_Error
1147
-     * @throws InvalidArgumentException
1148
-     * @throws InvalidDataTypeException
1149
-     * @throws InvalidInterfaceException
1150
-     * @throws ReflectionException
1151
-     */
1152
-    public function getSubTaxes(): array
1153
-    {
1154
-        if (! $this->is_line_item()) {
1155
-            return [];
1156
-        }
1157
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     * returns true if this is a line item with a direct descendent of the type sub-tax
1163
-     *
1164
-     * @return bool
1165
-     * @throws EE_Error
1166
-     * @throws InvalidArgumentException
1167
-     * @throws InvalidDataTypeException
1168
-     * @throws InvalidInterfaceException
1169
-     * @throws ReflectionException
1170
-     */
1171
-    public function hasSubTaxes(): bool
1172
-    {
1173
-        if (! $this->is_line_item()) {
1174
-            return false;
1175
-        }
1176
-        $sub_taxes = $this->getSubTaxes();
1177
-        return ! empty($sub_taxes);
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * @return bool
1183
-     * @throws EE_Error
1184
-     * @throws ReflectionException
1185
-     * @deprecated   5.0.0.p
1186
-     */
1187
-    public function is_tax(): bool
1188
-    {
1189
-        return $this->isGlobalTax();
1190
-    }
1191
-
1192
-
1193
-    /**
1194
-     * @return bool
1195
-     * @throws EE_Error
1196
-     * @throws InvalidArgumentException
1197
-     * @throws InvalidDataTypeException
1198
-     * @throws InvalidInterfaceException
1199
-     * @throws ReflectionException
1200
-     */
1201
-    public function is_tax_sub_total()
1202
-    {
1203
-        return $this->type() === EEM_Line_Item::type_tax_sub_total;
1204
-    }
1205
-
1206
-
1207
-    /**
1208
-     * @return bool
1209
-     * @throws EE_Error
1210
-     * @throws InvalidArgumentException
1211
-     * @throws InvalidDataTypeException
1212
-     * @throws InvalidInterfaceException
1213
-     * @throws ReflectionException
1214
-     */
1215
-    public function is_line_item()
1216
-    {
1217
-        return $this->type() === EEM_Line_Item::type_line_item;
1218
-    }
1219
-
1220
-
1221
-    /**
1222
-     * @return bool
1223
-     * @throws EE_Error
1224
-     * @throws InvalidArgumentException
1225
-     * @throws InvalidDataTypeException
1226
-     * @throws InvalidInterfaceException
1227
-     * @throws ReflectionException
1228
-     */
1229
-    public function is_sub_line_item()
1230
-    {
1231
-        return $this->type() === EEM_Line_Item::type_sub_line_item;
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     * @return bool
1237
-     * @throws EE_Error
1238
-     * @throws InvalidArgumentException
1239
-     * @throws InvalidDataTypeException
1240
-     * @throws InvalidInterfaceException
1241
-     * @throws ReflectionException
1242
-     */
1243
-    public function is_sub_total()
1244
-    {
1245
-        return $this->type() === EEM_Line_Item::type_sub_total;
1246
-    }
1247
-
1248
-
1249
-    /**
1250
-     * Whether or not this line item is a cancellation line item
1251
-     *
1252
-     * @return boolean
1253
-     * @throws EE_Error
1254
-     * @throws InvalidArgumentException
1255
-     * @throws InvalidDataTypeException
1256
-     * @throws InvalidInterfaceException
1257
-     * @throws ReflectionException
1258
-     */
1259
-    public function is_cancellation()
1260
-    {
1261
-        return EEM_Line_Item::type_cancellation === $this->type();
1262
-    }
1263
-
1264
-
1265
-    /**
1266
-     * @return bool
1267
-     * @throws EE_Error
1268
-     * @throws InvalidArgumentException
1269
-     * @throws InvalidDataTypeException
1270
-     * @throws InvalidInterfaceException
1271
-     * @throws ReflectionException
1272
-     */
1273
-    public function is_total()
1274
-    {
1275
-        return $this->type() === EEM_Line_Item::type_total;
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * @return bool
1281
-     * @throws EE_Error
1282
-     * @throws InvalidArgumentException
1283
-     * @throws InvalidDataTypeException
1284
-     * @throws InvalidInterfaceException
1285
-     * @throws ReflectionException
1286
-     */
1287
-    public function is_cancelled()
1288
-    {
1289
-        return $this->type() === EEM_Line_Item::type_cancellation;
1290
-    }
1291
-
1292
-
1293
-    /**
1294
-     * @return string like '2, 004.00', formatted according to the localized currency
1295
-     * @throws EE_Error
1296
-     * @throws ReflectionException
1297
-     */
1298
-    public function unit_price_no_code(): string
1299
-    {
1300
-        return $this->prettyUnitPrice();
1301
-    }
1302
-
1303
-
1304
-    /**
1305
-     * @return string like '2, 004.00', formatted according to the localized currency
1306
-     * @throws EE_Error
1307
-     * @throws ReflectionException
1308
-     * @since 5.0.0.p
1309
-     */
1310
-    public function prettyUnitPrice(): string
1311
-    {
1312
-        return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1313
-    }
1314
-
1315
-
1316
-    /**
1317
-     * @return string like '2, 004.00', formatted according to the localized currency
1318
-     * @throws EE_Error
1319
-     * @throws ReflectionException
1320
-     */
1321
-    public function total_no_code(): string
1322
-    {
1323
-        return $this->prettyTotal();
1324
-    }
1325
-
1326
-
1327
-    /**
1328
-     * @return string like '2, 004.00', formatted according to the localized currency
1329
-     * @throws EE_Error
1330
-     * @throws ReflectionException
1331
-     * @since 5.0.0.p
1332
-     */
1333
-    public function prettyTotal(): string
1334
-    {
1335
-        return $this->get_pretty('LIN_total', 'no_currency_code');
1336
-    }
1337
-
1338
-
1339
-    /**
1340
-     * Gets the final total on this item, taking taxes into account.
1341
-     * Has the side-effect of setting the sub-total as it was just calculated.
1342
-     * If this is used on a grand-total line item, also updates the transaction's
1343
-     * TXN_total (provided this line item is allowed to persist, otherwise we don't
1344
-     * want to change a persistable transaction with info from a non-persistent line item)
1345
-     *
1346
-     * @param bool $update_txn_status
1347
-     * @return float
1348
-     * @throws EE_Error
1349
-     * @throws InvalidArgumentException
1350
-     * @throws InvalidDataTypeException
1351
-     * @throws InvalidInterfaceException
1352
-     * @throws ReflectionException
1353
-     * @throws RuntimeException
1354
-     */
1355
-    public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1356
-    {
1357
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1358
-        return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1359
-    }
1360
-
1361
-
1362
-    /**
1363
-     * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1364
-     * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1365
-     * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1366
-     * when this is called on the grand total
1367
-     *
1368
-     * @return float
1369
-     * @throws EE_Error
1370
-     * @throws InvalidArgumentException
1371
-     * @throws InvalidDataTypeException
1372
-     * @throws InvalidInterfaceException
1373
-     * @throws ReflectionException
1374
-     */
1375
-    public function recalculate_pre_tax_total(): float
1376
-    {
1377
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1378
-        [$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1379
-        return (float) $total;
1380
-    }
1381
-
1382
-
1383
-    /**
1384
-     * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1385
-     * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1386
-     * and tax sub-total if already in the DB
1387
-     *
1388
-     * @return float
1389
-     * @throws EE_Error
1390
-     * @throws InvalidArgumentException
1391
-     * @throws InvalidDataTypeException
1392
-     * @throws InvalidInterfaceException
1393
-     * @throws ReflectionException
1394
-     */
1395
-    public function recalculate_taxes_and_tax_total(): float
1396
-    {
1397
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1398
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1399
-    }
1400
-
1401
-
1402
-    /**
1403
-     * Gets the total tax on this line item. Assumes taxes have already been calculated using
1404
-     * recalculate_taxes_and_total
1405
-     *
1406
-     * @return float
1407
-     * @throws EE_Error
1408
-     * @throws InvalidArgumentException
1409
-     * @throws InvalidDataTypeException
1410
-     * @throws InvalidInterfaceException
1411
-     * @throws ReflectionException
1412
-     */
1413
-    public function get_total_tax()
1414
-    {
1415
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1416
-        return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1417
-    }
1418
-
1419
-
1420
-    /**
1421
-     * Gets the total for all the items purchased only
1422
-     *
1423
-     * @return float
1424
-     * @throws EE_Error
1425
-     * @throws InvalidArgumentException
1426
-     * @throws InvalidDataTypeException
1427
-     * @throws InvalidInterfaceException
1428
-     * @throws ReflectionException
1429
-     */
1430
-    public function get_items_total()
1431
-    {
1432
-        // by default, let's make sure we're consistent with the existing line item
1433
-        if ($this->is_total()) {
1434
-            return $this->pretaxTotal();
1435
-        }
1436
-        $total = 0;
1437
-        foreach ($this->get_items() as $item) {
1438
-            if ($item instanceof EE_Line_Item) {
1439
-                $total += $item->pretaxTotal();
1440
-            }
1441
-        }
1442
-        return $total;
1443
-    }
1444
-
1445
-
1446
-    /**
1447
-     * Gets all the descendants (ie, children or children of children etc) that
1448
-     * are of the type 'tax'
1449
-     *
1450
-     * @return EE_Line_Item[]
1451
-     * @throws EE_Error
1452
-     */
1453
-    public function tax_descendants()
1454
-    {
1455
-        return EEH_Line_Item::get_tax_descendants($this);
1456
-    }
1457
-
1458
-
1459
-    /**
1460
-     * Gets all the real items purchased which are children of this item
1461
-     *
1462
-     * @return EE_Line_Item[]
1463
-     * @throws EE_Error
1464
-     */
1465
-    public function get_items()
1466
-    {
1467
-        return EEH_Line_Item::get_line_item_descendants($this);
1468
-    }
1469
-
1470
-
1471
-    /**
1472
-     * Returns the amount taxable among this line item's children (or if it has no children,
1473
-     * how much of it is taxable). Does not recalculate totals or subtotals.
1474
-     * If the taxable total is negative, (eg, if none of the tickets were taxable,
1475
-     * but there is a "Taxable" discount), returns 0.
1476
-     *
1477
-     * @return float
1478
-     * @throws EE_Error
1479
-     * @throws InvalidArgumentException
1480
-     * @throws InvalidDataTypeException
1481
-     * @throws InvalidInterfaceException
1482
-     * @throws ReflectionException
1483
-     */
1484
-    public function taxable_total(): float
1485
-    {
1486
-        return $this->calculator->taxableAmountForGlobalTaxes($this);
1487
-    }
1488
-
1489
-
1490
-    /**
1491
-     * Gets the transaction for this line item
1492
-     *
1493
-     * @return EE_Base_Class|EE_Transaction
1494
-     * @throws EE_Error
1495
-     * @throws InvalidArgumentException
1496
-     * @throws InvalidDataTypeException
1497
-     * @throws InvalidInterfaceException
1498
-     * @throws ReflectionException
1499
-     */
1500
-    public function transaction()
1501
-    {
1502
-        return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1503
-    }
1504
-
1505
-
1506
-    /**
1507
-     * Saves this line item to the DB, and recursively saves its descendants.
1508
-     * Because there currently is no proper parent-child relation on the model,
1509
-     * save_this_and_cached() will NOT save the descendants.
1510
-     * Also sets the transaction on this line item and all its descendants before saving
1511
-     *
1512
-     * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1513
-     * @return int count of items saved
1514
-     * @throws EE_Error
1515
-     * @throws InvalidArgumentException
1516
-     * @throws InvalidDataTypeException
1517
-     * @throws InvalidInterfaceException
1518
-     * @throws ReflectionException
1519
-     */
1520
-    public function save_this_and_descendants_to_txn($txn_id = null)
1521
-    {
1522
-        $count = 0;
1523
-        if (! $txn_id) {
1524
-            $txn_id = $this->TXN_ID();
1525
-        }
1526
-        $this->set_TXN_ID($txn_id);
1527
-        $children = $this->children();
1528
-        $count += $this->save()
1529
-            ? 1
1530
-            : 0;
1531
-        foreach ($children as $child_line_item) {
1532
-            if ($child_line_item instanceof EE_Line_Item) {
1533
-                $child_line_item->set_parent_ID($this->ID());
1534
-                $count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1535
-            }
1536
-        }
1537
-        return $count;
1538
-    }
1539
-
1540
-
1541
-    /**
1542
-     * Saves this line item to the DB, and recursively saves its descendants.
1543
-     *
1544
-     * @return int count of items saved
1545
-     * @throws EE_Error
1546
-     * @throws InvalidArgumentException
1547
-     * @throws InvalidDataTypeException
1548
-     * @throws InvalidInterfaceException
1549
-     * @throws ReflectionException
1550
-     */
1551
-    public function save_this_and_descendants()
1552
-    {
1553
-        $count = 0;
1554
-        $children = $this->children();
1555
-        $count += $this->save()
1556
-            ? 1
1557
-            : 0;
1558
-        foreach ($children as $child_line_item) {
1559
-            if ($child_line_item instanceof EE_Line_Item) {
1560
-                $child_line_item->set_parent_ID($this->ID());
1561
-                $count += $child_line_item->save_this_and_descendants();
1562
-            }
1563
-        }
1564
-        return $count;
1565
-    }
1566
-
1567
-
1568
-    /**
1569
-     * returns the cancellation line item if this item was cancelled
1570
-     *
1571
-     * @return EE_Line_Item[]
1572
-     * @throws InvalidArgumentException
1573
-     * @throws InvalidInterfaceException
1574
-     * @throws InvalidDataTypeException
1575
-     * @throws ReflectionException
1576
-     * @throws EE_Error
1577
-     */
1578
-    public function get_cancellations()
1579
-    {
1580
-        return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1581
-    }
1582
-
1583
-
1584
-    /**
1585
-     * If this item has an ID, then this saves it again to update the db
1586
-     *
1587
-     * @return int count of items saved
1588
-     * @throws EE_Error
1589
-     * @throws InvalidArgumentException
1590
-     * @throws InvalidDataTypeException
1591
-     * @throws InvalidInterfaceException
1592
-     * @throws ReflectionException
1593
-     */
1594
-    public function maybe_save()
1595
-    {
1596
-        if ($this->ID()) {
1597
-            return $this->save();
1598
-        }
1599
-        return false;
1600
-    }
1601
-
1602
-
1603
-    /**
1604
-     * clears the cached children and parent from the line item
1605
-     *
1606
-     * @return void
1607
-     */
1608
-    public function clear_related_line_item_cache()
1609
-    {
1610
-        $this->_children = array();
1611
-        $this->_parent = null;
1612
-    }
1613
-
1614
-
1615
-    /**
1616
-     * @param bool $raw
1617
-     * @return int
1618
-     * @throws EE_Error
1619
-     * @throws InvalidArgumentException
1620
-     * @throws InvalidDataTypeException
1621
-     * @throws InvalidInterfaceException
1622
-     * @throws ReflectionException
1623
-     */
1624
-    public function timestamp($raw = false)
1625
-    {
1626
-        return $raw
1627
-            ? $this->get_raw('LIN_timestamp')
1628
-            : $this->get('LIN_timestamp');
1629
-    }
1630
-
1631
-
1632
-
1633
-
1634
-    /************************* DEPRECATED *************************/
1635
-    /**
1636
-     * @deprecated 4.6.0
1637
-     * @param string $type one of the constants on EEM_Line_Item
1638
-     * @return EE_Line_Item[]
1639
-     * @throws EE_Error
1640
-     */
1641
-    protected function _get_descendants_of_type($type)
1642
-    {
1643
-        EE_Error::doing_it_wrong(
1644
-            'EE_Line_Item::_get_descendants_of_type()',
1645
-            sprintf(
1646
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1647
-                'EEH_Line_Item::get_descendants_of_type()'
1648
-            ),
1649
-            '4.6.0'
1650
-        );
1651
-        return EEH_Line_Item::get_descendants_of_type($this, $type);
1652
-    }
1653
-
1654
-
1655
-    /**
1656
-     * @deprecated 4.6.0
1657
-     * @param string $type like one of the EEM_Line_Item::type_*
1658
-     * @return EE_Line_Item
1659
-     * @throws EE_Error
1660
-     * @throws InvalidArgumentException
1661
-     * @throws InvalidDataTypeException
1662
-     * @throws InvalidInterfaceException
1663
-     * @throws ReflectionException
1664
-     */
1665
-    public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1666
-    {
1667
-        EE_Error::doing_it_wrong(
1668
-            'EE_Line_Item::get_nearest_descendant_of_type()',
1669
-            sprintf(
1670
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1671
-                'EEH_Line_Item::get_nearest_descendant_of_type()'
1672
-            ),
1673
-            '4.6.0'
1674
-        );
1675
-        return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1676
-    }
18
+	/**
19
+	 * for children line items (currently not a normal relation)
20
+	 *
21
+	 * @type EE_Line_Item[]
22
+	 */
23
+	protected $_children = array();
24
+
25
+	/**
26
+	 * for the parent line item
27
+	 *
28
+	 * @var EE_Line_Item
29
+	 */
30
+	protected $_parent;
31
+
32
+	/**
33
+	 * @var LineItemCalculator
34
+	 */
35
+	protected $calculator;
36
+
37
+
38
+	/**
39
+	 * @param array  $props_n_values          incoming values
40
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
41
+	 *                                        used.)
42
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
43
+	 *                                        date_format and the second value is the time format
44
+	 * @return EE_Line_Item
45
+	 * @throws EE_Error
46
+	 * @throws InvalidArgumentException
47
+	 * @throws InvalidDataTypeException
48
+	 * @throws InvalidInterfaceException
49
+	 * @throws ReflectionException
50
+	 */
51
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
+	{
53
+		$has_object = parent::_check_for_object(
54
+			$props_n_values,
55
+			__CLASS__,
56
+			$timezone,
57
+			$date_formats
58
+		);
59
+		return $has_object
60
+			? $has_object
61
+			: new self($props_n_values, false, $timezone);
62
+	}
63
+
64
+
65
+	/**
66
+	 * @param array  $props_n_values  incoming values from the database
67
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
68
+	 *                                the website will be used.
69
+	 * @return EE_Line_Item
70
+	 * @throws EE_Error
71
+	 * @throws InvalidArgumentException
72
+	 * @throws InvalidDataTypeException
73
+	 * @throws InvalidInterfaceException
74
+	 * @throws ReflectionException
75
+	 */
76
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
77
+	{
78
+		return new self($props_n_values, true, $timezone);
79
+	}
80
+
81
+
82
+	/**
83
+	 * Adds some defaults if they're not specified
84
+	 *
85
+	 * @param array  $fieldValues
86
+	 * @param bool   $bydb
87
+	 * @param string $timezone
88
+	 * @throws EE_Error
89
+	 * @throws InvalidArgumentException
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 * @throws ReflectionException
93
+	 */
94
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '')
95
+	{
96
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
97
+		parent::__construct($fieldValues, $bydb, $timezone);
98
+		if (! $this->get('LIN_code')) {
99
+			$this->set_code($this->generate_code());
100
+		}
101
+	}
102
+
103
+
104
+	public function __wakeup()
105
+	{
106
+		$this->calculator = LoaderFactory::getShared(LineItemCalculator::class);
107
+		parent::__wakeup();
108
+	}
109
+
110
+
111
+	/**
112
+	 * Gets ID
113
+	 *
114
+	 * @return int
115
+	 * @throws EE_Error
116
+	 * @throws InvalidArgumentException
117
+	 * @throws InvalidDataTypeException
118
+	 * @throws InvalidInterfaceException
119
+	 * @throws ReflectionException
120
+	 */
121
+	public function ID()
122
+	{
123
+		return $this->get('LIN_ID');
124
+	}
125
+
126
+
127
+	/**
128
+	 * Gets TXN_ID
129
+	 *
130
+	 * @return int
131
+	 * @throws EE_Error
132
+	 * @throws InvalidArgumentException
133
+	 * @throws InvalidDataTypeException
134
+	 * @throws InvalidInterfaceException
135
+	 * @throws ReflectionException
136
+	 */
137
+	public function TXN_ID()
138
+	{
139
+		return $this->get('TXN_ID');
140
+	}
141
+
142
+
143
+	/**
144
+	 * Sets TXN_ID
145
+	 *
146
+	 * @param int $TXN_ID
147
+	 * @throws EE_Error
148
+	 * @throws InvalidArgumentException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws InvalidInterfaceException
151
+	 * @throws ReflectionException
152
+	 */
153
+	public function set_TXN_ID($TXN_ID)
154
+	{
155
+		$this->set('TXN_ID', $TXN_ID);
156
+	}
157
+
158
+
159
+	/**
160
+	 * Gets name
161
+	 *
162
+	 * @return string
163
+	 * @throws EE_Error
164
+	 * @throws InvalidArgumentException
165
+	 * @throws InvalidDataTypeException
166
+	 * @throws InvalidInterfaceException
167
+	 * @throws ReflectionException
168
+	 */
169
+	public function name()
170
+	{
171
+		$name = $this->get('LIN_name');
172
+		if (! $name) {
173
+			$name = ucwords(str_replace('-', ' ', $this->type()));
174
+		}
175
+		return $name;
176
+	}
177
+
178
+
179
+	/**
180
+	 * Sets name
181
+	 *
182
+	 * @param string $name
183
+	 * @throws EE_Error
184
+	 * @throws InvalidArgumentException
185
+	 * @throws InvalidDataTypeException
186
+	 * @throws InvalidInterfaceException
187
+	 * @throws ReflectionException
188
+	 */
189
+	public function set_name($name)
190
+	{
191
+		$this->set('LIN_name', $name);
192
+	}
193
+
194
+
195
+	/**
196
+	 * Gets desc
197
+	 *
198
+	 * @return string
199
+	 * @throws EE_Error
200
+	 * @throws InvalidArgumentException
201
+	 * @throws InvalidDataTypeException
202
+	 * @throws InvalidInterfaceException
203
+	 * @throws ReflectionException
204
+	 */
205
+	public function desc()
206
+	{
207
+		return $this->get('LIN_desc');
208
+	}
209
+
210
+
211
+	/**
212
+	 * Sets desc
213
+	 *
214
+	 * @param string $desc
215
+	 * @throws EE_Error
216
+	 * @throws InvalidArgumentException
217
+	 * @throws InvalidDataTypeException
218
+	 * @throws InvalidInterfaceException
219
+	 * @throws ReflectionException
220
+	 */
221
+	public function set_desc($desc)
222
+	{
223
+		$this->set('LIN_desc', $desc);
224
+	}
225
+
226
+
227
+	/**
228
+	 * Gets quantity
229
+	 *
230
+	 * @return int
231
+	 * @throws EE_Error
232
+	 * @throws InvalidArgumentException
233
+	 * @throws InvalidDataTypeException
234
+	 * @throws InvalidInterfaceException
235
+	 * @throws ReflectionException
236
+	 */
237
+	public function quantity(): int
238
+	{
239
+		return (int) $this->get('LIN_quantity');
240
+	}
241
+
242
+
243
+	/**
244
+	 * Sets quantity
245
+	 *
246
+	 * @param int $quantity
247
+	 * @throws EE_Error
248
+	 * @throws InvalidArgumentException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws InvalidInterfaceException
251
+	 * @throws ReflectionException
252
+	 */
253
+	public function set_quantity($quantity)
254
+	{
255
+		$this->set('LIN_quantity', max($quantity, 0));
256
+	}
257
+
258
+
259
+	/**
260
+	 * Gets item_id
261
+	 *
262
+	 * @return int
263
+	 * @throws EE_Error
264
+	 * @throws InvalidArgumentException
265
+	 * @throws InvalidDataTypeException
266
+	 * @throws InvalidInterfaceException
267
+	 * @throws ReflectionException
268
+	 */
269
+	public function OBJ_ID()
270
+	{
271
+		return $this->get('OBJ_ID');
272
+	}
273
+
274
+
275
+	/**
276
+	 * Sets item_id
277
+	 *
278
+	 * @param int $item_id
279
+	 * @throws EE_Error
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidDataTypeException
282
+	 * @throws InvalidInterfaceException
283
+	 * @throws ReflectionException
284
+	 */
285
+	public function set_OBJ_ID($item_id)
286
+	{
287
+		$this->set('OBJ_ID', $item_id);
288
+	}
289
+
290
+
291
+	/**
292
+	 * Gets item_type
293
+	 *
294
+	 * @return string
295
+	 * @throws EE_Error
296
+	 * @throws InvalidArgumentException
297
+	 * @throws InvalidDataTypeException
298
+	 * @throws InvalidInterfaceException
299
+	 * @throws ReflectionException
300
+	 */
301
+	public function OBJ_type()
302
+	{
303
+		return $this->get('OBJ_type');
304
+	}
305
+
306
+
307
+	/**
308
+	 * Gets item_type
309
+	 *
310
+	 * @return string
311
+	 * @throws EE_Error
312
+	 * @throws InvalidArgumentException
313
+	 * @throws InvalidDataTypeException
314
+	 * @throws InvalidInterfaceException
315
+	 * @throws ReflectionException
316
+	 */
317
+	public function OBJ_type_i18n()
318
+	{
319
+		$obj_type = $this->OBJ_type();
320
+		switch ($obj_type) {
321
+			case EEM_Line_Item::OBJ_TYPE_EVENT:
322
+				$obj_type = esc_html__('Event', 'event_espresso');
323
+				break;
324
+			case EEM_Line_Item::OBJ_TYPE_PRICE:
325
+				$obj_type = esc_html__('Price', 'event_espresso');
326
+				break;
327
+			case EEM_Line_Item::OBJ_TYPE_PROMOTION:
328
+				$obj_type = esc_html__('Promotion', 'event_espresso');
329
+				break;
330
+			case EEM_Line_Item::OBJ_TYPE_TICKET:
331
+				$obj_type = esc_html__('Ticket', 'event_espresso');
332
+				break;
333
+			case EEM_Line_Item::OBJ_TYPE_TRANSACTION:
334
+				$obj_type = esc_html__('Transaction', 'event_espresso');
335
+				break;
336
+		}
337
+		return apply_filters('FHEE__EE_Line_Item__OBJ_type_i18n', $obj_type, $this);
338
+	}
339
+
340
+
341
+	/**
342
+	 * Sets item_type
343
+	 *
344
+	 * @param string $OBJ_type
345
+	 * @throws EE_Error
346
+	 * @throws InvalidArgumentException
347
+	 * @throws InvalidDataTypeException
348
+	 * @throws InvalidInterfaceException
349
+	 * @throws ReflectionException
350
+	 */
351
+	public function set_OBJ_type($OBJ_type)
352
+	{
353
+		$this->set('OBJ_type', $OBJ_type);
354
+	}
355
+
356
+
357
+	/**
358
+	 * Gets unit_price
359
+	 *
360
+	 * @return float
361
+	 * @throws EE_Error
362
+	 * @throws InvalidArgumentException
363
+	 * @throws InvalidDataTypeException
364
+	 * @throws InvalidInterfaceException
365
+	 * @throws ReflectionException
366
+	 */
367
+	public function unit_price()
368
+	{
369
+		return $this->get('LIN_unit_price');
370
+	}
371
+
372
+
373
+	/**
374
+	 * Sets unit_price
375
+	 *
376
+	 * @param float $unit_price
377
+	 * @throws EE_Error
378
+	 * @throws InvalidArgumentException
379
+	 * @throws InvalidDataTypeException
380
+	 * @throws InvalidInterfaceException
381
+	 * @throws ReflectionException
382
+	 */
383
+	public function set_unit_price($unit_price)
384
+	{
385
+		$this->set('LIN_unit_price', $unit_price);
386
+	}
387
+
388
+
389
+	/**
390
+	 * Checks if this item is a percentage modifier or not
391
+	 *
392
+	 * @return boolean
393
+	 * @throws EE_Error
394
+	 * @throws InvalidArgumentException
395
+	 * @throws InvalidDataTypeException
396
+	 * @throws InvalidInterfaceException
397
+	 * @throws ReflectionException
398
+	 */
399
+	public function is_percent()
400
+	{
401
+		if ($this->is_tax_sub_total()) {
402
+			// tax subtotals HAVE a percent on them, that percentage only applies
403
+			// to taxable items, so its' an exception. Treat it like a flat line item
404
+			return false;
405
+		}
406
+		$unit_price = abs($this->get('LIN_unit_price'));
407
+		$percent = abs($this->get('LIN_percent'));
408
+		if ($unit_price < .001 && $percent) {
409
+			return true;
410
+		}
411
+		if ($unit_price >= .001 && ! $percent) {
412
+			return false;
413
+		}
414
+		if ($unit_price >= .001 && $percent) {
415
+			throw new EE_Error(
416
+				sprintf(
417
+					esc_html__(
418
+						'A Line Item can not have a unit price of (%s) AND a percent (%s)!',
419
+						'event_espresso'
420
+					),
421
+					$unit_price,
422
+					$percent
423
+				)
424
+			);
425
+		}
426
+		// if they're both 0, assume its not a percent item
427
+		return false;
428
+	}
429
+
430
+
431
+	/**
432
+	 * Gets percent (between 100-.001)
433
+	 *
434
+	 * @return float
435
+	 * @throws EE_Error
436
+	 * @throws InvalidArgumentException
437
+	 * @throws InvalidDataTypeException
438
+	 * @throws InvalidInterfaceException
439
+	 * @throws ReflectionException
440
+	 */
441
+	public function percent()
442
+	{
443
+		return $this->get('LIN_percent');
444
+	}
445
+
446
+
447
+	/**
448
+	 * @return string
449
+	 * @throws EE_Error
450
+	 * @throws ReflectionException
451
+	 * @since 5.0.0.p
452
+	 */
453
+	public function prettyPercent(): string
454
+	{
455
+		return $this->get_pretty('LIN_percent');
456
+	}
457
+
458
+
459
+	/**
460
+	 * Sets percent (between 100-0.01)
461
+	 *
462
+	 * @param float $percent
463
+	 * @throws EE_Error
464
+	 * @throws InvalidArgumentException
465
+	 * @throws InvalidDataTypeException
466
+	 * @throws InvalidInterfaceException
467
+	 * @throws ReflectionException
468
+	 */
469
+	public function set_percent($percent)
470
+	{
471
+		$this->set('LIN_percent', $percent);
472
+	}
473
+
474
+
475
+	/**
476
+	 * Gets total
477
+	 *
478
+	 * @return float
479
+	 * @throws EE_Error
480
+	 * @throws InvalidArgumentException
481
+	 * @throws InvalidDataTypeException
482
+	 * @throws InvalidInterfaceException
483
+	 * @throws ReflectionException
484
+	 */
485
+	public function pretaxTotal(): float
486
+	{
487
+		return (float) $this->get('LIN_pretax');
488
+	}
489
+
490
+
491
+	/**
492
+	 * Sets total
493
+	 *
494
+	 * @param float $pretax_total
495
+	 * @throws EE_Error
496
+	 * @throws InvalidArgumentException
497
+	 * @throws InvalidDataTypeException
498
+	 * @throws InvalidInterfaceException
499
+	 * @throws ReflectionException
500
+	 */
501
+	public function setPretaxTotal(float $pretax_total)
502
+	{
503
+		$this->set('LIN_pretax', $pretax_total);
504
+	}
505
+
506
+
507
+	/**
508
+	 * @return float
509
+	 * @throws EE_Error
510
+	 * @throws ReflectionException
511
+	 * @since  5.0.0.p
512
+	 */
513
+	public function totalWithTax(): float
514
+	{
515
+		return (float) $this->get('LIN_total');
516
+	}
517
+
518
+
519
+	/**
520
+	 * Sets total
521
+	 *
522
+	 * @param float $total
523
+	 * @throws EE_Error
524
+	 * @throws ReflectionException
525
+	 * @since  5.0.0.p
526
+	 */
527
+	public function setTotalWithTax(float $total)
528
+	{
529
+		$this->set('LIN_total', $total);
530
+	}
531
+
532
+
533
+	/**
534
+	 * Gets total
535
+	 *
536
+	 * @return float
537
+	 * @throws EE_Error
538
+	 * @throws ReflectionException
539
+	 * @deprecatd 5.0.0.p
540
+	 */
541
+	public function total(): float
542
+	{
543
+		return $this->totalWithTax();
544
+	}
545
+
546
+
547
+	/**
548
+	 * Sets total
549
+	 *
550
+	 * @param float $total
551
+	 * @throws EE_Error
552
+	 * @throws ReflectionException
553
+	 * @deprecatd 5.0.0.p
554
+	 */
555
+	public function set_total($total)
556
+	{
557
+		$this->setTotalWithTax($total);
558
+	}
559
+
560
+
561
+	/**
562
+	 * Gets order
563
+	 *
564
+	 * @return int
565
+	 * @throws EE_Error
566
+	 * @throws InvalidArgumentException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws InvalidInterfaceException
569
+	 * @throws ReflectionException
570
+	 */
571
+	public function order()
572
+	{
573
+		return $this->get('LIN_order');
574
+	}
575
+
576
+
577
+	/**
578
+	 * Sets order
579
+	 *
580
+	 * @param int $order
581
+	 * @throws EE_Error
582
+	 * @throws InvalidArgumentException
583
+	 * @throws InvalidDataTypeException
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws ReflectionException
586
+	 */
587
+	public function set_order($order)
588
+	{
589
+		$this->set('LIN_order', $order);
590
+	}
591
+
592
+
593
+	/**
594
+	 * Gets parent
595
+	 *
596
+	 * @return int
597
+	 * @throws EE_Error
598
+	 * @throws InvalidArgumentException
599
+	 * @throws InvalidDataTypeException
600
+	 * @throws InvalidInterfaceException
601
+	 * @throws ReflectionException
602
+	 */
603
+	public function parent_ID()
604
+	{
605
+		return $this->get('LIN_parent');
606
+	}
607
+
608
+
609
+	/**
610
+	 * Sets parent
611
+	 *
612
+	 * @param int $parent
613
+	 * @throws EE_Error
614
+	 * @throws InvalidArgumentException
615
+	 * @throws InvalidDataTypeException
616
+	 * @throws InvalidInterfaceException
617
+	 * @throws ReflectionException
618
+	 */
619
+	public function set_parent_ID($parent)
620
+	{
621
+		$this->set('LIN_parent', $parent);
622
+	}
623
+
624
+
625
+	/**
626
+	 * Gets type
627
+	 *
628
+	 * @return string
629
+	 * @throws EE_Error
630
+	 * @throws InvalidArgumentException
631
+	 * @throws InvalidDataTypeException
632
+	 * @throws InvalidInterfaceException
633
+	 * @throws ReflectionException
634
+	 */
635
+	public function type()
636
+	{
637
+		return $this->get('LIN_type');
638
+	}
639
+
640
+
641
+	/**
642
+	 * Sets type
643
+	 *
644
+	 * @param string $type
645
+	 * @throws EE_Error
646
+	 * @throws InvalidArgumentException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws InvalidInterfaceException
649
+	 * @throws ReflectionException
650
+	 */
651
+	public function set_type($type)
652
+	{
653
+		$this->set('LIN_type', $type);
654
+	}
655
+
656
+
657
+	/**
658
+	 * Gets the line item of which this item is a composite. Eg, if this is a subtotal, the parent might be a total\
659
+	 * If this line item is saved to the DB, fetches the parent from the DB. However, if this line item isn't in the DB
660
+	 * it uses its cached reference to its parent line item (which would have been set by `EE_Line_Item::set_parent()`
661
+	 * or indirectly by `EE_Line_item::add_child_line_item()`)
662
+	 *
663
+	 * @return EE_Base_Class|EE_Line_Item
664
+	 * @throws EE_Error
665
+	 * @throws InvalidArgumentException
666
+	 * @throws InvalidDataTypeException
667
+	 * @throws InvalidInterfaceException
668
+	 * @throws ReflectionException
669
+	 */
670
+	public function parent()
671
+	{
672
+		return $this->ID()
673
+			? $this->get_model()->get_one_by_ID($this->parent_ID())
674
+			: $this->_parent;
675
+	}
676
+
677
+
678
+	/**
679
+	 * Gets ALL the children of this line item (ie, all the parts that contribute towards this total).
680
+	 *
681
+	 * @return EE_Line_Item[]
682
+	 * @throws EE_Error
683
+	 * @throws InvalidArgumentException
684
+	 * @throws InvalidDataTypeException
685
+	 * @throws InvalidInterfaceException
686
+	 * @throws ReflectionException
687
+	 */
688
+	public function children(array $query_params = []): array
689
+	{
690
+		if ($this->ID()) {
691
+			// ensure where params are an array
692
+			$query_params[0] = $query_params[0] ?? [];
693
+			// add defaults for line item parent and orderby
694
+			$query_params[0] += ['LIN_parent' => $this->ID()];
695
+			$query_params += ['order_by' => ['LIN_order' => 'ASC']];
696
+			return $this->get_model()->get_all($query_params);
697
+		}
698
+		if (! is_array($this->_children)) {
699
+			$this->_children = array();
700
+		}
701
+		return $this->_children;
702
+	}
703
+
704
+
705
+	/**
706
+	 * Gets code
707
+	 *
708
+	 * @return string
709
+	 * @throws EE_Error
710
+	 * @throws InvalidArgumentException
711
+	 * @throws InvalidDataTypeException
712
+	 * @throws InvalidInterfaceException
713
+	 * @throws ReflectionException
714
+	 */
715
+	public function code()
716
+	{
717
+		return $this->get('LIN_code');
718
+	}
719
+
720
+
721
+	/**
722
+	 * Sets code
723
+	 *
724
+	 * @param string $code
725
+	 * @throws EE_Error
726
+	 * @throws InvalidArgumentException
727
+	 * @throws InvalidDataTypeException
728
+	 * @throws InvalidInterfaceException
729
+	 * @throws ReflectionException
730
+	 */
731
+	public function set_code($code)
732
+	{
733
+		$this->set('LIN_code', $code);
734
+	}
735
+
736
+
737
+	/**
738
+	 * Gets is_taxable
739
+	 *
740
+	 * @return boolean
741
+	 * @throws EE_Error
742
+	 * @throws InvalidArgumentException
743
+	 * @throws InvalidDataTypeException
744
+	 * @throws InvalidInterfaceException
745
+	 * @throws ReflectionException
746
+	 */
747
+	public function is_taxable()
748
+	{
749
+		return $this->get('LIN_is_taxable');
750
+	}
751
+
752
+
753
+	/**
754
+	 * Sets is_taxable
755
+	 *
756
+	 * @param boolean $is_taxable
757
+	 * @throws EE_Error
758
+	 * @throws InvalidArgumentException
759
+	 * @throws InvalidDataTypeException
760
+	 * @throws InvalidInterfaceException
761
+	 * @throws ReflectionException
762
+	 */
763
+	public function set_is_taxable($is_taxable)
764
+	{
765
+		$this->set('LIN_is_taxable', $is_taxable);
766
+	}
767
+
768
+
769
+	/**
770
+	 * @param int $timestamp
771
+	 * @throws EE_Error
772
+	 * @throws ReflectionException
773
+	 * @since 5.0.0.p
774
+	 */
775
+	public function setTimestamp(int $timestamp)
776
+	{
777
+		$this->set('LIN_timestamp', $timestamp);
778
+	}
779
+
780
+
781
+	/**
782
+	 * Gets the object that this model-joins-to.
783
+	 * returns one of the model objects that the field OBJ_ID can point to... see the 'OBJ_ID' field on
784
+	 * EEM_Promotion_Object
785
+	 *        Eg, if this line item join model object is for a ticket, this will return the EE_Ticket object
786
+	 *
787
+	 * @return EE_Base_Class | NULL
788
+	 * @throws EE_Error
789
+	 * @throws InvalidArgumentException
790
+	 * @throws InvalidDataTypeException
791
+	 * @throws InvalidInterfaceException
792
+	 * @throws ReflectionException
793
+	 */
794
+	public function get_object()
795
+	{
796
+		$model_name_of_related_obj = $this->OBJ_type();
797
+		return $this->get_model()->has_relation($model_name_of_related_obj)
798
+			? $this->get_first_related($model_name_of_related_obj)
799
+			: null;
800
+	}
801
+
802
+
803
+	/**
804
+	 * Like EE_Line_Item::get_object(), but can only ever actually return an EE_Ticket.
805
+	 * (IE, if this line item is for a price or something else, will return NULL)
806
+	 *
807
+	 * @param array $query_params
808
+	 * @return EE_Base_Class|EE_Ticket
809
+	 * @throws EE_Error
810
+	 * @throws InvalidArgumentException
811
+	 * @throws InvalidDataTypeException
812
+	 * @throws InvalidInterfaceException
813
+	 * @throws ReflectionException
814
+	 */
815
+	public function ticket($query_params = array())
816
+	{
817
+		// we're going to assume that when this method is called
818
+		// we always want to receive the attached ticket EVEN if that ticket is archived.
819
+		// This can be overridden via the incoming $query_params argument
820
+		$remove_defaults = array('default_where_conditions' => 'none');
821
+		$query_params = array_merge($remove_defaults, $query_params);
822
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TICKET, $query_params);
823
+	}
824
+
825
+
826
+	/**
827
+	 * Gets the EE_Datetime that's related to the ticket, IF this is for a ticket
828
+	 *
829
+	 * @return EE_Datetime | NULL
830
+	 * @throws EE_Error
831
+	 * @throws InvalidArgumentException
832
+	 * @throws InvalidDataTypeException
833
+	 * @throws InvalidInterfaceException
834
+	 * @throws ReflectionException
835
+	 */
836
+	public function get_ticket_datetime()
837
+	{
838
+		if ($this->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
839
+			$ticket = $this->ticket();
840
+			if ($ticket instanceof EE_Ticket) {
841
+				$datetime = $ticket->first_datetime();
842
+				if ($datetime instanceof EE_Datetime) {
843
+					return $datetime;
844
+				}
845
+			}
846
+		}
847
+		return null;
848
+	}
849
+
850
+
851
+	/**
852
+	 * Gets the event's name that's related to the ticket, if this is for
853
+	 * a ticket
854
+	 *
855
+	 * @return string
856
+	 * @throws EE_Error
857
+	 * @throws InvalidArgumentException
858
+	 * @throws InvalidDataTypeException
859
+	 * @throws InvalidInterfaceException
860
+	 * @throws ReflectionException
861
+	 */
862
+	public function ticket_event_name()
863
+	{
864
+		$event_name = esc_html__('Unknown', 'event_espresso');
865
+		$event = $this->ticket_event();
866
+		if ($event instanceof EE_Event) {
867
+			$event_name = $event->name();
868
+		}
869
+		return $event_name;
870
+	}
871
+
872
+
873
+	/**
874
+	 * Gets the event that's related to the ticket, if this line item represents a ticket.
875
+	 *
876
+	 * @return EE_Event|null
877
+	 * @throws EE_Error
878
+	 * @throws InvalidArgumentException
879
+	 * @throws InvalidDataTypeException
880
+	 * @throws InvalidInterfaceException
881
+	 * @throws ReflectionException
882
+	 */
883
+	public function ticket_event()
884
+	{
885
+		$event = null;
886
+		$ticket = $this->ticket();
887
+		if ($ticket instanceof EE_Ticket) {
888
+			$datetime = $ticket->first_datetime();
889
+			if ($datetime instanceof EE_Datetime) {
890
+				$event = $datetime->event();
891
+			}
892
+		}
893
+		return $event;
894
+	}
895
+
896
+
897
+	/**
898
+	 * Gets the first datetime for this lien item, assuming it's for a ticket
899
+	 *
900
+	 * @param string $date_format
901
+	 * @param string $time_format
902
+	 * @return string
903
+	 * @throws EE_Error
904
+	 * @throws InvalidArgumentException
905
+	 * @throws InvalidDataTypeException
906
+	 * @throws InvalidInterfaceException
907
+	 * @throws ReflectionException
908
+	 */
909
+	public function ticket_datetime_start($date_format = '', $time_format = '')
910
+	{
911
+		$first_datetime_string = esc_html__('Unknown', 'event_espresso');
912
+		$datetime = $this->get_ticket_datetime();
913
+		if ($datetime) {
914
+			$first_datetime_string = $datetime->start_date_and_time($date_format, $time_format);
915
+		}
916
+		return $first_datetime_string;
917
+	}
918
+
919
+
920
+	/**
921
+	 * Adds the line item as a child to this line item. If there is another child line
922
+	 * item with the same LIN_code, it is overwritten by this new one
923
+	 *
924
+	 * @param EE_Line_Item $line_item
925
+	 * @param bool          $set_order
926
+	 * @return bool success
927
+	 * @throws EE_Error
928
+	 * @throws InvalidArgumentException
929
+	 * @throws InvalidDataTypeException
930
+	 * @throws InvalidInterfaceException
931
+	 * @throws ReflectionException
932
+	 */
933
+	public function add_child_line_item(EE_Line_Item $line_item, $set_order = true)
934
+	{
935
+		// should we calculate the LIN_order for this line item ?
936
+		if ($set_order || $line_item->order() === null) {
937
+			$line_item->set_order(count($this->children()));
938
+		}
939
+		if ($this->ID()) {
940
+			// check for any duplicate line items (with the same code), if so, this replaces it
941
+			$line_item_with_same_code = $this->get_child_line_item($line_item->code());
942
+			if ($line_item_with_same_code instanceof EE_Line_Item && $line_item_with_same_code !== $line_item) {
943
+				$this->delete_child_line_item($line_item_with_same_code->code());
944
+			}
945
+			$line_item->set_parent_ID($this->ID());
946
+			if ($this->TXN_ID()) {
947
+				$line_item->set_TXN_ID($this->TXN_ID());
948
+			}
949
+			return $line_item->save();
950
+		}
951
+		$this->_children[ $line_item->code() ] = $line_item;
952
+		if ($line_item->parent() !== $this) {
953
+			$line_item->set_parent($this);
954
+		}
955
+		return true;
956
+	}
957
+
958
+
959
+	/**
960
+	 * Similar to EE_Base_Class::_add_relation_to, except this isn't a normal relation.
961
+	 * If this line item is saved to the DB, this is just a wrapper for set_parent_ID() and save()
962
+	 * However, if this line item is NOT saved to the DB, this just caches the parent on
963
+	 * the EE_Line_Item::_parent property.
964
+	 *
965
+	 * @param EE_Line_Item $line_item
966
+	 * @throws EE_Error
967
+	 * @throws InvalidArgumentException
968
+	 * @throws InvalidDataTypeException
969
+	 * @throws InvalidInterfaceException
970
+	 * @throws ReflectionException
971
+	 */
972
+	public function set_parent($line_item)
973
+	{
974
+		if ($this->ID()) {
975
+			if (! $line_item->ID()) {
976
+				$line_item->save();
977
+			}
978
+			$this->set_parent_ID($line_item->ID());
979
+			$this->save();
980
+		} else {
981
+			$this->_parent = $line_item;
982
+			$this->set_parent_ID($line_item->ID());
983
+		}
984
+	}
985
+
986
+
987
+	/**
988
+	 * Gets the child line item as specified by its code. Because this returns an object (by reference)
989
+	 * you can modify this child line item and the parent (this object) can know about them
990
+	 * because it also has a reference to that line item
991
+	 *
992
+	 * @param string $code
993
+	 * @return EE_Base_Class|EE_Line_Item|EE_Soft_Delete_Base_Class|NULL
994
+	 * @throws EE_Error
995
+	 * @throws InvalidArgumentException
996
+	 * @throws InvalidDataTypeException
997
+	 * @throws InvalidInterfaceException
998
+	 * @throws ReflectionException
999
+	 */
1000
+	public function get_child_line_item($code)
1001
+	{
1002
+		if ($this->ID()) {
1003
+			return $this->get_model()->get_one(
1004
+				array(array('LIN_parent' => $this->ID(), 'LIN_code' => $code))
1005
+			);
1006
+		}
1007
+		return isset($this->_children[ $code ])
1008
+			? $this->_children[ $code ]
1009
+			: null;
1010
+	}
1011
+
1012
+
1013
+	/**
1014
+	 * Returns how many items are deleted (or, if this item has not been saved ot the DB yet, just how many it HAD
1015
+	 * cached on it)
1016
+	 *
1017
+	 * @return int
1018
+	 * @throws EE_Error
1019
+	 * @throws InvalidArgumentException
1020
+	 * @throws InvalidDataTypeException
1021
+	 * @throws InvalidInterfaceException
1022
+	 * @throws ReflectionException
1023
+	 */
1024
+	public function delete_children_line_items()
1025
+	{
1026
+		if ($this->ID()) {
1027
+			return $this->get_model()->delete(array(array('LIN_parent' => $this->ID())));
1028
+		}
1029
+		$count = count($this->_children);
1030
+		$this->_children = array();
1031
+		return $count;
1032
+	}
1033
+
1034
+
1035
+	/**
1036
+	 * If this line item has been saved to the DB, deletes its child with LIN_code == $code. If this line
1037
+	 * HAS NOT been saved to the DB, removes the child line item with index $code.
1038
+	 * Also searches through the child's children for a matching line item. However, once a line item has been found
1039
+	 * and deleted, stops searching (so if there are line items with duplicate codes, only the first one found will be
1040
+	 * deleted)
1041
+	 *
1042
+	 * @param string $code
1043
+	 * @param bool   $stop_search_once_found
1044
+	 * @return int count of items deleted (or simply removed from the line item's cache, if not has not been saved to
1045
+	 *             the DB yet)
1046
+	 * @throws EE_Error
1047
+	 * @throws InvalidArgumentException
1048
+	 * @throws InvalidDataTypeException
1049
+	 * @throws InvalidInterfaceException
1050
+	 * @throws ReflectionException
1051
+	 */
1052
+	public function delete_child_line_item($code, $stop_search_once_found = true)
1053
+	{
1054
+		if ($this->ID()) {
1055
+			$items_deleted = 0;
1056
+			if ($this->code() === $code) {
1057
+				$items_deleted += EEH_Line_Item::delete_all_child_items($this);
1058
+				$items_deleted += (int) $this->delete();
1059
+				if ($stop_search_once_found) {
1060
+					return $items_deleted;
1061
+				}
1062
+			}
1063
+			foreach ($this->children() as $child_line_item) {
1064
+				$items_deleted += $child_line_item->delete_child_line_item($code, $stop_search_once_found);
1065
+			}
1066
+			return $items_deleted;
1067
+		}
1068
+		if (isset($this->_children[ $code ])) {
1069
+			unset($this->_children[ $code ]);
1070
+			return 1;
1071
+		}
1072
+		return 0;
1073
+	}
1074
+
1075
+
1076
+	/**
1077
+	 * If this line item is in the database, is of the type subtotal, and
1078
+	 * has no children, why do we have it? It should be deleted so this function
1079
+	 * does that
1080
+	 *
1081
+	 * @return boolean
1082
+	 * @throws EE_Error
1083
+	 * @throws InvalidArgumentException
1084
+	 * @throws InvalidDataTypeException
1085
+	 * @throws InvalidInterfaceException
1086
+	 * @throws ReflectionException
1087
+	 */
1088
+	public function delete_if_childless_subtotal()
1089
+	{
1090
+		if ($this->ID() && $this->type() === EEM_Line_Item::type_sub_total && ! $this->children()) {
1091
+			return $this->delete();
1092
+		}
1093
+		return false;
1094
+	}
1095
+
1096
+
1097
+	/**
1098
+	 * Creates a code and returns a string. doesn't assign the code to this model object
1099
+	 *
1100
+	 * @return string
1101
+	 * @throws EE_Error
1102
+	 * @throws InvalidArgumentException
1103
+	 * @throws InvalidDataTypeException
1104
+	 * @throws InvalidInterfaceException
1105
+	 * @throws ReflectionException
1106
+	 */
1107
+	public function generate_code()
1108
+	{
1109
+		// each line item in the cart requires a unique identifier
1110
+		return md5($this->get('OBJ_type') . $this->get('OBJ_ID') . microtime());
1111
+	}
1112
+
1113
+
1114
+	/**
1115
+	 * @return bool
1116
+	 * @throws EE_Error
1117
+	 * @throws InvalidArgumentException
1118
+	 * @throws InvalidDataTypeException
1119
+	 * @throws InvalidInterfaceException
1120
+	 * @throws ReflectionException
1121
+	 */
1122
+	public function isGlobalTax(): bool
1123
+	{
1124
+		return $this->type() === EEM_Line_Item::type_tax;
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * @return bool
1130
+	 * @throws EE_Error
1131
+	 * @throws InvalidArgumentException
1132
+	 * @throws InvalidDataTypeException
1133
+	 * @throws InvalidInterfaceException
1134
+	 * @throws ReflectionException
1135
+	 */
1136
+	public function isSubTax(): bool
1137
+	{
1138
+		return $this->type() === EEM_Line_Item::type_sub_tax;
1139
+	}
1140
+
1141
+
1142
+	/**
1143
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1144
+	 *
1145
+	 * @return array
1146
+	 * @throws EE_Error
1147
+	 * @throws InvalidArgumentException
1148
+	 * @throws InvalidDataTypeException
1149
+	 * @throws InvalidInterfaceException
1150
+	 * @throws ReflectionException
1151
+	 */
1152
+	public function getSubTaxes(): array
1153
+	{
1154
+		if (! $this->is_line_item()) {
1155
+			return [];
1156
+		}
1157
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_sub_tax);
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 * returns true if this is a line item with a direct descendent of the type sub-tax
1163
+	 *
1164
+	 * @return bool
1165
+	 * @throws EE_Error
1166
+	 * @throws InvalidArgumentException
1167
+	 * @throws InvalidDataTypeException
1168
+	 * @throws InvalidInterfaceException
1169
+	 * @throws ReflectionException
1170
+	 */
1171
+	public function hasSubTaxes(): bool
1172
+	{
1173
+		if (! $this->is_line_item()) {
1174
+			return false;
1175
+		}
1176
+		$sub_taxes = $this->getSubTaxes();
1177
+		return ! empty($sub_taxes);
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * @return bool
1183
+	 * @throws EE_Error
1184
+	 * @throws ReflectionException
1185
+	 * @deprecated   5.0.0.p
1186
+	 */
1187
+	public function is_tax(): bool
1188
+	{
1189
+		return $this->isGlobalTax();
1190
+	}
1191
+
1192
+
1193
+	/**
1194
+	 * @return bool
1195
+	 * @throws EE_Error
1196
+	 * @throws InvalidArgumentException
1197
+	 * @throws InvalidDataTypeException
1198
+	 * @throws InvalidInterfaceException
1199
+	 * @throws ReflectionException
1200
+	 */
1201
+	public function is_tax_sub_total()
1202
+	{
1203
+		return $this->type() === EEM_Line_Item::type_tax_sub_total;
1204
+	}
1205
+
1206
+
1207
+	/**
1208
+	 * @return bool
1209
+	 * @throws EE_Error
1210
+	 * @throws InvalidArgumentException
1211
+	 * @throws InvalidDataTypeException
1212
+	 * @throws InvalidInterfaceException
1213
+	 * @throws ReflectionException
1214
+	 */
1215
+	public function is_line_item()
1216
+	{
1217
+		return $this->type() === EEM_Line_Item::type_line_item;
1218
+	}
1219
+
1220
+
1221
+	/**
1222
+	 * @return bool
1223
+	 * @throws EE_Error
1224
+	 * @throws InvalidArgumentException
1225
+	 * @throws InvalidDataTypeException
1226
+	 * @throws InvalidInterfaceException
1227
+	 * @throws ReflectionException
1228
+	 */
1229
+	public function is_sub_line_item()
1230
+	{
1231
+		return $this->type() === EEM_Line_Item::type_sub_line_item;
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 * @return bool
1237
+	 * @throws EE_Error
1238
+	 * @throws InvalidArgumentException
1239
+	 * @throws InvalidDataTypeException
1240
+	 * @throws InvalidInterfaceException
1241
+	 * @throws ReflectionException
1242
+	 */
1243
+	public function is_sub_total()
1244
+	{
1245
+		return $this->type() === EEM_Line_Item::type_sub_total;
1246
+	}
1247
+
1248
+
1249
+	/**
1250
+	 * Whether or not this line item is a cancellation line item
1251
+	 *
1252
+	 * @return boolean
1253
+	 * @throws EE_Error
1254
+	 * @throws InvalidArgumentException
1255
+	 * @throws InvalidDataTypeException
1256
+	 * @throws InvalidInterfaceException
1257
+	 * @throws ReflectionException
1258
+	 */
1259
+	public function is_cancellation()
1260
+	{
1261
+		return EEM_Line_Item::type_cancellation === $this->type();
1262
+	}
1263
+
1264
+
1265
+	/**
1266
+	 * @return bool
1267
+	 * @throws EE_Error
1268
+	 * @throws InvalidArgumentException
1269
+	 * @throws InvalidDataTypeException
1270
+	 * @throws InvalidInterfaceException
1271
+	 * @throws ReflectionException
1272
+	 */
1273
+	public function is_total()
1274
+	{
1275
+		return $this->type() === EEM_Line_Item::type_total;
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * @return bool
1281
+	 * @throws EE_Error
1282
+	 * @throws InvalidArgumentException
1283
+	 * @throws InvalidDataTypeException
1284
+	 * @throws InvalidInterfaceException
1285
+	 * @throws ReflectionException
1286
+	 */
1287
+	public function is_cancelled()
1288
+	{
1289
+		return $this->type() === EEM_Line_Item::type_cancellation;
1290
+	}
1291
+
1292
+
1293
+	/**
1294
+	 * @return string like '2, 004.00', formatted according to the localized currency
1295
+	 * @throws EE_Error
1296
+	 * @throws ReflectionException
1297
+	 */
1298
+	public function unit_price_no_code(): string
1299
+	{
1300
+		return $this->prettyUnitPrice();
1301
+	}
1302
+
1303
+
1304
+	/**
1305
+	 * @return string like '2, 004.00', formatted according to the localized currency
1306
+	 * @throws EE_Error
1307
+	 * @throws ReflectionException
1308
+	 * @since 5.0.0.p
1309
+	 */
1310
+	public function prettyUnitPrice(): string
1311
+	{
1312
+		return $this->get_pretty('LIN_unit_price', 'no_currency_code');
1313
+	}
1314
+
1315
+
1316
+	/**
1317
+	 * @return string like '2, 004.00', formatted according to the localized currency
1318
+	 * @throws EE_Error
1319
+	 * @throws ReflectionException
1320
+	 */
1321
+	public function total_no_code(): string
1322
+	{
1323
+		return $this->prettyTotal();
1324
+	}
1325
+
1326
+
1327
+	/**
1328
+	 * @return string like '2, 004.00', formatted according to the localized currency
1329
+	 * @throws EE_Error
1330
+	 * @throws ReflectionException
1331
+	 * @since 5.0.0.p
1332
+	 */
1333
+	public function prettyTotal(): string
1334
+	{
1335
+		return $this->get_pretty('LIN_total', 'no_currency_code');
1336
+	}
1337
+
1338
+
1339
+	/**
1340
+	 * Gets the final total on this item, taking taxes into account.
1341
+	 * Has the side-effect of setting the sub-total as it was just calculated.
1342
+	 * If this is used on a grand-total line item, also updates the transaction's
1343
+	 * TXN_total (provided this line item is allowed to persist, otherwise we don't
1344
+	 * want to change a persistable transaction with info from a non-persistent line item)
1345
+	 *
1346
+	 * @param bool $update_txn_status
1347
+	 * @return float
1348
+	 * @throws EE_Error
1349
+	 * @throws InvalidArgumentException
1350
+	 * @throws InvalidDataTypeException
1351
+	 * @throws InvalidInterfaceException
1352
+	 * @throws ReflectionException
1353
+	 * @throws RuntimeException
1354
+	 */
1355
+	public function recalculate_total_including_taxes(bool $update_txn_status = false): float
1356
+	{
1357
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1358
+		return $this->calculator->recalculateTotalIncludingTaxes($grand_total_line_item, $update_txn_status);
1359
+	}
1360
+
1361
+
1362
+	/**
1363
+	 * Recursively goes through all the children and recalculates sub-totals EXCEPT for
1364
+	 * tax-sub-totals (they're a an odd beast). Updates the 'total' on each line item according to either its
1365
+	 * unit price * quantity or the total of all its children EXCEPT when we're only calculating the taxable total and
1366
+	 * when this is called on the grand total
1367
+	 *
1368
+	 * @return float
1369
+	 * @throws EE_Error
1370
+	 * @throws InvalidArgumentException
1371
+	 * @throws InvalidDataTypeException
1372
+	 * @throws InvalidInterfaceException
1373
+	 * @throws ReflectionException
1374
+	 */
1375
+	public function recalculate_pre_tax_total(): float
1376
+	{
1377
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1378
+		[$total] = $this->calculator->recalculateLineItemTotals($grand_total_line_item);
1379
+		return (float) $total;
1380
+	}
1381
+
1382
+
1383
+	/**
1384
+	 * Recalculates the total on each individual tax (based on a recalculation of the pre-tax total), sets
1385
+	 * the totals on each tax calculated, and returns the final tax total. Re-saves tax line items
1386
+	 * and tax sub-total if already in the DB
1387
+	 *
1388
+	 * @return float
1389
+	 * @throws EE_Error
1390
+	 * @throws InvalidArgumentException
1391
+	 * @throws InvalidDataTypeException
1392
+	 * @throws InvalidInterfaceException
1393
+	 * @throws ReflectionException
1394
+	 */
1395
+	public function recalculate_taxes_and_tax_total(): float
1396
+	{
1397
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1398
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1399
+	}
1400
+
1401
+
1402
+	/**
1403
+	 * Gets the total tax on this line item. Assumes taxes have already been calculated using
1404
+	 * recalculate_taxes_and_total
1405
+	 *
1406
+	 * @return float
1407
+	 * @throws EE_Error
1408
+	 * @throws InvalidArgumentException
1409
+	 * @throws InvalidDataTypeException
1410
+	 * @throws InvalidInterfaceException
1411
+	 * @throws ReflectionException
1412
+	 */
1413
+	public function get_total_tax()
1414
+	{
1415
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($this);
1416
+		return $this->calculator->recalculateTaxesAndTaxTotal($grand_total_line_item);
1417
+	}
1418
+
1419
+
1420
+	/**
1421
+	 * Gets the total for all the items purchased only
1422
+	 *
1423
+	 * @return float
1424
+	 * @throws EE_Error
1425
+	 * @throws InvalidArgumentException
1426
+	 * @throws InvalidDataTypeException
1427
+	 * @throws InvalidInterfaceException
1428
+	 * @throws ReflectionException
1429
+	 */
1430
+	public function get_items_total()
1431
+	{
1432
+		// by default, let's make sure we're consistent with the existing line item
1433
+		if ($this->is_total()) {
1434
+			return $this->pretaxTotal();
1435
+		}
1436
+		$total = 0;
1437
+		foreach ($this->get_items() as $item) {
1438
+			if ($item instanceof EE_Line_Item) {
1439
+				$total += $item->pretaxTotal();
1440
+			}
1441
+		}
1442
+		return $total;
1443
+	}
1444
+
1445
+
1446
+	/**
1447
+	 * Gets all the descendants (ie, children or children of children etc) that
1448
+	 * are of the type 'tax'
1449
+	 *
1450
+	 * @return EE_Line_Item[]
1451
+	 * @throws EE_Error
1452
+	 */
1453
+	public function tax_descendants()
1454
+	{
1455
+		return EEH_Line_Item::get_tax_descendants($this);
1456
+	}
1457
+
1458
+
1459
+	/**
1460
+	 * Gets all the real items purchased which are children of this item
1461
+	 *
1462
+	 * @return EE_Line_Item[]
1463
+	 * @throws EE_Error
1464
+	 */
1465
+	public function get_items()
1466
+	{
1467
+		return EEH_Line_Item::get_line_item_descendants($this);
1468
+	}
1469
+
1470
+
1471
+	/**
1472
+	 * Returns the amount taxable among this line item's children (or if it has no children,
1473
+	 * how much of it is taxable). Does not recalculate totals or subtotals.
1474
+	 * If the taxable total is negative, (eg, if none of the tickets were taxable,
1475
+	 * but there is a "Taxable" discount), returns 0.
1476
+	 *
1477
+	 * @return float
1478
+	 * @throws EE_Error
1479
+	 * @throws InvalidArgumentException
1480
+	 * @throws InvalidDataTypeException
1481
+	 * @throws InvalidInterfaceException
1482
+	 * @throws ReflectionException
1483
+	 */
1484
+	public function taxable_total(): float
1485
+	{
1486
+		return $this->calculator->taxableAmountForGlobalTaxes($this);
1487
+	}
1488
+
1489
+
1490
+	/**
1491
+	 * Gets the transaction for this line item
1492
+	 *
1493
+	 * @return EE_Base_Class|EE_Transaction
1494
+	 * @throws EE_Error
1495
+	 * @throws InvalidArgumentException
1496
+	 * @throws InvalidDataTypeException
1497
+	 * @throws InvalidInterfaceException
1498
+	 * @throws ReflectionException
1499
+	 */
1500
+	public function transaction()
1501
+	{
1502
+		return $this->get_first_related(EEM_Line_Item::OBJ_TYPE_TRANSACTION);
1503
+	}
1504
+
1505
+
1506
+	/**
1507
+	 * Saves this line item to the DB, and recursively saves its descendants.
1508
+	 * Because there currently is no proper parent-child relation on the model,
1509
+	 * save_this_and_cached() will NOT save the descendants.
1510
+	 * Also sets the transaction on this line item and all its descendants before saving
1511
+	 *
1512
+	 * @param int $txn_id if none is provided, assumes $this->TXN_ID()
1513
+	 * @return int count of items saved
1514
+	 * @throws EE_Error
1515
+	 * @throws InvalidArgumentException
1516
+	 * @throws InvalidDataTypeException
1517
+	 * @throws InvalidInterfaceException
1518
+	 * @throws ReflectionException
1519
+	 */
1520
+	public function save_this_and_descendants_to_txn($txn_id = null)
1521
+	{
1522
+		$count = 0;
1523
+		if (! $txn_id) {
1524
+			$txn_id = $this->TXN_ID();
1525
+		}
1526
+		$this->set_TXN_ID($txn_id);
1527
+		$children = $this->children();
1528
+		$count += $this->save()
1529
+			? 1
1530
+			: 0;
1531
+		foreach ($children as $child_line_item) {
1532
+			if ($child_line_item instanceof EE_Line_Item) {
1533
+				$child_line_item->set_parent_ID($this->ID());
1534
+				$count += $child_line_item->save_this_and_descendants_to_txn($txn_id);
1535
+			}
1536
+		}
1537
+		return $count;
1538
+	}
1539
+
1540
+
1541
+	/**
1542
+	 * Saves this line item to the DB, and recursively saves its descendants.
1543
+	 *
1544
+	 * @return int count of items saved
1545
+	 * @throws EE_Error
1546
+	 * @throws InvalidArgumentException
1547
+	 * @throws InvalidDataTypeException
1548
+	 * @throws InvalidInterfaceException
1549
+	 * @throws ReflectionException
1550
+	 */
1551
+	public function save_this_and_descendants()
1552
+	{
1553
+		$count = 0;
1554
+		$children = $this->children();
1555
+		$count += $this->save()
1556
+			? 1
1557
+			: 0;
1558
+		foreach ($children as $child_line_item) {
1559
+			if ($child_line_item instanceof EE_Line_Item) {
1560
+				$child_line_item->set_parent_ID($this->ID());
1561
+				$count += $child_line_item->save_this_and_descendants();
1562
+			}
1563
+		}
1564
+		return $count;
1565
+	}
1566
+
1567
+
1568
+	/**
1569
+	 * returns the cancellation line item if this item was cancelled
1570
+	 *
1571
+	 * @return EE_Line_Item[]
1572
+	 * @throws InvalidArgumentException
1573
+	 * @throws InvalidInterfaceException
1574
+	 * @throws InvalidDataTypeException
1575
+	 * @throws ReflectionException
1576
+	 * @throws EE_Error
1577
+	 */
1578
+	public function get_cancellations()
1579
+	{
1580
+		return EEH_Line_Item::get_descendants_of_type($this, EEM_Line_Item::type_cancellation);
1581
+	}
1582
+
1583
+
1584
+	/**
1585
+	 * If this item has an ID, then this saves it again to update the db
1586
+	 *
1587
+	 * @return int count of items saved
1588
+	 * @throws EE_Error
1589
+	 * @throws InvalidArgumentException
1590
+	 * @throws InvalidDataTypeException
1591
+	 * @throws InvalidInterfaceException
1592
+	 * @throws ReflectionException
1593
+	 */
1594
+	public function maybe_save()
1595
+	{
1596
+		if ($this->ID()) {
1597
+			return $this->save();
1598
+		}
1599
+		return false;
1600
+	}
1601
+
1602
+
1603
+	/**
1604
+	 * clears the cached children and parent from the line item
1605
+	 *
1606
+	 * @return void
1607
+	 */
1608
+	public function clear_related_line_item_cache()
1609
+	{
1610
+		$this->_children = array();
1611
+		$this->_parent = null;
1612
+	}
1613
+
1614
+
1615
+	/**
1616
+	 * @param bool $raw
1617
+	 * @return int
1618
+	 * @throws EE_Error
1619
+	 * @throws InvalidArgumentException
1620
+	 * @throws InvalidDataTypeException
1621
+	 * @throws InvalidInterfaceException
1622
+	 * @throws ReflectionException
1623
+	 */
1624
+	public function timestamp($raw = false)
1625
+	{
1626
+		return $raw
1627
+			? $this->get_raw('LIN_timestamp')
1628
+			: $this->get('LIN_timestamp');
1629
+	}
1630
+
1631
+
1632
+
1633
+
1634
+	/************************* DEPRECATED *************************/
1635
+	/**
1636
+	 * @deprecated 4.6.0
1637
+	 * @param string $type one of the constants on EEM_Line_Item
1638
+	 * @return EE_Line_Item[]
1639
+	 * @throws EE_Error
1640
+	 */
1641
+	protected function _get_descendants_of_type($type)
1642
+	{
1643
+		EE_Error::doing_it_wrong(
1644
+			'EE_Line_Item::_get_descendants_of_type()',
1645
+			sprintf(
1646
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1647
+				'EEH_Line_Item::get_descendants_of_type()'
1648
+			),
1649
+			'4.6.0'
1650
+		);
1651
+		return EEH_Line_Item::get_descendants_of_type($this, $type);
1652
+	}
1653
+
1654
+
1655
+	/**
1656
+	 * @deprecated 4.6.0
1657
+	 * @param string $type like one of the EEM_Line_Item::type_*
1658
+	 * @return EE_Line_Item
1659
+	 * @throws EE_Error
1660
+	 * @throws InvalidArgumentException
1661
+	 * @throws InvalidDataTypeException
1662
+	 * @throws InvalidInterfaceException
1663
+	 * @throws ReflectionException
1664
+	 */
1665
+	public function get_nearest_descendant_of_type(string $type): EE_Line_Item
1666
+	{
1667
+		EE_Error::doing_it_wrong(
1668
+			'EE_Line_Item::get_nearest_descendant_of_type()',
1669
+			sprintf(
1670
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1671
+				'EEH_Line_Item::get_nearest_descendant_of_type()'
1672
+			),
1673
+			'4.6.0'
1674
+		);
1675
+		return EEH_Line_Item::get_nearest_descendant_of_type($this, $type);
1676
+	}
1677 1677
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Ticket.class.php 1 patch
Indentation   +2140 added lines, -2140 removed lines patch added patch discarded remove patch
@@ -14,2148 +14,2148 @@
 block discarded – undo
14 14
  */
15 15
 class EE_Ticket extends EE_Soft_Delete_Base_Class implements EEI_Line_Item_Object, EEI_Event_Relation, EEI_Has_Icon
16 16
 {
17
-    /**
18
-     * TicKet Archived:
19
-     * constant used by ticket_status() to indicate that a ticket is archived
20
-     * and no longer available for purchase
21
-     */
22
-    const archived = 'TKA';
23
-
24
-    /**
25
-     * TicKet Expired:
26
-     * constant used by ticket_status() to indicate that a ticket is expired
27
-     * and no longer available for purchase
28
-     */
29
-    const expired = 'TKE';
30
-
31
-    /**
32
-     * TicKet On sale:
33
-     * constant used by ticket_status() to indicate that a ticket is On Sale
34
-     * and IS available for purchase
35
-     */
36
-    const onsale = 'TKO';
37
-
38
-    /**
39
-     * TicKet Pending:
40
-     * constant used by ticket_status() to indicate that a ticket is pending
41
-     * and is NOT YET available for purchase
42
-     */
43
-    const pending = 'TKP';
44
-
45
-    /**
46
-     * TicKet Sold out:
47
-     * constant used by ticket_status() to indicate that a ticket is sold out
48
-     * and no longer available for purchases
49
-     */
50
-    const sold_out = 'TKS';
51
-
52
-    /**
53
-     * extra meta key for tracking ticket reservations
54
-     *
55
-     * @type string
56
-     */
57
-    const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
58
-
59
-    /**
60
-     * override of parent property
61
-     *
62
-     * @var EEM_Ticket
63
-     */
64
-    protected $_model;
65
-
66
-    /**
67
-     * cached result from method of the same name
68
-     *
69
-     * @var float $_ticket_total_with_taxes
70
-     */
71
-    private $_ticket_total_with_taxes;
72
-
73
-    /**
74
-     * @var TicketPriceModifiers
75
-     */
76
-    protected $ticket_price_modifiers;
77
-
78
-
79
-    /**
80
-     * @param array  $props_n_values          incoming values
81
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
82
-     *                                        used.)
83
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
84
-     *                                        date_format and the second value is the time format
85
-     * @return EE_Ticket
86
-     * @throws EE_Error
87
-     * @throws ReflectionException
88
-     */
89
-    public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
90
-    {
91
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
92
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
93
-    }
94
-
95
-
96
-    /**
97
-     * @param array  $props_n_values  incoming values from the database
98
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
99
-     *                                the website will be used.
100
-     * @return EE_Ticket
101
-     * @throws EE_Error
102
-     * @throws ReflectionException
103
-     */
104
-    public static function new_instance_from_db($props_n_values = [], $timezone = null)
105
-    {
106
-        return new self($props_n_values, true, $timezone);
107
-    }
108
-
109
-
110
-    /**
111
-     * @param array  $fieldValues
112
-     * @param false  $bydb
113
-     * @param string $timezone
114
-     * @param array  $date_formats
115
-     * @throws EE_Error
116
-     * @throws ReflectionException
117
-     */
118
-    public function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
119
-    {
120
-        parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
121
-        $this->ticket_price_modifiers = new TicketPriceModifiers($this);
122
-    }
123
-
124
-
125
-    /**
126
-     * @return bool
127
-     * @throws EE_Error
128
-     * @throws ReflectionException
129
-     */
130
-    public function parent()
131
-    {
132
-        return $this->get('TKT_parent');
133
-    }
134
-
135
-
136
-    /**
137
-     * return if a ticket has quantities available for purchase
138
-     *
139
-     * @param int $DTT_ID the primary key for a particular datetime
140
-     * @return boolean
141
-     * @throws EE_Error
142
-     * @throws ReflectionException
143
-     */
144
-    public function available($DTT_ID = 0)
145
-    {
146
-        // are we checking availability for a particular datetime ?
147
-        if ($DTT_ID) {
148
-            // get that datetime object
149
-            $datetime = $this->get_first_related('Datetime', [['DTT_ID' => $DTT_ID]]);
150
-            // if  ticket sales for this datetime have exceeded the reg limit...
151
-            if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
152
-                return false;
153
-            }
154
-        }
155
-        // datetime is still open for registration, but is this ticket sold out ?
156
-        return $this->qty() < 1 || $this->qty() > $this->sold();
157
-    }
158
-
159
-
160
-    /**
161
-     * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
162
-     *
163
-     * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
164
-     *                               relevant status const
165
-     * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
166
-     *                               further processing
167
-     * @return mixed status int if the display string isn't requested
168
-     * @throws EE_Error
169
-     * @throws ReflectionException
170
-     */
171
-    public function ticket_status($display = false, $remaining = null)
172
-    {
173
-        $remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
174
-        if (! $remaining) {
175
-            return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
176
-        }
177
-        if ($this->get('TKT_deleted')) {
178
-            return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
179
-        }
180
-        if ($this->is_expired()) {
181
-            return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
182
-        }
183
-        if ($this->is_pending()) {
184
-            return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
185
-        }
186
-        if ($this->is_on_sale()) {
187
-            return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
188
-        }
189
-        return '';
190
-    }
191
-
192
-
193
-    /**
194
-     * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
195
-     * considering ALL the factors used for figuring that out.
196
-     *
197
-     * @param int $DTT_ID if an int above 0 is included here then we get a specific dtt.
198
-     * @return boolean         true = tickets remaining, false not.
199
-     * @throws EE_Error
200
-     * @throws ReflectionException
201
-     */
202
-    public function is_remaining($DTT_ID = 0)
203
-    {
204
-        $num_remaining = $this->remaining($DTT_ID);
205
-        if ($num_remaining === 0) {
206
-            return false;
207
-        }
208
-        if ($num_remaining > 0 && $num_remaining < $this->min()) {
209
-            return false;
210
-        }
211
-        return true;
212
-    }
213
-
214
-
215
-    /**
216
-     * return the total number of tickets available for purchase
217
-     *
218
-     * @param int $DTT_ID  the primary key for a particular datetime.
219
-     *                     set to 0 for all related datetimes
220
-     * @return int
221
-     * @throws EE_Error
222
-     * @throws ReflectionException
223
-     */
224
-    public function remaining($DTT_ID = 0)
225
-    {
226
-        return $this->real_quantity_on_ticket('saleable', $DTT_ID);
227
-    }
228
-
229
-
230
-    /**
231
-     * Gets min
232
-     *
233
-     * @return int
234
-     * @throws EE_Error
235
-     * @throws ReflectionException
236
-     */
237
-    public function min()
238
-    {
239
-        return $this->get('TKT_min');
240
-    }
241
-
242
-
243
-    /**
244
-     * return if a ticket is no longer available cause its available dates have expired.
245
-     *
246
-     * @return boolean
247
-     * @throws EE_Error
248
-     * @throws ReflectionException
249
-     */
250
-    public function is_expired()
251
-    {
252
-        return ($this->get_raw('TKT_end_date') < time());
253
-    }
254
-
255
-
256
-    /**
257
-     * Return if a ticket is yet to go on sale or not
258
-     *
259
-     * @return boolean
260
-     * @throws EE_Error
261
-     * @throws ReflectionException
262
-     */
263
-    public function is_pending()
264
-    {
265
-        return ($this->get_raw('TKT_start_date') >= time());
266
-    }
267
-
268
-
269
-    /**
270
-     * Return if a ticket is on sale or not
271
-     *
272
-     * @return boolean
273
-     * @throws EE_Error
274
-     * @throws ReflectionException
275
-     */
276
-    public function is_on_sale()
277
-    {
278
-        return ($this->get_raw('TKT_start_date') <= time() && $this->get_raw('TKT_end_date') >= time());
279
-    }
280
-
281
-
282
-    /**
283
-     * This returns the chronologically last datetime that this ticket is associated with
284
-     *
285
-     * @param string $date_format
286
-     * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
287
-     *                            the end date ie: Jan 01 "to" Dec 31
288
-     * @return string
289
-     * @throws EE_Error
290
-     * @throws ReflectionException
291
-     */
292
-    public function date_range($date_format = '', $conjunction = ' - ')
293
-    {
294
-        $date_format = ! empty($date_format) ? $date_format : $this->_dt_frmt;
295
-        $first_date  = $this->first_datetime() instanceof EE_Datetime
296
-            ? $this->first_datetime()->get_i18n_datetime('DTT_EVT_start', $date_format)
297
-            : '';
298
-        $last_date   = $this->last_datetime() instanceof EE_Datetime
299
-            ? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $date_format)
300
-            : '';
301
-
302
-        return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
303
-    }
304
-
305
-
306
-    /**
307
-     * This returns the chronologically first datetime that this ticket is associated with
308
-     *
309
-     * @return EE_Datetime
310
-     * @throws EE_Error
311
-     * @throws ReflectionException
312
-     */
313
-    public function first_datetime()
314
-    {
315
-        $datetimes = $this->datetimes(['limit' => 1]);
316
-        return reset($datetimes);
317
-    }
318
-
319
-
320
-    /**
321
-     * Gets all the datetimes this ticket can be used for attending.
322
-     * Unless otherwise specified, orders datetimes by start date.
323
-     *
324
-     * @param array $query_params
325
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
326
-     * @return EE_Datetime[]|EE_Base_Class[]
327
-     * @throws EE_Error
328
-     * @throws ReflectionException
329
-     */
330
-    public function datetimes($query_params = [])
331
-    {
332
-        if (! isset($query_params['order_by'])) {
333
-            $query_params['order_by']['DTT_order'] = 'ASC';
334
-        }
335
-        return $this->get_many_related('Datetime', $query_params);
336
-    }
337
-
338
-
339
-    /**
340
-     * This returns the chronologically last datetime that this ticket is associated with
341
-     *
342
-     * @return EE_Datetime
343
-     * @throws EE_Error
344
-     * @throws ReflectionException
345
-     */
346
-    public function last_datetime()
347
-    {
348
-        $datetimes = $this->datetimes(['limit' => 1, 'order_by' => ['DTT_EVT_start' => 'DESC']]);
349
-        return end($datetimes);
350
-    }
351
-
352
-
353
-    /**
354
-     * This returns the total tickets sold depending on the given parameters.
355
-     *
356
-     * @param string $what    Can be one of two options: 'ticket', 'datetime'.
357
-     *                        'ticket' = total ticket sales for all datetimes this ticket is related to
358
-     *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
359
-     *                        'datetime' = total ticket sales in the datetime_ticket table.
360
-     *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
361
-     *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
362
-     * @param int    $dtt_id  [optional] include the dtt_id with $what = 'datetime'.
363
-     * @return mixed (array|int)          how many tickets have sold
364
-     * @throws EE_Error
365
-     * @throws ReflectionException
366
-     */
367
-    public function tickets_sold($what = 'ticket', $dtt_id = null)
368
-    {
369
-        $total        = 0;
370
-        $tickets_sold = $this->_all_tickets_sold();
371
-        switch ($what) {
372
-            case 'ticket':
373
-                return $tickets_sold['ticket'];
374
-
375
-            case 'datetime':
376
-                if (empty($tickets_sold['datetime'])) {
377
-                    return $total;
378
-                }
379
-                if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
380
-                    EE_Error::add_error(
381
-                        esc_html__(
382
-                            'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
383
-                            'event_espresso'
384
-                        ),
385
-                        __FILE__,
386
-                        __FUNCTION__,
387
-                        __LINE__
388
-                    );
389
-                    return $total;
390
-                }
391
-                return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
392
-
393
-            default:
394
-                return $total;
395
-        }
396
-    }
397
-
398
-
399
-    /**
400
-     * This returns an array indexed by datetime_id for tickets sold with this ticket.
401
-     *
402
-     * @return EE_Ticket[]
403
-     * @throws EE_Error
404
-     * @throws ReflectionException
405
-     */
406
-    protected function _all_tickets_sold()
407
-    {
408
-        $datetimes    = $this->get_many_related('Datetime');
409
-        $tickets_sold = [];
410
-        if (! empty($datetimes)) {
411
-            foreach ($datetimes as $datetime) {
412
-                $tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
413
-            }
414
-        }
415
-        // Tickets sold
416
-        $tickets_sold['ticket'] = $this->sold();
417
-        return $tickets_sold;
418
-    }
419
-
420
-
421
-    /**
422
-     * This returns the base price object for the ticket.
423
-     *
424
-     * @param bool $return_array whether to return as an array indexed by price id or just the object.
425
-     * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
426
-     * @throws EE_Error
427
-     * @throws ReflectionException
428
-     */
429
-    public function base_price(bool $return_array = false)
430
-    {
431
-        $base_price = $this->ticket_price_modifiers->getBasePrice();
432
-        if (! empty($base_price)) {
433
-            return $return_array ? $base_price : reset($base_price);
434
-        }
435
-        $_where = ['Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price];
436
-        return $return_array
437
-            ? $this->get_many_related('Price', [$_where])
438
-            : $this->get_first_related('Price', [$_where]);
439
-    }
440
-
441
-
442
-    /**
443
-     * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
444
-     *
445
-     * @return EE_Price[]
446
-     * @throws EE_Error
447
-     * @throws ReflectionException
448
-     */
449
-    public function price_modifiers(): array
450
-    {
451
-        $price_modifiers = $this->usesGlobalTaxes()
452
-            ? $this->ticket_price_modifiers->getAllDiscountAndSurchargeModifiersForTicket()
453
-            : $this->ticket_price_modifiers ->getAllModifiersForTicket();
454
-        if (! empty($price_modifiers)) {
455
-            return $price_modifiers;
456
-        }
457
-        return $this->prices(
458
-            [
459
-                [
460
-                    'Price_Type.PBT_ID' => [
461
-                        'NOT IN',
462
-                        [EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax],
463
-                    ]
464
-                ]
465
-            ]
466
-        );
467
-    }
468
-
469
-
470
-    /**
471
-     * This returns ONLY the TAX price modifiers for the ticket
472
-     *
473
-     * @return EE_Price[]
474
-     * @throws EE_Error
475
-     * @throws ReflectionException
476
-     */
477
-    public function tax_price_modifiers(): array
478
-    {
479
-        $tax_price_modifiers = $this->ticket_price_modifiers->getAllTaxesForTicket();
480
-        if (! empty($tax_price_modifiers)) {
481
-            return $tax_price_modifiers;
482
-        }
483
-        return $this->prices([['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax]]);
484
-    }
485
-
486
-
487
-    /**
488
-     * Gets all the prices that combine to form the final price of this ticket
489
-     *
490
-     * @param array $query_params
491
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
492
-     * @return EE_Price[]|EE_Base_Class[]
493
-     * @throws EE_Error
494
-     * @throws ReflectionException
495
-     */
496
-    public function prices(array $query_params = []): array
497
-    {
498
-        if (! isset($query_params['order_by'])) {
499
-            $query_params['order_by']['PRC_order'] = 'ASC';
500
-        }
501
-        return $this->get_many_related('Price', $query_params);
502
-    }
503
-
504
-
505
-    /**
506
-     * Gets all the ticket datetimes (ie, relations between datetimes and tickets)
507
-     *
508
-     * @param array $query_params
509
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
510
-     * @return EE_Datetime_Ticket|EE_Base_Class[]
511
-     * @throws EE_Error
512
-     * @throws ReflectionException
513
-     */
514
-    public function datetime_tickets($query_params = [])
515
-    {
516
-        return $this->get_many_related('Datetime_Ticket', $query_params);
517
-    }
518
-
519
-
520
-    /**
521
-     * Gets all the datetimes from the db ordered by DTT_order
522
-     *
523
-     * @param boolean $show_expired
524
-     * @param boolean $show_deleted
525
-     * @return EE_Datetime[]
526
-     * @throws EE_Error
527
-     * @throws ReflectionException
528
-     */
529
-    public function datetimes_ordered($show_expired = true, $show_deleted = false)
530
-    {
531
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
532
-            $this->ID(),
533
-            $show_expired,
534
-            $show_deleted
535
-        );
536
-    }
537
-
538
-
539
-    /**
540
-     * Gets ID
541
-     *
542
-     * @return int
543
-     * @throws EE_Error
544
-     * @throws ReflectionException
545
-     */
546
-    public function ID()
547
-    {
548
-        return (int) $this->get('TKT_ID');
549
-    }
550
-
551
-
552
-    /**
553
-     * get the author of the ticket.
554
-     *
555
-     * @return int
556
-     * @throws EE_Error
557
-     * @throws ReflectionException
558
-     * @since 4.5.0
559
-     */
560
-    public function wp_user()
561
-    {
562
-        return $this->get('TKT_wp_user');
563
-    }
564
-
565
-
566
-    /**
567
-     * Gets the template for the ticket
568
-     *
569
-     * @return EE_Ticket_Template|EE_Base_Class
570
-     * @throws EE_Error
571
-     * @throws ReflectionException
572
-     */
573
-    public function template()
574
-    {
575
-        return $this->get_first_related('Ticket_Template');
576
-    }
577
-
578
-
579
-    /**
580
-     * Simply returns an array of EE_Price objects that are taxes.
581
-     *
582
-     * @return EE_Price[]
583
-     * @throws EE_Error
584
-     * @throws ReflectionException
585
-     */
586
-    public function get_ticket_taxes_for_admin(): array
587
-    {
588
-        return $this->usesGlobalTaxes() ? EE_Taxes::get_taxes_for_admin() : $this->tax_price_modifiers();
589
-    }
590
-
591
-
592
-    /**
593
-     * alias of taxable() to better indicate that ticket uses the legacy method of applying default "global" taxes
594
-     * as opposed to having tax price modifiers added directly to each ticket
595
-     *
596
-     * @return bool
597
-     * @throws EE_Error
598
-     * @throws ReflectionException
599
-     * @since   5.0.0.p
600
-     */
601
-    public function usesGlobalTaxes(): bool
602
-    {
603
-        return $this->taxable();
604
-    }
605
-
606
-
607
-    /**
608
-     * @return float
609
-     * @throws EE_Error
610
-     * @throws ReflectionException
611
-     */
612
-    public function ticket_price()
613
-    {
614
-        return $this->get('TKT_price');
615
-    }
616
-
617
-
618
-    /**
619
-     * @return mixed
620
-     * @throws EE_Error
621
-     * @throws ReflectionException
622
-     */
623
-    public function pretty_price()
624
-    {
625
-        return $this->get_pretty('TKT_price');
626
-    }
627
-
628
-
629
-    /**
630
-     * @return bool
631
-     * @throws EE_Error
632
-     * @throws ReflectionException
633
-     */
634
-    public function is_free()
635
-    {
636
-        return $this->get_ticket_total_with_taxes() === (float) 0;
637
-    }
638
-
639
-
640
-    /**
641
-     * get_ticket_total_with_taxes
642
-     *
643
-     * @param bool $no_cache
644
-     * @return float
645
-     * @throws EE_Error
646
-     * @throws ReflectionException
647
-     */
648
-    public function get_ticket_total_with_taxes($no_cache = false)
649
-    {
650
-        if ($this->_ticket_total_with_taxes === null || $no_cache) {
651
-            $this->_ticket_total_with_taxes = $this->usesGlobalTaxes()
652
-                ? $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin()
653
-                : $this->ticket_price();
654
-        }
655
-        return (float) $this->_ticket_total_with_taxes;
656
-    }
657
-
658
-
659
-    /**
660
-     * @throws EE_Error
661
-     * @throws ReflectionException
662
-     */
663
-    public function ensure_TKT_Price_correct()
664
-    {
665
-        $this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
666
-        $this->save();
667
-    }
668
-
669
-
670
-    /**
671
-     * @return float
672
-     * @throws EE_Error
673
-     * @throws ReflectionException
674
-     */
675
-    public function get_ticket_subtotal()
676
-    {
677
-        return EE_Taxes::get_subtotal_for_admin($this);
678
-    }
679
-
680
-
681
-    /**
682
-     * Returns the total taxes applied to this ticket
683
-     *
684
-     * @return float
685
-     * @throws EE_Error
686
-     * @throws ReflectionException
687
-     */
688
-    public function get_ticket_taxes_total_for_admin()
689
-    {
690
-        return EE_Taxes::get_total_taxes_for_admin($this);
691
-    }
692
-
693
-
694
-    /**
695
-     * Sets name
696
-     *
697
-     * @param string $name
698
-     * @throws EE_Error
699
-     * @throws ReflectionException
700
-     */
701
-    public function set_name($name)
702
-    {
703
-        $this->set('TKT_name', $name);
704
-    }
705
-
706
-
707
-    /**
708
-     * Gets description
709
-     *
710
-     * @return string
711
-     * @throws EE_Error
712
-     * @throws ReflectionException
713
-     */
714
-    public function description()
715
-    {
716
-        return $this->get('TKT_description');
717
-    }
718
-
719
-
720
-    /**
721
-     * Sets description
722
-     *
723
-     * @param string $description
724
-     * @throws EE_Error
725
-     * @throws ReflectionException
726
-     */
727
-    public function set_description($description)
728
-    {
729
-        $this->set('TKT_description', $description);
730
-    }
731
-
732
-
733
-    /**
734
-     * Gets start_date
735
-     *
736
-     * @param string|null $date_format
737
-     * @param string|null $time_format
738
-     * @return string
739
-     * @throws EE_Error
740
-     * @throws ReflectionException
741
-     */
742
-    public function start_date(?string $date_format = '', ?string $time_format = ''): string
743
-    {
744
-        return $this->_get_datetime('TKT_start_date', $date_format, $time_format);
745
-    }
746
-
747
-
748
-    /**
749
-     * Sets start_date
750
-     *
751
-     * @param string $start_date
752
-     * @return void
753
-     * @throws EE_Error
754
-     * @throws ReflectionException
755
-     */
756
-    public function set_start_date($start_date)
757
-    {
758
-        $this->_set_date_time('B', $start_date, 'TKT_start_date');
759
-    }
760
-
761
-
762
-    /**
763
-     * Gets end_date
764
-     *
765
-     * @param string|null $date_format
766
-     * @param string|null $time_format
767
-     * @return string
768
-     * @throws EE_Error
769
-     * @throws ReflectionException
770
-     */
771
-    public function end_date(?string $date_format = '', ?string $time_format = ''): string
772
-    {
773
-        return $this->_get_datetime('TKT_end_date', $date_format, $time_format);
774
-    }
775
-
776
-
777
-    /**
778
-     * Sets end_date
779
-     *
780
-     * @param string $end_date
781
-     * @return void
782
-     * @throws EE_Error
783
-     * @throws ReflectionException
784
-     */
785
-    public function set_end_date($end_date)
786
-    {
787
-        $this->_set_date_time('B', $end_date, 'TKT_end_date');
788
-    }
789
-
790
-
791
-    /**
792
-     * Sets sell until time
793
-     *
794
-     * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
795
-     * @throws EE_Error
796
-     * @throws ReflectionException
797
-     * @since 4.5.0
798
-     */
799
-    public function set_end_time($time)
800
-    {
801
-        $this->_set_time_for($time, 'TKT_end_date');
802
-    }
803
-
804
-
805
-    /**
806
-     * Sets min
807
-     *
808
-     * @param int $min
809
-     * @return void
810
-     * @throws EE_Error
811
-     * @throws ReflectionException
812
-     */
813
-    public function set_min($min)
814
-    {
815
-        $this->set('TKT_min', $min);
816
-    }
817
-
818
-
819
-    /**
820
-     * Gets max
821
-     *
822
-     * @return int
823
-     * @throws EE_Error
824
-     * @throws ReflectionException
825
-     */
826
-    public function max()
827
-    {
828
-        return $this->get('TKT_max');
829
-    }
830
-
831
-
832
-    /**
833
-     * Sets max
834
-     *
835
-     * @param int $max
836
-     * @return void
837
-     * @throws EE_Error
838
-     * @throws ReflectionException
839
-     */
840
-    public function set_max($max)
841
-    {
842
-        $this->set('TKT_max', $max);
843
-    }
844
-
845
-
846
-    /**
847
-     * Sets price
848
-     *
849
-     * @param float $price
850
-     * @return void
851
-     * @throws EE_Error
852
-     * @throws ReflectionException
853
-     */
854
-    public function set_price($price)
855
-    {
856
-        $this->set('TKT_price', $price);
857
-    }
858
-
859
-
860
-    /**
861
-     * Gets sold
862
-     *
863
-     * @return int
864
-     * @throws EE_Error
865
-     * @throws ReflectionException
866
-     */
867
-    public function sold(): int
868
-    {
869
-        return (int) $this->get_raw('TKT_sold');
870
-    }
871
-
872
-
873
-    /**
874
-     * Sets sold
875
-     *
876
-     * @param int $sold
877
-     * @return void
878
-     * @throws EE_Error
879
-     * @throws ReflectionException
880
-     */
881
-    public function set_sold($sold)
882
-    {
883
-        // sold can not go below zero
884
-        $sold = max(0, $sold);
885
-        $this->set('TKT_sold', $sold);
886
-    }
887
-
888
-
889
-    /**
890
-     * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
891
-     * associated datetimes.
892
-     *
893
-     * @param int $qty
894
-     * @return boolean
895
-     * @throws EE_Error
896
-     * @throws InvalidArgumentException
897
-     * @throws InvalidDataTypeException
898
-     * @throws InvalidInterfaceException
899
-     * @throws ReflectionException
900
-     * @since 4.9.80.p
901
-     */
902
-    public function increaseSold($qty = 1)
903
-    {
904
-        $qty = absint($qty);
905
-        // increment sold and decrement reserved datetime quantities simultaneously
906
-        // don't worry about failures, because they must have already had a spot reserved
907
-        $this->increaseSoldForDatetimes($qty);
908
-        // Increment and decrement ticket quantities simultaneously
909
-        $success = $this->adjustNumericFieldsInDb(
910
-            [
911
-                'TKT_reserved' => $qty * -1,
912
-                'TKT_sold'     => $qty,
913
-            ]
914
-        );
915
-        do_action(
916
-            'AHEE__EE_Ticket__increase_sold',
917
-            $this,
918
-            $qty,
919
-            $this->sold(),
920
-            $success
921
-        );
922
-        return $success;
923
-    }
924
-
925
-
926
-    /**
927
-     * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
928
-     *
929
-     * @param int           $qty positive or negative. Positive means to increase sold counts (and decrease reserved
930
-     *                           counts), Negative means to decreases old counts (and increase reserved counts).
931
-     * @param EE_Datetime[] $datetimes
932
-     * @throws EE_Error
933
-     * @throws InvalidArgumentException
934
-     * @throws InvalidDataTypeException
935
-     * @throws InvalidInterfaceException
936
-     * @throws ReflectionException
937
-     * @since 4.9.80.p
938
-     */
939
-    protected function increaseSoldForDatetimes($qty, array $datetimes = [])
940
-    {
941
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
942
-        foreach ($datetimes as $datetime) {
943
-            $datetime->increaseSold($qty);
944
-        }
945
-    }
946
-
947
-
948
-    /**
949
-     * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
950
-     * DB and then updates the model objects.
951
-     * Does not affect the reserved counts.
952
-     *
953
-     * @param int $qty
954
-     * @return boolean
955
-     * @throws EE_Error
956
-     * @throws InvalidArgumentException
957
-     * @throws InvalidDataTypeException
958
-     * @throws InvalidInterfaceException
959
-     * @throws ReflectionException
960
-     * @since 4.9.80.p
961
-     */
962
-    public function decreaseSold($qty = 1)
963
-    {
964
-        $qty = absint($qty);
965
-        $this->decreaseSoldForDatetimes($qty);
966
-        $success = $this->adjustNumericFieldsInDb(
967
-            [
968
-                'TKT_sold' => $qty * -1,
969
-            ]
970
-        );
971
-        do_action(
972
-            'AHEE__EE_Ticket__decrease_sold',
973
-            $this,
974
-            $qty,
975
-            $this->sold(),
976
-            $success
977
-        );
978
-        return $success;
979
-    }
980
-
981
-
982
-    /**
983
-     * Decreases sold on related datetimes
984
-     *
985
-     * @param int           $qty
986
-     * @param EE_Datetime[] $datetimes
987
-     * @return void
988
-     * @throws EE_Error
989
-     * @throws InvalidArgumentException
990
-     * @throws InvalidDataTypeException
991
-     * @throws InvalidInterfaceException
992
-     * @throws ReflectionException
993
-     * @since 4.9.80.p
994
-     */
995
-    protected function decreaseSoldForDatetimes($qty = 1, array $datetimes = [])
996
-    {
997
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
998
-        if (is_array($datetimes)) {
999
-            foreach ($datetimes as $datetime) {
1000
-                if ($datetime instanceof EE_Datetime) {
1001
-                    $datetime->decreaseSold($qty);
1002
-                }
1003
-            }
1004
-        }
1005
-    }
1006
-
1007
-
1008
-    /**
1009
-     * Gets qty of reserved tickets
1010
-     *
1011
-     * @return int
1012
-     * @throws EE_Error
1013
-     * @throws ReflectionException
1014
-     */
1015
-    public function reserved(): int
1016
-    {
1017
-        return (int) $this->get_raw('TKT_reserved');
1018
-    }
1019
-
1020
-
1021
-    /**
1022
-     * Sets reserved
1023
-     *
1024
-     * @param int $reserved
1025
-     * @return void
1026
-     * @throws EE_Error
1027
-     * @throws ReflectionException
1028
-     */
1029
-    public function set_reserved($reserved)
1030
-    {
1031
-        // reserved can not go below zero
1032
-        $reserved = max(0, (int) $reserved);
1033
-        $this->set('TKT_reserved', $reserved);
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1039
-     *
1040
-     * @param int    $qty
1041
-     * @param string $source
1042
-     * @return bool whether we successfully reserved the ticket or not.
1043
-     * @throws EE_Error
1044
-     * @throws InvalidArgumentException
1045
-     * @throws ReflectionException
1046
-     * @throws InvalidDataTypeException
1047
-     * @throws InvalidInterfaceException
1048
-     * @since 4.9.80.p
1049
-     */
1050
-    public function increaseReserved($qty = 1, $source = 'unknown')
1051
-    {
1052
-        $qty = absint($qty);
1053
-        do_action(
1054
-            'AHEE__EE_Ticket__increase_reserved__begin',
1055
-            $this,
1056
-            $qty,
1057
-            $source
1058
-        );
1059
-        $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "{$qty} from {$source}");
1060
-        $success                         = false;
1061
-        $datetimes_adjusted_successfully = $this->increaseReservedForDatetimes($qty);
1062
-        if ($datetimes_adjusted_successfully) {
1063
-            $success = $this->incrementFieldConditionallyInDb(
1064
-                'TKT_reserved',
1065
-                'TKT_sold',
1066
-                'TKT_qty',
1067
-                $qty
1068
-            );
1069
-            if (! $success) {
1070
-                // The datetimes were successfully bumped, but not the
1071
-                // ticket. So we need to manually rollback the datetimes.
1072
-                $this->decreaseReservedForDatetimes($qty);
1073
-            }
1074
-        }
1075
-        do_action(
1076
-            'AHEE__EE_Ticket__increase_reserved',
1077
-            $this,
1078
-            $qty,
1079
-            $this->reserved(),
1080
-            $success
1081
-        );
1082
-        return $success;
1083
-    }
1084
-
1085
-
1086
-    /**
1087
-     * Increases reserved counts on related datetimes
1088
-     *
1089
-     * @param int           $qty
1090
-     * @param EE_Datetime[] $datetimes
1091
-     * @return boolean indicating success
1092
-     * @throws EE_Error
1093
-     * @throws InvalidArgumentException
1094
-     * @throws InvalidDataTypeException
1095
-     * @throws InvalidInterfaceException
1096
-     * @throws ReflectionException
1097
-     * @since 4.9.80.p
1098
-     */
1099
-    protected function increaseReservedForDatetimes($qty = 1, array $datetimes = [])
1100
-    {
1101
-        $datetimes         = ! empty($datetimes) ? $datetimes : $this->datetimes();
1102
-        $datetimes_updated = [];
1103
-        $limit_exceeded    = false;
1104
-        if (is_array($datetimes)) {
1105
-            foreach ($datetimes as $datetime) {
1106
-                if ($datetime instanceof EE_Datetime) {
1107
-                    if ($datetime->increaseReserved($qty)) {
1108
-                        $datetimes_updated[] = $datetime;
1109
-                    } else {
1110
-                        $limit_exceeded = true;
1111
-                        break;
1112
-                    }
1113
-                }
1114
-            }
1115
-            // If somewhere along the way we detected a datetime whose
1116
-            // limit was exceeded, do a manual rollback.
1117
-            if ($limit_exceeded) {
1118
-                $this->decreaseReservedForDatetimes($qty, $datetimes_updated);
1119
-                return false;
1120
-            }
1121
-        }
1122
-        return true;
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1128
-     *
1129
-     * @param int    $qty
1130
-     * @param bool   $adjust_datetimes
1131
-     * @param string $source
1132
-     * @return boolean
1133
-     * @throws EE_Error
1134
-     * @throws InvalidArgumentException
1135
-     * @throws ReflectionException
1136
-     * @throws InvalidDataTypeException
1137
-     * @throws InvalidInterfaceException
1138
-     * @since 4.9.80.p
1139
-     */
1140
-    public function decreaseReserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1141
-    {
1142
-        $qty = absint($qty);
1143
-        $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "-{$qty} from {$source}");
1144
-        if ($adjust_datetimes) {
1145
-            $this->decreaseReservedForDatetimes($qty);
1146
-        }
1147
-        $success = $this->adjustNumericFieldsInDb(
1148
-            [
1149
-                'TKT_reserved' => $qty * -1,
1150
-            ]
1151
-        );
1152
-        do_action(
1153
-            'AHEE__EE_Ticket__decrease_reserved',
1154
-            $this,
1155
-            $qty,
1156
-            $this->reserved(),
1157
-            $success
1158
-        );
1159
-        return $success;
1160
-    }
1161
-
1162
-
1163
-    /**
1164
-     * Decreases the reserved count on the specified datetimes.
1165
-     *
1166
-     * @param int           $qty
1167
-     * @param EE_Datetime[] $datetimes
1168
-     * @throws EE_Error
1169
-     * @throws InvalidArgumentException
1170
-     * @throws ReflectionException
1171
-     * @throws InvalidDataTypeException
1172
-     * @throws InvalidInterfaceException
1173
-     * @since 4.9.80.p
1174
-     */
1175
-    protected function decreaseReservedForDatetimes($qty = 1, array $datetimes = [])
1176
-    {
1177
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1178
-        foreach ($datetimes as $datetime) {
1179
-            if ($datetime instanceof EE_Datetime) {
1180
-                $datetime->decreaseReserved($qty);
1181
-            }
1182
-        }
1183
-    }
1184
-
1185
-
1186
-    /**
1187
-     * Gets ticket quantity
1188
-     *
1189
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1190
-     *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
1191
-     *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
1192
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1193
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1194
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1195
-     * @return int
1196
-     * @throws EE_Error
1197
-     * @throws ReflectionException
1198
-     */
1199
-    public function qty($context = '')
1200
-    {
1201
-        switch ($context) {
1202
-            case 'reg_limit':
1203
-                return $this->real_quantity_on_ticket();
1204
-            case 'saleable':
1205
-                return $this->real_quantity_on_ticket('saleable');
1206
-            default:
1207
-                return $this->get_raw('TKT_qty');
1208
-        }
1209
-    }
1210
-
1211
-
1212
-    /**
1213
-     * Gets ticket quantity
1214
-     *
1215
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1216
-     *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1217
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1218
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1219
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1220
-     * @param int    $DTT_ID      the primary key for a particular datetime.
1221
-     *                            set to 0 for all related datetimes
1222
-     * @return int|float          int for finite quantity or float for INF
1223
-     * @throws EE_Error
1224
-     * @throws ReflectionException
1225
-     */
1226
-    public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1227
-    {
1228
-        $raw = $this->get_raw('TKT_qty');
1229
-        // return immediately if it's zero
1230
-        if ($raw === 0) {
1231
-            return $raw;
1232
-        }
1233
-        // echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1234
-        // ensure qty doesn't exceed raw value for THIS ticket
1235
-        $qty = min(EE_INF, $raw);
1236
-        // echo "\n . qty: " . $qty . '<br />';
1237
-        // calculate this ticket's total sales and reservations
1238
-        $sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1239
-        // echo "\n . sold: " . $this->sold() . '<br />';
1240
-        // echo "\n . reserved: " . $this->reserved() . '<br />';
1241
-        // echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1242
-        // first we need to calculate the maximum number of tickets available for the datetime
1243
-        // do we want data for one datetime or all of them ?
1244
-        $query_params = $DTT_ID ? [['DTT_ID' => $DTT_ID]] : [];
1245
-        $datetimes    = $this->datetimes($query_params);
1246
-        if (is_array($datetimes) && ! empty($datetimes)) {
1247
-            foreach ($datetimes as $datetime) {
1248
-                if ($datetime instanceof EE_Datetime) {
1249
-                    $datetime->refresh_from_db();
1250
-                    // echo "\n . . datetime name: " . $datetime->name() . '<br />';
1251
-                    // echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1252
-                    // initialize with no restrictions for each datetime
1253
-                    // but adjust datetime qty based on datetime reg limit
1254
-                    $datetime_qty = min(EE_INF, $datetime->reg_limit());
1255
-                    // echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1256
-                    // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1257
-                    // if we want the actual saleable amount, then we need to consider OTHER ticket sales
1258
-                    // and reservations for this datetime, that do NOT include sales and reservations
1259
-                    // for this ticket (so we add $this->sold() and $this->reserved() back in)
1260
-                    if ($context === 'saleable') {
1261
-                        $datetime_qty = max(
1262
-                            $datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1263
-                            0
1264
-                        );
1265
-                        // echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1266
-                        // echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1267
-                        // echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1268
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1269
-                        $datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1270
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1271
-                    }
1272
-                    $qty = min($datetime_qty, $qty);
1273
-                    // echo "\n . . qty: " . $qty . '<br />';
1274
-                }
1275
-            }
1276
-        }
1277
-        // NOW that we know the  maximum number of tickets available for the datetime
1278
-        // we can finally factor in the details for this specific ticket
1279
-        if ($qty > 0 && $context === 'saleable') {
1280
-            // and subtract the sales for THIS ticket
1281
-            $qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1282
-            // echo "\n . qty: " . $qty . '<br />';
1283
-        }
1284
-        // echo "\nFINAL QTY: " . $qty . "<br /><br />";
1285
-        return $qty;
1286
-    }
1287
-
1288
-
1289
-    /**
1290
-     * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1291
-     *
1292
-     * @param int $qty
1293
-     * @return void
1294
-     * @throws EE_Error
1295
-     * @throws ReflectionException
1296
-     */
1297
-    public function set_qty($qty)
1298
-    {
1299
-        $datetimes = $this->datetimes();
1300
-        foreach ($datetimes as $datetime) {
1301
-            if ($datetime instanceof EE_Datetime) {
1302
-                $qty = min($qty, $datetime->reg_limit());
1303
-            }
1304
-        }
1305
-        $this->set('TKT_qty', $qty);
1306
-    }
1307
-
1308
-
1309
-    /**
1310
-     * Gets uses
1311
-     *
1312
-     * @return int
1313
-     * @throws EE_Error
1314
-     * @throws ReflectionException
1315
-     */
1316
-    public function uses()
1317
-    {
1318
-        return $this->get('TKT_uses');
1319
-    }
1320
-
1321
-
1322
-    /**
1323
-     * Sets uses
1324
-     *
1325
-     * @param int $uses
1326
-     * @return void
1327
-     * @throws EE_Error
1328
-     * @throws ReflectionException
1329
-     */
1330
-    public function set_uses($uses)
1331
-    {
1332
-        $this->set('TKT_uses', $uses);
1333
-    }
1334
-
1335
-
1336
-    /**
1337
-     * returns whether ticket is required or not.
1338
-     *
1339
-     * @return boolean
1340
-     * @throws EE_Error
1341
-     * @throws ReflectionException
1342
-     */
1343
-    public function required()
1344
-    {
1345
-        return $this->get('TKT_required');
1346
-    }
1347
-
1348
-
1349
-    /**
1350
-     * sets the TKT_required property
1351
-     *
1352
-     * @param boolean $required
1353
-     * @return void
1354
-     * @throws EE_Error
1355
-     * @throws ReflectionException
1356
-     */
1357
-    public function set_required($required)
1358
-    {
1359
-        $this->set('TKT_required', $required);
1360
-    }
1361
-
1362
-
1363
-    /**
1364
-     * Gets taxable
1365
-     *
1366
-     * @return boolean
1367
-     * @throws EE_Error
1368
-     * @throws ReflectionException
1369
-     */
1370
-    public function taxable()
1371
-    {
1372
-        return $this->get('TKT_taxable');
1373
-    }
1374
-
1375
-
1376
-    /**
1377
-     * Sets taxable
1378
-     *
1379
-     * @param boolean $taxable
1380
-     * @return void
1381
-     * @throws EE_Error
1382
-     * @throws ReflectionException
1383
-     */
1384
-    public function set_taxable($taxable)
1385
-    {
1386
-        $this->set('TKT_taxable', $taxable);
1387
-    }
1388
-
1389
-
1390
-    /**
1391
-     * Gets is_default
1392
-     *
1393
-     * @return boolean
1394
-     * @throws EE_Error
1395
-     * @throws ReflectionException
1396
-     */
1397
-    public function is_default()
1398
-    {
1399
-        return $this->get('TKT_is_default');
1400
-    }
1401
-
1402
-
1403
-    /**
1404
-     * Sets is_default
1405
-     *
1406
-     * @param boolean $is_default
1407
-     * @return void
1408
-     * @throws EE_Error
1409
-     * @throws ReflectionException
1410
-     */
1411
-    public function set_is_default($is_default)
1412
-    {
1413
-        $this->set('TKT_is_default', $is_default);
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * Gets order
1419
-     *
1420
-     * @return int
1421
-     * @throws EE_Error
1422
-     * @throws ReflectionException
1423
-     */
1424
-    public function order()
1425
-    {
1426
-        return $this->get('TKT_order');
1427
-    }
1428
-
1429
-
1430
-    /**
1431
-     * Sets order
1432
-     *
1433
-     * @param int $order
1434
-     * @return void
1435
-     * @throws EE_Error
1436
-     * @throws ReflectionException
1437
-     */
1438
-    public function set_order($order)
1439
-    {
1440
-        $this->set('TKT_order', $order);
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * Gets row
1446
-     *
1447
-     * @return int
1448
-     * @throws EE_Error
1449
-     * @throws ReflectionException
1450
-     */
1451
-    public function row()
1452
-    {
1453
-        return $this->get('TKT_row');
1454
-    }
1455
-
1456
-
1457
-    /**
1458
-     * Sets row
1459
-     *
1460
-     * @param int $row
1461
-     * @return void
1462
-     * @throws EE_Error
1463
-     * @throws ReflectionException
1464
-     */
1465
-    public function set_row($row)
1466
-    {
1467
-        $this->set('TKT_row', $row);
1468
-    }
1469
-
1470
-
1471
-    /**
1472
-     * Gets deleted
1473
-     *
1474
-     * @return boolean
1475
-     * @throws EE_Error
1476
-     * @throws ReflectionException
1477
-     */
1478
-    public function deleted()
1479
-    {
1480
-        return $this->get('TKT_deleted');
1481
-    }
1482
-
1483
-
1484
-    /**
1485
-     * Sets deleted
1486
-     *
1487
-     * @param boolean $deleted
1488
-     * @return void
1489
-     * @throws EE_Error
1490
-     * @throws ReflectionException
1491
-     */
1492
-    public function set_deleted($deleted)
1493
-    {
1494
-        $this->set('TKT_deleted', $deleted);
1495
-    }
1496
-
1497
-
1498
-    /**
1499
-     * Gets parent
1500
-     *
1501
-     * @return int
1502
-     * @throws EE_Error
1503
-     * @throws ReflectionException
1504
-     */
1505
-    public function parent_ID()
1506
-    {
1507
-        return $this->get('TKT_parent');
1508
-    }
1509
-
1510
-
1511
-    /**
1512
-     * Sets parent
1513
-     *
1514
-     * @param int $parent
1515
-     * @return void
1516
-     * @throws EE_Error
1517
-     * @throws ReflectionException
1518
-     */
1519
-    public function set_parent_ID($parent)
1520
-    {
1521
-        $this->set('TKT_parent', $parent);
1522
-    }
1523
-
1524
-
1525
-    /**
1526
-     * @return boolean
1527
-     * @throws EE_Error
1528
-     * @throws InvalidArgumentException
1529
-     * @throws InvalidDataTypeException
1530
-     * @throws InvalidInterfaceException
1531
-     * @throws ReflectionException
1532
-     */
1533
-    public function reverse_calculate()
1534
-    {
1535
-        return $this->get('TKT_reverse_calculate');
1536
-    }
1537
-
1538
-
1539
-    /**
1540
-     * @param boolean $reverse_calculate
1541
-     * @throws EE_Error
1542
-     * @throws InvalidArgumentException
1543
-     * @throws InvalidDataTypeException
1544
-     * @throws InvalidInterfaceException
1545
-     * @throws ReflectionException
1546
-     */
1547
-    public function set_reverse_calculate($reverse_calculate)
1548
-    {
1549
-        $this->set('TKT_reverse_calculate', $reverse_calculate);
1550
-    }
1551
-
1552
-
1553
-    /**
1554
-     * Gets a string which is handy for showing in gateways etc that describes the ticket.
1555
-     *
1556
-     * @return string
1557
-     * @throws EE_Error
1558
-     * @throws ReflectionException
1559
-     */
1560
-    public function name_and_info()
1561
-    {
1562
-        $times = [];
1563
-        foreach ($this->datetimes() as $datetime) {
1564
-            $times[] = $datetime->start_date_and_time();
1565
-        }
1566
-        /* translators: %1$s ticket name, %2$s start datetimes separated by comma, %3$s ticket price */
1567
-        return sprintf(
1568
-            esc_html__('%1$s @ %2$s for %3$s', 'event_espresso'),
1569
-            $this->name(),
1570
-            implode(', ', $times),
1571
-            $this->pretty_price()
1572
-        );
1573
-    }
1574
-
1575
-
1576
-    /**
1577
-     * Gets name
1578
-     *
1579
-     * @return string
1580
-     * @throws EE_Error
1581
-     * @throws ReflectionException
1582
-     */
1583
-    public function name()
1584
-    {
1585
-        return $this->get('TKT_name');
1586
-    }
1587
-
1588
-
1589
-    /**
1590
-     * Gets price
1591
-     *
1592
-     * @return float
1593
-     * @throws EE_Error
1594
-     * @throws ReflectionException
1595
-     */
1596
-    public function price()
1597
-    {
1598
-        return $this->get('TKT_price');
1599
-    }
1600
-
1601
-
1602
-    /**
1603
-     * Gets all the registrations for this ticket
1604
-     *
1605
-     * @param array $query_params
1606
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1607
-     * @return EE_Registration[]|EE_Base_Class[]
1608
-     * @throws EE_Error
1609
-     * @throws ReflectionException
1610
-     */
1611
-    public function registrations($query_params = [])
1612
-    {
1613
-        return $this->get_many_related('Registration', $query_params);
1614
-    }
1615
-
1616
-
1617
-    /**
1618
-     * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1619
-     *
1620
-     * @return int
1621
-     * @throws EE_Error
1622
-     * @throws ReflectionException
1623
-     */
1624
-    public function update_tickets_sold()
1625
-    {
1626
-        $count_regs_for_this_ticket = $this->count_registrations(
1627
-            [
1628
-                [
1629
-                    'STS_ID'      => EEM_Registration::status_id_approved,
1630
-                    'REG_deleted' => 0,
1631
-                ],
1632
-            ]
1633
-        );
1634
-        $this->set_sold($count_regs_for_this_ticket);
1635
-        $this->save();
1636
-        return $count_regs_for_this_ticket;
1637
-    }
1638
-
1639
-
1640
-    /**
1641
-     * Counts the registrations for this ticket
1642
-     *
1643
-     * @param array $query_params
1644
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1645
-     * @return int
1646
-     * @throws EE_Error
1647
-     * @throws ReflectionException
1648
-     */
1649
-    public function count_registrations($query_params = [])
1650
-    {
1651
-        return $this->count_related('Registration', $query_params);
1652
-    }
1653
-
1654
-
1655
-    /**
1656
-     * Implementation for EEI_Has_Icon interface method.
1657
-     *
1658
-     * @return string
1659
-     * @see EEI_Visual_Representation for comments
1660
-     */
1661
-    public function get_icon()
1662
-    {
1663
-        return '<span class="dashicons dashicons-tickets-alt"></span>';
1664
-    }
1665
-
1666
-
1667
-    /**
1668
-     * Implementation of the EEI_Event_Relation interface method
1669
-     *
1670
-     * @return EE_Event
1671
-     * @throws EE_Error
1672
-     * @throws UnexpectedEntityException
1673
-     * @throws ReflectionException
1674
-     * @see EEI_Event_Relation for comments
1675
-     */
1676
-    public function get_related_event()
1677
-    {
1678
-        // get one datetime to use for getting the event
1679
-        $datetime = $this->first_datetime();
1680
-        if (! $datetime instanceof EE_Datetime) {
1681
-            throw new UnexpectedEntityException(
1682
-                $datetime,
1683
-                'EE_Datetime',
1684
-                sprintf(
1685
-                    esc_html__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1686
-                    $this->name()
1687
-                )
1688
-            );
1689
-        }
1690
-        $event = $datetime->event();
1691
-        if (! $event instanceof EE_Event) {
1692
-            throw new UnexpectedEntityException(
1693
-                $event,
1694
-                'EE_Event',
1695
-                sprintf(
1696
-                    esc_html__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1697
-                    $this->name()
1698
-                )
1699
-            );
1700
-        }
1701
-        return $event;
1702
-    }
1703
-
1704
-
1705
-    /**
1706
-     * Implementation of the EEI_Event_Relation interface method
1707
-     *
1708
-     * @return string
1709
-     * @throws UnexpectedEntityException
1710
-     * @throws EE_Error
1711
-     * @throws ReflectionException
1712
-     * @see EEI_Event_Relation for comments
1713
-     */
1714
-    public function get_event_name()
1715
-    {
1716
-        $event = $this->get_related_event();
1717
-        return $event instanceof EE_Event ? $event->name() : '';
1718
-    }
1719
-
1720
-
1721
-    /**
1722
-     * Implementation of the EEI_Event_Relation interface method
1723
-     *
1724
-     * @return int
1725
-     * @throws UnexpectedEntityException
1726
-     * @throws EE_Error
1727
-     * @throws ReflectionException
1728
-     * @see EEI_Event_Relation for comments
1729
-     */
1730
-    public function get_event_ID()
1731
-    {
1732
-        $event = $this->get_related_event();
1733
-        return $event instanceof EE_Event ? $event->ID() : 0;
1734
-    }
1735
-
1736
-
1737
-    /**
1738
-     * This simply returns whether a ticket can be permanently deleted or not.
1739
-     * The criteria for determining this is whether the ticket has any related registrations.
1740
-     * If there are none then it can be permanently deleted.
1741
-     *
1742
-     * @return bool
1743
-     * @throws EE_Error
1744
-     * @throws ReflectionException
1745
-     */
1746
-    public function is_permanently_deleteable()
1747
-    {
1748
-        return $this->count_registrations() === 0;
1749
-    }
1750
-
1751
-
1752
-    /**
1753
-     * @return int
1754
-     * @throws EE_Error
1755
-     * @throws ReflectionException
1756
-     * @since   5.0.0.p
1757
-     */
1758
-    public function visibility(): int
1759
-    {
1760
-        return $this->get('TKT_visibility');
1761
-    }
1762
-
1763
-
1764
-    /**
1765
-     * @return int
1766
-     * @throws EE_Error
1767
-     * @throws ReflectionException
1768
-     * @since   5.0.0.p
1769
-     */
1770
-    public function isHidden(): int
1771
-    {
1772
-        return $this->visibility() === EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1773
-    }
1774
-
1775
-
1776
-    /**
1777
-     * @return int
1778
-     * @throws EE_Error
1779
-     * @throws ReflectionException
1780
-     * @since   5.0.0.p
1781
-     */
1782
-    public function isNotHidden(): int
1783
-    {
1784
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1785
-    }
1786
-
1787
-
1788
-    /**
1789
-     * @return int
1790
-     * @throws EE_Error
1791
-     * @throws ReflectionException
1792
-     * @since   5.0.0.p
1793
-     */
1794
-    public function isPublicOnly(): int
1795
-    {
1796
-        return $this->isNotHidden() && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE;
1797
-    }
1798
-
1799
-
1800
-    /**
1801
-     * @return int
1802
-     * @throws EE_Error
1803
-     * @throws ReflectionException
1804
-     * @since   5.0.0.p
1805
-     */
1806
-    public function isMembersOnly(): int
1807
-    {
1808
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE
1809
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE;
1810
-    }
1811
-
1812
-
1813
-    /**
1814
-     * @return int
1815
-     * @throws EE_Error
1816
-     * @throws ReflectionException
1817
-     * @since   5.0.0.p
1818
-     */
1819
-    public function isAdminsOnly(): int
1820
-    {
1821
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE
1822
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE;
1823
-    }
1824
-
1825
-
1826
-    /**
1827
-     * @return int
1828
-     * @throws EE_Error
1829
-     * @throws ReflectionException
1830
-     * @since   5.0.0.p
1831
-     */
1832
-    public function isAdminUiOnly(): int
1833
-    {
1834
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE
1835
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE;
1836
-    }
1837
-
1838
-
1839
-    /**
1840
-     * @param int $visibility
1841
-     * @throws EE_Error
1842
-     * @throws ReflectionException
1843
-     * @since   5.0.0.p
1844
-     */
1845
-    public function set_visibility(int $visibility)
1846
-    {
1847
-
1848
-        $ticket_visibility_options = $this->_model->ticketVisibilityOptions();
1849
-        $ticket_visibility         = -1;
1850
-        foreach ($ticket_visibility_options as $ticket_visibility_option) {
1851
-            if ($visibility === $ticket_visibility_option) {
1852
-                $ticket_visibility = $visibility;
1853
-            }
1854
-        }
1855
-        if ($ticket_visibility === -1) {
1856
-            throw new DomainException(
1857
-                sprintf(
1858
-                    esc_html__(
1859
-                        'The supplied ticket visibility setting of "%1$s" is not valid. It needs to match one of the keys in the following array:%2$s %3$s ',
1860
-                        'event_espresso'
1861
-                    ),
1862
-                    $visibility,
1863
-                    '<br />',
1864
-                    var_export($ticket_visibility_options, true)
1865
-                )
1866
-            );
1867
-        }
1868
-        $this->set('TKT_visibility', $ticket_visibility);
1869
-    }
1870
-
1871
-
1872
-    /**
1873
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1874
-     * @param string                   $relationName
1875
-     * @param array                    $extra_join_model_fields_n_values
1876
-     * @param string|null              $cache_id
1877
-     * @return EE_Base_Class
1878
-     * @throws EE_Error
1879
-     * @throws ReflectionException
1880
-     * @since   5.0.0.p
1881
-     */
1882
-    public function _add_relation_to(
1883
-        $otherObjectModelObjectOrID,
1884
-        $relationName,
1885
-        $extra_join_model_fields_n_values = [],
1886
-        $cache_id = null
1887
-    ) {
1888
-        if ($relationName === 'Datetime' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1889
-            /** @var EE_Datetime $datetime */
1890
-            $datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1891
-            $datetime->increaseSold($this->sold(), false);
1892
-            $datetime->increaseReserved($this->reserved());
1893
-            $datetime->save();
1894
-            $otherObjectModelObjectOrID = $datetime;
1895
-        }
1896
-        return parent::_add_relation_to(
1897
-            $otherObjectModelObjectOrID,
1898
-            $relationName,
1899
-            $extra_join_model_fields_n_values,
1900
-            $cache_id
1901
-        );
1902
-    }
1903
-
1904
-
1905
-    /**
1906
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1907
-     * @param string                   $relationName
1908
-     * @param array                    $where_query
1909
-     * @return bool|EE_Base_Class|null
1910
-     * @throws EE_Error
1911
-     * @throws ReflectionException
1912
-     * @since   5.0.0.p
1913
-     */
1914
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1915
-    {
1916
-        // if we're adding a new relation to a datetime
1917
-        if ($relationName === 'Datetime' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1918
-            /** @var EE_Datetime $datetime */
1919
-            $datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1920
-            $datetime->decreaseSold($this->sold());
1921
-            $datetime->decreaseReserved($this->reserved());
1922
-            $datetime->save();
1923
-            $otherObjectModelObjectOrID = $datetime;
1924
-        }
1925
-        return parent::_remove_relation_to(
1926
-            $otherObjectModelObjectOrID,
1927
-            $relationName,
1928
-            $where_query
1929
-        );
1930
-    }
1931
-
1932
-
1933
-    /**
1934
-     * Removes ALL the related things for the $relationName.
1935
-     *
1936
-     * @param string $relationName
1937
-     * @param array  $where_query_params
1938
-     * @return EE_Base_Class
1939
-     * @throws ReflectionException
1940
-     * @throws InvalidArgumentException
1941
-     * @throws InvalidInterfaceException
1942
-     * @throws InvalidDataTypeException
1943
-     * @throws EE_Error
1944
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1945
-     */
1946
-    public function _remove_relations($relationName, $where_query_params = [])
1947
-    {
1948
-        if ($relationName === 'Datetime') {
1949
-            $datetimes = $this->datetimes();
1950
-            foreach ($datetimes as $datetime) {
1951
-                $datetime->decreaseSold($this->sold());
1952
-                $datetime->decreaseReserved($this->reserved());
1953
-                $datetime->save();
1954
-            }
1955
-        }
1956
-        return parent::_remove_relations($relationName, $where_query_params);
1957
-    }
1958
-
1959
-
1960
-    /*******************************************************************
17
+	/**
18
+	 * TicKet Archived:
19
+	 * constant used by ticket_status() to indicate that a ticket is archived
20
+	 * and no longer available for purchase
21
+	 */
22
+	const archived = 'TKA';
23
+
24
+	/**
25
+	 * TicKet Expired:
26
+	 * constant used by ticket_status() to indicate that a ticket is expired
27
+	 * and no longer available for purchase
28
+	 */
29
+	const expired = 'TKE';
30
+
31
+	/**
32
+	 * TicKet On sale:
33
+	 * constant used by ticket_status() to indicate that a ticket is On Sale
34
+	 * and IS available for purchase
35
+	 */
36
+	const onsale = 'TKO';
37
+
38
+	/**
39
+	 * TicKet Pending:
40
+	 * constant used by ticket_status() to indicate that a ticket is pending
41
+	 * and is NOT YET available for purchase
42
+	 */
43
+	const pending = 'TKP';
44
+
45
+	/**
46
+	 * TicKet Sold out:
47
+	 * constant used by ticket_status() to indicate that a ticket is sold out
48
+	 * and no longer available for purchases
49
+	 */
50
+	const sold_out = 'TKS';
51
+
52
+	/**
53
+	 * extra meta key for tracking ticket reservations
54
+	 *
55
+	 * @type string
56
+	 */
57
+	const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
58
+
59
+	/**
60
+	 * override of parent property
61
+	 *
62
+	 * @var EEM_Ticket
63
+	 */
64
+	protected $_model;
65
+
66
+	/**
67
+	 * cached result from method of the same name
68
+	 *
69
+	 * @var float $_ticket_total_with_taxes
70
+	 */
71
+	private $_ticket_total_with_taxes;
72
+
73
+	/**
74
+	 * @var TicketPriceModifiers
75
+	 */
76
+	protected $ticket_price_modifiers;
77
+
78
+
79
+	/**
80
+	 * @param array  $props_n_values          incoming values
81
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
82
+	 *                                        used.)
83
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
84
+	 *                                        date_format and the second value is the time format
85
+	 * @return EE_Ticket
86
+	 * @throws EE_Error
87
+	 * @throws ReflectionException
88
+	 */
89
+	public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
90
+	{
91
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
92
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
93
+	}
94
+
95
+
96
+	/**
97
+	 * @param array  $props_n_values  incoming values from the database
98
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
99
+	 *                                the website will be used.
100
+	 * @return EE_Ticket
101
+	 * @throws EE_Error
102
+	 * @throws ReflectionException
103
+	 */
104
+	public static function new_instance_from_db($props_n_values = [], $timezone = null)
105
+	{
106
+		return new self($props_n_values, true, $timezone);
107
+	}
108
+
109
+
110
+	/**
111
+	 * @param array  $fieldValues
112
+	 * @param false  $bydb
113
+	 * @param string $timezone
114
+	 * @param array  $date_formats
115
+	 * @throws EE_Error
116
+	 * @throws ReflectionException
117
+	 */
118
+	public function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
119
+	{
120
+		parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
121
+		$this->ticket_price_modifiers = new TicketPriceModifiers($this);
122
+	}
123
+
124
+
125
+	/**
126
+	 * @return bool
127
+	 * @throws EE_Error
128
+	 * @throws ReflectionException
129
+	 */
130
+	public function parent()
131
+	{
132
+		return $this->get('TKT_parent');
133
+	}
134
+
135
+
136
+	/**
137
+	 * return if a ticket has quantities available for purchase
138
+	 *
139
+	 * @param int $DTT_ID the primary key for a particular datetime
140
+	 * @return boolean
141
+	 * @throws EE_Error
142
+	 * @throws ReflectionException
143
+	 */
144
+	public function available($DTT_ID = 0)
145
+	{
146
+		// are we checking availability for a particular datetime ?
147
+		if ($DTT_ID) {
148
+			// get that datetime object
149
+			$datetime = $this->get_first_related('Datetime', [['DTT_ID' => $DTT_ID]]);
150
+			// if  ticket sales for this datetime have exceeded the reg limit...
151
+			if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
152
+				return false;
153
+			}
154
+		}
155
+		// datetime is still open for registration, but is this ticket sold out ?
156
+		return $this->qty() < 1 || $this->qty() > $this->sold();
157
+	}
158
+
159
+
160
+	/**
161
+	 * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
162
+	 *
163
+	 * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
164
+	 *                               relevant status const
165
+	 * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
166
+	 *                               further processing
167
+	 * @return mixed status int if the display string isn't requested
168
+	 * @throws EE_Error
169
+	 * @throws ReflectionException
170
+	 */
171
+	public function ticket_status($display = false, $remaining = null)
172
+	{
173
+		$remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
174
+		if (! $remaining) {
175
+			return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
176
+		}
177
+		if ($this->get('TKT_deleted')) {
178
+			return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
179
+		}
180
+		if ($this->is_expired()) {
181
+			return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
182
+		}
183
+		if ($this->is_pending()) {
184
+			return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
185
+		}
186
+		if ($this->is_on_sale()) {
187
+			return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
188
+		}
189
+		return '';
190
+	}
191
+
192
+
193
+	/**
194
+	 * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
195
+	 * considering ALL the factors used for figuring that out.
196
+	 *
197
+	 * @param int $DTT_ID if an int above 0 is included here then we get a specific dtt.
198
+	 * @return boolean         true = tickets remaining, false not.
199
+	 * @throws EE_Error
200
+	 * @throws ReflectionException
201
+	 */
202
+	public function is_remaining($DTT_ID = 0)
203
+	{
204
+		$num_remaining = $this->remaining($DTT_ID);
205
+		if ($num_remaining === 0) {
206
+			return false;
207
+		}
208
+		if ($num_remaining > 0 && $num_remaining < $this->min()) {
209
+			return false;
210
+		}
211
+		return true;
212
+	}
213
+
214
+
215
+	/**
216
+	 * return the total number of tickets available for purchase
217
+	 *
218
+	 * @param int $DTT_ID  the primary key for a particular datetime.
219
+	 *                     set to 0 for all related datetimes
220
+	 * @return int
221
+	 * @throws EE_Error
222
+	 * @throws ReflectionException
223
+	 */
224
+	public function remaining($DTT_ID = 0)
225
+	{
226
+		return $this->real_quantity_on_ticket('saleable', $DTT_ID);
227
+	}
228
+
229
+
230
+	/**
231
+	 * Gets min
232
+	 *
233
+	 * @return int
234
+	 * @throws EE_Error
235
+	 * @throws ReflectionException
236
+	 */
237
+	public function min()
238
+	{
239
+		return $this->get('TKT_min');
240
+	}
241
+
242
+
243
+	/**
244
+	 * return if a ticket is no longer available cause its available dates have expired.
245
+	 *
246
+	 * @return boolean
247
+	 * @throws EE_Error
248
+	 * @throws ReflectionException
249
+	 */
250
+	public function is_expired()
251
+	{
252
+		return ($this->get_raw('TKT_end_date') < time());
253
+	}
254
+
255
+
256
+	/**
257
+	 * Return if a ticket is yet to go on sale or not
258
+	 *
259
+	 * @return boolean
260
+	 * @throws EE_Error
261
+	 * @throws ReflectionException
262
+	 */
263
+	public function is_pending()
264
+	{
265
+		return ($this->get_raw('TKT_start_date') >= time());
266
+	}
267
+
268
+
269
+	/**
270
+	 * Return if a ticket is on sale or not
271
+	 *
272
+	 * @return boolean
273
+	 * @throws EE_Error
274
+	 * @throws ReflectionException
275
+	 */
276
+	public function is_on_sale()
277
+	{
278
+		return ($this->get_raw('TKT_start_date') <= time() && $this->get_raw('TKT_end_date') >= time());
279
+	}
280
+
281
+
282
+	/**
283
+	 * This returns the chronologically last datetime that this ticket is associated with
284
+	 *
285
+	 * @param string $date_format
286
+	 * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
287
+	 *                            the end date ie: Jan 01 "to" Dec 31
288
+	 * @return string
289
+	 * @throws EE_Error
290
+	 * @throws ReflectionException
291
+	 */
292
+	public function date_range($date_format = '', $conjunction = ' - ')
293
+	{
294
+		$date_format = ! empty($date_format) ? $date_format : $this->_dt_frmt;
295
+		$first_date  = $this->first_datetime() instanceof EE_Datetime
296
+			? $this->first_datetime()->get_i18n_datetime('DTT_EVT_start', $date_format)
297
+			: '';
298
+		$last_date   = $this->last_datetime() instanceof EE_Datetime
299
+			? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $date_format)
300
+			: '';
301
+
302
+		return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
303
+	}
304
+
305
+
306
+	/**
307
+	 * This returns the chronologically first datetime that this ticket is associated with
308
+	 *
309
+	 * @return EE_Datetime
310
+	 * @throws EE_Error
311
+	 * @throws ReflectionException
312
+	 */
313
+	public function first_datetime()
314
+	{
315
+		$datetimes = $this->datetimes(['limit' => 1]);
316
+		return reset($datetimes);
317
+	}
318
+
319
+
320
+	/**
321
+	 * Gets all the datetimes this ticket can be used for attending.
322
+	 * Unless otherwise specified, orders datetimes by start date.
323
+	 *
324
+	 * @param array $query_params
325
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
326
+	 * @return EE_Datetime[]|EE_Base_Class[]
327
+	 * @throws EE_Error
328
+	 * @throws ReflectionException
329
+	 */
330
+	public function datetimes($query_params = [])
331
+	{
332
+		if (! isset($query_params['order_by'])) {
333
+			$query_params['order_by']['DTT_order'] = 'ASC';
334
+		}
335
+		return $this->get_many_related('Datetime', $query_params);
336
+	}
337
+
338
+
339
+	/**
340
+	 * This returns the chronologically last datetime that this ticket is associated with
341
+	 *
342
+	 * @return EE_Datetime
343
+	 * @throws EE_Error
344
+	 * @throws ReflectionException
345
+	 */
346
+	public function last_datetime()
347
+	{
348
+		$datetimes = $this->datetimes(['limit' => 1, 'order_by' => ['DTT_EVT_start' => 'DESC']]);
349
+		return end($datetimes);
350
+	}
351
+
352
+
353
+	/**
354
+	 * This returns the total tickets sold depending on the given parameters.
355
+	 *
356
+	 * @param string $what    Can be one of two options: 'ticket', 'datetime'.
357
+	 *                        'ticket' = total ticket sales for all datetimes this ticket is related to
358
+	 *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
359
+	 *                        'datetime' = total ticket sales in the datetime_ticket table.
360
+	 *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
361
+	 *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
362
+	 * @param int    $dtt_id  [optional] include the dtt_id with $what = 'datetime'.
363
+	 * @return mixed (array|int)          how many tickets have sold
364
+	 * @throws EE_Error
365
+	 * @throws ReflectionException
366
+	 */
367
+	public function tickets_sold($what = 'ticket', $dtt_id = null)
368
+	{
369
+		$total        = 0;
370
+		$tickets_sold = $this->_all_tickets_sold();
371
+		switch ($what) {
372
+			case 'ticket':
373
+				return $tickets_sold['ticket'];
374
+
375
+			case 'datetime':
376
+				if (empty($tickets_sold['datetime'])) {
377
+					return $total;
378
+				}
379
+				if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
380
+					EE_Error::add_error(
381
+						esc_html__(
382
+							'You\'ve requested the amount of tickets sold for a given ticket and datetime, however there are no records for the datetime id you included.  Are you SURE that is a datetime related to this ticket?',
383
+							'event_espresso'
384
+						),
385
+						__FILE__,
386
+						__FUNCTION__,
387
+						__LINE__
388
+					);
389
+					return $total;
390
+				}
391
+				return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
392
+
393
+			default:
394
+				return $total;
395
+		}
396
+	}
397
+
398
+
399
+	/**
400
+	 * This returns an array indexed by datetime_id for tickets sold with this ticket.
401
+	 *
402
+	 * @return EE_Ticket[]
403
+	 * @throws EE_Error
404
+	 * @throws ReflectionException
405
+	 */
406
+	protected function _all_tickets_sold()
407
+	{
408
+		$datetimes    = $this->get_many_related('Datetime');
409
+		$tickets_sold = [];
410
+		if (! empty($datetimes)) {
411
+			foreach ($datetimes as $datetime) {
412
+				$tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
413
+			}
414
+		}
415
+		// Tickets sold
416
+		$tickets_sold['ticket'] = $this->sold();
417
+		return $tickets_sold;
418
+	}
419
+
420
+
421
+	/**
422
+	 * This returns the base price object for the ticket.
423
+	 *
424
+	 * @param bool $return_array whether to return as an array indexed by price id or just the object.
425
+	 * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
426
+	 * @throws EE_Error
427
+	 * @throws ReflectionException
428
+	 */
429
+	public function base_price(bool $return_array = false)
430
+	{
431
+		$base_price = $this->ticket_price_modifiers->getBasePrice();
432
+		if (! empty($base_price)) {
433
+			return $return_array ? $base_price : reset($base_price);
434
+		}
435
+		$_where = ['Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price];
436
+		return $return_array
437
+			? $this->get_many_related('Price', [$_where])
438
+			: $this->get_first_related('Price', [$_where]);
439
+	}
440
+
441
+
442
+	/**
443
+	 * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
444
+	 *
445
+	 * @return EE_Price[]
446
+	 * @throws EE_Error
447
+	 * @throws ReflectionException
448
+	 */
449
+	public function price_modifiers(): array
450
+	{
451
+		$price_modifiers = $this->usesGlobalTaxes()
452
+			? $this->ticket_price_modifiers->getAllDiscountAndSurchargeModifiersForTicket()
453
+			: $this->ticket_price_modifiers ->getAllModifiersForTicket();
454
+		if (! empty($price_modifiers)) {
455
+			return $price_modifiers;
456
+		}
457
+		return $this->prices(
458
+			[
459
+				[
460
+					'Price_Type.PBT_ID' => [
461
+						'NOT IN',
462
+						[EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax],
463
+					]
464
+				]
465
+			]
466
+		);
467
+	}
468
+
469
+
470
+	/**
471
+	 * This returns ONLY the TAX price modifiers for the ticket
472
+	 *
473
+	 * @return EE_Price[]
474
+	 * @throws EE_Error
475
+	 * @throws ReflectionException
476
+	 */
477
+	public function tax_price_modifiers(): array
478
+	{
479
+		$tax_price_modifiers = $this->ticket_price_modifiers->getAllTaxesForTicket();
480
+		if (! empty($tax_price_modifiers)) {
481
+			return $tax_price_modifiers;
482
+		}
483
+		return $this->prices([['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax]]);
484
+	}
485
+
486
+
487
+	/**
488
+	 * Gets all the prices that combine to form the final price of this ticket
489
+	 *
490
+	 * @param array $query_params
491
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
492
+	 * @return EE_Price[]|EE_Base_Class[]
493
+	 * @throws EE_Error
494
+	 * @throws ReflectionException
495
+	 */
496
+	public function prices(array $query_params = []): array
497
+	{
498
+		if (! isset($query_params['order_by'])) {
499
+			$query_params['order_by']['PRC_order'] = 'ASC';
500
+		}
501
+		return $this->get_many_related('Price', $query_params);
502
+	}
503
+
504
+
505
+	/**
506
+	 * Gets all the ticket datetimes (ie, relations between datetimes and tickets)
507
+	 *
508
+	 * @param array $query_params
509
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
510
+	 * @return EE_Datetime_Ticket|EE_Base_Class[]
511
+	 * @throws EE_Error
512
+	 * @throws ReflectionException
513
+	 */
514
+	public function datetime_tickets($query_params = [])
515
+	{
516
+		return $this->get_many_related('Datetime_Ticket', $query_params);
517
+	}
518
+
519
+
520
+	/**
521
+	 * Gets all the datetimes from the db ordered by DTT_order
522
+	 *
523
+	 * @param boolean $show_expired
524
+	 * @param boolean $show_deleted
525
+	 * @return EE_Datetime[]
526
+	 * @throws EE_Error
527
+	 * @throws ReflectionException
528
+	 */
529
+	public function datetimes_ordered($show_expired = true, $show_deleted = false)
530
+	{
531
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
532
+			$this->ID(),
533
+			$show_expired,
534
+			$show_deleted
535
+		);
536
+	}
537
+
538
+
539
+	/**
540
+	 * Gets ID
541
+	 *
542
+	 * @return int
543
+	 * @throws EE_Error
544
+	 * @throws ReflectionException
545
+	 */
546
+	public function ID()
547
+	{
548
+		return (int) $this->get('TKT_ID');
549
+	}
550
+
551
+
552
+	/**
553
+	 * get the author of the ticket.
554
+	 *
555
+	 * @return int
556
+	 * @throws EE_Error
557
+	 * @throws ReflectionException
558
+	 * @since 4.5.0
559
+	 */
560
+	public function wp_user()
561
+	{
562
+		return $this->get('TKT_wp_user');
563
+	}
564
+
565
+
566
+	/**
567
+	 * Gets the template for the ticket
568
+	 *
569
+	 * @return EE_Ticket_Template|EE_Base_Class
570
+	 * @throws EE_Error
571
+	 * @throws ReflectionException
572
+	 */
573
+	public function template()
574
+	{
575
+		return $this->get_first_related('Ticket_Template');
576
+	}
577
+
578
+
579
+	/**
580
+	 * Simply returns an array of EE_Price objects that are taxes.
581
+	 *
582
+	 * @return EE_Price[]
583
+	 * @throws EE_Error
584
+	 * @throws ReflectionException
585
+	 */
586
+	public function get_ticket_taxes_for_admin(): array
587
+	{
588
+		return $this->usesGlobalTaxes() ? EE_Taxes::get_taxes_for_admin() : $this->tax_price_modifiers();
589
+	}
590
+
591
+
592
+	/**
593
+	 * alias of taxable() to better indicate that ticket uses the legacy method of applying default "global" taxes
594
+	 * as opposed to having tax price modifiers added directly to each ticket
595
+	 *
596
+	 * @return bool
597
+	 * @throws EE_Error
598
+	 * @throws ReflectionException
599
+	 * @since   5.0.0.p
600
+	 */
601
+	public function usesGlobalTaxes(): bool
602
+	{
603
+		return $this->taxable();
604
+	}
605
+
606
+
607
+	/**
608
+	 * @return float
609
+	 * @throws EE_Error
610
+	 * @throws ReflectionException
611
+	 */
612
+	public function ticket_price()
613
+	{
614
+		return $this->get('TKT_price');
615
+	}
616
+
617
+
618
+	/**
619
+	 * @return mixed
620
+	 * @throws EE_Error
621
+	 * @throws ReflectionException
622
+	 */
623
+	public function pretty_price()
624
+	{
625
+		return $this->get_pretty('TKT_price');
626
+	}
627
+
628
+
629
+	/**
630
+	 * @return bool
631
+	 * @throws EE_Error
632
+	 * @throws ReflectionException
633
+	 */
634
+	public function is_free()
635
+	{
636
+		return $this->get_ticket_total_with_taxes() === (float) 0;
637
+	}
638
+
639
+
640
+	/**
641
+	 * get_ticket_total_with_taxes
642
+	 *
643
+	 * @param bool $no_cache
644
+	 * @return float
645
+	 * @throws EE_Error
646
+	 * @throws ReflectionException
647
+	 */
648
+	public function get_ticket_total_with_taxes($no_cache = false)
649
+	{
650
+		if ($this->_ticket_total_with_taxes === null || $no_cache) {
651
+			$this->_ticket_total_with_taxes = $this->usesGlobalTaxes()
652
+				? $this->get_ticket_subtotal() + $this->get_ticket_taxes_total_for_admin()
653
+				: $this->ticket_price();
654
+		}
655
+		return (float) $this->_ticket_total_with_taxes;
656
+	}
657
+
658
+
659
+	/**
660
+	 * @throws EE_Error
661
+	 * @throws ReflectionException
662
+	 */
663
+	public function ensure_TKT_Price_correct()
664
+	{
665
+		$this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
666
+		$this->save();
667
+	}
668
+
669
+
670
+	/**
671
+	 * @return float
672
+	 * @throws EE_Error
673
+	 * @throws ReflectionException
674
+	 */
675
+	public function get_ticket_subtotal()
676
+	{
677
+		return EE_Taxes::get_subtotal_for_admin($this);
678
+	}
679
+
680
+
681
+	/**
682
+	 * Returns the total taxes applied to this ticket
683
+	 *
684
+	 * @return float
685
+	 * @throws EE_Error
686
+	 * @throws ReflectionException
687
+	 */
688
+	public function get_ticket_taxes_total_for_admin()
689
+	{
690
+		return EE_Taxes::get_total_taxes_for_admin($this);
691
+	}
692
+
693
+
694
+	/**
695
+	 * Sets name
696
+	 *
697
+	 * @param string $name
698
+	 * @throws EE_Error
699
+	 * @throws ReflectionException
700
+	 */
701
+	public function set_name($name)
702
+	{
703
+		$this->set('TKT_name', $name);
704
+	}
705
+
706
+
707
+	/**
708
+	 * Gets description
709
+	 *
710
+	 * @return string
711
+	 * @throws EE_Error
712
+	 * @throws ReflectionException
713
+	 */
714
+	public function description()
715
+	{
716
+		return $this->get('TKT_description');
717
+	}
718
+
719
+
720
+	/**
721
+	 * Sets description
722
+	 *
723
+	 * @param string $description
724
+	 * @throws EE_Error
725
+	 * @throws ReflectionException
726
+	 */
727
+	public function set_description($description)
728
+	{
729
+		$this->set('TKT_description', $description);
730
+	}
731
+
732
+
733
+	/**
734
+	 * Gets start_date
735
+	 *
736
+	 * @param string|null $date_format
737
+	 * @param string|null $time_format
738
+	 * @return string
739
+	 * @throws EE_Error
740
+	 * @throws ReflectionException
741
+	 */
742
+	public function start_date(?string $date_format = '', ?string $time_format = ''): string
743
+	{
744
+		return $this->_get_datetime('TKT_start_date', $date_format, $time_format);
745
+	}
746
+
747
+
748
+	/**
749
+	 * Sets start_date
750
+	 *
751
+	 * @param string $start_date
752
+	 * @return void
753
+	 * @throws EE_Error
754
+	 * @throws ReflectionException
755
+	 */
756
+	public function set_start_date($start_date)
757
+	{
758
+		$this->_set_date_time('B', $start_date, 'TKT_start_date');
759
+	}
760
+
761
+
762
+	/**
763
+	 * Gets end_date
764
+	 *
765
+	 * @param string|null $date_format
766
+	 * @param string|null $time_format
767
+	 * @return string
768
+	 * @throws EE_Error
769
+	 * @throws ReflectionException
770
+	 */
771
+	public function end_date(?string $date_format = '', ?string $time_format = ''): string
772
+	{
773
+		return $this->_get_datetime('TKT_end_date', $date_format, $time_format);
774
+	}
775
+
776
+
777
+	/**
778
+	 * Sets end_date
779
+	 *
780
+	 * @param string $end_date
781
+	 * @return void
782
+	 * @throws EE_Error
783
+	 * @throws ReflectionException
784
+	 */
785
+	public function set_end_date($end_date)
786
+	{
787
+		$this->_set_date_time('B', $end_date, 'TKT_end_date');
788
+	}
789
+
790
+
791
+	/**
792
+	 * Sets sell until time
793
+	 *
794
+	 * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
795
+	 * @throws EE_Error
796
+	 * @throws ReflectionException
797
+	 * @since 4.5.0
798
+	 */
799
+	public function set_end_time($time)
800
+	{
801
+		$this->_set_time_for($time, 'TKT_end_date');
802
+	}
803
+
804
+
805
+	/**
806
+	 * Sets min
807
+	 *
808
+	 * @param int $min
809
+	 * @return void
810
+	 * @throws EE_Error
811
+	 * @throws ReflectionException
812
+	 */
813
+	public function set_min($min)
814
+	{
815
+		$this->set('TKT_min', $min);
816
+	}
817
+
818
+
819
+	/**
820
+	 * Gets max
821
+	 *
822
+	 * @return int
823
+	 * @throws EE_Error
824
+	 * @throws ReflectionException
825
+	 */
826
+	public function max()
827
+	{
828
+		return $this->get('TKT_max');
829
+	}
830
+
831
+
832
+	/**
833
+	 * Sets max
834
+	 *
835
+	 * @param int $max
836
+	 * @return void
837
+	 * @throws EE_Error
838
+	 * @throws ReflectionException
839
+	 */
840
+	public function set_max($max)
841
+	{
842
+		$this->set('TKT_max', $max);
843
+	}
844
+
845
+
846
+	/**
847
+	 * Sets price
848
+	 *
849
+	 * @param float $price
850
+	 * @return void
851
+	 * @throws EE_Error
852
+	 * @throws ReflectionException
853
+	 */
854
+	public function set_price($price)
855
+	{
856
+		$this->set('TKT_price', $price);
857
+	}
858
+
859
+
860
+	/**
861
+	 * Gets sold
862
+	 *
863
+	 * @return int
864
+	 * @throws EE_Error
865
+	 * @throws ReflectionException
866
+	 */
867
+	public function sold(): int
868
+	{
869
+		return (int) $this->get_raw('TKT_sold');
870
+	}
871
+
872
+
873
+	/**
874
+	 * Sets sold
875
+	 *
876
+	 * @param int $sold
877
+	 * @return void
878
+	 * @throws EE_Error
879
+	 * @throws ReflectionException
880
+	 */
881
+	public function set_sold($sold)
882
+	{
883
+		// sold can not go below zero
884
+		$sold = max(0, $sold);
885
+		$this->set('TKT_sold', $sold);
886
+	}
887
+
888
+
889
+	/**
890
+	 * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
891
+	 * associated datetimes.
892
+	 *
893
+	 * @param int $qty
894
+	 * @return boolean
895
+	 * @throws EE_Error
896
+	 * @throws InvalidArgumentException
897
+	 * @throws InvalidDataTypeException
898
+	 * @throws InvalidInterfaceException
899
+	 * @throws ReflectionException
900
+	 * @since 4.9.80.p
901
+	 */
902
+	public function increaseSold($qty = 1)
903
+	{
904
+		$qty = absint($qty);
905
+		// increment sold and decrement reserved datetime quantities simultaneously
906
+		// don't worry about failures, because they must have already had a spot reserved
907
+		$this->increaseSoldForDatetimes($qty);
908
+		// Increment and decrement ticket quantities simultaneously
909
+		$success = $this->adjustNumericFieldsInDb(
910
+			[
911
+				'TKT_reserved' => $qty * -1,
912
+				'TKT_sold'     => $qty,
913
+			]
914
+		);
915
+		do_action(
916
+			'AHEE__EE_Ticket__increase_sold',
917
+			$this,
918
+			$qty,
919
+			$this->sold(),
920
+			$success
921
+		);
922
+		return $success;
923
+	}
924
+
925
+
926
+	/**
927
+	 * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
928
+	 *
929
+	 * @param int           $qty positive or negative. Positive means to increase sold counts (and decrease reserved
930
+	 *                           counts), Negative means to decreases old counts (and increase reserved counts).
931
+	 * @param EE_Datetime[] $datetimes
932
+	 * @throws EE_Error
933
+	 * @throws InvalidArgumentException
934
+	 * @throws InvalidDataTypeException
935
+	 * @throws InvalidInterfaceException
936
+	 * @throws ReflectionException
937
+	 * @since 4.9.80.p
938
+	 */
939
+	protected function increaseSoldForDatetimes($qty, array $datetimes = [])
940
+	{
941
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
942
+		foreach ($datetimes as $datetime) {
943
+			$datetime->increaseSold($qty);
944
+		}
945
+	}
946
+
947
+
948
+	/**
949
+	 * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
950
+	 * DB and then updates the model objects.
951
+	 * Does not affect the reserved counts.
952
+	 *
953
+	 * @param int $qty
954
+	 * @return boolean
955
+	 * @throws EE_Error
956
+	 * @throws InvalidArgumentException
957
+	 * @throws InvalidDataTypeException
958
+	 * @throws InvalidInterfaceException
959
+	 * @throws ReflectionException
960
+	 * @since 4.9.80.p
961
+	 */
962
+	public function decreaseSold($qty = 1)
963
+	{
964
+		$qty = absint($qty);
965
+		$this->decreaseSoldForDatetimes($qty);
966
+		$success = $this->adjustNumericFieldsInDb(
967
+			[
968
+				'TKT_sold' => $qty * -1,
969
+			]
970
+		);
971
+		do_action(
972
+			'AHEE__EE_Ticket__decrease_sold',
973
+			$this,
974
+			$qty,
975
+			$this->sold(),
976
+			$success
977
+		);
978
+		return $success;
979
+	}
980
+
981
+
982
+	/**
983
+	 * Decreases sold on related datetimes
984
+	 *
985
+	 * @param int           $qty
986
+	 * @param EE_Datetime[] $datetimes
987
+	 * @return void
988
+	 * @throws EE_Error
989
+	 * @throws InvalidArgumentException
990
+	 * @throws InvalidDataTypeException
991
+	 * @throws InvalidInterfaceException
992
+	 * @throws ReflectionException
993
+	 * @since 4.9.80.p
994
+	 */
995
+	protected function decreaseSoldForDatetimes($qty = 1, array $datetimes = [])
996
+	{
997
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
998
+		if (is_array($datetimes)) {
999
+			foreach ($datetimes as $datetime) {
1000
+				if ($datetime instanceof EE_Datetime) {
1001
+					$datetime->decreaseSold($qty);
1002
+				}
1003
+			}
1004
+		}
1005
+	}
1006
+
1007
+
1008
+	/**
1009
+	 * Gets qty of reserved tickets
1010
+	 *
1011
+	 * @return int
1012
+	 * @throws EE_Error
1013
+	 * @throws ReflectionException
1014
+	 */
1015
+	public function reserved(): int
1016
+	{
1017
+		return (int) $this->get_raw('TKT_reserved');
1018
+	}
1019
+
1020
+
1021
+	/**
1022
+	 * Sets reserved
1023
+	 *
1024
+	 * @param int $reserved
1025
+	 * @return void
1026
+	 * @throws EE_Error
1027
+	 * @throws ReflectionException
1028
+	 */
1029
+	public function set_reserved($reserved)
1030
+	{
1031
+		// reserved can not go below zero
1032
+		$reserved = max(0, (int) $reserved);
1033
+		$this->set('TKT_reserved', $reserved);
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1039
+	 *
1040
+	 * @param int    $qty
1041
+	 * @param string $source
1042
+	 * @return bool whether we successfully reserved the ticket or not.
1043
+	 * @throws EE_Error
1044
+	 * @throws InvalidArgumentException
1045
+	 * @throws ReflectionException
1046
+	 * @throws InvalidDataTypeException
1047
+	 * @throws InvalidInterfaceException
1048
+	 * @since 4.9.80.p
1049
+	 */
1050
+	public function increaseReserved($qty = 1, $source = 'unknown')
1051
+	{
1052
+		$qty = absint($qty);
1053
+		do_action(
1054
+			'AHEE__EE_Ticket__increase_reserved__begin',
1055
+			$this,
1056
+			$qty,
1057
+			$source
1058
+		);
1059
+		$this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "{$qty} from {$source}");
1060
+		$success                         = false;
1061
+		$datetimes_adjusted_successfully = $this->increaseReservedForDatetimes($qty);
1062
+		if ($datetimes_adjusted_successfully) {
1063
+			$success = $this->incrementFieldConditionallyInDb(
1064
+				'TKT_reserved',
1065
+				'TKT_sold',
1066
+				'TKT_qty',
1067
+				$qty
1068
+			);
1069
+			if (! $success) {
1070
+				// The datetimes were successfully bumped, but not the
1071
+				// ticket. So we need to manually rollback the datetimes.
1072
+				$this->decreaseReservedForDatetimes($qty);
1073
+			}
1074
+		}
1075
+		do_action(
1076
+			'AHEE__EE_Ticket__increase_reserved',
1077
+			$this,
1078
+			$qty,
1079
+			$this->reserved(),
1080
+			$success
1081
+		);
1082
+		return $success;
1083
+	}
1084
+
1085
+
1086
+	/**
1087
+	 * Increases reserved counts on related datetimes
1088
+	 *
1089
+	 * @param int           $qty
1090
+	 * @param EE_Datetime[] $datetimes
1091
+	 * @return boolean indicating success
1092
+	 * @throws EE_Error
1093
+	 * @throws InvalidArgumentException
1094
+	 * @throws InvalidDataTypeException
1095
+	 * @throws InvalidInterfaceException
1096
+	 * @throws ReflectionException
1097
+	 * @since 4.9.80.p
1098
+	 */
1099
+	protected function increaseReservedForDatetimes($qty = 1, array $datetimes = [])
1100
+	{
1101
+		$datetimes         = ! empty($datetimes) ? $datetimes : $this->datetimes();
1102
+		$datetimes_updated = [];
1103
+		$limit_exceeded    = false;
1104
+		if (is_array($datetimes)) {
1105
+			foreach ($datetimes as $datetime) {
1106
+				if ($datetime instanceof EE_Datetime) {
1107
+					if ($datetime->increaseReserved($qty)) {
1108
+						$datetimes_updated[] = $datetime;
1109
+					} else {
1110
+						$limit_exceeded = true;
1111
+						break;
1112
+					}
1113
+				}
1114
+			}
1115
+			// If somewhere along the way we detected a datetime whose
1116
+			// limit was exceeded, do a manual rollback.
1117
+			if ($limit_exceeded) {
1118
+				$this->decreaseReservedForDatetimes($qty, $datetimes_updated);
1119
+				return false;
1120
+			}
1121
+		}
1122
+		return true;
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1128
+	 *
1129
+	 * @param int    $qty
1130
+	 * @param bool   $adjust_datetimes
1131
+	 * @param string $source
1132
+	 * @return boolean
1133
+	 * @throws EE_Error
1134
+	 * @throws InvalidArgumentException
1135
+	 * @throws ReflectionException
1136
+	 * @throws InvalidDataTypeException
1137
+	 * @throws InvalidInterfaceException
1138
+	 * @since 4.9.80.p
1139
+	 */
1140
+	public function decreaseReserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1141
+	{
1142
+		$qty = absint($qty);
1143
+		$this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "-{$qty} from {$source}");
1144
+		if ($adjust_datetimes) {
1145
+			$this->decreaseReservedForDatetimes($qty);
1146
+		}
1147
+		$success = $this->adjustNumericFieldsInDb(
1148
+			[
1149
+				'TKT_reserved' => $qty * -1,
1150
+			]
1151
+		);
1152
+		do_action(
1153
+			'AHEE__EE_Ticket__decrease_reserved',
1154
+			$this,
1155
+			$qty,
1156
+			$this->reserved(),
1157
+			$success
1158
+		);
1159
+		return $success;
1160
+	}
1161
+
1162
+
1163
+	/**
1164
+	 * Decreases the reserved count on the specified datetimes.
1165
+	 *
1166
+	 * @param int           $qty
1167
+	 * @param EE_Datetime[] $datetimes
1168
+	 * @throws EE_Error
1169
+	 * @throws InvalidArgumentException
1170
+	 * @throws ReflectionException
1171
+	 * @throws InvalidDataTypeException
1172
+	 * @throws InvalidInterfaceException
1173
+	 * @since 4.9.80.p
1174
+	 */
1175
+	protected function decreaseReservedForDatetimes($qty = 1, array $datetimes = [])
1176
+	{
1177
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1178
+		foreach ($datetimes as $datetime) {
1179
+			if ($datetime instanceof EE_Datetime) {
1180
+				$datetime->decreaseReserved($qty);
1181
+			}
1182
+		}
1183
+	}
1184
+
1185
+
1186
+	/**
1187
+	 * Gets ticket quantity
1188
+	 *
1189
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1190
+	 *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
1191
+	 *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
1192
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1193
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1194
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1195
+	 * @return int
1196
+	 * @throws EE_Error
1197
+	 * @throws ReflectionException
1198
+	 */
1199
+	public function qty($context = '')
1200
+	{
1201
+		switch ($context) {
1202
+			case 'reg_limit':
1203
+				return $this->real_quantity_on_ticket();
1204
+			case 'saleable':
1205
+				return $this->real_quantity_on_ticket('saleable');
1206
+			default:
1207
+				return $this->get_raw('TKT_qty');
1208
+		}
1209
+	}
1210
+
1211
+
1212
+	/**
1213
+	 * Gets ticket quantity
1214
+	 *
1215
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1216
+	 *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1217
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1218
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1219
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1220
+	 * @param int    $DTT_ID      the primary key for a particular datetime.
1221
+	 *                            set to 0 for all related datetimes
1222
+	 * @return int|float          int for finite quantity or float for INF
1223
+	 * @throws EE_Error
1224
+	 * @throws ReflectionException
1225
+	 */
1226
+	public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1227
+	{
1228
+		$raw = $this->get_raw('TKT_qty');
1229
+		// return immediately if it's zero
1230
+		if ($raw === 0) {
1231
+			return $raw;
1232
+		}
1233
+		// echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1234
+		// ensure qty doesn't exceed raw value for THIS ticket
1235
+		$qty = min(EE_INF, $raw);
1236
+		// echo "\n . qty: " . $qty . '<br />';
1237
+		// calculate this ticket's total sales and reservations
1238
+		$sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1239
+		// echo "\n . sold: " . $this->sold() . '<br />';
1240
+		// echo "\n . reserved: " . $this->reserved() . '<br />';
1241
+		// echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1242
+		// first we need to calculate the maximum number of tickets available for the datetime
1243
+		// do we want data for one datetime or all of them ?
1244
+		$query_params = $DTT_ID ? [['DTT_ID' => $DTT_ID]] : [];
1245
+		$datetimes    = $this->datetimes($query_params);
1246
+		if (is_array($datetimes) && ! empty($datetimes)) {
1247
+			foreach ($datetimes as $datetime) {
1248
+				if ($datetime instanceof EE_Datetime) {
1249
+					$datetime->refresh_from_db();
1250
+					// echo "\n . . datetime name: " . $datetime->name() . '<br />';
1251
+					// echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1252
+					// initialize with no restrictions for each datetime
1253
+					// but adjust datetime qty based on datetime reg limit
1254
+					$datetime_qty = min(EE_INF, $datetime->reg_limit());
1255
+					// echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1256
+					// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1257
+					// if we want the actual saleable amount, then we need to consider OTHER ticket sales
1258
+					// and reservations for this datetime, that do NOT include sales and reservations
1259
+					// for this ticket (so we add $this->sold() and $this->reserved() back in)
1260
+					if ($context === 'saleable') {
1261
+						$datetime_qty = max(
1262
+							$datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1263
+							0
1264
+						);
1265
+						// echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1266
+						// echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1267
+						// echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1268
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1269
+						$datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1270
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1271
+					}
1272
+					$qty = min($datetime_qty, $qty);
1273
+					// echo "\n . . qty: " . $qty . '<br />';
1274
+				}
1275
+			}
1276
+		}
1277
+		// NOW that we know the  maximum number of tickets available for the datetime
1278
+		// we can finally factor in the details for this specific ticket
1279
+		if ($qty > 0 && $context === 'saleable') {
1280
+			// and subtract the sales for THIS ticket
1281
+			$qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1282
+			// echo "\n . qty: " . $qty . '<br />';
1283
+		}
1284
+		// echo "\nFINAL QTY: " . $qty . "<br /><br />";
1285
+		return $qty;
1286
+	}
1287
+
1288
+
1289
+	/**
1290
+	 * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1291
+	 *
1292
+	 * @param int $qty
1293
+	 * @return void
1294
+	 * @throws EE_Error
1295
+	 * @throws ReflectionException
1296
+	 */
1297
+	public function set_qty($qty)
1298
+	{
1299
+		$datetimes = $this->datetimes();
1300
+		foreach ($datetimes as $datetime) {
1301
+			if ($datetime instanceof EE_Datetime) {
1302
+				$qty = min($qty, $datetime->reg_limit());
1303
+			}
1304
+		}
1305
+		$this->set('TKT_qty', $qty);
1306
+	}
1307
+
1308
+
1309
+	/**
1310
+	 * Gets uses
1311
+	 *
1312
+	 * @return int
1313
+	 * @throws EE_Error
1314
+	 * @throws ReflectionException
1315
+	 */
1316
+	public function uses()
1317
+	{
1318
+		return $this->get('TKT_uses');
1319
+	}
1320
+
1321
+
1322
+	/**
1323
+	 * Sets uses
1324
+	 *
1325
+	 * @param int $uses
1326
+	 * @return void
1327
+	 * @throws EE_Error
1328
+	 * @throws ReflectionException
1329
+	 */
1330
+	public function set_uses($uses)
1331
+	{
1332
+		$this->set('TKT_uses', $uses);
1333
+	}
1334
+
1335
+
1336
+	/**
1337
+	 * returns whether ticket is required or not.
1338
+	 *
1339
+	 * @return boolean
1340
+	 * @throws EE_Error
1341
+	 * @throws ReflectionException
1342
+	 */
1343
+	public function required()
1344
+	{
1345
+		return $this->get('TKT_required');
1346
+	}
1347
+
1348
+
1349
+	/**
1350
+	 * sets the TKT_required property
1351
+	 *
1352
+	 * @param boolean $required
1353
+	 * @return void
1354
+	 * @throws EE_Error
1355
+	 * @throws ReflectionException
1356
+	 */
1357
+	public function set_required($required)
1358
+	{
1359
+		$this->set('TKT_required', $required);
1360
+	}
1361
+
1362
+
1363
+	/**
1364
+	 * Gets taxable
1365
+	 *
1366
+	 * @return boolean
1367
+	 * @throws EE_Error
1368
+	 * @throws ReflectionException
1369
+	 */
1370
+	public function taxable()
1371
+	{
1372
+		return $this->get('TKT_taxable');
1373
+	}
1374
+
1375
+
1376
+	/**
1377
+	 * Sets taxable
1378
+	 *
1379
+	 * @param boolean $taxable
1380
+	 * @return void
1381
+	 * @throws EE_Error
1382
+	 * @throws ReflectionException
1383
+	 */
1384
+	public function set_taxable($taxable)
1385
+	{
1386
+		$this->set('TKT_taxable', $taxable);
1387
+	}
1388
+
1389
+
1390
+	/**
1391
+	 * Gets is_default
1392
+	 *
1393
+	 * @return boolean
1394
+	 * @throws EE_Error
1395
+	 * @throws ReflectionException
1396
+	 */
1397
+	public function is_default()
1398
+	{
1399
+		return $this->get('TKT_is_default');
1400
+	}
1401
+
1402
+
1403
+	/**
1404
+	 * Sets is_default
1405
+	 *
1406
+	 * @param boolean $is_default
1407
+	 * @return void
1408
+	 * @throws EE_Error
1409
+	 * @throws ReflectionException
1410
+	 */
1411
+	public function set_is_default($is_default)
1412
+	{
1413
+		$this->set('TKT_is_default', $is_default);
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * Gets order
1419
+	 *
1420
+	 * @return int
1421
+	 * @throws EE_Error
1422
+	 * @throws ReflectionException
1423
+	 */
1424
+	public function order()
1425
+	{
1426
+		return $this->get('TKT_order');
1427
+	}
1428
+
1429
+
1430
+	/**
1431
+	 * Sets order
1432
+	 *
1433
+	 * @param int $order
1434
+	 * @return void
1435
+	 * @throws EE_Error
1436
+	 * @throws ReflectionException
1437
+	 */
1438
+	public function set_order($order)
1439
+	{
1440
+		$this->set('TKT_order', $order);
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * Gets row
1446
+	 *
1447
+	 * @return int
1448
+	 * @throws EE_Error
1449
+	 * @throws ReflectionException
1450
+	 */
1451
+	public function row()
1452
+	{
1453
+		return $this->get('TKT_row');
1454
+	}
1455
+
1456
+
1457
+	/**
1458
+	 * Sets row
1459
+	 *
1460
+	 * @param int $row
1461
+	 * @return void
1462
+	 * @throws EE_Error
1463
+	 * @throws ReflectionException
1464
+	 */
1465
+	public function set_row($row)
1466
+	{
1467
+		$this->set('TKT_row', $row);
1468
+	}
1469
+
1470
+
1471
+	/**
1472
+	 * Gets deleted
1473
+	 *
1474
+	 * @return boolean
1475
+	 * @throws EE_Error
1476
+	 * @throws ReflectionException
1477
+	 */
1478
+	public function deleted()
1479
+	{
1480
+		return $this->get('TKT_deleted');
1481
+	}
1482
+
1483
+
1484
+	/**
1485
+	 * Sets deleted
1486
+	 *
1487
+	 * @param boolean $deleted
1488
+	 * @return void
1489
+	 * @throws EE_Error
1490
+	 * @throws ReflectionException
1491
+	 */
1492
+	public function set_deleted($deleted)
1493
+	{
1494
+		$this->set('TKT_deleted', $deleted);
1495
+	}
1496
+
1497
+
1498
+	/**
1499
+	 * Gets parent
1500
+	 *
1501
+	 * @return int
1502
+	 * @throws EE_Error
1503
+	 * @throws ReflectionException
1504
+	 */
1505
+	public function parent_ID()
1506
+	{
1507
+		return $this->get('TKT_parent');
1508
+	}
1509
+
1510
+
1511
+	/**
1512
+	 * Sets parent
1513
+	 *
1514
+	 * @param int $parent
1515
+	 * @return void
1516
+	 * @throws EE_Error
1517
+	 * @throws ReflectionException
1518
+	 */
1519
+	public function set_parent_ID($parent)
1520
+	{
1521
+		$this->set('TKT_parent', $parent);
1522
+	}
1523
+
1524
+
1525
+	/**
1526
+	 * @return boolean
1527
+	 * @throws EE_Error
1528
+	 * @throws InvalidArgumentException
1529
+	 * @throws InvalidDataTypeException
1530
+	 * @throws InvalidInterfaceException
1531
+	 * @throws ReflectionException
1532
+	 */
1533
+	public function reverse_calculate()
1534
+	{
1535
+		return $this->get('TKT_reverse_calculate');
1536
+	}
1537
+
1538
+
1539
+	/**
1540
+	 * @param boolean $reverse_calculate
1541
+	 * @throws EE_Error
1542
+	 * @throws InvalidArgumentException
1543
+	 * @throws InvalidDataTypeException
1544
+	 * @throws InvalidInterfaceException
1545
+	 * @throws ReflectionException
1546
+	 */
1547
+	public function set_reverse_calculate($reverse_calculate)
1548
+	{
1549
+		$this->set('TKT_reverse_calculate', $reverse_calculate);
1550
+	}
1551
+
1552
+
1553
+	/**
1554
+	 * Gets a string which is handy for showing in gateways etc that describes the ticket.
1555
+	 *
1556
+	 * @return string
1557
+	 * @throws EE_Error
1558
+	 * @throws ReflectionException
1559
+	 */
1560
+	public function name_and_info()
1561
+	{
1562
+		$times = [];
1563
+		foreach ($this->datetimes() as $datetime) {
1564
+			$times[] = $datetime->start_date_and_time();
1565
+		}
1566
+		/* translators: %1$s ticket name, %2$s start datetimes separated by comma, %3$s ticket price */
1567
+		return sprintf(
1568
+			esc_html__('%1$s @ %2$s for %3$s', 'event_espresso'),
1569
+			$this->name(),
1570
+			implode(', ', $times),
1571
+			$this->pretty_price()
1572
+		);
1573
+	}
1574
+
1575
+
1576
+	/**
1577
+	 * Gets name
1578
+	 *
1579
+	 * @return string
1580
+	 * @throws EE_Error
1581
+	 * @throws ReflectionException
1582
+	 */
1583
+	public function name()
1584
+	{
1585
+		return $this->get('TKT_name');
1586
+	}
1587
+
1588
+
1589
+	/**
1590
+	 * Gets price
1591
+	 *
1592
+	 * @return float
1593
+	 * @throws EE_Error
1594
+	 * @throws ReflectionException
1595
+	 */
1596
+	public function price()
1597
+	{
1598
+		return $this->get('TKT_price');
1599
+	}
1600
+
1601
+
1602
+	/**
1603
+	 * Gets all the registrations for this ticket
1604
+	 *
1605
+	 * @param array $query_params
1606
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1607
+	 * @return EE_Registration[]|EE_Base_Class[]
1608
+	 * @throws EE_Error
1609
+	 * @throws ReflectionException
1610
+	 */
1611
+	public function registrations($query_params = [])
1612
+	{
1613
+		return $this->get_many_related('Registration', $query_params);
1614
+	}
1615
+
1616
+
1617
+	/**
1618
+	 * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1619
+	 *
1620
+	 * @return int
1621
+	 * @throws EE_Error
1622
+	 * @throws ReflectionException
1623
+	 */
1624
+	public function update_tickets_sold()
1625
+	{
1626
+		$count_regs_for_this_ticket = $this->count_registrations(
1627
+			[
1628
+				[
1629
+					'STS_ID'      => EEM_Registration::status_id_approved,
1630
+					'REG_deleted' => 0,
1631
+				],
1632
+			]
1633
+		);
1634
+		$this->set_sold($count_regs_for_this_ticket);
1635
+		$this->save();
1636
+		return $count_regs_for_this_ticket;
1637
+	}
1638
+
1639
+
1640
+	/**
1641
+	 * Counts the registrations for this ticket
1642
+	 *
1643
+	 * @param array $query_params
1644
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1645
+	 * @return int
1646
+	 * @throws EE_Error
1647
+	 * @throws ReflectionException
1648
+	 */
1649
+	public function count_registrations($query_params = [])
1650
+	{
1651
+		return $this->count_related('Registration', $query_params);
1652
+	}
1653
+
1654
+
1655
+	/**
1656
+	 * Implementation for EEI_Has_Icon interface method.
1657
+	 *
1658
+	 * @return string
1659
+	 * @see EEI_Visual_Representation for comments
1660
+	 */
1661
+	public function get_icon()
1662
+	{
1663
+		return '<span class="dashicons dashicons-tickets-alt"></span>';
1664
+	}
1665
+
1666
+
1667
+	/**
1668
+	 * Implementation of the EEI_Event_Relation interface method
1669
+	 *
1670
+	 * @return EE_Event
1671
+	 * @throws EE_Error
1672
+	 * @throws UnexpectedEntityException
1673
+	 * @throws ReflectionException
1674
+	 * @see EEI_Event_Relation for comments
1675
+	 */
1676
+	public function get_related_event()
1677
+	{
1678
+		// get one datetime to use for getting the event
1679
+		$datetime = $this->first_datetime();
1680
+		if (! $datetime instanceof EE_Datetime) {
1681
+			throw new UnexpectedEntityException(
1682
+				$datetime,
1683
+				'EE_Datetime',
1684
+				sprintf(
1685
+					esc_html__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1686
+					$this->name()
1687
+				)
1688
+			);
1689
+		}
1690
+		$event = $datetime->event();
1691
+		if (! $event instanceof EE_Event) {
1692
+			throw new UnexpectedEntityException(
1693
+				$event,
1694
+				'EE_Event',
1695
+				sprintf(
1696
+					esc_html__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1697
+					$this->name()
1698
+				)
1699
+			);
1700
+		}
1701
+		return $event;
1702
+	}
1703
+
1704
+
1705
+	/**
1706
+	 * Implementation of the EEI_Event_Relation interface method
1707
+	 *
1708
+	 * @return string
1709
+	 * @throws UnexpectedEntityException
1710
+	 * @throws EE_Error
1711
+	 * @throws ReflectionException
1712
+	 * @see EEI_Event_Relation for comments
1713
+	 */
1714
+	public function get_event_name()
1715
+	{
1716
+		$event = $this->get_related_event();
1717
+		return $event instanceof EE_Event ? $event->name() : '';
1718
+	}
1719
+
1720
+
1721
+	/**
1722
+	 * Implementation of the EEI_Event_Relation interface method
1723
+	 *
1724
+	 * @return int
1725
+	 * @throws UnexpectedEntityException
1726
+	 * @throws EE_Error
1727
+	 * @throws ReflectionException
1728
+	 * @see EEI_Event_Relation for comments
1729
+	 */
1730
+	public function get_event_ID()
1731
+	{
1732
+		$event = $this->get_related_event();
1733
+		return $event instanceof EE_Event ? $event->ID() : 0;
1734
+	}
1735
+
1736
+
1737
+	/**
1738
+	 * This simply returns whether a ticket can be permanently deleted or not.
1739
+	 * The criteria for determining this is whether the ticket has any related registrations.
1740
+	 * If there are none then it can be permanently deleted.
1741
+	 *
1742
+	 * @return bool
1743
+	 * @throws EE_Error
1744
+	 * @throws ReflectionException
1745
+	 */
1746
+	public function is_permanently_deleteable()
1747
+	{
1748
+		return $this->count_registrations() === 0;
1749
+	}
1750
+
1751
+
1752
+	/**
1753
+	 * @return int
1754
+	 * @throws EE_Error
1755
+	 * @throws ReflectionException
1756
+	 * @since   5.0.0.p
1757
+	 */
1758
+	public function visibility(): int
1759
+	{
1760
+		return $this->get('TKT_visibility');
1761
+	}
1762
+
1763
+
1764
+	/**
1765
+	 * @return int
1766
+	 * @throws EE_Error
1767
+	 * @throws ReflectionException
1768
+	 * @since   5.0.0.p
1769
+	 */
1770
+	public function isHidden(): int
1771
+	{
1772
+		return $this->visibility() === EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1773
+	}
1774
+
1775
+
1776
+	/**
1777
+	 * @return int
1778
+	 * @throws EE_Error
1779
+	 * @throws ReflectionException
1780
+	 * @since   5.0.0.p
1781
+	 */
1782
+	public function isNotHidden(): int
1783
+	{
1784
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1785
+	}
1786
+
1787
+
1788
+	/**
1789
+	 * @return int
1790
+	 * @throws EE_Error
1791
+	 * @throws ReflectionException
1792
+	 * @since   5.0.0.p
1793
+	 */
1794
+	public function isPublicOnly(): int
1795
+	{
1796
+		return $this->isNotHidden() && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE;
1797
+	}
1798
+
1799
+
1800
+	/**
1801
+	 * @return int
1802
+	 * @throws EE_Error
1803
+	 * @throws ReflectionException
1804
+	 * @since   5.0.0.p
1805
+	 */
1806
+	public function isMembersOnly(): int
1807
+	{
1808
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE
1809
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE;
1810
+	}
1811
+
1812
+
1813
+	/**
1814
+	 * @return int
1815
+	 * @throws EE_Error
1816
+	 * @throws ReflectionException
1817
+	 * @since   5.0.0.p
1818
+	 */
1819
+	public function isAdminsOnly(): int
1820
+	{
1821
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE
1822
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE;
1823
+	}
1824
+
1825
+
1826
+	/**
1827
+	 * @return int
1828
+	 * @throws EE_Error
1829
+	 * @throws ReflectionException
1830
+	 * @since   5.0.0.p
1831
+	 */
1832
+	public function isAdminUiOnly(): int
1833
+	{
1834
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE
1835
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE;
1836
+	}
1837
+
1838
+
1839
+	/**
1840
+	 * @param int $visibility
1841
+	 * @throws EE_Error
1842
+	 * @throws ReflectionException
1843
+	 * @since   5.0.0.p
1844
+	 */
1845
+	public function set_visibility(int $visibility)
1846
+	{
1847
+
1848
+		$ticket_visibility_options = $this->_model->ticketVisibilityOptions();
1849
+		$ticket_visibility         = -1;
1850
+		foreach ($ticket_visibility_options as $ticket_visibility_option) {
1851
+			if ($visibility === $ticket_visibility_option) {
1852
+				$ticket_visibility = $visibility;
1853
+			}
1854
+		}
1855
+		if ($ticket_visibility === -1) {
1856
+			throw new DomainException(
1857
+				sprintf(
1858
+					esc_html__(
1859
+						'The supplied ticket visibility setting of "%1$s" is not valid. It needs to match one of the keys in the following array:%2$s %3$s ',
1860
+						'event_espresso'
1861
+					),
1862
+					$visibility,
1863
+					'<br />',
1864
+					var_export($ticket_visibility_options, true)
1865
+				)
1866
+			);
1867
+		}
1868
+		$this->set('TKT_visibility', $ticket_visibility);
1869
+	}
1870
+
1871
+
1872
+	/**
1873
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1874
+	 * @param string                   $relationName
1875
+	 * @param array                    $extra_join_model_fields_n_values
1876
+	 * @param string|null              $cache_id
1877
+	 * @return EE_Base_Class
1878
+	 * @throws EE_Error
1879
+	 * @throws ReflectionException
1880
+	 * @since   5.0.0.p
1881
+	 */
1882
+	public function _add_relation_to(
1883
+		$otherObjectModelObjectOrID,
1884
+		$relationName,
1885
+		$extra_join_model_fields_n_values = [],
1886
+		$cache_id = null
1887
+	) {
1888
+		if ($relationName === 'Datetime' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1889
+			/** @var EE_Datetime $datetime */
1890
+			$datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1891
+			$datetime->increaseSold($this->sold(), false);
1892
+			$datetime->increaseReserved($this->reserved());
1893
+			$datetime->save();
1894
+			$otherObjectModelObjectOrID = $datetime;
1895
+		}
1896
+		return parent::_add_relation_to(
1897
+			$otherObjectModelObjectOrID,
1898
+			$relationName,
1899
+			$extra_join_model_fields_n_values,
1900
+			$cache_id
1901
+		);
1902
+	}
1903
+
1904
+
1905
+	/**
1906
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1907
+	 * @param string                   $relationName
1908
+	 * @param array                    $where_query
1909
+	 * @return bool|EE_Base_Class|null
1910
+	 * @throws EE_Error
1911
+	 * @throws ReflectionException
1912
+	 * @since   5.0.0.p
1913
+	 */
1914
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1915
+	{
1916
+		// if we're adding a new relation to a datetime
1917
+		if ($relationName === 'Datetime' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1918
+			/** @var EE_Datetime $datetime */
1919
+			$datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1920
+			$datetime->decreaseSold($this->sold());
1921
+			$datetime->decreaseReserved($this->reserved());
1922
+			$datetime->save();
1923
+			$otherObjectModelObjectOrID = $datetime;
1924
+		}
1925
+		return parent::_remove_relation_to(
1926
+			$otherObjectModelObjectOrID,
1927
+			$relationName,
1928
+			$where_query
1929
+		);
1930
+	}
1931
+
1932
+
1933
+	/**
1934
+	 * Removes ALL the related things for the $relationName.
1935
+	 *
1936
+	 * @param string $relationName
1937
+	 * @param array  $where_query_params
1938
+	 * @return EE_Base_Class
1939
+	 * @throws ReflectionException
1940
+	 * @throws InvalidArgumentException
1941
+	 * @throws InvalidInterfaceException
1942
+	 * @throws InvalidDataTypeException
1943
+	 * @throws EE_Error
1944
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1945
+	 */
1946
+	public function _remove_relations($relationName, $where_query_params = [])
1947
+	{
1948
+		if ($relationName === 'Datetime') {
1949
+			$datetimes = $this->datetimes();
1950
+			foreach ($datetimes as $datetime) {
1951
+				$datetime->decreaseSold($this->sold());
1952
+				$datetime->decreaseReserved($this->reserved());
1953
+				$datetime->save();
1954
+			}
1955
+		}
1956
+		return parent::_remove_relations($relationName, $where_query_params);
1957
+	}
1958
+
1959
+
1960
+	/*******************************************************************
1961 1961
      ***********************  DEPRECATED METHODS  **********************
1962 1962
      *******************************************************************/
1963 1963
 
1964 1964
 
1965
-    /**
1966
-     * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
1967
-     * associated datetimes.
1968
-     *
1969
-     * @param int $qty
1970
-     * @return void
1971
-     * @throws EE_Error
1972
-     * @throws InvalidArgumentException
1973
-     * @throws InvalidDataTypeException
1974
-     * @throws InvalidInterfaceException
1975
-     * @throws ReflectionException
1976
-     * @deprecated 4.9.80.p
1977
-     */
1978
-    public function increase_sold($qty = 1)
1979
-    {
1980
-        EE_Error::doing_it_wrong(
1981
-            __FUNCTION__,
1982
-            esc_html__('Please use EE_Ticket::increaseSold() instead', 'event_espresso'),
1983
-            '4.9.80.p',
1984
-            '5.0.0.p'
1985
-        );
1986
-        $this->increaseSold($qty);
1987
-    }
1988
-
1989
-
1990
-    /**
1991
-     * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
1992
-     *
1993
-     * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
1994
-     *                 Negative means to decreases old counts (and increase reserved counts).
1995
-     * @throws EE_Error
1996
-     * @throws InvalidArgumentException
1997
-     * @throws InvalidDataTypeException
1998
-     * @throws InvalidInterfaceException
1999
-     * @throws ReflectionException
2000
-     * @deprecated 4.9.80.p
2001
-     */
2002
-    protected function _increase_sold_for_datetimes($qty)
2003
-    {
2004
-        EE_Error::doing_it_wrong(
2005
-            __FUNCTION__,
2006
-            esc_html__('Please use EE_Ticket::increaseSoldForDatetimes() instead', 'event_espresso'),
2007
-            '4.9.80.p',
2008
-            '5.0.0.p'
2009
-        );
2010
-        $this->increaseSoldForDatetimes($qty);
2011
-    }
2012
-
2013
-
2014
-    /**
2015
-     * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
2016
-     * DB and then updates the model objects.
2017
-     * Does not affect the reserved counts.
2018
-     *
2019
-     * @param int $qty
2020
-     * @return void
2021
-     * @throws EE_Error
2022
-     * @throws InvalidArgumentException
2023
-     * @throws InvalidDataTypeException
2024
-     * @throws InvalidInterfaceException
2025
-     * @throws ReflectionException
2026
-     * @deprecated 4.9.80.p
2027
-     */
2028
-    public function decrease_sold($qty = 1)
2029
-    {
2030
-        EE_Error::doing_it_wrong(
2031
-            __FUNCTION__,
2032
-            esc_html__('Please use EE_Ticket::decreaseSold() instead', 'event_espresso'),
2033
-            '4.9.80.p',
2034
-            '5.0.0.p'
2035
-        );
2036
-        $this->decreaseSold($qty);
2037
-    }
2038
-
2039
-
2040
-    /**
2041
-     * Decreases sold on related datetimes
2042
-     *
2043
-     * @param int $qty
2044
-     * @return void
2045
-     * @throws EE_Error
2046
-     * @throws InvalidArgumentException
2047
-     * @throws InvalidDataTypeException
2048
-     * @throws InvalidInterfaceException
2049
-     * @throws ReflectionException
2050
-     * @deprecated 4.9.80.p
2051
-     */
2052
-    protected function _decrease_sold_for_datetimes($qty = 1)
2053
-    {
2054
-        EE_Error::doing_it_wrong(
2055
-            __FUNCTION__,
2056
-            esc_html__('Please use EE_Ticket::decreaseSoldForDatetimes() instead', 'event_espresso'),
2057
-            '4.9.80.p',
2058
-            '5.0.0.p'
2059
-        );
2060
-        $this->decreaseSoldForDatetimes($qty);
2061
-    }
2062
-
2063
-
2064
-    /**
2065
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
2066
-     *
2067
-     * @param int    $qty
2068
-     * @param string $source
2069
-     * @return bool whether we successfully reserved the ticket or not.
2070
-     * @throws EE_Error
2071
-     * @throws InvalidArgumentException
2072
-     * @throws ReflectionException
2073
-     * @throws InvalidDataTypeException
2074
-     * @throws InvalidInterfaceException
2075
-     * @deprecated 4.9.80.p
2076
-     */
2077
-    public function increase_reserved($qty = 1, $source = 'unknown')
2078
-    {
2079
-        EE_Error::doing_it_wrong(
2080
-            __FUNCTION__,
2081
-            esc_html__('Please use EE_Ticket::increaseReserved() instead', 'event_espresso'),
2082
-            '4.9.80.p',
2083
-            '5.0.0.p'
2084
-        );
2085
-        return $this->increaseReserved($qty);
2086
-    }
2087
-
2088
-
2089
-    /**
2090
-     * Increases sold on related datetimes
2091
-     *
2092
-     * @param int $qty
2093
-     * @return boolean indicating success
2094
-     * @throws EE_Error
2095
-     * @throws InvalidArgumentException
2096
-     * @throws InvalidDataTypeException
2097
-     * @throws InvalidInterfaceException
2098
-     * @throws ReflectionException
2099
-     * @deprecated 4.9.80.p
2100
-     */
2101
-    protected function _increase_reserved_for_datetimes($qty = 1)
2102
-    {
2103
-        EE_Error::doing_it_wrong(
2104
-            __FUNCTION__,
2105
-            esc_html__('Please use EE_Ticket::increaseReservedForDatetimes() instead', 'event_espresso'),
2106
-            '4.9.80.p',
2107
-            '5.0.0.p'
2108
-        );
2109
-        return $this->increaseReservedForDatetimes($qty);
2110
-    }
2111
-
2112
-
2113
-    /**
2114
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
2115
-     *
2116
-     * @param int    $qty
2117
-     * @param bool   $adjust_datetimes
2118
-     * @param string $source
2119
-     * @return void
2120
-     * @throws EE_Error
2121
-     * @throws InvalidArgumentException
2122
-     * @throws ReflectionException
2123
-     * @throws InvalidDataTypeException
2124
-     * @throws InvalidInterfaceException
2125
-     * @deprecated 4.9.80.p
2126
-     */
2127
-    public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
2128
-    {
2129
-        EE_Error::doing_it_wrong(
2130
-            __FUNCTION__,
2131
-            esc_html__('Please use EE_Ticket::decreaseReserved() instead', 'event_espresso'),
2132
-            '4.9.80.p',
2133
-            '5.0.0.p'
2134
-        );
2135
-        $this->decreaseReserved($qty);
2136
-    }
2137
-
2138
-
2139
-    /**
2140
-     * Decreases reserved on related datetimes
2141
-     *
2142
-     * @param int $qty
2143
-     * @return void
2144
-     * @throws EE_Error
2145
-     * @throws InvalidArgumentException
2146
-     * @throws ReflectionException
2147
-     * @throws InvalidDataTypeException
2148
-     * @throws InvalidInterfaceException
2149
-     * @deprecated 4.9.80.p
2150
-     */
2151
-    protected function _decrease_reserved_for_datetimes($qty = 1)
2152
-    {
2153
-        EE_Error::doing_it_wrong(
2154
-            __FUNCTION__,
2155
-            esc_html__('Please use EE_Ticket::decreaseReservedForDatetimes() instead', 'event_espresso'),
2156
-            '4.9.80.p',
2157
-            '5.0.0.p'
2158
-        );
2159
-        $this->decreaseReservedForDatetimes($qty);
2160
-    }
1965
+	/**
1966
+	 * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
1967
+	 * associated datetimes.
1968
+	 *
1969
+	 * @param int $qty
1970
+	 * @return void
1971
+	 * @throws EE_Error
1972
+	 * @throws InvalidArgumentException
1973
+	 * @throws InvalidDataTypeException
1974
+	 * @throws InvalidInterfaceException
1975
+	 * @throws ReflectionException
1976
+	 * @deprecated 4.9.80.p
1977
+	 */
1978
+	public function increase_sold($qty = 1)
1979
+	{
1980
+		EE_Error::doing_it_wrong(
1981
+			__FUNCTION__,
1982
+			esc_html__('Please use EE_Ticket::increaseSold() instead', 'event_espresso'),
1983
+			'4.9.80.p',
1984
+			'5.0.0.p'
1985
+		);
1986
+		$this->increaseSold($qty);
1987
+	}
1988
+
1989
+
1990
+	/**
1991
+	 * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
1992
+	 *
1993
+	 * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
1994
+	 *                 Negative means to decreases old counts (and increase reserved counts).
1995
+	 * @throws EE_Error
1996
+	 * @throws InvalidArgumentException
1997
+	 * @throws InvalidDataTypeException
1998
+	 * @throws InvalidInterfaceException
1999
+	 * @throws ReflectionException
2000
+	 * @deprecated 4.9.80.p
2001
+	 */
2002
+	protected function _increase_sold_for_datetimes($qty)
2003
+	{
2004
+		EE_Error::doing_it_wrong(
2005
+			__FUNCTION__,
2006
+			esc_html__('Please use EE_Ticket::increaseSoldForDatetimes() instead', 'event_espresso'),
2007
+			'4.9.80.p',
2008
+			'5.0.0.p'
2009
+		);
2010
+		$this->increaseSoldForDatetimes($qty);
2011
+	}
2012
+
2013
+
2014
+	/**
2015
+	 * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
2016
+	 * DB and then updates the model objects.
2017
+	 * Does not affect the reserved counts.
2018
+	 *
2019
+	 * @param int $qty
2020
+	 * @return void
2021
+	 * @throws EE_Error
2022
+	 * @throws InvalidArgumentException
2023
+	 * @throws InvalidDataTypeException
2024
+	 * @throws InvalidInterfaceException
2025
+	 * @throws ReflectionException
2026
+	 * @deprecated 4.9.80.p
2027
+	 */
2028
+	public function decrease_sold($qty = 1)
2029
+	{
2030
+		EE_Error::doing_it_wrong(
2031
+			__FUNCTION__,
2032
+			esc_html__('Please use EE_Ticket::decreaseSold() instead', 'event_espresso'),
2033
+			'4.9.80.p',
2034
+			'5.0.0.p'
2035
+		);
2036
+		$this->decreaseSold($qty);
2037
+	}
2038
+
2039
+
2040
+	/**
2041
+	 * Decreases sold on related datetimes
2042
+	 *
2043
+	 * @param int $qty
2044
+	 * @return void
2045
+	 * @throws EE_Error
2046
+	 * @throws InvalidArgumentException
2047
+	 * @throws InvalidDataTypeException
2048
+	 * @throws InvalidInterfaceException
2049
+	 * @throws ReflectionException
2050
+	 * @deprecated 4.9.80.p
2051
+	 */
2052
+	protected function _decrease_sold_for_datetimes($qty = 1)
2053
+	{
2054
+		EE_Error::doing_it_wrong(
2055
+			__FUNCTION__,
2056
+			esc_html__('Please use EE_Ticket::decreaseSoldForDatetimes() instead', 'event_espresso'),
2057
+			'4.9.80.p',
2058
+			'5.0.0.p'
2059
+		);
2060
+		$this->decreaseSoldForDatetimes($qty);
2061
+	}
2062
+
2063
+
2064
+	/**
2065
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
2066
+	 *
2067
+	 * @param int    $qty
2068
+	 * @param string $source
2069
+	 * @return bool whether we successfully reserved the ticket or not.
2070
+	 * @throws EE_Error
2071
+	 * @throws InvalidArgumentException
2072
+	 * @throws ReflectionException
2073
+	 * @throws InvalidDataTypeException
2074
+	 * @throws InvalidInterfaceException
2075
+	 * @deprecated 4.9.80.p
2076
+	 */
2077
+	public function increase_reserved($qty = 1, $source = 'unknown')
2078
+	{
2079
+		EE_Error::doing_it_wrong(
2080
+			__FUNCTION__,
2081
+			esc_html__('Please use EE_Ticket::increaseReserved() instead', 'event_espresso'),
2082
+			'4.9.80.p',
2083
+			'5.0.0.p'
2084
+		);
2085
+		return $this->increaseReserved($qty);
2086
+	}
2087
+
2088
+
2089
+	/**
2090
+	 * Increases sold on related datetimes
2091
+	 *
2092
+	 * @param int $qty
2093
+	 * @return boolean indicating success
2094
+	 * @throws EE_Error
2095
+	 * @throws InvalidArgumentException
2096
+	 * @throws InvalidDataTypeException
2097
+	 * @throws InvalidInterfaceException
2098
+	 * @throws ReflectionException
2099
+	 * @deprecated 4.9.80.p
2100
+	 */
2101
+	protected function _increase_reserved_for_datetimes($qty = 1)
2102
+	{
2103
+		EE_Error::doing_it_wrong(
2104
+			__FUNCTION__,
2105
+			esc_html__('Please use EE_Ticket::increaseReservedForDatetimes() instead', 'event_espresso'),
2106
+			'4.9.80.p',
2107
+			'5.0.0.p'
2108
+		);
2109
+		return $this->increaseReservedForDatetimes($qty);
2110
+	}
2111
+
2112
+
2113
+	/**
2114
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
2115
+	 *
2116
+	 * @param int    $qty
2117
+	 * @param bool   $adjust_datetimes
2118
+	 * @param string $source
2119
+	 * @return void
2120
+	 * @throws EE_Error
2121
+	 * @throws InvalidArgumentException
2122
+	 * @throws ReflectionException
2123
+	 * @throws InvalidDataTypeException
2124
+	 * @throws InvalidInterfaceException
2125
+	 * @deprecated 4.9.80.p
2126
+	 */
2127
+	public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
2128
+	{
2129
+		EE_Error::doing_it_wrong(
2130
+			__FUNCTION__,
2131
+			esc_html__('Please use EE_Ticket::decreaseReserved() instead', 'event_espresso'),
2132
+			'4.9.80.p',
2133
+			'5.0.0.p'
2134
+		);
2135
+		$this->decreaseReserved($qty);
2136
+	}
2137
+
2138
+
2139
+	/**
2140
+	 * Decreases reserved on related datetimes
2141
+	 *
2142
+	 * @param int $qty
2143
+	 * @return void
2144
+	 * @throws EE_Error
2145
+	 * @throws InvalidArgumentException
2146
+	 * @throws ReflectionException
2147
+	 * @throws InvalidDataTypeException
2148
+	 * @throws InvalidInterfaceException
2149
+	 * @deprecated 4.9.80.p
2150
+	 */
2151
+	protected function _decrease_reserved_for_datetimes($qty = 1)
2152
+	{
2153
+		EE_Error::doing_it_wrong(
2154
+			__FUNCTION__,
2155
+			esc_html__('Please use EE_Ticket::decreaseReservedForDatetimes() instead', 'event_espresso'),
2156
+			'4.9.80.p',
2157
+			'5.0.0.p'
2158
+		);
2159
+		$this->decreaseReservedForDatetimes($qty);
2160
+	}
2161 2161
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Datetime.class.php 1 patch
Indentation   +1552 added lines, -1552 removed lines patch added patch discarded remove patch
@@ -12,1560 +12,1560 @@
 block discarded – undo
12 12
  */
13 13
 class EE_Datetime extends EE_Soft_Delete_Base_Class
14 14
 {
15
-    /**
16
-     * constant used by get_active_status, indicates datetime has no more available spaces
17
-     */
18
-    const sold_out = 'DTS';
19
-
20
-    /**
21
-     * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
22
-     */
23
-    const active = 'DTA';
24
-
25
-    /**
26
-     * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
27
-     * expired
28
-     */
29
-    const upcoming = 'DTU';
30
-
31
-    /**
32
-     * Datetime is postponed
33
-     */
34
-    const postponed = 'DTP';
35
-
36
-    /**
37
-     * Datetime is cancelled
38
-     */
39
-    const cancelled = 'DTC';
40
-
41
-    /**
42
-     * constant used by get_active_status, indicates datetime has expired (event is over)
43
-     */
44
-    const expired = 'DTE';
45
-
46
-    /**
47
-     * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
48
-     */
49
-    const inactive = 'DTI';
50
-
51
-
52
-    /**
53
-     * @param array  $props_n_values    incoming values
54
-     * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
55
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
56
-     *                                  and the second value is the time format
57
-     * @return EE_Datetime
58
-     * @throws ReflectionException
59
-     * @throws InvalidArgumentException
60
-     * @throws InvalidInterfaceException
61
-     * @throws InvalidDataTypeException
62
-     * @throws EE_Error
63
-     */
64
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
65
-    {
66
-        $has_object = parent::_check_for_object(
67
-            $props_n_values,
68
-            __CLASS__,
69
-            $timezone,
70
-            $date_formats
71
-        );
72
-        return $has_object
73
-            ? $has_object
74
-            : new self($props_n_values, false, $timezone, $date_formats);
75
-    }
76
-
77
-
78
-    /**
79
-     * @param array  $props_n_values  incoming values from the database
80
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
-     *                                the website will be used.
82
-     * @return EE_Datetime
83
-     * @throws ReflectionException
84
-     * @throws InvalidArgumentException
85
-     * @throws InvalidInterfaceException
86
-     * @throws InvalidDataTypeException
87
-     * @throws EE_Error
88
-     */
89
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
90
-    {
91
-        return new self($props_n_values, true, $timezone);
92
-    }
93
-
94
-
95
-    /**
96
-     * @param $name
97
-     * @throws ReflectionException
98
-     * @throws InvalidArgumentException
99
-     * @throws InvalidInterfaceException
100
-     * @throws InvalidDataTypeException
101
-     * @throws EE_Error
102
-     */
103
-    public function set_name($name)
104
-    {
105
-        $this->set('DTT_name', $name);
106
-    }
107
-
108
-
109
-    /**
110
-     * @param $description
111
-     * @throws ReflectionException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidInterfaceException
114
-     * @throws InvalidDataTypeException
115
-     * @throws EE_Error
116
-     */
117
-    public function set_description($description)
118
-    {
119
-        $this->set('DTT_description', $description);
120
-    }
121
-
122
-
123
-    /**
124
-     * Set event start date
125
-     * set the start date for an event
126
-     *
127
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
128
-     * @throws ReflectionException
129
-     * @throws InvalidArgumentException
130
-     * @throws InvalidInterfaceException
131
-     * @throws InvalidDataTypeException
132
-     * @throws EE_Error
133
-     */
134
-    public function set_start_date($date)
135
-    {
136
-        $this->_set_date_for($date, 'DTT_EVT_start');
137
-    }
138
-
139
-
140
-    /**
141
-     * Set event start time
142
-     * set the start time for an event
143
-     *
144
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
145
-     * @throws ReflectionException
146
-     * @throws InvalidArgumentException
147
-     * @throws InvalidInterfaceException
148
-     * @throws InvalidDataTypeException
149
-     * @throws EE_Error
150
-     */
151
-    public function set_start_time($time)
152
-    {
153
-        $this->_set_time_for($time, 'DTT_EVT_start');
154
-    }
155
-
156
-
157
-    /**
158
-     * Set event end date
159
-     * set the end date for an event
160
-     *
161
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
162
-     * @throws ReflectionException
163
-     * @throws InvalidArgumentException
164
-     * @throws InvalidInterfaceException
165
-     * @throws InvalidDataTypeException
166
-     * @throws EE_Error
167
-     */
168
-    public function set_end_date($date)
169
-    {
170
-        $this->_set_date_for($date, 'DTT_EVT_end');
171
-    }
172
-
173
-
174
-    /**
175
-     * Set event end time
176
-     * set the end time for an event
177
-     *
178
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
179
-     * @throws ReflectionException
180
-     * @throws InvalidArgumentException
181
-     * @throws InvalidInterfaceException
182
-     * @throws InvalidDataTypeException
183
-     * @throws EE_Error
184
-     */
185
-    public function set_end_time($time)
186
-    {
187
-        $this->_set_time_for($time, 'DTT_EVT_end');
188
-    }
189
-
190
-
191
-    /**
192
-     * Set registration limit
193
-     * set the maximum number of attendees that can be registered for this datetime slot
194
-     *
195
-     * @param int|float $reg_limit
196
-     * @throws ReflectionException
197
-     * @throws InvalidArgumentException
198
-     * @throws InvalidInterfaceException
199
-     * @throws InvalidDataTypeException
200
-     * @throws EE_Error
201
-     */
202
-    public function set_reg_limit($reg_limit)
203
-    {
204
-        $this->set('DTT_reg_limit', $reg_limit);
205
-    }
206
-
207
-
208
-    /**
209
-     * get the number of tickets sold for this datetime slot
210
-     *
211
-     * @return mixed int on success, FALSE on fail
212
-     * @throws ReflectionException
213
-     * @throws InvalidArgumentException
214
-     * @throws InvalidInterfaceException
215
-     * @throws InvalidDataTypeException
216
-     * @throws EE_Error
217
-     */
218
-    public function sold()
219
-    {
220
-        return $this->get_raw('DTT_sold');
221
-    }
222
-
223
-
224
-    /**
225
-     * @param int $sold
226
-     * @throws ReflectionException
227
-     * @throws InvalidArgumentException
228
-     * @throws InvalidInterfaceException
229
-     * @throws InvalidDataTypeException
230
-     * @throws EE_Error
231
-     */
232
-    public function set_sold($sold)
233
-    {
234
-        // sold can not go below zero
235
-        $sold = max(0, $sold);
236
-        $this->set('DTT_sold', $sold);
237
-    }
238
-
239
-
240
-    /**
241
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
242
-     * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
243
-     *
244
-     * @param int $qty
245
-     * @param boolean $also_decrease_reserved
246
-     * @return boolean indicating success
247
-     * @throws ReflectionException
248
-     * @throws InvalidArgumentException
249
-     * @throws InvalidInterfaceException
250
-     * @throws InvalidDataTypeException
251
-     * @throws EE_Error
252
-     */
253
-    public function increaseSold(int $qty = 1, bool $also_decrease_reserved = true): bool
254
-    {
255
-        $qty = absint($qty);
256
-        if ($also_decrease_reserved) {
257
-            $success = $this->adjustNumericFieldsInDb(
258
-                [
259
-                    'DTT_reserved' => $qty * -1,
260
-                    'DTT_sold' => $qty
261
-                ]
262
-            );
263
-        } else {
264
-            $success = $this->adjustNumericFieldsInDb(
265
-                [
266
-                    'DTT_sold' => $qty
267
-                ]
268
-            );
269
-        }
270
-
271
-        do_action(
272
-            'AHEE__EE_Datetime__increase_sold',
273
-            $this,
274
-            $qty,
275
-            $this->sold(),
276
-            $success
277
-        );
278
-        return $success;
279
-    }
280
-
281
-
282
-    /**
283
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
284
-     * to save afterwards.)
285
-     *
286
-     * @param int $qty
287
-     * @return boolean indicating success
288
-     * @throws ReflectionException
289
-     * @throws InvalidArgumentException
290
-     * @throws InvalidInterfaceException
291
-     * @throws InvalidDataTypeException
292
-     * @throws EE_Error
293
-     */
294
-    public function decreaseSold(int $qty = 1): bool
295
-    {
296
-        $qty = absint($qty);
297
-        $success = $this->adjustNumericFieldsInDb(
298
-            [
299
-                'DTT_sold' => $qty * -1
300
-            ]
301
-        );
302
-        do_action(
303
-            'AHEE__EE_Datetime__decrease_sold',
304
-            $this,
305
-            $qty,
306
-            $this->sold(),
307
-            $success
308
-        );
309
-        return $success;
310
-    }
311
-
312
-
313
-    /**
314
-     * Gets qty of reserved tickets for this datetime
315
-     *
316
-     * @return int
317
-     * @throws ReflectionException
318
-     * @throws InvalidArgumentException
319
-     * @throws InvalidInterfaceException
320
-     * @throws InvalidDataTypeException
321
-     * @throws EE_Error
322
-     */
323
-    public function reserved(): int
324
-    {
325
-        return $this->get_raw('DTT_reserved');
326
-    }
327
-
328
-
329
-    /**
330
-     * Sets qty of reserved tickets for this datetime
331
-     *
332
-     * @param int $reserved
333
-     * @throws ReflectionException
334
-     * @throws InvalidArgumentException
335
-     * @throws InvalidInterfaceException
336
-     * @throws InvalidDataTypeException
337
-     * @throws EE_Error
338
-     */
339
-    public function set_reserved(int $reserved)
340
-    {
341
-        // reserved can not go below zero
342
-        $reserved = max(0, $reserved);
343
-        $this->set('DTT_reserved', $reserved);
344
-    }
345
-
346
-
347
-    /**
348
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
349
-     *
350
-     * @param int $qty
351
-     * @return boolean indicating success
352
-     * @throws ReflectionException
353
-     * @throws InvalidArgumentException
354
-     * @throws InvalidInterfaceException
355
-     * @throws InvalidDataTypeException
356
-     * @throws EE_Error
357
-     */
358
-    public function increaseReserved(int $qty = 1): bool
359
-    {
360
-        $qty = absint($qty);
361
-        $success = $this->incrementFieldConditionallyInDb(
362
-            'DTT_reserved',
363
-            'DTT_sold',
364
-            'DTT_reg_limit',
365
-            $qty
366
-        );
367
-        do_action(
368
-            'AHEE__EE_Datetime__increase_reserved',
369
-            $this,
370
-            $qty,
371
-            $this->reserved(),
372
-            $success
373
-        );
374
-        return $success;
375
-    }
376
-
377
-
378
-    /**
379
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
380
-     *
381
-     * @param int $qty
382
-     * @return boolean indicating success
383
-     * @throws ReflectionException
384
-     * @throws InvalidArgumentException
385
-     * @throws InvalidInterfaceException
386
-     * @throws InvalidDataTypeException
387
-     * @throws EE_Error
388
-     */
389
-    public function decreaseReserved(int $qty = 1): bool
390
-    {
391
-        $qty = absint($qty);
392
-        $success = $this->adjustNumericFieldsInDb(
393
-            [
394
-                'DTT_reserved' => $qty * -1
395
-            ]
396
-        );
397
-        do_action(
398
-            'AHEE__EE_Datetime__decrease_reserved',
399
-            $this,
400
-            $qty,
401
-            $this->reserved(),
402
-            $success
403
-        );
404
-        return $success;
405
-    }
406
-
407
-
408
-    /**
409
-     * total sold and reserved tickets
410
-     *
411
-     * @return int
412
-     * @throws ReflectionException
413
-     * @throws InvalidArgumentException
414
-     * @throws InvalidInterfaceException
415
-     * @throws InvalidDataTypeException
416
-     * @throws EE_Error
417
-     */
418
-    public function sold_and_reserved(): int
419
-    {
420
-        return $this->sold() + $this->reserved();
421
-    }
422
-
423
-
424
-    /**
425
-     * returns the datetime name
426
-     *
427
-     * @return string
428
-     * @throws ReflectionException
429
-     * @throws InvalidArgumentException
430
-     * @throws InvalidInterfaceException
431
-     * @throws InvalidDataTypeException
432
-     * @throws EE_Error
433
-     */
434
-    public function name(): string
435
-    {
436
-        return $this->get('DTT_name');
437
-    }
438
-
439
-
440
-    /**
441
-     * returns the datetime description
442
-     *
443
-     * @return string
444
-     * @throws ReflectionException
445
-     * @throws InvalidArgumentException
446
-     * @throws InvalidInterfaceException
447
-     * @throws InvalidDataTypeException
448
-     * @throws EE_Error
449
-     */
450
-    public function description(): string
451
-    {
452
-        return $this->get('DTT_description');
453
-    }
454
-
455
-
456
-    /**
457
-     * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
458
-     *
459
-     * @return boolean  TRUE if is primary, FALSE if not.
460
-     * @throws ReflectionException
461
-     * @throws InvalidArgumentException
462
-     * @throws InvalidInterfaceException
463
-     * @throws InvalidDataTypeException
464
-     * @throws EE_Error
465
-     */
466
-    public function is_primary(): bool
467
-    {
468
-        return $this->get('DTT_is_primary');
469
-    }
470
-
471
-
472
-    /**
473
-     * This helper simply returns the order for the datetime
474
-     *
475
-     * @return int  The order of the datetime for this event.
476
-     * @throws ReflectionException
477
-     * @throws InvalidArgumentException
478
-     * @throws InvalidInterfaceException
479
-     * @throws InvalidDataTypeException
480
-     * @throws EE_Error
481
-     */
482
-    public function order(): int
483
-    {
484
-        return $this->get('DTT_order');
485
-    }
486
-
487
-
488
-    /**
489
-     * This helper simply returns the parent id for the datetime
490
-     *
491
-     * @return int
492
-     * @throws ReflectionException
493
-     * @throws InvalidArgumentException
494
-     * @throws InvalidInterfaceException
495
-     * @throws InvalidDataTypeException
496
-     * @throws EE_Error
497
-     */
498
-    public function parent(): int
499
-    {
500
-        return $this->get('DTT_parent');
501
-    }
502
-
503
-
504
-    /**
505
-     * show date and/or time
506
-     *
507
-     * @param string $date_or_time    whether to display a date or time or both
508
-     * @param string $start_or_end    whether to display start or end datetimes
509
-     * @param string $dt_frmt
510
-     * @param string $tm_frmt
511
-     * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
512
-     *                                otherwise we use the standard formats)
513
-     * @return string|bool  string on success, FALSE on fail
514
-     * @throws ReflectionException
515
-     * @throws InvalidArgumentException
516
-     * @throws InvalidInterfaceException
517
-     * @throws InvalidDataTypeException
518
-     * @throws EE_Error
519
-     */
520
-    private function _show_datetime(
521
-        $date_or_time = null,
522
-        $start_or_end = 'start',
523
-        $dt_frmt = '',
524
-        $tm_frmt = '',
525
-        $echo = false
526
-    ) {
527
-        $field_name = "DTT_EVT_{$start_or_end}";
528
-        $dtt = $this->_get_datetime(
529
-            $field_name,
530
-            $dt_frmt,
531
-            $tm_frmt,
532
-            $date_or_time,
533
-            $echo
534
-        );
535
-        if (! $echo) {
536
-            return $dtt;
537
-        }
538
-        return '';
539
-    }
540
-
541
-
542
-    /**
543
-     * get event start date.  Provide either the date format, or NULL to re-use the
544
-     * last-used format, or '' to use the default date format
545
-     *
546
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
547
-     * @return mixed            string on success, FALSE on fail
548
-     * @throws ReflectionException
549
-     * @throws InvalidArgumentException
550
-     * @throws InvalidInterfaceException
551
-     * @throws InvalidDataTypeException
552
-     * @throws EE_Error
553
-     */
554
-    public function start_date($dt_frmt = '')
555
-    {
556
-        return $this->_show_datetime('D', 'start', $dt_frmt);
557
-    }
558
-
559
-
560
-    /**
561
-     * Echoes start_date()
562
-     *
563
-     * @param string $dt_frmt
564
-     * @throws ReflectionException
565
-     * @throws InvalidArgumentException
566
-     * @throws InvalidInterfaceException
567
-     * @throws InvalidDataTypeException
568
-     * @throws EE_Error
569
-     */
570
-    public function e_start_date($dt_frmt = '')
571
-    {
572
-        $this->_show_datetime('D', 'start', $dt_frmt, null, true);
573
-    }
574
-
575
-
576
-    /**
577
-     * get end date. Provide either the date format, or NULL to re-use the
578
-     * last-used format, or '' to use the default date format
579
-     *
580
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
581
-     * @return mixed            string on success, FALSE on fail
582
-     * @throws ReflectionException
583
-     * @throws InvalidArgumentException
584
-     * @throws InvalidInterfaceException
585
-     * @throws InvalidDataTypeException
586
-     * @throws EE_Error
587
-     */
588
-    public function end_date($dt_frmt = '')
589
-    {
590
-        return $this->_show_datetime('D', 'end', $dt_frmt);
591
-    }
592
-
593
-
594
-    /**
595
-     * Echoes the end date. See end_date()
596
-     *
597
-     * @param string $dt_frmt
598
-     * @throws ReflectionException
599
-     * @throws InvalidArgumentException
600
-     * @throws InvalidInterfaceException
601
-     * @throws InvalidDataTypeException
602
-     * @throws EE_Error
603
-     */
604
-    public function e_end_date($dt_frmt = '')
605
-    {
606
-        $this->_show_datetime('D', 'end', $dt_frmt, null, true);
607
-    }
608
-
609
-
610
-    /**
611
-     * get date_range - meaning the start AND end date
612
-     *
613
-     * @access public
614
-     * @param string $dt_frmt     string representation of date format defaults to WP settings
615
-     * @param string $conjunction conjunction junction what's your function ?
616
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
617
-     * @return mixed              string on success, FALSE on fail
618
-     * @throws ReflectionException
619
-     * @throws InvalidArgumentException
620
-     * @throws InvalidInterfaceException
621
-     * @throws InvalidDataTypeException
622
-     * @throws EE_Error
623
-     */
624
-    public function date_range($dt_frmt = '', $conjunction = ' - ')
625
-    {
626
-        $dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
627
-        $start = str_replace(
628
-            ' ',
629
-            '&nbsp;',
630
-            $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
631
-        );
632
-        $end = str_replace(
633
-            ' ',
634
-            '&nbsp;',
635
-            $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
636
-        );
637
-        return $start !== $end ? $start . $conjunction . $end : $start;
638
-    }
639
-
640
-
641
-    /**
642
-     * @param string $dt_frmt
643
-     * @param string $conjunction
644
-     * @throws ReflectionException
645
-     * @throws InvalidArgumentException
646
-     * @throws InvalidInterfaceException
647
-     * @throws InvalidDataTypeException
648
-     * @throws EE_Error
649
-     */
650
-    public function e_date_range($dt_frmt = '', $conjunction = ' - ')
651
-    {
652
-        echo esc_html($this->date_range($dt_frmt, $conjunction));
653
-    }
654
-
655
-
656
-    /**
657
-     * get start time
658
-     *
659
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
660
-     * @return mixed        string on success, FALSE on fail
661
-     * @throws ReflectionException
662
-     * @throws InvalidArgumentException
663
-     * @throws InvalidInterfaceException
664
-     * @throws InvalidDataTypeException
665
-     * @throws EE_Error
666
-     */
667
-    public function start_time($tm_format = '')
668
-    {
669
-        return $this->_show_datetime('T', 'start', null, $tm_format);
670
-    }
671
-
672
-
673
-    /**
674
-     * @param string $tm_format
675
-     * @throws ReflectionException
676
-     * @throws InvalidArgumentException
677
-     * @throws InvalidInterfaceException
678
-     * @throws InvalidDataTypeException
679
-     * @throws EE_Error
680
-     */
681
-    public function e_start_time($tm_format = '')
682
-    {
683
-        $this->_show_datetime('T', 'start', null, $tm_format, true);
684
-    }
685
-
686
-
687
-    /**
688
-     * get end time
689
-     *
690
-     * @param string $tm_format string representation of time format defaults to 'g:i a'
691
-     * @return mixed                string on success, FALSE on fail
692
-     * @throws ReflectionException
693
-     * @throws InvalidArgumentException
694
-     * @throws InvalidInterfaceException
695
-     * @throws InvalidDataTypeException
696
-     * @throws EE_Error
697
-     */
698
-    public function end_time($tm_format = '')
699
-    {
700
-        return $this->_show_datetime('T', 'end', null, $tm_format);
701
-    }
702
-
703
-
704
-    /**
705
-     * @param string $tm_format
706
-     * @throws ReflectionException
707
-     * @throws InvalidArgumentException
708
-     * @throws InvalidInterfaceException
709
-     * @throws InvalidDataTypeException
710
-     * @throws EE_Error
711
-     */
712
-    public function e_end_time($tm_format = '')
713
-    {
714
-        $this->_show_datetime('T', 'end', null, $tm_format, true);
715
-    }
716
-
717
-
718
-    /**
719
-     * get time_range
720
-     *
721
-     * @access public
722
-     * @param string $tm_format   string representation of time format defaults to 'g:i a'
723
-     * @param string $conjunction conjunction junction what's your function ?
724
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
725
-     * @return mixed              string on success, FALSE on fail
726
-     * @throws ReflectionException
727
-     * @throws InvalidArgumentException
728
-     * @throws InvalidInterfaceException
729
-     * @throws InvalidDataTypeException
730
-     * @throws EE_Error
731
-     */
732
-    public function time_range($tm_format = '', $conjunction = ' - ')
733
-    {
734
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
735
-        $start = str_replace(
736
-            ' ',
737
-            '&nbsp;',
738
-            $this->get_i18n_datetime('DTT_EVT_start', $tm_format)
739
-        );
740
-        $end = str_replace(
741
-            ' ',
742
-            '&nbsp;',
743
-            $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
744
-        );
745
-        return $start !== $end ? $start . $conjunction . $end : $start;
746
-    }
747
-
748
-
749
-    /**
750
-     * @param string $tm_format
751
-     * @param string $conjunction
752
-     * @throws ReflectionException
753
-     * @throws InvalidArgumentException
754
-     * @throws InvalidInterfaceException
755
-     * @throws InvalidDataTypeException
756
-     * @throws EE_Error
757
-     */
758
-    public function e_time_range($tm_format = '', $conjunction = ' - ')
759
-    {
760
-        echo esc_html($this->time_range($tm_format, $conjunction));
761
-    }
762
-
763
-
764
-    /**
765
-     * This returns a range representation of the date and times.
766
-     * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
767
-     * Also, the return value is localized.
768
-     *
769
-     * @param string $dt_format
770
-     * @param string $tm_format
771
-     * @param string $conjunction used between two different dates or times.
772
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
773
-     * @param string $separator   used between the date and time formats.
774
-     *                            ex: Dec 1, 2016{$separator}2pm
775
-     * @return string
776
-     * @throws ReflectionException
777
-     * @throws InvalidArgumentException
778
-     * @throws InvalidInterfaceException
779
-     * @throws InvalidDataTypeException
780
-     * @throws EE_Error
781
-     */
782
-    public function date_and_time_range(
783
-        $dt_format = '',
784
-        $tm_format = '',
785
-        $conjunction = ' - ',
786
-        $separator = ' '
787
-    ) {
788
-        $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
789
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
790
-        $full_format = $dt_format . $separator . $tm_format;
791
-        // the range output depends on various conditions
792
-        switch (true) {
793
-            // start date timestamp and end date timestamp are the same.
794
-            case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
795
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
796
-                break;
797
-            // start and end date are the same but times are different
798
-            case ($this->start_date() === $this->end_date()):
799
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
800
-                          . $conjunction
801
-                          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
802
-                break;
803
-            // all other conditions
804
-            default:
805
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
806
-                          . $conjunction
807
-                          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
808
-                break;
809
-        }
810
-        return $output;
811
-    }
812
-
813
-
814
-    /**
815
-     * This echos the results of date and time range.
816
-     *
817
-     * @see date_and_time_range() for more details on purpose.
818
-     * @param string $dt_format
819
-     * @param string $tm_format
820
-     * @param string $conjunction
821
-     * @return void
822
-     * @throws ReflectionException
823
-     * @throws InvalidArgumentException
824
-     * @throws InvalidInterfaceException
825
-     * @throws InvalidDataTypeException
826
-     * @throws EE_Error
827
-     */
828
-    public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
829
-    {
830
-        echo esc_html($this->date_and_time_range($dt_format, $tm_format, $conjunction));
831
-    }
832
-
833
-
834
-    /**
835
-     * get start date and start time
836
-     *
837
-     * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
838
-     * @param    string $tm_format - string representation of time format defaults to 'g:i a'
839
-     * @return    mixed    string on success, FALSE on fail
840
-     * @throws ReflectionException
841
-     * @throws InvalidArgumentException
842
-     * @throws InvalidInterfaceException
843
-     * @throws InvalidDataTypeException
844
-     * @throws EE_Error
845
-     */
846
-    public function start_date_and_time($dt_format = '', $tm_format = '')
847
-    {
848
-        return $this->_show_datetime('', 'start', $dt_format, $tm_format);
849
-    }
850
-
851
-
852
-    /**
853
-     * @param string $dt_frmt
854
-     * @param string $tm_format
855
-     * @throws ReflectionException
856
-     * @throws InvalidArgumentException
857
-     * @throws InvalidInterfaceException
858
-     * @throws InvalidDataTypeException
859
-     * @throws EE_Error
860
-     */
861
-    public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
862
-    {
863
-        $this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
864
-    }
865
-
866
-
867
-    /**
868
-     * Shows the length of the event (start to end time).
869
-     * Can be shown in 'seconds','minutes','hours', or 'days'.
870
-     * By default, rounds up. (So if you use 'days', and then event
871
-     * only occurs for 1 hour, it will return 1 day).
872
-     *
873
-     * @param string $units 'seconds','minutes','hours','days'
874
-     * @param bool   $round_up
875
-     * @return float|int|mixed
876
-     * @throws ReflectionException
877
-     * @throws InvalidArgumentException
878
-     * @throws InvalidInterfaceException
879
-     * @throws InvalidDataTypeException
880
-     * @throws EE_Error
881
-     */
882
-    public function length($units = 'seconds', $round_up = false)
883
-    {
884
-        $start = $this->get_raw('DTT_EVT_start');
885
-        $end = $this->get_raw('DTT_EVT_end');
886
-        $length_in_units = $end - $start;
887
-        switch ($units) {
888
-            // NOTE: We purposefully don't use "break;" in order to chain the divisions
889
-            /** @noinspection PhpMissingBreakStatementInspection */
890
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
891
-            case 'days':
892
-                $length_in_units /= 24;
893
-            /** @noinspection PhpMissingBreakStatementInspection */
894
-            case 'hours':
895
-                // fall through is intentional
896
-                $length_in_units /= 60;
897
-            /** @noinspection PhpMissingBreakStatementInspection */
898
-            case 'minutes':
899
-                // fall through is intentional
900
-                $length_in_units /= 60;
901
-            case 'seconds':
902
-            default:
903
-                $length_in_units = ceil($length_in_units);
904
-        }
905
-        // phpcs:enable
906
-        if ($round_up) {
907
-            $length_in_units = max($length_in_units, 1);
908
-        }
909
-        return $length_in_units;
910
-    }
911
-
912
-
913
-    /**
914
-     *        get end date and time
915
-     *
916
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
917
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
918
-     * @return    mixed                string on success, FALSE on fail
919
-     * @throws ReflectionException
920
-     * @throws InvalidArgumentException
921
-     * @throws InvalidInterfaceException
922
-     * @throws InvalidDataTypeException
923
-     * @throws EE_Error
924
-     */
925
-    public function end_date_and_time($dt_frmt = '', $tm_format = '')
926
-    {
927
-        return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
928
-    }
929
-
930
-
931
-    /**
932
-     * @param string $dt_frmt
933
-     * @param string $tm_format
934
-     * @throws ReflectionException
935
-     * @throws InvalidArgumentException
936
-     * @throws InvalidInterfaceException
937
-     * @throws InvalidDataTypeException
938
-     * @throws EE_Error
939
-     */
940
-    public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
941
-    {
942
-        $this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
943
-    }
944
-
945
-
946
-    /**
947
-     *        get start timestamp
948
-     *
949
-     * @return        int
950
-     * @throws ReflectionException
951
-     * @throws InvalidArgumentException
952
-     * @throws InvalidInterfaceException
953
-     * @throws InvalidDataTypeException
954
-     * @throws EE_Error
955
-     */
956
-    public function start()
957
-    {
958
-        return $this->get_raw('DTT_EVT_start');
959
-    }
960
-
961
-
962
-    /**
963
-     *        get end timestamp
964
-     *
965
-     * @return        int
966
-     * @throws ReflectionException
967
-     * @throws InvalidArgumentException
968
-     * @throws InvalidInterfaceException
969
-     * @throws InvalidDataTypeException
970
-     * @throws EE_Error
971
-     */
972
-    public function end()
973
-    {
974
-        return $this->get_raw('DTT_EVT_end');
975
-    }
976
-
977
-
978
-    /**
979
-     *    get the registration limit for this datetime slot
980
-     *
981
-     * @return int|float                int = finite limit   EE_INF(float) = unlimited
982
-     * @throws ReflectionException
983
-     * @throws InvalidArgumentException
984
-     * @throws InvalidInterfaceException
985
-     * @throws InvalidDataTypeException
986
-     * @throws EE_Error
987
-     */
988
-    public function reg_limit()
989
-    {
990
-        return $this->get_raw('DTT_reg_limit');
991
-    }
992
-
993
-
994
-    /**
995
-     *    have the tickets sold for this datetime, met or exceed the registration limit ?
996
-     *
997
-     * @return boolean
998
-     * @throws ReflectionException
999
-     * @throws InvalidArgumentException
1000
-     * @throws InvalidInterfaceException
1001
-     * @throws InvalidDataTypeException
1002
-     * @throws EE_Error
1003
-     */
1004
-    public function sold_out()
1005
-    {
1006
-        return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1007
-    }
1008
-
1009
-
1010
-    /**
1011
-     * return the total number of spaces remaining at this venue.
1012
-     * This only takes the venue's capacity into account, NOT the tickets available for sale
1013
-     *
1014
-     * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1015
-     *                               Because if all tickets attached to this datetime have no spaces left,
1016
-     *                               then this datetime IS effectively sold out.
1017
-     *                               However, there are cases where we just want to know the spaces
1018
-     *                               remaining for this particular datetime, hence the flag.
1019
-     * @return int|float
1020
-     * @throws ReflectionException
1021
-     * @throws InvalidArgumentException
1022
-     * @throws InvalidInterfaceException
1023
-     * @throws InvalidDataTypeException
1024
-     * @throws EE_Error
1025
-     */
1026
-    public function spaces_remaining($consider_tickets = false)
1027
-    {
1028
-        // tickets remaining available for purchase
1029
-        // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1030
-        $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1031
-        if (! $consider_tickets) {
1032
-            return $dtt_remaining;
1033
-        }
1034
-        $tickets_remaining = $this->tickets_remaining();
1035
-        return min($dtt_remaining, $tickets_remaining);
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * Counts the total tickets available
1041
-     * (from all the different types of tickets which are available for this datetime).
1042
-     *
1043
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1044
-     * @return int
1045
-     * @throws ReflectionException
1046
-     * @throws InvalidArgumentException
1047
-     * @throws InvalidInterfaceException
1048
-     * @throws InvalidDataTypeException
1049
-     * @throws EE_Error
1050
-     */
1051
-    public function tickets_remaining($query_params = array())
1052
-    {
1053
-        $sum = 0;
1054
-        $tickets = $this->tickets($query_params);
1055
-        if (! empty($tickets)) {
1056
-            foreach ($tickets as $ticket) {
1057
-                if ($ticket instanceof EE_Ticket) {
1058
-                    // get the actual amount of tickets that can be sold
1059
-                    $qty = $ticket->qty('saleable');
1060
-                    if ($qty === EE_INF) {
1061
-                        return EE_INF;
1062
-                    }
1063
-                    // no negative ticket quantities plz
1064
-                    if ($qty > 0) {
1065
-                        $sum += $qty;
1066
-                    }
1067
-                }
1068
-            }
1069
-        }
1070
-        return $sum;
1071
-    }
1072
-
1073
-
1074
-    /**
1075
-     * Gets the count of all the tickets available at this datetime (not ticket types)
1076
-     * before any were sold
1077
-     *
1078
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1079
-     * @return int
1080
-     * @throws ReflectionException
1081
-     * @throws InvalidArgumentException
1082
-     * @throws InvalidInterfaceException
1083
-     * @throws InvalidDataTypeException
1084
-     * @throws EE_Error
1085
-     */
1086
-    public function sum_tickets_initially_available($query_params = array())
1087
-    {
1088
-        return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1089
-    }
1090
-
1091
-
1092
-    /**
1093
-     * Returns the lesser-of-the two: spaces remaining at this datetime, or
1094
-     * the total tickets remaining (a sum of the tickets remaining for each ticket type
1095
-     * that is available for this datetime).
1096
-     *
1097
-     * @return int
1098
-     * @throws ReflectionException
1099
-     * @throws InvalidArgumentException
1100
-     * @throws InvalidInterfaceException
1101
-     * @throws InvalidDataTypeException
1102
-     * @throws EE_Error
1103
-     */
1104
-    public function total_tickets_available_at_this_datetime()
1105
-    {
1106
-        return $this->spaces_remaining(true);
1107
-    }
1108
-
1109
-
1110
-    /**
1111
-     * This simply compares the internal dtt for the given string with NOW
1112
-     * and determines if the date is upcoming or not.
1113
-     *
1114
-     * @access public
1115
-     * @return boolean
1116
-     * @throws ReflectionException
1117
-     * @throws InvalidArgumentException
1118
-     * @throws InvalidInterfaceException
1119
-     * @throws InvalidDataTypeException
1120
-     * @throws EE_Error
1121
-     */
1122
-    public function is_upcoming()
1123
-    {
1124
-        return ($this->get_raw('DTT_EVT_start') > time());
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * This simply compares the internal datetime for the given string with NOW
1130
-     * and returns if the date is active (i.e. start and end time)
1131
-     *
1132
-     * @return boolean
1133
-     * @throws ReflectionException
1134
-     * @throws InvalidArgumentException
1135
-     * @throws InvalidInterfaceException
1136
-     * @throws InvalidDataTypeException
1137
-     * @throws EE_Error
1138
-     */
1139
-    public function is_active()
1140
-    {
1141
-        return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1142
-    }
1143
-
1144
-
1145
-    /**
1146
-     * This simply compares the internal dtt for the given string with NOW
1147
-     * and determines if the date is expired or not.
1148
-     *
1149
-     * @return boolean
1150
-     * @throws ReflectionException
1151
-     * @throws InvalidArgumentException
1152
-     * @throws InvalidInterfaceException
1153
-     * @throws InvalidDataTypeException
1154
-     * @throws EE_Error
1155
-     */
1156
-    public function is_expired()
1157
-    {
1158
-        return ($this->get_raw('DTT_EVT_end') < time());
1159
-    }
1160
-
1161
-
1162
-    /**
1163
-     * This returns the active status for whether an event is active, upcoming, or expired
1164
-     *
1165
-     * @return int return value will be one of the EE_Datetime status constants.
1166
-     * @throws ReflectionException
1167
-     * @throws InvalidArgumentException
1168
-     * @throws InvalidInterfaceException
1169
-     * @throws InvalidDataTypeException
1170
-     * @throws EE_Error
1171
-     */
1172
-    public function get_active_status()
1173
-    {
1174
-        $total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1175
-        if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1176
-            return EE_Datetime::sold_out;
1177
-        }
1178
-        if ($this->is_expired()) {
1179
-            return EE_Datetime::expired;
1180
-        }
1181
-        if ($this->is_upcoming()) {
1182
-            return EE_Datetime::upcoming;
1183
-        }
1184
-        if ($this->is_active()) {
1185
-            return EE_Datetime::active;
1186
-        }
1187
-        return null;
1188
-    }
1189
-
1190
-
1191
-    /**
1192
-     * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1193
-     *
1194
-     * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1195
-     * @return string
1196
-     * @throws ReflectionException
1197
-     * @throws InvalidArgumentException
1198
-     * @throws InvalidInterfaceException
1199
-     * @throws InvalidDataTypeException
1200
-     * @throws EE_Error
1201
-     */
1202
-    public function get_dtt_display_name($use_dtt_name = false)
1203
-    {
1204
-        if ($use_dtt_name) {
1205
-            $dtt_name = $this->name();
1206
-            if (! empty($dtt_name)) {
1207
-                return $dtt_name;
1208
-            }
1209
-        }
1210
-        // first condition is to see if the months are different
1211
-        if (
1212
-            date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1213
-        ) {
1214
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
-            // next condition is if its the same month but different day
1216
-        } else {
1217
-            if (
1218
-                date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1219
-                && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1220
-            ) {
1221
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
-            } else {
1223
-                $display_date = $this->start_date('F j\, Y')
1224
-                                . ' @ '
1225
-                                . $this->start_date('g:i a')
1226
-                                . ' - '
1227
-                                . $this->end_date('g:i a');
1228
-            }
1229
-        }
1230
-        return $display_date;
1231
-    }
1232
-
1233
-
1234
-    /**
1235
-     * Gets all the tickets for this datetime
1236
-     *
1237
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1238
-     * @return EE_Base_Class[]|EE_Ticket[]
1239
-     * @throws ReflectionException
1240
-     * @throws InvalidArgumentException
1241
-     * @throws InvalidInterfaceException
1242
-     * @throws InvalidDataTypeException
1243
-     * @throws EE_Error
1244
-     */
1245
-    public function tickets($query_params = array())
1246
-    {
1247
-        return $this->get_many_related('Ticket', $query_params);
1248
-    }
1249
-
1250
-
1251
-    /**
1252
-     * Gets all the ticket types currently available for purchase
1253
-     *
1254
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1255
-     * @return EE_Ticket[]
1256
-     * @throws ReflectionException
1257
-     * @throws InvalidArgumentException
1258
-     * @throws InvalidInterfaceException
1259
-     * @throws InvalidDataTypeException
1260
-     * @throws EE_Error
1261
-     */
1262
-    public function ticket_types_available_for_purchase($query_params = array())
1263
-    {
1264
-        // first check if datetime is valid
1265
-        if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1266
-            return array();
1267
-        }
1268
-        if (empty($query_params)) {
1269
-            $query_params = array(
1270
-                array(
1271
-                    'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1272
-                    'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1273
-                    'TKT_deleted'    => false,
1274
-                ),
1275
-            );
1276
-        }
1277
-        return $this->tickets($query_params);
1278
-    }
1279
-
1280
-
1281
-    /**
1282
-     * @return EE_Base_Class|EE_Event
1283
-     * @throws ReflectionException
1284
-     * @throws InvalidArgumentException
1285
-     * @throws InvalidInterfaceException
1286
-     * @throws InvalidDataTypeException
1287
-     * @throws EE_Error
1288
-     */
1289
-    public function event()
1290
-    {
1291
-        return $this->get_first_related('Event');
1292
-    }
1293
-
1294
-
1295
-    /**
1296
-     * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1297
-     * (via the tickets).
1298
-     *
1299
-     * @return int
1300
-     * @throws ReflectionException
1301
-     * @throws InvalidArgumentException
1302
-     * @throws InvalidInterfaceException
1303
-     * @throws InvalidDataTypeException
1304
-     * @throws EE_Error
1305
-     */
1306
-    public function update_sold()
1307
-    {
1308
-        $count_regs_for_this_datetime = EEM_Registration::instance()->count(
1309
-            array(
1310
-                array(
1311
-                    'STS_ID'                 => EEM_Registration::status_id_approved,
1312
-                    'REG_deleted'            => 0,
1313
-                    'Ticket.Datetime.DTT_ID' => $this->ID(),
1314
-                ),
1315
-            )
1316
-        );
1317
-        $this->set_sold($count_regs_for_this_datetime);
1318
-        $this->save();
1319
-        return $count_regs_for_this_datetime;
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * Adds a venue to this event
1325
-     *
1326
-     * @param int|EE_Venue /int $venue_id_or_obj
1327
-     * @return EE_Base_Class|EE_Venue
1328
-     * @throws EE_Error
1329
-     * @throws ReflectionException
1330
-     */
1331
-    public function add_venue($venue_id_or_obj): EE_Venue
1332
-    {
1333
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
1334
-    }
1335
-
1336
-
1337
-    /**
1338
-     * Removes a venue from the event
1339
-     *
1340
-     * @param EE_Venue /int $venue_id_or_obj
1341
-     * @return EE_Base_Class|EE_Venue
1342
-     * @throws EE_Error
1343
-     * @throws ReflectionException
1344
-     */
1345
-    public function remove_venue($venue_id_or_obj): EE_Venue
1346
-    {
1347
-        $venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
1348
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
1349
-    }
1350
-
1351
-
1352
-    /**
1353
-     * Gets the venue related to the event. May provide additional $query_params if desired
1354
-     *
1355
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1356
-     * @return int
1357
-     * @throws EE_Error
1358
-     * @throws ReflectionException
1359
-     */
1360
-    public function venue_ID(array $query_params = []): int
1361
-    {
1362
-        $venue = $this->get_first_related('Venue', $query_params);
1363
-        return $venue instanceof EE_Venue
1364
-            ? $venue->ID()
1365
-            : 0;
1366
-    }
1367
-
1368
-
1369
-    /**
1370
-     * Gets the venue related to the event. May provide additional $query_params if desired
1371
-     *
1372
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1373
-     * @return EE_Base_Class|EE_Venue
1374
-     * @throws EE_Error
1375
-     * @throws ReflectionException
1376
-     */
1377
-    public function venue(array $query_params = [])
1378
-    {
1379
-        return $this->get_first_related('Venue', $query_params);
1380
-    }
1381
-
1382
-
1383
-    /**
1384
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1385
-     * @param string                   $relationName
1386
-     * @param array                    $extra_join_model_fields_n_values
1387
-     * @param string|null              $cache_id
1388
-     * @return EE_Base_Class
1389
-     * @throws EE_Error
1390
-     * @throws ReflectionException
1391
-     * @since   5.0.0.p
1392
-     */
1393
-    public function _add_relation_to(
1394
-        $otherObjectModelObjectOrID,
1395
-        $relationName,
1396
-        $extra_join_model_fields_n_values = [],
1397
-        $cache_id = null
1398
-    ) {
1399
-        // if we're adding a new relation to a ticket
1400
-        if ($relationName === 'Ticket' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1401
-            /** @var EE_Ticket $ticket */
1402
-            $ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1403
-            $this->increaseSold($ticket->sold(), false);
1404
-            $this->increaseReserved($ticket->reserved());
1405
-            $this->save();
1406
-            $otherObjectModelObjectOrID = $ticket;
1407
-        }
1408
-        return parent::_add_relation_to(
1409
-            $otherObjectModelObjectOrID,
1410
-            $relationName,
1411
-            $extra_join_model_fields_n_values,
1412
-            $cache_id
1413
-        );
1414
-    }
1415
-
1416
-
1417
-    /**
1418
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1419
-     * @param string                   $relationName
1420
-     * @param array                    $where_query
1421
-     * @return bool|EE_Base_Class|null
1422
-     * @throws EE_Error
1423
-     * @throws ReflectionException
1424
-     * @since   5.0.0.p
1425
-     */
1426
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1427
-    {
1428
-        if ($relationName === 'Ticket' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1429
-            /** @var EE_Ticket $ticket */
1430
-            $ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1431
-            $this->decreaseSold($ticket->sold());
1432
-            $this->decreaseReserved($ticket->reserved());
1433
-            $this->save();
1434
-            $otherObjectModelObjectOrID = $ticket;
1435
-        }
1436
-        return parent::_remove_relation_to(
1437
-            $otherObjectModelObjectOrID,
1438
-            $relationName,
1439
-            $where_query
1440
-        );
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * Removes ALL the related things for the $relationName.
1446
-     *
1447
-     * @param string $relationName
1448
-     * @param array  $where_query_params
1449
-     * @return EE_Base_Class
1450
-     * @throws ReflectionException
1451
-     * @throws InvalidArgumentException
1452
-     * @throws InvalidInterfaceException
1453
-     * @throws InvalidDataTypeException
1454
-     * @throws EE_Error
1455
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1456
-     */
1457
-    public function _remove_relations($relationName, $where_query_params = [])
1458
-    {
1459
-        if ($relationName === 'Ticket') {
1460
-            $tickets = $this->tickets();
1461
-            foreach ($tickets as $ticket) {
1462
-                $this->decreaseSold($ticket->sold());
1463
-                $this->decreaseReserved($ticket->reserved());
1464
-                $this->save();
1465
-            }
1466
-        }
1467
-        return parent::_remove_relations($relationName, $where_query_params);
1468
-    }
1469
-
1470
-
1471
-    /*******************************************************************
15
+	/**
16
+	 * constant used by get_active_status, indicates datetime has no more available spaces
17
+	 */
18
+	const sold_out = 'DTS';
19
+
20
+	/**
21
+	 * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
22
+	 */
23
+	const active = 'DTA';
24
+
25
+	/**
26
+	 * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
27
+	 * expired
28
+	 */
29
+	const upcoming = 'DTU';
30
+
31
+	/**
32
+	 * Datetime is postponed
33
+	 */
34
+	const postponed = 'DTP';
35
+
36
+	/**
37
+	 * Datetime is cancelled
38
+	 */
39
+	const cancelled = 'DTC';
40
+
41
+	/**
42
+	 * constant used by get_active_status, indicates datetime has expired (event is over)
43
+	 */
44
+	const expired = 'DTE';
45
+
46
+	/**
47
+	 * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
48
+	 */
49
+	const inactive = 'DTI';
50
+
51
+
52
+	/**
53
+	 * @param array  $props_n_values    incoming values
54
+	 * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
55
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
56
+	 *                                  and the second value is the time format
57
+	 * @return EE_Datetime
58
+	 * @throws ReflectionException
59
+	 * @throws InvalidArgumentException
60
+	 * @throws InvalidInterfaceException
61
+	 * @throws InvalidDataTypeException
62
+	 * @throws EE_Error
63
+	 */
64
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
65
+	{
66
+		$has_object = parent::_check_for_object(
67
+			$props_n_values,
68
+			__CLASS__,
69
+			$timezone,
70
+			$date_formats
71
+		);
72
+		return $has_object
73
+			? $has_object
74
+			: new self($props_n_values, false, $timezone, $date_formats);
75
+	}
76
+
77
+
78
+	/**
79
+	 * @param array  $props_n_values  incoming values from the database
80
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
81
+	 *                                the website will be used.
82
+	 * @return EE_Datetime
83
+	 * @throws ReflectionException
84
+	 * @throws InvalidArgumentException
85
+	 * @throws InvalidInterfaceException
86
+	 * @throws InvalidDataTypeException
87
+	 * @throws EE_Error
88
+	 */
89
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
90
+	{
91
+		return new self($props_n_values, true, $timezone);
92
+	}
93
+
94
+
95
+	/**
96
+	 * @param $name
97
+	 * @throws ReflectionException
98
+	 * @throws InvalidArgumentException
99
+	 * @throws InvalidInterfaceException
100
+	 * @throws InvalidDataTypeException
101
+	 * @throws EE_Error
102
+	 */
103
+	public function set_name($name)
104
+	{
105
+		$this->set('DTT_name', $name);
106
+	}
107
+
108
+
109
+	/**
110
+	 * @param $description
111
+	 * @throws ReflectionException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidInterfaceException
114
+	 * @throws InvalidDataTypeException
115
+	 * @throws EE_Error
116
+	 */
117
+	public function set_description($description)
118
+	{
119
+		$this->set('DTT_description', $description);
120
+	}
121
+
122
+
123
+	/**
124
+	 * Set event start date
125
+	 * set the start date for an event
126
+	 *
127
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
128
+	 * @throws ReflectionException
129
+	 * @throws InvalidArgumentException
130
+	 * @throws InvalidInterfaceException
131
+	 * @throws InvalidDataTypeException
132
+	 * @throws EE_Error
133
+	 */
134
+	public function set_start_date($date)
135
+	{
136
+		$this->_set_date_for($date, 'DTT_EVT_start');
137
+	}
138
+
139
+
140
+	/**
141
+	 * Set event start time
142
+	 * set the start time for an event
143
+	 *
144
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
145
+	 * @throws ReflectionException
146
+	 * @throws InvalidArgumentException
147
+	 * @throws InvalidInterfaceException
148
+	 * @throws InvalidDataTypeException
149
+	 * @throws EE_Error
150
+	 */
151
+	public function set_start_time($time)
152
+	{
153
+		$this->_set_time_for($time, 'DTT_EVT_start');
154
+	}
155
+
156
+
157
+	/**
158
+	 * Set event end date
159
+	 * set the end date for an event
160
+	 *
161
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
162
+	 * @throws ReflectionException
163
+	 * @throws InvalidArgumentException
164
+	 * @throws InvalidInterfaceException
165
+	 * @throws InvalidDataTypeException
166
+	 * @throws EE_Error
167
+	 */
168
+	public function set_end_date($date)
169
+	{
170
+		$this->_set_date_for($date, 'DTT_EVT_end');
171
+	}
172
+
173
+
174
+	/**
175
+	 * Set event end time
176
+	 * set the end time for an event
177
+	 *
178
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
179
+	 * @throws ReflectionException
180
+	 * @throws InvalidArgumentException
181
+	 * @throws InvalidInterfaceException
182
+	 * @throws InvalidDataTypeException
183
+	 * @throws EE_Error
184
+	 */
185
+	public function set_end_time($time)
186
+	{
187
+		$this->_set_time_for($time, 'DTT_EVT_end');
188
+	}
189
+
190
+
191
+	/**
192
+	 * Set registration limit
193
+	 * set the maximum number of attendees that can be registered for this datetime slot
194
+	 *
195
+	 * @param int|float $reg_limit
196
+	 * @throws ReflectionException
197
+	 * @throws InvalidArgumentException
198
+	 * @throws InvalidInterfaceException
199
+	 * @throws InvalidDataTypeException
200
+	 * @throws EE_Error
201
+	 */
202
+	public function set_reg_limit($reg_limit)
203
+	{
204
+		$this->set('DTT_reg_limit', $reg_limit);
205
+	}
206
+
207
+
208
+	/**
209
+	 * get the number of tickets sold for this datetime slot
210
+	 *
211
+	 * @return mixed int on success, FALSE on fail
212
+	 * @throws ReflectionException
213
+	 * @throws InvalidArgumentException
214
+	 * @throws InvalidInterfaceException
215
+	 * @throws InvalidDataTypeException
216
+	 * @throws EE_Error
217
+	 */
218
+	public function sold()
219
+	{
220
+		return $this->get_raw('DTT_sold');
221
+	}
222
+
223
+
224
+	/**
225
+	 * @param int $sold
226
+	 * @throws ReflectionException
227
+	 * @throws InvalidArgumentException
228
+	 * @throws InvalidInterfaceException
229
+	 * @throws InvalidDataTypeException
230
+	 * @throws EE_Error
231
+	 */
232
+	public function set_sold($sold)
233
+	{
234
+		// sold can not go below zero
235
+		$sold = max(0, $sold);
236
+		$this->set('DTT_sold', $sold);
237
+	}
238
+
239
+
240
+	/**
241
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
242
+	 * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
243
+	 *
244
+	 * @param int $qty
245
+	 * @param boolean $also_decrease_reserved
246
+	 * @return boolean indicating success
247
+	 * @throws ReflectionException
248
+	 * @throws InvalidArgumentException
249
+	 * @throws InvalidInterfaceException
250
+	 * @throws InvalidDataTypeException
251
+	 * @throws EE_Error
252
+	 */
253
+	public function increaseSold(int $qty = 1, bool $also_decrease_reserved = true): bool
254
+	{
255
+		$qty = absint($qty);
256
+		if ($also_decrease_reserved) {
257
+			$success = $this->adjustNumericFieldsInDb(
258
+				[
259
+					'DTT_reserved' => $qty * -1,
260
+					'DTT_sold' => $qty
261
+				]
262
+			);
263
+		} else {
264
+			$success = $this->adjustNumericFieldsInDb(
265
+				[
266
+					'DTT_sold' => $qty
267
+				]
268
+			);
269
+		}
270
+
271
+		do_action(
272
+			'AHEE__EE_Datetime__increase_sold',
273
+			$this,
274
+			$qty,
275
+			$this->sold(),
276
+			$success
277
+		);
278
+		return $success;
279
+	}
280
+
281
+
282
+	/**
283
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
284
+	 * to save afterwards.)
285
+	 *
286
+	 * @param int $qty
287
+	 * @return boolean indicating success
288
+	 * @throws ReflectionException
289
+	 * @throws InvalidArgumentException
290
+	 * @throws InvalidInterfaceException
291
+	 * @throws InvalidDataTypeException
292
+	 * @throws EE_Error
293
+	 */
294
+	public function decreaseSold(int $qty = 1): bool
295
+	{
296
+		$qty = absint($qty);
297
+		$success = $this->adjustNumericFieldsInDb(
298
+			[
299
+				'DTT_sold' => $qty * -1
300
+			]
301
+		);
302
+		do_action(
303
+			'AHEE__EE_Datetime__decrease_sold',
304
+			$this,
305
+			$qty,
306
+			$this->sold(),
307
+			$success
308
+		);
309
+		return $success;
310
+	}
311
+
312
+
313
+	/**
314
+	 * Gets qty of reserved tickets for this datetime
315
+	 *
316
+	 * @return int
317
+	 * @throws ReflectionException
318
+	 * @throws InvalidArgumentException
319
+	 * @throws InvalidInterfaceException
320
+	 * @throws InvalidDataTypeException
321
+	 * @throws EE_Error
322
+	 */
323
+	public function reserved(): int
324
+	{
325
+		return $this->get_raw('DTT_reserved');
326
+	}
327
+
328
+
329
+	/**
330
+	 * Sets qty of reserved tickets for this datetime
331
+	 *
332
+	 * @param int $reserved
333
+	 * @throws ReflectionException
334
+	 * @throws InvalidArgumentException
335
+	 * @throws InvalidInterfaceException
336
+	 * @throws InvalidDataTypeException
337
+	 * @throws EE_Error
338
+	 */
339
+	public function set_reserved(int $reserved)
340
+	{
341
+		// reserved can not go below zero
342
+		$reserved = max(0, $reserved);
343
+		$this->set('DTT_reserved', $reserved);
344
+	}
345
+
346
+
347
+	/**
348
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
349
+	 *
350
+	 * @param int $qty
351
+	 * @return boolean indicating success
352
+	 * @throws ReflectionException
353
+	 * @throws InvalidArgumentException
354
+	 * @throws InvalidInterfaceException
355
+	 * @throws InvalidDataTypeException
356
+	 * @throws EE_Error
357
+	 */
358
+	public function increaseReserved(int $qty = 1): bool
359
+	{
360
+		$qty = absint($qty);
361
+		$success = $this->incrementFieldConditionallyInDb(
362
+			'DTT_reserved',
363
+			'DTT_sold',
364
+			'DTT_reg_limit',
365
+			$qty
366
+		);
367
+		do_action(
368
+			'AHEE__EE_Datetime__increase_reserved',
369
+			$this,
370
+			$qty,
371
+			$this->reserved(),
372
+			$success
373
+		);
374
+		return $success;
375
+	}
376
+
377
+
378
+	/**
379
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
380
+	 *
381
+	 * @param int $qty
382
+	 * @return boolean indicating success
383
+	 * @throws ReflectionException
384
+	 * @throws InvalidArgumentException
385
+	 * @throws InvalidInterfaceException
386
+	 * @throws InvalidDataTypeException
387
+	 * @throws EE_Error
388
+	 */
389
+	public function decreaseReserved(int $qty = 1): bool
390
+	{
391
+		$qty = absint($qty);
392
+		$success = $this->adjustNumericFieldsInDb(
393
+			[
394
+				'DTT_reserved' => $qty * -1
395
+			]
396
+		);
397
+		do_action(
398
+			'AHEE__EE_Datetime__decrease_reserved',
399
+			$this,
400
+			$qty,
401
+			$this->reserved(),
402
+			$success
403
+		);
404
+		return $success;
405
+	}
406
+
407
+
408
+	/**
409
+	 * total sold and reserved tickets
410
+	 *
411
+	 * @return int
412
+	 * @throws ReflectionException
413
+	 * @throws InvalidArgumentException
414
+	 * @throws InvalidInterfaceException
415
+	 * @throws InvalidDataTypeException
416
+	 * @throws EE_Error
417
+	 */
418
+	public function sold_and_reserved(): int
419
+	{
420
+		return $this->sold() + $this->reserved();
421
+	}
422
+
423
+
424
+	/**
425
+	 * returns the datetime name
426
+	 *
427
+	 * @return string
428
+	 * @throws ReflectionException
429
+	 * @throws InvalidArgumentException
430
+	 * @throws InvalidInterfaceException
431
+	 * @throws InvalidDataTypeException
432
+	 * @throws EE_Error
433
+	 */
434
+	public function name(): string
435
+	{
436
+		return $this->get('DTT_name');
437
+	}
438
+
439
+
440
+	/**
441
+	 * returns the datetime description
442
+	 *
443
+	 * @return string
444
+	 * @throws ReflectionException
445
+	 * @throws InvalidArgumentException
446
+	 * @throws InvalidInterfaceException
447
+	 * @throws InvalidDataTypeException
448
+	 * @throws EE_Error
449
+	 */
450
+	public function description(): string
451
+	{
452
+		return $this->get('DTT_description');
453
+	}
454
+
455
+
456
+	/**
457
+	 * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
458
+	 *
459
+	 * @return boolean  TRUE if is primary, FALSE if not.
460
+	 * @throws ReflectionException
461
+	 * @throws InvalidArgumentException
462
+	 * @throws InvalidInterfaceException
463
+	 * @throws InvalidDataTypeException
464
+	 * @throws EE_Error
465
+	 */
466
+	public function is_primary(): bool
467
+	{
468
+		return $this->get('DTT_is_primary');
469
+	}
470
+
471
+
472
+	/**
473
+	 * This helper simply returns the order for the datetime
474
+	 *
475
+	 * @return int  The order of the datetime for this event.
476
+	 * @throws ReflectionException
477
+	 * @throws InvalidArgumentException
478
+	 * @throws InvalidInterfaceException
479
+	 * @throws InvalidDataTypeException
480
+	 * @throws EE_Error
481
+	 */
482
+	public function order(): int
483
+	{
484
+		return $this->get('DTT_order');
485
+	}
486
+
487
+
488
+	/**
489
+	 * This helper simply returns the parent id for the datetime
490
+	 *
491
+	 * @return int
492
+	 * @throws ReflectionException
493
+	 * @throws InvalidArgumentException
494
+	 * @throws InvalidInterfaceException
495
+	 * @throws InvalidDataTypeException
496
+	 * @throws EE_Error
497
+	 */
498
+	public function parent(): int
499
+	{
500
+		return $this->get('DTT_parent');
501
+	}
502
+
503
+
504
+	/**
505
+	 * show date and/or time
506
+	 *
507
+	 * @param string $date_or_time    whether to display a date or time or both
508
+	 * @param string $start_or_end    whether to display start or end datetimes
509
+	 * @param string $dt_frmt
510
+	 * @param string $tm_frmt
511
+	 * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
512
+	 *                                otherwise we use the standard formats)
513
+	 * @return string|bool  string on success, FALSE on fail
514
+	 * @throws ReflectionException
515
+	 * @throws InvalidArgumentException
516
+	 * @throws InvalidInterfaceException
517
+	 * @throws InvalidDataTypeException
518
+	 * @throws EE_Error
519
+	 */
520
+	private function _show_datetime(
521
+		$date_or_time = null,
522
+		$start_or_end = 'start',
523
+		$dt_frmt = '',
524
+		$tm_frmt = '',
525
+		$echo = false
526
+	) {
527
+		$field_name = "DTT_EVT_{$start_or_end}";
528
+		$dtt = $this->_get_datetime(
529
+			$field_name,
530
+			$dt_frmt,
531
+			$tm_frmt,
532
+			$date_or_time,
533
+			$echo
534
+		);
535
+		if (! $echo) {
536
+			return $dtt;
537
+		}
538
+		return '';
539
+	}
540
+
541
+
542
+	/**
543
+	 * get event start date.  Provide either the date format, or NULL to re-use the
544
+	 * last-used format, or '' to use the default date format
545
+	 *
546
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
547
+	 * @return mixed            string on success, FALSE on fail
548
+	 * @throws ReflectionException
549
+	 * @throws InvalidArgumentException
550
+	 * @throws InvalidInterfaceException
551
+	 * @throws InvalidDataTypeException
552
+	 * @throws EE_Error
553
+	 */
554
+	public function start_date($dt_frmt = '')
555
+	{
556
+		return $this->_show_datetime('D', 'start', $dt_frmt);
557
+	}
558
+
559
+
560
+	/**
561
+	 * Echoes start_date()
562
+	 *
563
+	 * @param string $dt_frmt
564
+	 * @throws ReflectionException
565
+	 * @throws InvalidArgumentException
566
+	 * @throws InvalidInterfaceException
567
+	 * @throws InvalidDataTypeException
568
+	 * @throws EE_Error
569
+	 */
570
+	public function e_start_date($dt_frmt = '')
571
+	{
572
+		$this->_show_datetime('D', 'start', $dt_frmt, null, true);
573
+	}
574
+
575
+
576
+	/**
577
+	 * get end date. Provide either the date format, or NULL to re-use the
578
+	 * last-used format, or '' to use the default date format
579
+	 *
580
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
581
+	 * @return mixed            string on success, FALSE on fail
582
+	 * @throws ReflectionException
583
+	 * @throws InvalidArgumentException
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws InvalidDataTypeException
586
+	 * @throws EE_Error
587
+	 */
588
+	public function end_date($dt_frmt = '')
589
+	{
590
+		return $this->_show_datetime('D', 'end', $dt_frmt);
591
+	}
592
+
593
+
594
+	/**
595
+	 * Echoes the end date. See end_date()
596
+	 *
597
+	 * @param string $dt_frmt
598
+	 * @throws ReflectionException
599
+	 * @throws InvalidArgumentException
600
+	 * @throws InvalidInterfaceException
601
+	 * @throws InvalidDataTypeException
602
+	 * @throws EE_Error
603
+	 */
604
+	public function e_end_date($dt_frmt = '')
605
+	{
606
+		$this->_show_datetime('D', 'end', $dt_frmt, null, true);
607
+	}
608
+
609
+
610
+	/**
611
+	 * get date_range - meaning the start AND end date
612
+	 *
613
+	 * @access public
614
+	 * @param string $dt_frmt     string representation of date format defaults to WP settings
615
+	 * @param string $conjunction conjunction junction what's your function ?
616
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
617
+	 * @return mixed              string on success, FALSE on fail
618
+	 * @throws ReflectionException
619
+	 * @throws InvalidArgumentException
620
+	 * @throws InvalidInterfaceException
621
+	 * @throws InvalidDataTypeException
622
+	 * @throws EE_Error
623
+	 */
624
+	public function date_range($dt_frmt = '', $conjunction = ' - ')
625
+	{
626
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
627
+		$start = str_replace(
628
+			' ',
629
+			'&nbsp;',
630
+			$this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
631
+		);
632
+		$end = str_replace(
633
+			' ',
634
+			'&nbsp;',
635
+			$this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
636
+		);
637
+		return $start !== $end ? $start . $conjunction . $end : $start;
638
+	}
639
+
640
+
641
+	/**
642
+	 * @param string $dt_frmt
643
+	 * @param string $conjunction
644
+	 * @throws ReflectionException
645
+	 * @throws InvalidArgumentException
646
+	 * @throws InvalidInterfaceException
647
+	 * @throws InvalidDataTypeException
648
+	 * @throws EE_Error
649
+	 */
650
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ')
651
+	{
652
+		echo esc_html($this->date_range($dt_frmt, $conjunction));
653
+	}
654
+
655
+
656
+	/**
657
+	 * get start time
658
+	 *
659
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
660
+	 * @return mixed        string on success, FALSE on fail
661
+	 * @throws ReflectionException
662
+	 * @throws InvalidArgumentException
663
+	 * @throws InvalidInterfaceException
664
+	 * @throws InvalidDataTypeException
665
+	 * @throws EE_Error
666
+	 */
667
+	public function start_time($tm_format = '')
668
+	{
669
+		return $this->_show_datetime('T', 'start', null, $tm_format);
670
+	}
671
+
672
+
673
+	/**
674
+	 * @param string $tm_format
675
+	 * @throws ReflectionException
676
+	 * @throws InvalidArgumentException
677
+	 * @throws InvalidInterfaceException
678
+	 * @throws InvalidDataTypeException
679
+	 * @throws EE_Error
680
+	 */
681
+	public function e_start_time($tm_format = '')
682
+	{
683
+		$this->_show_datetime('T', 'start', null, $tm_format, true);
684
+	}
685
+
686
+
687
+	/**
688
+	 * get end time
689
+	 *
690
+	 * @param string $tm_format string representation of time format defaults to 'g:i a'
691
+	 * @return mixed                string on success, FALSE on fail
692
+	 * @throws ReflectionException
693
+	 * @throws InvalidArgumentException
694
+	 * @throws InvalidInterfaceException
695
+	 * @throws InvalidDataTypeException
696
+	 * @throws EE_Error
697
+	 */
698
+	public function end_time($tm_format = '')
699
+	{
700
+		return $this->_show_datetime('T', 'end', null, $tm_format);
701
+	}
702
+
703
+
704
+	/**
705
+	 * @param string $tm_format
706
+	 * @throws ReflectionException
707
+	 * @throws InvalidArgumentException
708
+	 * @throws InvalidInterfaceException
709
+	 * @throws InvalidDataTypeException
710
+	 * @throws EE_Error
711
+	 */
712
+	public function e_end_time($tm_format = '')
713
+	{
714
+		$this->_show_datetime('T', 'end', null, $tm_format, true);
715
+	}
716
+
717
+
718
+	/**
719
+	 * get time_range
720
+	 *
721
+	 * @access public
722
+	 * @param string $tm_format   string representation of time format defaults to 'g:i a'
723
+	 * @param string $conjunction conjunction junction what's your function ?
724
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
725
+	 * @return mixed              string on success, FALSE on fail
726
+	 * @throws ReflectionException
727
+	 * @throws InvalidArgumentException
728
+	 * @throws InvalidInterfaceException
729
+	 * @throws InvalidDataTypeException
730
+	 * @throws EE_Error
731
+	 */
732
+	public function time_range($tm_format = '', $conjunction = ' - ')
733
+	{
734
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
735
+		$start = str_replace(
736
+			' ',
737
+			'&nbsp;',
738
+			$this->get_i18n_datetime('DTT_EVT_start', $tm_format)
739
+		);
740
+		$end = str_replace(
741
+			' ',
742
+			'&nbsp;',
743
+			$this->get_i18n_datetime('DTT_EVT_end', $tm_format)
744
+		);
745
+		return $start !== $end ? $start . $conjunction . $end : $start;
746
+	}
747
+
748
+
749
+	/**
750
+	 * @param string $tm_format
751
+	 * @param string $conjunction
752
+	 * @throws ReflectionException
753
+	 * @throws InvalidArgumentException
754
+	 * @throws InvalidInterfaceException
755
+	 * @throws InvalidDataTypeException
756
+	 * @throws EE_Error
757
+	 */
758
+	public function e_time_range($tm_format = '', $conjunction = ' - ')
759
+	{
760
+		echo esc_html($this->time_range($tm_format, $conjunction));
761
+	}
762
+
763
+
764
+	/**
765
+	 * This returns a range representation of the date and times.
766
+	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
767
+	 * Also, the return value is localized.
768
+	 *
769
+	 * @param string $dt_format
770
+	 * @param string $tm_format
771
+	 * @param string $conjunction used between two different dates or times.
772
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
773
+	 * @param string $separator   used between the date and time formats.
774
+	 *                            ex: Dec 1, 2016{$separator}2pm
775
+	 * @return string
776
+	 * @throws ReflectionException
777
+	 * @throws InvalidArgumentException
778
+	 * @throws InvalidInterfaceException
779
+	 * @throws InvalidDataTypeException
780
+	 * @throws EE_Error
781
+	 */
782
+	public function date_and_time_range(
783
+		$dt_format = '',
784
+		$tm_format = '',
785
+		$conjunction = ' - ',
786
+		$separator = ' '
787
+	) {
788
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
789
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
790
+		$full_format = $dt_format . $separator . $tm_format;
791
+		// the range output depends on various conditions
792
+		switch (true) {
793
+			// start date timestamp and end date timestamp are the same.
794
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
795
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
796
+				break;
797
+			// start and end date are the same but times are different
798
+			case ($this->start_date() === $this->end_date()):
799
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
800
+						  . $conjunction
801
+						  . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
802
+				break;
803
+			// all other conditions
804
+			default:
805
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
806
+						  . $conjunction
807
+						  . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
808
+				break;
809
+		}
810
+		return $output;
811
+	}
812
+
813
+
814
+	/**
815
+	 * This echos the results of date and time range.
816
+	 *
817
+	 * @see date_and_time_range() for more details on purpose.
818
+	 * @param string $dt_format
819
+	 * @param string $tm_format
820
+	 * @param string $conjunction
821
+	 * @return void
822
+	 * @throws ReflectionException
823
+	 * @throws InvalidArgumentException
824
+	 * @throws InvalidInterfaceException
825
+	 * @throws InvalidDataTypeException
826
+	 * @throws EE_Error
827
+	 */
828
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
829
+	{
830
+		echo esc_html($this->date_and_time_range($dt_format, $tm_format, $conjunction));
831
+	}
832
+
833
+
834
+	/**
835
+	 * get start date and start time
836
+	 *
837
+	 * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
838
+	 * @param    string $tm_format - string representation of time format defaults to 'g:i a'
839
+	 * @return    mixed    string on success, FALSE on fail
840
+	 * @throws ReflectionException
841
+	 * @throws InvalidArgumentException
842
+	 * @throws InvalidInterfaceException
843
+	 * @throws InvalidDataTypeException
844
+	 * @throws EE_Error
845
+	 */
846
+	public function start_date_and_time($dt_format = '', $tm_format = '')
847
+	{
848
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
849
+	}
850
+
851
+
852
+	/**
853
+	 * @param string $dt_frmt
854
+	 * @param string $tm_format
855
+	 * @throws ReflectionException
856
+	 * @throws InvalidArgumentException
857
+	 * @throws InvalidInterfaceException
858
+	 * @throws InvalidDataTypeException
859
+	 * @throws EE_Error
860
+	 */
861
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
862
+	{
863
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
864
+	}
865
+
866
+
867
+	/**
868
+	 * Shows the length of the event (start to end time).
869
+	 * Can be shown in 'seconds','minutes','hours', or 'days'.
870
+	 * By default, rounds up. (So if you use 'days', and then event
871
+	 * only occurs for 1 hour, it will return 1 day).
872
+	 *
873
+	 * @param string $units 'seconds','minutes','hours','days'
874
+	 * @param bool   $round_up
875
+	 * @return float|int|mixed
876
+	 * @throws ReflectionException
877
+	 * @throws InvalidArgumentException
878
+	 * @throws InvalidInterfaceException
879
+	 * @throws InvalidDataTypeException
880
+	 * @throws EE_Error
881
+	 */
882
+	public function length($units = 'seconds', $round_up = false)
883
+	{
884
+		$start = $this->get_raw('DTT_EVT_start');
885
+		$end = $this->get_raw('DTT_EVT_end');
886
+		$length_in_units = $end - $start;
887
+		switch ($units) {
888
+			// NOTE: We purposefully don't use "break;" in order to chain the divisions
889
+			/** @noinspection PhpMissingBreakStatementInspection */
890
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
891
+			case 'days':
892
+				$length_in_units /= 24;
893
+			/** @noinspection PhpMissingBreakStatementInspection */
894
+			case 'hours':
895
+				// fall through is intentional
896
+				$length_in_units /= 60;
897
+			/** @noinspection PhpMissingBreakStatementInspection */
898
+			case 'minutes':
899
+				// fall through is intentional
900
+				$length_in_units /= 60;
901
+			case 'seconds':
902
+			default:
903
+				$length_in_units = ceil($length_in_units);
904
+		}
905
+		// phpcs:enable
906
+		if ($round_up) {
907
+			$length_in_units = max($length_in_units, 1);
908
+		}
909
+		return $length_in_units;
910
+	}
911
+
912
+
913
+	/**
914
+	 *        get end date and time
915
+	 *
916
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
917
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
918
+	 * @return    mixed                string on success, FALSE on fail
919
+	 * @throws ReflectionException
920
+	 * @throws InvalidArgumentException
921
+	 * @throws InvalidInterfaceException
922
+	 * @throws InvalidDataTypeException
923
+	 * @throws EE_Error
924
+	 */
925
+	public function end_date_and_time($dt_frmt = '', $tm_format = '')
926
+	{
927
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
928
+	}
929
+
930
+
931
+	/**
932
+	 * @param string $dt_frmt
933
+	 * @param string $tm_format
934
+	 * @throws ReflectionException
935
+	 * @throws InvalidArgumentException
936
+	 * @throws InvalidInterfaceException
937
+	 * @throws InvalidDataTypeException
938
+	 * @throws EE_Error
939
+	 */
940
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
941
+	{
942
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
943
+	}
944
+
945
+
946
+	/**
947
+	 *        get start timestamp
948
+	 *
949
+	 * @return        int
950
+	 * @throws ReflectionException
951
+	 * @throws InvalidArgumentException
952
+	 * @throws InvalidInterfaceException
953
+	 * @throws InvalidDataTypeException
954
+	 * @throws EE_Error
955
+	 */
956
+	public function start()
957
+	{
958
+		return $this->get_raw('DTT_EVT_start');
959
+	}
960
+
961
+
962
+	/**
963
+	 *        get end timestamp
964
+	 *
965
+	 * @return        int
966
+	 * @throws ReflectionException
967
+	 * @throws InvalidArgumentException
968
+	 * @throws InvalidInterfaceException
969
+	 * @throws InvalidDataTypeException
970
+	 * @throws EE_Error
971
+	 */
972
+	public function end()
973
+	{
974
+		return $this->get_raw('DTT_EVT_end');
975
+	}
976
+
977
+
978
+	/**
979
+	 *    get the registration limit for this datetime slot
980
+	 *
981
+	 * @return int|float                int = finite limit   EE_INF(float) = unlimited
982
+	 * @throws ReflectionException
983
+	 * @throws InvalidArgumentException
984
+	 * @throws InvalidInterfaceException
985
+	 * @throws InvalidDataTypeException
986
+	 * @throws EE_Error
987
+	 */
988
+	public function reg_limit()
989
+	{
990
+		return $this->get_raw('DTT_reg_limit');
991
+	}
992
+
993
+
994
+	/**
995
+	 *    have the tickets sold for this datetime, met or exceed the registration limit ?
996
+	 *
997
+	 * @return boolean
998
+	 * @throws ReflectionException
999
+	 * @throws InvalidArgumentException
1000
+	 * @throws InvalidInterfaceException
1001
+	 * @throws InvalidDataTypeException
1002
+	 * @throws EE_Error
1003
+	 */
1004
+	public function sold_out()
1005
+	{
1006
+		return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1007
+	}
1008
+
1009
+
1010
+	/**
1011
+	 * return the total number of spaces remaining at this venue.
1012
+	 * This only takes the venue's capacity into account, NOT the tickets available for sale
1013
+	 *
1014
+	 * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1015
+	 *                               Because if all tickets attached to this datetime have no spaces left,
1016
+	 *                               then this datetime IS effectively sold out.
1017
+	 *                               However, there are cases where we just want to know the spaces
1018
+	 *                               remaining for this particular datetime, hence the flag.
1019
+	 * @return int|float
1020
+	 * @throws ReflectionException
1021
+	 * @throws InvalidArgumentException
1022
+	 * @throws InvalidInterfaceException
1023
+	 * @throws InvalidDataTypeException
1024
+	 * @throws EE_Error
1025
+	 */
1026
+	public function spaces_remaining($consider_tickets = false)
1027
+	{
1028
+		// tickets remaining available for purchase
1029
+		// no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1030
+		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1031
+		if (! $consider_tickets) {
1032
+			return $dtt_remaining;
1033
+		}
1034
+		$tickets_remaining = $this->tickets_remaining();
1035
+		return min($dtt_remaining, $tickets_remaining);
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * Counts the total tickets available
1041
+	 * (from all the different types of tickets which are available for this datetime).
1042
+	 *
1043
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1044
+	 * @return int
1045
+	 * @throws ReflectionException
1046
+	 * @throws InvalidArgumentException
1047
+	 * @throws InvalidInterfaceException
1048
+	 * @throws InvalidDataTypeException
1049
+	 * @throws EE_Error
1050
+	 */
1051
+	public function tickets_remaining($query_params = array())
1052
+	{
1053
+		$sum = 0;
1054
+		$tickets = $this->tickets($query_params);
1055
+		if (! empty($tickets)) {
1056
+			foreach ($tickets as $ticket) {
1057
+				if ($ticket instanceof EE_Ticket) {
1058
+					// get the actual amount of tickets that can be sold
1059
+					$qty = $ticket->qty('saleable');
1060
+					if ($qty === EE_INF) {
1061
+						return EE_INF;
1062
+					}
1063
+					// no negative ticket quantities plz
1064
+					if ($qty > 0) {
1065
+						$sum += $qty;
1066
+					}
1067
+				}
1068
+			}
1069
+		}
1070
+		return $sum;
1071
+	}
1072
+
1073
+
1074
+	/**
1075
+	 * Gets the count of all the tickets available at this datetime (not ticket types)
1076
+	 * before any were sold
1077
+	 *
1078
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1079
+	 * @return int
1080
+	 * @throws ReflectionException
1081
+	 * @throws InvalidArgumentException
1082
+	 * @throws InvalidInterfaceException
1083
+	 * @throws InvalidDataTypeException
1084
+	 * @throws EE_Error
1085
+	 */
1086
+	public function sum_tickets_initially_available($query_params = array())
1087
+	{
1088
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1089
+	}
1090
+
1091
+
1092
+	/**
1093
+	 * Returns the lesser-of-the two: spaces remaining at this datetime, or
1094
+	 * the total tickets remaining (a sum of the tickets remaining for each ticket type
1095
+	 * that is available for this datetime).
1096
+	 *
1097
+	 * @return int
1098
+	 * @throws ReflectionException
1099
+	 * @throws InvalidArgumentException
1100
+	 * @throws InvalidInterfaceException
1101
+	 * @throws InvalidDataTypeException
1102
+	 * @throws EE_Error
1103
+	 */
1104
+	public function total_tickets_available_at_this_datetime()
1105
+	{
1106
+		return $this->spaces_remaining(true);
1107
+	}
1108
+
1109
+
1110
+	/**
1111
+	 * This simply compares the internal dtt for the given string with NOW
1112
+	 * and determines if the date is upcoming or not.
1113
+	 *
1114
+	 * @access public
1115
+	 * @return boolean
1116
+	 * @throws ReflectionException
1117
+	 * @throws InvalidArgumentException
1118
+	 * @throws InvalidInterfaceException
1119
+	 * @throws InvalidDataTypeException
1120
+	 * @throws EE_Error
1121
+	 */
1122
+	public function is_upcoming()
1123
+	{
1124
+		return ($this->get_raw('DTT_EVT_start') > time());
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * This simply compares the internal datetime for the given string with NOW
1130
+	 * and returns if the date is active (i.e. start and end time)
1131
+	 *
1132
+	 * @return boolean
1133
+	 * @throws ReflectionException
1134
+	 * @throws InvalidArgumentException
1135
+	 * @throws InvalidInterfaceException
1136
+	 * @throws InvalidDataTypeException
1137
+	 * @throws EE_Error
1138
+	 */
1139
+	public function is_active()
1140
+	{
1141
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1142
+	}
1143
+
1144
+
1145
+	/**
1146
+	 * This simply compares the internal dtt for the given string with NOW
1147
+	 * and determines if the date is expired or not.
1148
+	 *
1149
+	 * @return boolean
1150
+	 * @throws ReflectionException
1151
+	 * @throws InvalidArgumentException
1152
+	 * @throws InvalidInterfaceException
1153
+	 * @throws InvalidDataTypeException
1154
+	 * @throws EE_Error
1155
+	 */
1156
+	public function is_expired()
1157
+	{
1158
+		return ($this->get_raw('DTT_EVT_end') < time());
1159
+	}
1160
+
1161
+
1162
+	/**
1163
+	 * This returns the active status for whether an event is active, upcoming, or expired
1164
+	 *
1165
+	 * @return int return value will be one of the EE_Datetime status constants.
1166
+	 * @throws ReflectionException
1167
+	 * @throws InvalidArgumentException
1168
+	 * @throws InvalidInterfaceException
1169
+	 * @throws InvalidDataTypeException
1170
+	 * @throws EE_Error
1171
+	 */
1172
+	public function get_active_status()
1173
+	{
1174
+		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1175
+		if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1176
+			return EE_Datetime::sold_out;
1177
+		}
1178
+		if ($this->is_expired()) {
1179
+			return EE_Datetime::expired;
1180
+		}
1181
+		if ($this->is_upcoming()) {
1182
+			return EE_Datetime::upcoming;
1183
+		}
1184
+		if ($this->is_active()) {
1185
+			return EE_Datetime::active;
1186
+		}
1187
+		return null;
1188
+	}
1189
+
1190
+
1191
+	/**
1192
+	 * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1193
+	 *
1194
+	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1195
+	 * @return string
1196
+	 * @throws ReflectionException
1197
+	 * @throws InvalidArgumentException
1198
+	 * @throws InvalidInterfaceException
1199
+	 * @throws InvalidDataTypeException
1200
+	 * @throws EE_Error
1201
+	 */
1202
+	public function get_dtt_display_name($use_dtt_name = false)
1203
+	{
1204
+		if ($use_dtt_name) {
1205
+			$dtt_name = $this->name();
1206
+			if (! empty($dtt_name)) {
1207
+				return $dtt_name;
1208
+			}
1209
+		}
1210
+		// first condition is to see if the months are different
1211
+		if (
1212
+			date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1213
+		) {
1214
+			$display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
+			// next condition is if its the same month but different day
1216
+		} else {
1217
+			if (
1218
+				date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1219
+				&& date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1220
+			) {
1221
+				$display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
+			} else {
1223
+				$display_date = $this->start_date('F j\, Y')
1224
+								. ' @ '
1225
+								. $this->start_date('g:i a')
1226
+								. ' - '
1227
+								. $this->end_date('g:i a');
1228
+			}
1229
+		}
1230
+		return $display_date;
1231
+	}
1232
+
1233
+
1234
+	/**
1235
+	 * Gets all the tickets for this datetime
1236
+	 *
1237
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1238
+	 * @return EE_Base_Class[]|EE_Ticket[]
1239
+	 * @throws ReflectionException
1240
+	 * @throws InvalidArgumentException
1241
+	 * @throws InvalidInterfaceException
1242
+	 * @throws InvalidDataTypeException
1243
+	 * @throws EE_Error
1244
+	 */
1245
+	public function tickets($query_params = array())
1246
+	{
1247
+		return $this->get_many_related('Ticket', $query_params);
1248
+	}
1249
+
1250
+
1251
+	/**
1252
+	 * Gets all the ticket types currently available for purchase
1253
+	 *
1254
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1255
+	 * @return EE_Ticket[]
1256
+	 * @throws ReflectionException
1257
+	 * @throws InvalidArgumentException
1258
+	 * @throws InvalidInterfaceException
1259
+	 * @throws InvalidDataTypeException
1260
+	 * @throws EE_Error
1261
+	 */
1262
+	public function ticket_types_available_for_purchase($query_params = array())
1263
+	{
1264
+		// first check if datetime is valid
1265
+		if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1266
+			return array();
1267
+		}
1268
+		if (empty($query_params)) {
1269
+			$query_params = array(
1270
+				array(
1271
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1272
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1273
+					'TKT_deleted'    => false,
1274
+				),
1275
+			);
1276
+		}
1277
+		return $this->tickets($query_params);
1278
+	}
1279
+
1280
+
1281
+	/**
1282
+	 * @return EE_Base_Class|EE_Event
1283
+	 * @throws ReflectionException
1284
+	 * @throws InvalidArgumentException
1285
+	 * @throws InvalidInterfaceException
1286
+	 * @throws InvalidDataTypeException
1287
+	 * @throws EE_Error
1288
+	 */
1289
+	public function event()
1290
+	{
1291
+		return $this->get_first_related('Event');
1292
+	}
1293
+
1294
+
1295
+	/**
1296
+	 * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1297
+	 * (via the tickets).
1298
+	 *
1299
+	 * @return int
1300
+	 * @throws ReflectionException
1301
+	 * @throws InvalidArgumentException
1302
+	 * @throws InvalidInterfaceException
1303
+	 * @throws InvalidDataTypeException
1304
+	 * @throws EE_Error
1305
+	 */
1306
+	public function update_sold()
1307
+	{
1308
+		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
1309
+			array(
1310
+				array(
1311
+					'STS_ID'                 => EEM_Registration::status_id_approved,
1312
+					'REG_deleted'            => 0,
1313
+					'Ticket.Datetime.DTT_ID' => $this->ID(),
1314
+				),
1315
+			)
1316
+		);
1317
+		$this->set_sold($count_regs_for_this_datetime);
1318
+		$this->save();
1319
+		return $count_regs_for_this_datetime;
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * Adds a venue to this event
1325
+	 *
1326
+	 * @param int|EE_Venue /int $venue_id_or_obj
1327
+	 * @return EE_Base_Class|EE_Venue
1328
+	 * @throws EE_Error
1329
+	 * @throws ReflectionException
1330
+	 */
1331
+	public function add_venue($venue_id_or_obj): EE_Venue
1332
+	{
1333
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
1334
+	}
1335
+
1336
+
1337
+	/**
1338
+	 * Removes a venue from the event
1339
+	 *
1340
+	 * @param EE_Venue /int $venue_id_or_obj
1341
+	 * @return EE_Base_Class|EE_Venue
1342
+	 * @throws EE_Error
1343
+	 * @throws ReflectionException
1344
+	 */
1345
+	public function remove_venue($venue_id_or_obj): EE_Venue
1346
+	{
1347
+		$venue_id_or_obj = ! empty($venue_id_or_obj) ? $venue_id_or_obj : $this->venue();
1348
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
1349
+	}
1350
+
1351
+
1352
+	/**
1353
+	 * Gets the venue related to the event. May provide additional $query_params if desired
1354
+	 *
1355
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1356
+	 * @return int
1357
+	 * @throws EE_Error
1358
+	 * @throws ReflectionException
1359
+	 */
1360
+	public function venue_ID(array $query_params = []): int
1361
+	{
1362
+		$venue = $this->get_first_related('Venue', $query_params);
1363
+		return $venue instanceof EE_Venue
1364
+			? $venue->ID()
1365
+			: 0;
1366
+	}
1367
+
1368
+
1369
+	/**
1370
+	 * Gets the venue related to the event. May provide additional $query_params if desired
1371
+	 *
1372
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1373
+	 * @return EE_Base_Class|EE_Venue
1374
+	 * @throws EE_Error
1375
+	 * @throws ReflectionException
1376
+	 */
1377
+	public function venue(array $query_params = [])
1378
+	{
1379
+		return $this->get_first_related('Venue', $query_params);
1380
+	}
1381
+
1382
+
1383
+	/**
1384
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1385
+	 * @param string                   $relationName
1386
+	 * @param array                    $extra_join_model_fields_n_values
1387
+	 * @param string|null              $cache_id
1388
+	 * @return EE_Base_Class
1389
+	 * @throws EE_Error
1390
+	 * @throws ReflectionException
1391
+	 * @since   5.0.0.p
1392
+	 */
1393
+	public function _add_relation_to(
1394
+		$otherObjectModelObjectOrID,
1395
+		$relationName,
1396
+		$extra_join_model_fields_n_values = [],
1397
+		$cache_id = null
1398
+	) {
1399
+		// if we're adding a new relation to a ticket
1400
+		if ($relationName === 'Ticket' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1401
+			/** @var EE_Ticket $ticket */
1402
+			$ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1403
+			$this->increaseSold($ticket->sold(), false);
1404
+			$this->increaseReserved($ticket->reserved());
1405
+			$this->save();
1406
+			$otherObjectModelObjectOrID = $ticket;
1407
+		}
1408
+		return parent::_add_relation_to(
1409
+			$otherObjectModelObjectOrID,
1410
+			$relationName,
1411
+			$extra_join_model_fields_n_values,
1412
+			$cache_id
1413
+		);
1414
+	}
1415
+
1416
+
1417
+	/**
1418
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1419
+	 * @param string                   $relationName
1420
+	 * @param array                    $where_query
1421
+	 * @return bool|EE_Base_Class|null
1422
+	 * @throws EE_Error
1423
+	 * @throws ReflectionException
1424
+	 * @since   5.0.0.p
1425
+	 */
1426
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1427
+	{
1428
+		if ($relationName === 'Ticket' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1429
+			/** @var EE_Ticket $ticket */
1430
+			$ticket = EEM_Ticket::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1431
+			$this->decreaseSold($ticket->sold());
1432
+			$this->decreaseReserved($ticket->reserved());
1433
+			$this->save();
1434
+			$otherObjectModelObjectOrID = $ticket;
1435
+		}
1436
+		return parent::_remove_relation_to(
1437
+			$otherObjectModelObjectOrID,
1438
+			$relationName,
1439
+			$where_query
1440
+		);
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * Removes ALL the related things for the $relationName.
1446
+	 *
1447
+	 * @param string $relationName
1448
+	 * @param array  $where_query_params
1449
+	 * @return EE_Base_Class
1450
+	 * @throws ReflectionException
1451
+	 * @throws InvalidArgumentException
1452
+	 * @throws InvalidInterfaceException
1453
+	 * @throws InvalidDataTypeException
1454
+	 * @throws EE_Error
1455
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1456
+	 */
1457
+	public function _remove_relations($relationName, $where_query_params = [])
1458
+	{
1459
+		if ($relationName === 'Ticket') {
1460
+			$tickets = $this->tickets();
1461
+			foreach ($tickets as $ticket) {
1462
+				$this->decreaseSold($ticket->sold());
1463
+				$this->decreaseReserved($ticket->reserved());
1464
+				$this->save();
1465
+			}
1466
+		}
1467
+		return parent::_remove_relations($relationName, $where_query_params);
1468
+	}
1469
+
1470
+
1471
+	/*******************************************************************
1472 1472
      ***********************  DEPRECATED METHODS  **********************
1473 1473
      *******************************************************************/
1474 1474
 
1475 1475
 
1476
-    /**
1477
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
1478
-     *
1479
-     * @deprecated 4.9.80.p
1480
-     * @param int $qty
1481
-     * @return boolean
1482
-     * @throws ReflectionException
1483
-     * @throws InvalidArgumentException
1484
-     * @throws InvalidInterfaceException
1485
-     * @throws InvalidDataTypeException
1486
-     * @throws EE_Error
1487
-     */
1488
-    public function increase_sold($qty = 1)
1489
-    {
1490
-        EE_Error::doing_it_wrong(
1491
-            __FUNCTION__,
1492
-            esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1493
-            '4.9.80.p',
1494
-            '5.0.0.p'
1495
-        );
1496
-        return $this->increaseSold($qty);
1497
-    }
1498
-
1499
-
1500
-    /**
1501
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1502
-     * to save afterwards.)
1503
-     *
1504
-     * @deprecated 4.9.80.p
1505
-     * @param int $qty
1506
-     * @return boolean
1507
-     * @throws ReflectionException
1508
-     * @throws InvalidArgumentException
1509
-     * @throws InvalidInterfaceException
1510
-     * @throws InvalidDataTypeException
1511
-     * @throws EE_Error
1512
-     */
1513
-    public function decrease_sold($qty = 1)
1514
-    {
1515
-        EE_Error::doing_it_wrong(
1516
-            __FUNCTION__,
1517
-            esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1518
-            '4.9.80.p',
1519
-            '5.0.0.p'
1520
-        );
1521
-        return $this->decreaseSold($qty);
1522
-    }
1523
-
1524
-
1525
-    /**
1526
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1527
-     *
1528
-     * @deprecated 4.9.80.p
1529
-     * @param int $qty
1530
-     * @return boolean indicating success
1531
-     * @throws ReflectionException
1532
-     * @throws InvalidArgumentException
1533
-     * @throws InvalidInterfaceException
1534
-     * @throws InvalidDataTypeException
1535
-     * @throws EE_Error
1536
-     */
1537
-    public function increase_reserved($qty = 1)
1538
-    {
1539
-        EE_Error::doing_it_wrong(
1540
-            __FUNCTION__,
1541
-            esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1542
-            '4.9.80.p',
1543
-            '5.0.0.p'
1544
-        );
1545
-        return $this->increaseReserved($qty);
1546
-    }
1547
-
1548
-
1549
-    /**
1550
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1551
-     *
1552
-     * @deprecated 4.9.80.p
1553
-     * @param int $qty
1554
-     * @return boolean
1555
-     * @throws ReflectionException
1556
-     * @throws InvalidArgumentException
1557
-     * @throws InvalidInterfaceException
1558
-     * @throws InvalidDataTypeException
1559
-     * @throws EE_Error
1560
-     */
1561
-    public function decrease_reserved($qty = 1)
1562
-    {
1563
-        EE_Error::doing_it_wrong(
1564
-            __FUNCTION__,
1565
-            esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1566
-            '4.9.80.p',
1567
-            '5.0.0.p'
1568
-        );
1569
-        return $this->decreaseReserved($qty);
1570
-    }
1476
+	/**
1477
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
1478
+	 *
1479
+	 * @deprecated 4.9.80.p
1480
+	 * @param int $qty
1481
+	 * @return boolean
1482
+	 * @throws ReflectionException
1483
+	 * @throws InvalidArgumentException
1484
+	 * @throws InvalidInterfaceException
1485
+	 * @throws InvalidDataTypeException
1486
+	 * @throws EE_Error
1487
+	 */
1488
+	public function increase_sold($qty = 1)
1489
+	{
1490
+		EE_Error::doing_it_wrong(
1491
+			__FUNCTION__,
1492
+			esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1493
+			'4.9.80.p',
1494
+			'5.0.0.p'
1495
+		);
1496
+		return $this->increaseSold($qty);
1497
+	}
1498
+
1499
+
1500
+	/**
1501
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1502
+	 * to save afterwards.)
1503
+	 *
1504
+	 * @deprecated 4.9.80.p
1505
+	 * @param int $qty
1506
+	 * @return boolean
1507
+	 * @throws ReflectionException
1508
+	 * @throws InvalidArgumentException
1509
+	 * @throws InvalidInterfaceException
1510
+	 * @throws InvalidDataTypeException
1511
+	 * @throws EE_Error
1512
+	 */
1513
+	public function decrease_sold($qty = 1)
1514
+	{
1515
+		EE_Error::doing_it_wrong(
1516
+			__FUNCTION__,
1517
+			esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1518
+			'4.9.80.p',
1519
+			'5.0.0.p'
1520
+		);
1521
+		return $this->decreaseSold($qty);
1522
+	}
1523
+
1524
+
1525
+	/**
1526
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1527
+	 *
1528
+	 * @deprecated 4.9.80.p
1529
+	 * @param int $qty
1530
+	 * @return boolean indicating success
1531
+	 * @throws ReflectionException
1532
+	 * @throws InvalidArgumentException
1533
+	 * @throws InvalidInterfaceException
1534
+	 * @throws InvalidDataTypeException
1535
+	 * @throws EE_Error
1536
+	 */
1537
+	public function increase_reserved($qty = 1)
1538
+	{
1539
+		EE_Error::doing_it_wrong(
1540
+			__FUNCTION__,
1541
+			esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1542
+			'4.9.80.p',
1543
+			'5.0.0.p'
1544
+		);
1545
+		return $this->increaseReserved($qty);
1546
+	}
1547
+
1548
+
1549
+	/**
1550
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1551
+	 *
1552
+	 * @deprecated 4.9.80.p
1553
+	 * @param int $qty
1554
+	 * @return boolean
1555
+	 * @throws ReflectionException
1556
+	 * @throws InvalidArgumentException
1557
+	 * @throws InvalidInterfaceException
1558
+	 * @throws InvalidDataTypeException
1559
+	 * @throws EE_Error
1560
+	 */
1561
+	public function decrease_reserved($qty = 1)
1562
+	{
1563
+		EE_Error::doing_it_wrong(
1564
+			__FUNCTION__,
1565
+			esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1566
+			'4.9.80.p',
1567
+			'5.0.0.p'
1568
+		);
1569
+		return $this->decreaseReserved($qty);
1570
+	}
1571 1571
 }
Please login to merge, or discard this patch.
caffeinated/admin/new/pricing/Prices_List_Table.class.php 1 patch
Indentation   +270 added lines, -270 removed lines patch added patch discarded remove patch
@@ -13,274 +13,274 @@
 block discarded – undo
13 13
  */
14 14
 class Prices_List_Table extends EE_Admin_List_Table
15 15
 {
16
-    private $_PRT;
17
-
18
-    /**
19
-     * Array of price types.
20
-     *
21
-     * @var EE_Price_Type[]
22
-     */
23
-    protected $_price_types = [];
24
-
25
-
26
-    public function __construct(EE_Admin_Page $admin_page)
27
-    {
28
-        parent::__construct($admin_page);
29
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
30
-        $this->_PRT         = EEM_Price_Type::instance();
31
-        $this->_price_types = $this->_PRT->get_all_deleted_and_undeleted();
32
-    }
33
-
34
-
35
-    protected function _setup_data()
36
-    {
37
-        $trashed               = $this->_admin_page->get_view() == 'trashed' ? true : false;
38
-        $this->_data           = $this->_admin_page->get_prices_overview_data($this->_per_page, false, $trashed);
39
-        $this->_all_data_count = $this->_admin_page->get_prices_overview_data($this->_per_page, true, false);
40
-        $this->_trashed_count  = $this->_admin_page->get_prices_overview_data($this->_per_page, true, true);
41
-    }
42
-
43
-
44
-    protected function _set_properties()
45
-    {
46
-        $this->_wp_list_args = [
47
-            'singular' => esc_html__('price', 'event_espresso'),
48
-            'plural'   => esc_html__('prices', 'event_espresso'),
49
-            'ajax'     => true,
50
-            'screen'   => $this->_admin_page->get_current_screen()->id,
51
-        ];
52
-
53
-        $this->_columns = [
54
-            'cb'          => '<input type="checkbox" />', // Render a checkbox instead of text
55
-            'id'          => esc_html__('ID', 'event_espresso'),
56
-            'name'        => esc_html__('Name', 'event_espresso'),
57
-            'type'        => esc_html__('Price Type', 'event_espresso'),
58
-            'description' => esc_html__('Description', 'event_espresso'),
59
-            'amount'      => esc_html__('Amount', 'event_espresso'),
60
-        ];
61
-        $this->_primary_column = 'id';
62
-
63
-        $this->_sortable_columns = [
64
-            // true means its already sorted
65
-            'name'   => ['name' => false],
66
-            'type'   => ['type' => false],
67
-            'amount' => ['amount' => false],
68
-        ];
69
-
70
-        $this->_hidden_columns = [];
71
-
72
-        $this->_ajax_sorting_callback = 'update_prices_order';
73
-    }
74
-
75
-
76
-    protected function _get_table_filters()
77
-    {
78
-        return [];
79
-    }
80
-
81
-
82
-    protected function _add_view_counts()
83
-    {
84
-        $this->_views['all']['count'] = $this->_all_data_count;
85
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_default_prices', 'pricing_trash_price')) {
86
-            $this->_views['trashed']['count'] = $this->_trashed_count;
87
-        }
88
-    }
89
-
90
-
91
-    /**
92
-     * overriding parent method so that we can make sure the row isn't sortable for certain items
93
-     *
94
-     * @param object $item the current item
95
-     * @return string
96
-     */
97
-    protected function _get_row_class($item)
98
-    {
99
-        return $item->type_obj() instanceof EE_Price_Type
100
-                     && $item->type_obj()->base_type() !== 1
101
-                     && $item->type_obj()->base_type() !== 4
102
-            ? ' class="rowsortable"'
103
-            : '';
104
-    }
105
-
106
-
107
-    /**
108
-     * @param EE_Price $price
109
-     * @param string   $action
110
-     * @return string
111
-     * @throws EE_Error
112
-     * @throws ReflectionException
113
-     * @since 5.0.0.p
114
-     */
115
-    protected function getActionUrl(EE_Price $price, string $action): string
116
-    {
117
-        if (! in_array($action, self::$actions)) {
118
-            throw new DomainException(esc_html__('Invalid Action', 'event_espresso'));
119
-        }
120
-        return EE_Admin_Page::add_query_args_and_nonce(
121
-            [
122
-                'action'   => "{$action}_price",
123
-                'id'       => $price->ID(),
124
-                'noheader' => $action !== self::ACTION_EDIT,
125
-            ],
126
-            PRICING_ADMIN_URL
127
-        );
128
-    }
129
-
130
-
131
-    public function column_cb($item)
132
-    {
133
-        return $item->type_obj() instanceof EE_Price_Type && $item->type_obj()->base_type() !== 1
134
-            ? sprintf(
135
-                '<input type="checkbox" name="checkbox[%1$s]" value="%1$s" />',
136
-                $item->ID()
137
-            )
138
-            : '';
139
-    }
140
-
141
-
142
-    /**
143
-     * @param EE_Price $item
144
-     * @return string
145
-     * @throws EE_Error
146
-     * @throws ReflectionException
147
-     */
148
-    public function column_id($item)
149
-    {
150
-        $content = '<span class="ee-entity-id">' . $item->ID() . '</span>';
151
-        $content .= '<span class="show-on-mobile-view-only">' . $this->column_name($item, false) . '</span>';
152
-        return $this->columnContent('id', $content, 'end');
153
-    }
154
-
155
-
156
-    /**
157
-     * @param EE_Price $price
158
-     * @param bool     $prep_content
159
-     * @return string
160
-     * @throws EE_Error
161
-     * @throws ReflectionException
162
-     */
163
-    public function column_name(EE_Price $price, bool $prep_content = true): string
164
-    {
165
-
166
-        // Build row actions
167
-        $actions = [];
168
-        // edit price link
169
-        if (
170
-            EE_Registry::instance()->CAP->current_user_can(
171
-                'ee_edit_default_price',
172
-                'pricing_edit_price',
173
-                $price->ID()
174
-            )
175
-        ) {
176
-            $actions['edit'] = $this->getActionLink(
177
-                $this->getActionUrl($price, self::ACTION_EDIT),
178
-                esc_html__('Edit', 'event_espresso'),
179
-                esc_attr__('Edit Price', 'event_espresso')
180
-            );
181
-        }
182
-
183
-        $name_link = EE_Registry::instance()->CAP->current_user_can(
184
-            'ee_edit_default_price',
185
-            'edit_price',
186
-            $price->ID()
187
-        )
188
-            ? $this->getActionLink(
189
-                $this->getActionUrl($price, self::ACTION_EDIT),
190
-                stripslashes($price->name()),
191
-                esc_attr__('Edit Price', 'event_espresso')
192
-            )
193
-            : $price->name();
194
-
195
-        if ($price->type_obj() instanceof EE_Price_Type && $price->type_obj()->base_type() !== 1) {
196
-            if ($this->_view == 'all') {
197
-                // trash price link
198
-                if (
199
-                    EE_Registry::instance()->CAP->current_user_can(
200
-                        'ee_delete_default_price',
201
-                        'pricing_trash_price',
202
-                        $price->ID()
203
-                    )
204
-                ) {
205
-                    $actions['trash'] = $this->getActionLink(
206
-                        $this->getActionUrl($price, self::ACTION_TRASH),
207
-                        esc_html__('Trash', 'event_espresso'),
208
-                        esc_attr__('Move Price to Trash', 'event_espresso')
209
-                    );
210
-                }
211
-            } else {
212
-                if (
213
-                    EE_Registry::instance()->CAP->current_user_can(
214
-                        'ee_delete_default_price',
215
-                        'pricing_restore_price',
216
-                        $price->ID()
217
-                    )
218
-                ) {
219
-                    $actions['restore'] = $this->getActionLink(
220
-                        $this->getActionUrl($price, self::ACTION_RESTORE),
221
-                        esc_html__('Restore', 'event_espresso'),
222
-                        esc_attr__('Restore Price', 'event_espresso')
223
-                    );
224
-                }
225
-
226
-                // delete price link
227
-                if (
228
-                    EE_Registry::instance()->CAP->current_user_can(
229
-                        'ee_delete_default_price',
230
-                        'pricing_delete_price',
231
-                        $price->ID()
232
-                    )
233
-                ) {
234
-                    $actions['delete'] = $this->getActionLink(
235
-                        $this->getActionUrl($price, self::ACTION_DELETE),
236
-                        esc_html__('Delete Permanently', 'event_espresso'),
237
-                        esc_attr__('Delete Price Permanently', 'event_espresso')
238
-                    );
239
-                }
240
-            }
241
-        }
242
-
243
-        $content = $prep_content ? $name_link . $this->row_actions($actions) : $name_link;
244
-        return $prep_content ? $this->columnContent('name', $content) : $content;
245
-    }
246
-
247
-
248
-    /**
249
-     * @throws EE_Error
250
-     * @throws ReflectionException
251
-     */
252
-    public function column_type(EE_Price $price): string
253
-    {
254
-        $content = isset($this->_price_types[ $price->type() ])
255
-            ? $this->_price_types[ $price->type() ]->name()
256
-            : '';
257
-        return $this->columnContent('type', $content);
258
-    }
259
-
260
-
261
-    /**
262
-     * @throws EE_Error
263
-     * @throws ReflectionException
264
-     */
265
-    public function column_description(EE_Price $price): string
266
-    {
267
-        $content = stripslashes($price->desc());
268
-        return $this->columnContent('description', $content);
269
-    }
270
-
271
-
272
-    /**
273
-     * @throws EE_Error
274
-     * @throws ReflectionException
275
-     */
276
-    public function column_amount(EE_Price $price): string
277
-    {
278
-        $price_type = isset($this->_price_types[ $price->type() ])
279
-            ? $this->_price_types[ $price->type() ]
280
-            : null;
281
-        $content = $price_type instanceof EE_Price_Type && $price_type->is_percent() ?
282
-            '<div class="pad-amnt-rght">' . number_format($price->amount(), 1) . '%</div>'
283
-            : '<div class="pad-amnt-rght">' . EEH_Template::format_currency($price->amount()) . '</div>';
284
-        return $this->columnContent('amount', $content, 'end');
285
-    }
16
+	private $_PRT;
17
+
18
+	/**
19
+	 * Array of price types.
20
+	 *
21
+	 * @var EE_Price_Type[]
22
+	 */
23
+	protected $_price_types = [];
24
+
25
+
26
+	public function __construct(EE_Admin_Page $admin_page)
27
+	{
28
+		parent::__construct($admin_page);
29
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
30
+		$this->_PRT         = EEM_Price_Type::instance();
31
+		$this->_price_types = $this->_PRT->get_all_deleted_and_undeleted();
32
+	}
33
+
34
+
35
+	protected function _setup_data()
36
+	{
37
+		$trashed               = $this->_admin_page->get_view() == 'trashed' ? true : false;
38
+		$this->_data           = $this->_admin_page->get_prices_overview_data($this->_per_page, false, $trashed);
39
+		$this->_all_data_count = $this->_admin_page->get_prices_overview_data($this->_per_page, true, false);
40
+		$this->_trashed_count  = $this->_admin_page->get_prices_overview_data($this->_per_page, true, true);
41
+	}
42
+
43
+
44
+	protected function _set_properties()
45
+	{
46
+		$this->_wp_list_args = [
47
+			'singular' => esc_html__('price', 'event_espresso'),
48
+			'plural'   => esc_html__('prices', 'event_espresso'),
49
+			'ajax'     => true,
50
+			'screen'   => $this->_admin_page->get_current_screen()->id,
51
+		];
52
+
53
+		$this->_columns = [
54
+			'cb'          => '<input type="checkbox" />', // Render a checkbox instead of text
55
+			'id'          => esc_html__('ID', 'event_espresso'),
56
+			'name'        => esc_html__('Name', 'event_espresso'),
57
+			'type'        => esc_html__('Price Type', 'event_espresso'),
58
+			'description' => esc_html__('Description', 'event_espresso'),
59
+			'amount'      => esc_html__('Amount', 'event_espresso'),
60
+		];
61
+		$this->_primary_column = 'id';
62
+
63
+		$this->_sortable_columns = [
64
+			// true means its already sorted
65
+			'name'   => ['name' => false],
66
+			'type'   => ['type' => false],
67
+			'amount' => ['amount' => false],
68
+		];
69
+
70
+		$this->_hidden_columns = [];
71
+
72
+		$this->_ajax_sorting_callback = 'update_prices_order';
73
+	}
74
+
75
+
76
+	protected function _get_table_filters()
77
+	{
78
+		return [];
79
+	}
80
+
81
+
82
+	protected function _add_view_counts()
83
+	{
84
+		$this->_views['all']['count'] = $this->_all_data_count;
85
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_default_prices', 'pricing_trash_price')) {
86
+			$this->_views['trashed']['count'] = $this->_trashed_count;
87
+		}
88
+	}
89
+
90
+
91
+	/**
92
+	 * overriding parent method so that we can make sure the row isn't sortable for certain items
93
+	 *
94
+	 * @param object $item the current item
95
+	 * @return string
96
+	 */
97
+	protected function _get_row_class($item)
98
+	{
99
+		return $item->type_obj() instanceof EE_Price_Type
100
+					 && $item->type_obj()->base_type() !== 1
101
+					 && $item->type_obj()->base_type() !== 4
102
+			? ' class="rowsortable"'
103
+			: '';
104
+	}
105
+
106
+
107
+	/**
108
+	 * @param EE_Price $price
109
+	 * @param string   $action
110
+	 * @return string
111
+	 * @throws EE_Error
112
+	 * @throws ReflectionException
113
+	 * @since 5.0.0.p
114
+	 */
115
+	protected function getActionUrl(EE_Price $price, string $action): string
116
+	{
117
+		if (! in_array($action, self::$actions)) {
118
+			throw new DomainException(esc_html__('Invalid Action', 'event_espresso'));
119
+		}
120
+		return EE_Admin_Page::add_query_args_and_nonce(
121
+			[
122
+				'action'   => "{$action}_price",
123
+				'id'       => $price->ID(),
124
+				'noheader' => $action !== self::ACTION_EDIT,
125
+			],
126
+			PRICING_ADMIN_URL
127
+		);
128
+	}
129
+
130
+
131
+	public function column_cb($item)
132
+	{
133
+		return $item->type_obj() instanceof EE_Price_Type && $item->type_obj()->base_type() !== 1
134
+			? sprintf(
135
+				'<input type="checkbox" name="checkbox[%1$s]" value="%1$s" />',
136
+				$item->ID()
137
+			)
138
+			: '';
139
+	}
140
+
141
+
142
+	/**
143
+	 * @param EE_Price $item
144
+	 * @return string
145
+	 * @throws EE_Error
146
+	 * @throws ReflectionException
147
+	 */
148
+	public function column_id($item)
149
+	{
150
+		$content = '<span class="ee-entity-id">' . $item->ID() . '</span>';
151
+		$content .= '<span class="show-on-mobile-view-only">' . $this->column_name($item, false) . '</span>';
152
+		return $this->columnContent('id', $content, 'end');
153
+	}
154
+
155
+
156
+	/**
157
+	 * @param EE_Price $price
158
+	 * @param bool     $prep_content
159
+	 * @return string
160
+	 * @throws EE_Error
161
+	 * @throws ReflectionException
162
+	 */
163
+	public function column_name(EE_Price $price, bool $prep_content = true): string
164
+	{
165
+
166
+		// Build row actions
167
+		$actions = [];
168
+		// edit price link
169
+		if (
170
+			EE_Registry::instance()->CAP->current_user_can(
171
+				'ee_edit_default_price',
172
+				'pricing_edit_price',
173
+				$price->ID()
174
+			)
175
+		) {
176
+			$actions['edit'] = $this->getActionLink(
177
+				$this->getActionUrl($price, self::ACTION_EDIT),
178
+				esc_html__('Edit', 'event_espresso'),
179
+				esc_attr__('Edit Price', 'event_espresso')
180
+			);
181
+		}
182
+
183
+		$name_link = EE_Registry::instance()->CAP->current_user_can(
184
+			'ee_edit_default_price',
185
+			'edit_price',
186
+			$price->ID()
187
+		)
188
+			? $this->getActionLink(
189
+				$this->getActionUrl($price, self::ACTION_EDIT),
190
+				stripslashes($price->name()),
191
+				esc_attr__('Edit Price', 'event_espresso')
192
+			)
193
+			: $price->name();
194
+
195
+		if ($price->type_obj() instanceof EE_Price_Type && $price->type_obj()->base_type() !== 1) {
196
+			if ($this->_view == 'all') {
197
+				// trash price link
198
+				if (
199
+					EE_Registry::instance()->CAP->current_user_can(
200
+						'ee_delete_default_price',
201
+						'pricing_trash_price',
202
+						$price->ID()
203
+					)
204
+				) {
205
+					$actions['trash'] = $this->getActionLink(
206
+						$this->getActionUrl($price, self::ACTION_TRASH),
207
+						esc_html__('Trash', 'event_espresso'),
208
+						esc_attr__('Move Price to Trash', 'event_espresso')
209
+					);
210
+				}
211
+			} else {
212
+				if (
213
+					EE_Registry::instance()->CAP->current_user_can(
214
+						'ee_delete_default_price',
215
+						'pricing_restore_price',
216
+						$price->ID()
217
+					)
218
+				) {
219
+					$actions['restore'] = $this->getActionLink(
220
+						$this->getActionUrl($price, self::ACTION_RESTORE),
221
+						esc_html__('Restore', 'event_espresso'),
222
+						esc_attr__('Restore Price', 'event_espresso')
223
+					);
224
+				}
225
+
226
+				// delete price link
227
+				if (
228
+					EE_Registry::instance()->CAP->current_user_can(
229
+						'ee_delete_default_price',
230
+						'pricing_delete_price',
231
+						$price->ID()
232
+					)
233
+				) {
234
+					$actions['delete'] = $this->getActionLink(
235
+						$this->getActionUrl($price, self::ACTION_DELETE),
236
+						esc_html__('Delete Permanently', 'event_espresso'),
237
+						esc_attr__('Delete Price Permanently', 'event_espresso')
238
+					);
239
+				}
240
+			}
241
+		}
242
+
243
+		$content = $prep_content ? $name_link . $this->row_actions($actions) : $name_link;
244
+		return $prep_content ? $this->columnContent('name', $content) : $content;
245
+	}
246
+
247
+
248
+	/**
249
+	 * @throws EE_Error
250
+	 * @throws ReflectionException
251
+	 */
252
+	public function column_type(EE_Price $price): string
253
+	{
254
+		$content = isset($this->_price_types[ $price->type() ])
255
+			? $this->_price_types[ $price->type() ]->name()
256
+			: '';
257
+		return $this->columnContent('type', $content);
258
+	}
259
+
260
+
261
+	/**
262
+	 * @throws EE_Error
263
+	 * @throws ReflectionException
264
+	 */
265
+	public function column_description(EE_Price $price): string
266
+	{
267
+		$content = stripslashes($price->desc());
268
+		return $this->columnContent('description', $content);
269
+	}
270
+
271
+
272
+	/**
273
+	 * @throws EE_Error
274
+	 * @throws ReflectionException
275
+	 */
276
+	public function column_amount(EE_Price $price): string
277
+	{
278
+		$price_type = isset($this->_price_types[ $price->type() ])
279
+			? $this->_price_types[ $price->type() ]
280
+			: null;
281
+		$content = $price_type instanceof EE_Price_Type && $price_type->is_percent() ?
282
+			'<div class="pad-amnt-rght">' . number_format($price->amount(), 1) . '%</div>'
283
+			: '<div class="pad-amnt-rght">' . EEH_Template::format_currency($price->amount()) . '</div>';
284
+		return $this->columnContent('amount', $content, 'end');
285
+	}
286 286
 }
Please login to merge, or discard this patch.
caffeinated/admin/new/pricing/Pricing_Admin_Page_Init.core.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -16,51 +16,51 @@
 block discarded – undo
16 16
  */
17 17
 class Pricing_Admin_Page_Init extends EE_Admin_Page_Init
18 18
 {
19
-    /**
20
-     * @Constructor
21
-     */
22
-    public function __construct()
23
-    {
24
-        if (! defined('PRICING_PG_SLUG')) {
25
-            define('PRICING_PG_SLUG', 'pricing');
26
-            define('PRICING_LABEL', esc_html__('Pricing', 'event_espresso'));
27
-            define('PRICING_PG_NAME', ucwords(str_replace('_', '', PRICING_PG_SLUG)));
28
-            define('PRICING_ADMIN', EE_CORE_CAF_ADMIN . 'new/' . PRICING_PG_SLUG . '/');
29
-            define('PRICING_ADMIN_URL', admin_url('admin.php?page=' . PRICING_PG_SLUG));
30
-            define('PRICING_ASSETS_PATH', PRICING_ADMIN . 'assets/');
31
-            define('PRICING_ASSETS_URL', EE_CORE_CAF_ADMIN_URL . 'new/' . PRICING_PG_SLUG . '/assets/');
32
-            define('PRICING_TEMPLATE_PATH', PRICING_ADMIN . 'templates/');
33
-            define('PRICING_TEMPLATE_URL', EE_CORE_CAF_ADMIN_URL . 'new/' . PRICING_PG_SLUG . '/templates/');
34
-        }
35
-        parent::__construct();
36
-        $this->_folder_path = EE_CORE_CAF_ADMIN . 'new/' . $this->_folder_name . '/';
37
-    }
19
+	/**
20
+	 * @Constructor
21
+	 */
22
+	public function __construct()
23
+	{
24
+		if (! defined('PRICING_PG_SLUG')) {
25
+			define('PRICING_PG_SLUG', 'pricing');
26
+			define('PRICING_LABEL', esc_html__('Pricing', 'event_espresso'));
27
+			define('PRICING_PG_NAME', ucwords(str_replace('_', '', PRICING_PG_SLUG)));
28
+			define('PRICING_ADMIN', EE_CORE_CAF_ADMIN . 'new/' . PRICING_PG_SLUG . '/');
29
+			define('PRICING_ADMIN_URL', admin_url('admin.php?page=' . PRICING_PG_SLUG));
30
+			define('PRICING_ASSETS_PATH', PRICING_ADMIN . 'assets/');
31
+			define('PRICING_ASSETS_URL', EE_CORE_CAF_ADMIN_URL . 'new/' . PRICING_PG_SLUG . '/assets/');
32
+			define('PRICING_TEMPLATE_PATH', PRICING_ADMIN . 'templates/');
33
+			define('PRICING_TEMPLATE_URL', EE_CORE_CAF_ADMIN_URL . 'new/' . PRICING_PG_SLUG . '/templates/');
34
+		}
35
+		parent::__construct();
36
+		$this->_folder_path = EE_CORE_CAF_ADMIN . 'new/' . $this->_folder_name . '/';
37
+	}
38 38
 
39 39
 
40
-    protected function _set_init_properties()
41
-    {
42
-        $this->label = PRICING_LABEL;
43
-    }
40
+	protected function _set_init_properties()
41
+	{
42
+		$this->label = PRICING_LABEL;
43
+	}
44 44
 
45 45
 
46
-    /**
47
-     * @return array|void
48
-     * @throws EE_Error
49
-     * @since 5.0.0.p
50
-     */
51
-    protected function _set_menu_map()
52
-    {
53
-        $this->_menu_map = new AdminMenuSubItem(
54
-            array(
55
-                'menu_group'      => 'management',
56
-                'menu_order'      => 20,
57
-                'show_on_menu'    => AdminMenuItem::DISPLAY_BLOG_ONLY,
58
-                'parent_slug'     => 'espresso_events',
59
-                'menu_slug'       => PRICING_PG_SLUG,
60
-                'menu_label'      => PRICING_LABEL,
61
-                'capability'      => 'ee_read_default_prices',
62
-                'admin_init_page' => $this,
63
-            )
64
-        );
65
-    }
46
+	/**
47
+	 * @return array|void
48
+	 * @throws EE_Error
49
+	 * @since 5.0.0.p
50
+	 */
51
+	protected function _set_menu_map()
52
+	{
53
+		$this->_menu_map = new AdminMenuSubItem(
54
+			array(
55
+				'menu_group'      => 'management',
56
+				'menu_order'      => 20,
57
+				'show_on_menu'    => AdminMenuItem::DISPLAY_BLOG_ONLY,
58
+				'parent_slug'     => 'espresso_events',
59
+				'menu_slug'       => PRICING_PG_SLUG,
60
+				'menu_label'      => PRICING_LABEL,
61
+				'capability'      => 'ee_read_default_prices',
62
+				'admin_init_page' => $this,
63
+			)
64
+		);
65
+	}
66 66
 }
Please login to merge, or discard this patch.
caffeinated/admin/new/pricing/Price_Types_List_Table.class.php 1 patch
Indentation   +250 added lines, -250 removed lines patch added patch discarded remove patch
@@ -13,254 +13,254 @@
 block discarded – undo
13 13
  */
14 14
 class Price_Types_List_Table extends EE_Admin_List_Table
15 15
 {
16
-    /**
17
-     * @var Pricing_Admin_Page
18
-     */
19
-    protected $_admin_page;
20
-
21
-
22
-    public function __construct($admin_page)
23
-    {
24
-        parent::__construct($admin_page);
25
-        require_once(EE_MODELS . 'EEM_Price_Type.model.php');
26
-        $this->_PRT = EEM_Price_Type::instance();
27
-    }
28
-
29
-
30
-    protected function _setup_data()
31
-    {
32
-        $trashed               = $this->_admin_page->get_view() == 'trashed';
33
-        $this->_data           = $this->_admin_page->get_price_types_overview_data($this->_per_page, false, $trashed);
34
-        $this->_all_data_count = $this->_admin_page->get_price_types_overview_data($this->_per_page, true);
35
-        $this->_trashed_count  = $this->_admin_page->get_price_types_overview_data($this->_per_page, true, true);
36
-    }
37
-
38
-
39
-    protected function _set_properties()
40
-    {
41
-        $this->_wp_list_args = [
42
-            'singular' => esc_html__('price type', 'event_espresso'),
43
-            'plural'   => esc_html__('price types', 'event_espresso'),
44
-            'ajax'     => true,
45
-            'screen'   => $this->_admin_page->get_current_screen()->id,
46
-        ];
47
-
48
-        $this->_columns = [
49
-            'cb'        => '<input type="checkbox" />', // Render a checkbox instead of text
50
-            'id'        => esc_html__('ID', 'event_espresso'),
51
-            'name'      => esc_html__('Name', 'event_espresso'),
52
-            'base_type' => esc_html__('Base Type', 'event_espresso'),
53
-            'percent'   => sprintf(
54
-                               /* translators: 1: HTML new line, 2: open span tag, 3: close span tag */
55
-                esc_html__('Applied %1$s as %2$s%%%3$s or %2$s$%3$s', 'event_espresso'),
56
-                '',
57
-                '<span class="big-text">',
58
-                '</span>'
59
-            ),
60
-            'order'     => esc_html__('Order of Application', 'event_espresso'),
61
-        ];
62
-
63
-        $this->_sortable_columns = [
64
-            // TRUE means its already sorted
65
-            'name' => ['name' => false],
66
-        ];
67
-
68
-        $this->_hidden_columns = [];
69
-    }
70
-
71
-
72
-    protected function _get_table_filters()
73
-    {
74
-        return [];
75
-    }
76
-
77
-
78
-    protected function _add_view_counts()
79
-    {
80
-        $this->_views['all']['count'] = $this->_all_data_count;
81
-        if (
82
-            EE_Registry::instance()->CAP->current_user_can(
83
-                'ee_delete_default_price_types',
84
-                'pricing_trash_price_type'
85
-            )
86
-        ) {
87
-            $this->_views['trashed']['count'] = $this->_trashed_count;
88
-        }
89
-    }
90
-
91
-
92
-    /**
93
-     * @param EE_Price_Type $price_type
94
-     * @param string   $action
95
-     * @return string
96
-     * @throws EE_Error
97
-     * @throws ReflectionException
98
-     * @since 5.0.0.p
99
-     */
100
-    protected function getActionUrl(EE_Price_Type $price_type, string $action): string
101
-    {
102
-        if (! in_array($action, self::$actions)) {
103
-            throw new DomainException(esc_html__('Invalid Action', 'event_espresso'));
104
-        }
105
-        return EE_Admin_Page::add_query_args_and_nonce(
106
-            [
107
-                'action'   => "{$action}_price_type",
108
-                'id'       => $price_type->ID(),
109
-                'noheader' => $action !== self::ACTION_EDIT,
110
-            ],
111
-            PRICING_ADMIN_URL
112
-        );
113
-    }
114
-
115
-
116
-    public function column_cb($item): string
117
-    {
118
-        if ($item->base_type() !== 1) {
119
-            return sprintf(
120
-                '<input type="checkbox" name="checkbox[%1$s]" />',
121
-                $item->ID()
122
-            );
123
-        }
124
-        return '';
125
-    }
126
-
127
-
128
-    /**
129
-     * @param EE_Price_Type $item
130
-     * @return string
131
-     * @throws EE_Error
132
-     * @throws ReflectionException
133
-     */
134
-    public function column_id($item): string
135
-    {
136
-        $content = '<span class="ee-entity-id">' . $item->ID() . '</span>';
137
-        $content .= '<span class="show-on-mobile-view-only">' . $this->column_name($item, false) . '</span>';
138
-        return $this->columnContent('id', $content, 'end');
139
-    }
140
-
141
-
142
-    /**
143
-     * @param EE_Price_Type $price_type
144
-     * @param bool          $prep_content
145
-     * @return string
146
-     * @throws EE_Error
147
-     * @throws ReflectionException
148
-     */
149
-    public function column_name(EE_Price_Type $price_type, bool $prep_content = true): string
150
-    {
151
-
152
-        // Build row actions
153
-        $actions   = [];
154
-        $name_link = $price_type->name();
155
-        // edit price link
156
-        if (
157
-            EE_Registry::instance()->CAP->current_user_can(
158
-                'ee_edit_default_price_type',
159
-                'pricing_edit_price_type',
160
-                $price_type->ID()
161
-            )
162
-        ) {
163
-            $name_link = $this->getActionLink(
164
-                $this->getActionUrl($price_type, self::ACTION_EDIT),
165
-                stripslashes($price_type->name()),
166
-                sprintf(
167
-                    /* translators: The name of the price type */
168
-                    esc_attr__('Edit Price Type (%s)', 'event_espresso'),
169
-                    $price_type->name()
170
-                )
171
-            );
172
-
173
-            $actions['edit'] = $this->getActionLink(
174
-                $this->getActionUrl($price_type, self::ACTION_EDIT),
175
-                esc_html__('Edit', 'event_espresso'),
176
-                sprintf(
177
-                    /* translators: The name of the price type */
178
-                    esc_attr__('Edit Price Type (%s)', 'event_espresso'),
179
-                    $price_type->name()
180
-                )
181
-            );
182
-        }
183
-
184
-        if ($price_type->base_type() !== 1) {
185
-            if ($this->_view == 'all') {
186
-                // trash price link
187
-                if (
188
-                    EE_Registry::instance()->CAP->current_user_can(
189
-                        'ee_delete_default_price_type',
190
-                        'pricing_trash_price_type',
191
-                        $price_type->ID()
192
-                    )
193
-                ) {
194
-                    $actions['trash'] = $this->getActionLink(
195
-                        $this->getActionUrl($price_type, self::ACTION_TRASH),
196
-                        esc_html__('Trash', 'event_espresso'),
197
-                        sprintf(
198
-                            /* translators: The name of the price type */
199
-                            esc_attr__('Move Price Type %s to Trash', 'event_espresso'),
200
-                            $price_type->name()
201
-                        )
202
-                    );
203
-                }
204
-            } else {
205
-                // restore price link
206
-                if (
207
-                    EE_Registry::instance()->CAP->current_user_can(
208
-                        'ee_delete_default_price_type',
209
-                        'pricing_restore_price_type',
210
-                        $price_type->ID()
211
-                    )
212
-                ) {
213
-                    $actions['restore'] = $this->getActionLink(
214
-                        $this->getActionUrl($price_type, self::ACTION_RESTORE),
215
-                        esc_html__('Restore', 'event_espresso'),
216
-                        sprintf(
217
-                            /* translators: The name of the price type */
218
-                            esc_attr__('Restore Price Type (%s)', 'event_espresso'),
219
-                            $price_type->name()
220
-                        )
221
-                    );
222
-                }
223
-                // delete price link
224
-                if (
225
-                    EE_Registry::instance()->CAP->current_user_can(
226
-                        'ee_delete_default_price_type',
227
-                        'pricing_delete_price_type',
228
-                        $price_type->ID()
229
-                    )
230
-                ) {
231
-                    $actions['delete'] = $this->getActionLink(
232
-                        $this->getActionUrl($price_type, self::ACTION_DELETE),
233
-                        esc_html__('Delete Permanently', 'event_espresso'),
234
-                        sprintf(
235
-                            /* translators: The name of the price type */
236
-                            esc_attr__('Delete Price Type %s Permanently', 'event_espresso'),
237
-                            $price_type->name()
238
-                        )
239
-                    );
240
-                }
241
-            }
242
-        }
243
-
244
-        $content = $prep_content ? $name_link . $this->row_actions($actions) : $name_link;
245
-        return $prep_content ? $this->columnContent('name', $content) : $content;
246
-    }
247
-
248
-
249
-    public function column_base_type($price_type): string
250
-    {
251
-        return $this->columnContent('base_type', $price_type->base_type_name());
252
-    }
253
-
254
-
255
-    public function column_percent($price_type): string
256
-    {
257
-        $content = $price_type->is_percent() ? '%' : EE_Registry::instance()->CFG->currency->sign;
258
-        return $this->columnContent('percent', $content, 'center');
259
-    }
260
-
261
-
262
-    public function column_order($price_type): string
263
-    {
264
-        return $this->columnContent('order', $price_type->order(), 'end');
265
-    }
16
+	/**
17
+	 * @var Pricing_Admin_Page
18
+	 */
19
+	protected $_admin_page;
20
+
21
+
22
+	public function __construct($admin_page)
23
+	{
24
+		parent::__construct($admin_page);
25
+		require_once(EE_MODELS . 'EEM_Price_Type.model.php');
26
+		$this->_PRT = EEM_Price_Type::instance();
27
+	}
28
+
29
+
30
+	protected function _setup_data()
31
+	{
32
+		$trashed               = $this->_admin_page->get_view() == 'trashed';
33
+		$this->_data           = $this->_admin_page->get_price_types_overview_data($this->_per_page, false, $trashed);
34
+		$this->_all_data_count = $this->_admin_page->get_price_types_overview_data($this->_per_page, true);
35
+		$this->_trashed_count  = $this->_admin_page->get_price_types_overview_data($this->_per_page, true, true);
36
+	}
37
+
38
+
39
+	protected function _set_properties()
40
+	{
41
+		$this->_wp_list_args = [
42
+			'singular' => esc_html__('price type', 'event_espresso'),
43
+			'plural'   => esc_html__('price types', 'event_espresso'),
44
+			'ajax'     => true,
45
+			'screen'   => $this->_admin_page->get_current_screen()->id,
46
+		];
47
+
48
+		$this->_columns = [
49
+			'cb'        => '<input type="checkbox" />', // Render a checkbox instead of text
50
+			'id'        => esc_html__('ID', 'event_espresso'),
51
+			'name'      => esc_html__('Name', 'event_espresso'),
52
+			'base_type' => esc_html__('Base Type', 'event_espresso'),
53
+			'percent'   => sprintf(
54
+							   /* translators: 1: HTML new line, 2: open span tag, 3: close span tag */
55
+				esc_html__('Applied %1$s as %2$s%%%3$s or %2$s$%3$s', 'event_espresso'),
56
+				'',
57
+				'<span class="big-text">',
58
+				'</span>'
59
+			),
60
+			'order'     => esc_html__('Order of Application', 'event_espresso'),
61
+		];
62
+
63
+		$this->_sortable_columns = [
64
+			// TRUE means its already sorted
65
+			'name' => ['name' => false],
66
+		];
67
+
68
+		$this->_hidden_columns = [];
69
+	}
70
+
71
+
72
+	protected function _get_table_filters()
73
+	{
74
+		return [];
75
+	}
76
+
77
+
78
+	protected function _add_view_counts()
79
+	{
80
+		$this->_views['all']['count'] = $this->_all_data_count;
81
+		if (
82
+			EE_Registry::instance()->CAP->current_user_can(
83
+				'ee_delete_default_price_types',
84
+				'pricing_trash_price_type'
85
+			)
86
+		) {
87
+			$this->_views['trashed']['count'] = $this->_trashed_count;
88
+		}
89
+	}
90
+
91
+
92
+	/**
93
+	 * @param EE_Price_Type $price_type
94
+	 * @param string   $action
95
+	 * @return string
96
+	 * @throws EE_Error
97
+	 * @throws ReflectionException
98
+	 * @since 5.0.0.p
99
+	 */
100
+	protected function getActionUrl(EE_Price_Type $price_type, string $action): string
101
+	{
102
+		if (! in_array($action, self::$actions)) {
103
+			throw new DomainException(esc_html__('Invalid Action', 'event_espresso'));
104
+		}
105
+		return EE_Admin_Page::add_query_args_and_nonce(
106
+			[
107
+				'action'   => "{$action}_price_type",
108
+				'id'       => $price_type->ID(),
109
+				'noheader' => $action !== self::ACTION_EDIT,
110
+			],
111
+			PRICING_ADMIN_URL
112
+		);
113
+	}
114
+
115
+
116
+	public function column_cb($item): string
117
+	{
118
+		if ($item->base_type() !== 1) {
119
+			return sprintf(
120
+				'<input type="checkbox" name="checkbox[%1$s]" />',
121
+				$item->ID()
122
+			);
123
+		}
124
+		return '';
125
+	}
126
+
127
+
128
+	/**
129
+	 * @param EE_Price_Type $item
130
+	 * @return string
131
+	 * @throws EE_Error
132
+	 * @throws ReflectionException
133
+	 */
134
+	public function column_id($item): string
135
+	{
136
+		$content = '<span class="ee-entity-id">' . $item->ID() . '</span>';
137
+		$content .= '<span class="show-on-mobile-view-only">' . $this->column_name($item, false) . '</span>';
138
+		return $this->columnContent('id', $content, 'end');
139
+	}
140
+
141
+
142
+	/**
143
+	 * @param EE_Price_Type $price_type
144
+	 * @param bool          $prep_content
145
+	 * @return string
146
+	 * @throws EE_Error
147
+	 * @throws ReflectionException
148
+	 */
149
+	public function column_name(EE_Price_Type $price_type, bool $prep_content = true): string
150
+	{
151
+
152
+		// Build row actions
153
+		$actions   = [];
154
+		$name_link = $price_type->name();
155
+		// edit price link
156
+		if (
157
+			EE_Registry::instance()->CAP->current_user_can(
158
+				'ee_edit_default_price_type',
159
+				'pricing_edit_price_type',
160
+				$price_type->ID()
161
+			)
162
+		) {
163
+			$name_link = $this->getActionLink(
164
+				$this->getActionUrl($price_type, self::ACTION_EDIT),
165
+				stripslashes($price_type->name()),
166
+				sprintf(
167
+					/* translators: The name of the price type */
168
+					esc_attr__('Edit Price Type (%s)', 'event_espresso'),
169
+					$price_type->name()
170
+				)
171
+			);
172
+
173
+			$actions['edit'] = $this->getActionLink(
174
+				$this->getActionUrl($price_type, self::ACTION_EDIT),
175
+				esc_html__('Edit', 'event_espresso'),
176
+				sprintf(
177
+					/* translators: The name of the price type */
178
+					esc_attr__('Edit Price Type (%s)', 'event_espresso'),
179
+					$price_type->name()
180
+				)
181
+			);
182
+		}
183
+
184
+		if ($price_type->base_type() !== 1) {
185
+			if ($this->_view == 'all') {
186
+				// trash price link
187
+				if (
188
+					EE_Registry::instance()->CAP->current_user_can(
189
+						'ee_delete_default_price_type',
190
+						'pricing_trash_price_type',
191
+						$price_type->ID()
192
+					)
193
+				) {
194
+					$actions['trash'] = $this->getActionLink(
195
+						$this->getActionUrl($price_type, self::ACTION_TRASH),
196
+						esc_html__('Trash', 'event_espresso'),
197
+						sprintf(
198
+							/* translators: The name of the price type */
199
+							esc_attr__('Move Price Type %s to Trash', 'event_espresso'),
200
+							$price_type->name()
201
+						)
202
+					);
203
+				}
204
+			} else {
205
+				// restore price link
206
+				if (
207
+					EE_Registry::instance()->CAP->current_user_can(
208
+						'ee_delete_default_price_type',
209
+						'pricing_restore_price_type',
210
+						$price_type->ID()
211
+					)
212
+				) {
213
+					$actions['restore'] = $this->getActionLink(
214
+						$this->getActionUrl($price_type, self::ACTION_RESTORE),
215
+						esc_html__('Restore', 'event_espresso'),
216
+						sprintf(
217
+							/* translators: The name of the price type */
218
+							esc_attr__('Restore Price Type (%s)', 'event_espresso'),
219
+							$price_type->name()
220
+						)
221
+					);
222
+				}
223
+				// delete price link
224
+				if (
225
+					EE_Registry::instance()->CAP->current_user_can(
226
+						'ee_delete_default_price_type',
227
+						'pricing_delete_price_type',
228
+						$price_type->ID()
229
+					)
230
+				) {
231
+					$actions['delete'] = $this->getActionLink(
232
+						$this->getActionUrl($price_type, self::ACTION_DELETE),
233
+						esc_html__('Delete Permanently', 'event_espresso'),
234
+						sprintf(
235
+							/* translators: The name of the price type */
236
+							esc_attr__('Delete Price Type %s Permanently', 'event_espresso'),
237
+							$price_type->name()
238
+						)
239
+					);
240
+				}
241
+			}
242
+		}
243
+
244
+		$content = $prep_content ? $name_link . $this->row_actions($actions) : $name_link;
245
+		return $prep_content ? $this->columnContent('name', $content) : $content;
246
+	}
247
+
248
+
249
+	public function column_base_type($price_type): string
250
+	{
251
+		return $this->columnContent('base_type', $price_type->base_type_name());
252
+	}
253
+
254
+
255
+	public function column_percent($price_type): string
256
+	{
257
+		$content = $price_type->is_percent() ? '%' : EE_Registry::instance()->CFG->currency->sign;
258
+		return $this->columnContent('percent', $content, 'center');
259
+	}
260
+
261
+
262
+	public function column_order($price_type): string
263
+	{
264
+		return $this->columnContent('order', $price_type->order(), 'end');
265
+	}
266 266
 }
Please login to merge, or discard this patch.