Completed
Branch master (8de7dd)
by
unknown
06:29
created
core/db_classes/EE_Soft_Delete_Base_Class.class.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -11,59 +11,59 @@
 block discarded – undo
11 11
  */
12 12
 abstract class EE_Soft_Delete_Base_Class extends EE_Base_Class
13 13
 {
14
-    /**
15
-     * Overrides parent _delete() so that we do soft deletes.
16
-     *
17
-     * @return int
18
-     * @throws EE_Error
19
-     * @throws ReflectionException
20
-     */
21
-    protected function _delete(): int
22
-    {
23
-        return $this->delete_or_restore();
24
-    }
14
+	/**
15
+	 * Overrides parent _delete() so that we do soft deletes.
16
+	 *
17
+	 * @return int
18
+	 * @throws EE_Error
19
+	 * @throws ReflectionException
20
+	 */
21
+	protected function _delete(): int
22
+	{
23
+		return $this->delete_or_restore();
24
+	}
25 25
 
26 26
 
27
-    /**
28
-     * Deletes or restores this object.
29
-     *
30
-     * @param bool $delete true=>delete, false=>restore
31
-     * @return int
32
-     * @throws EE_Error
33
-     * @throws ReflectionException
34
-     */
35
-    public function delete_or_restore(bool $delete = true): int
36
-    {
37
-        /**
38
-         * Called just before trashing (soft delete) or restoring a trashed item.
39
-         *
40
-         * @param EE_Base_Class $model_object about to be trashed or restored
41
-         * @param bool          $delete       true the item is being trashed, false the item is being restored.
42
-         */
43
-        do_action('AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__before', $this, $delete);
44
-        $model  = $this->get_model();
45
-        $result = $model->delete_or_restore_by_ID($delete, $this->ID());
46
-        /**
47
-         * Called just after trashing (soft delete) or restoring a trashed item.
48
-         *
49
-         * @param EE_Base_Class $model_object that was just trashed or restored.
50
-         * @param bool          $delete       true the item is being trashed, false the item is being restored.
51
-         * @param bool|int      $result
52
-         */
53
-        do_action('AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__after', $this, $delete, $result);
54
-        return $result;
55
-    }
27
+	/**
28
+	 * Deletes or restores this object.
29
+	 *
30
+	 * @param bool $delete true=>delete, false=>restore
31
+	 * @return int
32
+	 * @throws EE_Error
33
+	 * @throws ReflectionException
34
+	 */
35
+	public function delete_or_restore(bool $delete = true): int
36
+	{
37
+		/**
38
+		 * Called just before trashing (soft delete) or restoring a trashed item.
39
+		 *
40
+		 * @param EE_Base_Class $model_object about to be trashed or restored
41
+		 * @param bool          $delete       true the item is being trashed, false the item is being restored.
42
+		 */
43
+		do_action('AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__before', $this, $delete);
44
+		$model  = $this->get_model();
45
+		$result = $model->delete_or_restore_by_ID($delete, $this->ID());
46
+		/**
47
+		 * Called just after trashing (soft delete) or restoring a trashed item.
48
+		 *
49
+		 * @param EE_Base_Class $model_object that was just trashed or restored.
50
+		 * @param bool          $delete       true the item is being trashed, false the item is being restored.
51
+		 * @param bool|int      $result
52
+		 */
53
+		do_action('AHEE__EE_Soft_Delete_Base_Class__delete_or_restore__after', $this, $delete, $result);
54
+		return $result;
55
+	}
56 56
 
57 57
 
58
-    /**
59
-     * Performs a restoration (un-deletes) this object
60
-     *
61
-     * @return int
62
-     * @throws EE_Error
63
-     * @throws ReflectionException
64
-     */
65
-    public function restore(): int
66
-    {
67
-        return $this->delete_or_restore(false);
68
-    }
58
+	/**
59
+	 * Performs a restoration (un-deletes) this object
60
+	 *
61
+	 * @return int
62
+	 * @throws EE_Error
63
+	 * @throws ReflectionException
64
+	 */
65
+	public function restore(): int
66
+	{
67
+		return $this->delete_or_restore(false);
68
+	}
69 69
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Country.class.php 1 patch
Indentation   +217 added lines, -217 removed lines patch added patch discarded remove patch
@@ -9,221 +9,221 @@
 block discarded – undo
9 9
  */
10 10
 class EE_Country extends EE_Base_Class
11 11
 {
12
-    /**
13
-     * @param array $props_n_values
14
-     * @return EE_Country|mixed
15
-     * @throws EE_Error
16
-     * @throws ReflectionException
17
-     */
18
-    public static function new_instance($props_n_values = [])
19
-    {
20
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
21
-        return $has_object ?: new self($props_n_values);
22
-    }
23
-
24
-
25
-    /**
26
-     * @param array $props_n_values
27
-     * @return EE_Country
28
-     * @throws EE_Error
29
-     * @throws ReflectionException
30
-     */
31
-    public static function new_instance_from_db($props_n_values = []): EE_Country
32
-    {
33
-        return new self($props_n_values, true);
34
-    }
35
-
36
-
37
-    /**
38
-     * Gets the country name
39
-     *
40
-     * @return string
41
-     * @throws EE_Error
42
-     * @throws ReflectionException
43
-     */
44
-    public function name(): string
45
-    {
46
-        return (string) $this->get('CNT_name');
47
-    }
48
-
49
-
50
-    /**
51
-     * Whether the country is active/enabled
52
-     *
53
-     * @return bool
54
-     * @throws EE_Error
55
-     * @throws ReflectionException
56
-     */
57
-    public function isActive(): bool
58
-    {
59
-        return (bool) $this->get('CNT_active');
60
-    }
61
-
62
-
63
-    /**
64
-     * Gets the country ISO code
65
-     *
66
-     * @return string
67
-     * @throws EE_Error
68
-     * @throws ReflectionException
69
-     */
70
-    public function ISO(): string
71
-    {
72
-        return (string) $this->get('CNT_ISO');
73
-    }
74
-
75
-
76
-    /**
77
-     * Gets the country ISO3 code
78
-     *
79
-     * @return string
80
-     * @throws EE_Error
81
-     * @throws ReflectionException
82
-     */
83
-    public function ISO3(): string
84
-    {
85
-        return (string) $this->get('CNT_ISO3');
86
-    }
87
-
88
-
89
-    /**
90
-     * gets the country's currency code
91
-     *
92
-     * @return string
93
-     * @throws EE_Error
94
-     * @throws ReflectionException
95
-     */
96
-    public function currency_code(): string
97
-    {
98
-        return (string) $this->get('CNT_cur_code');
99
-    }
100
-
101
-
102
-    /**
103
-     * gets the country's currency sign/symbol
104
-     *
105
-     * @return string
106
-     * @throws EE_Error
107
-     * @throws ReflectionException
108
-     */
109
-    public function currency_sign(): string
110
-    {
111
-        return (string) $this->get('CNT_cur_sign');
112
-    }
113
-
114
-
115
-    /**
116
-     * Currency name singular
117
-     *
118
-     * @return string
119
-     * @throws EE_Error
120
-     * @throws ReflectionException
121
-     */
122
-    public function currency_name_single(): string
123
-    {
124
-        return (string) $this->get('CNT_cur_single');
125
-    }
126
-
127
-
128
-    /**
129
-     * Currency name plural
130
-     *
131
-     * @return string
132
-     * @throws EE_Error
133
-     * @throws ReflectionException
134
-     */
135
-    public function currency_name_plural(): string
136
-    {
137
-        return (string) $this->get('CNT_cur_plural');
138
-    }
139
-
140
-
141
-    /**
142
-     * currency_sign_before - ie: $TRUE  or  FALSE$
143
-     *
144
-     * @return boolean
145
-     * @throws EE_Error
146
-     * @throws ReflectionException
147
-     */
148
-    public function currency_sign_before(): bool
149
-    {
150
-        return (bool) $this->get('CNT_cur_sign_b4');
151
-    }
152
-
153
-
154
-    /**
155
-     * currency_decimal_places : 2 = 0.00   3 = 0.000
156
-     *
157
-     * @return integer
158
-     * @throws EE_Error
159
-     * @throws ReflectionException
160
-     */
161
-    public function currency_decimal_places(): int
162
-    {
163
-        return (int) $this->get('CNT_cur_dec_plc');
164
-    }
165
-
166
-
167
-    /**
168
-     * currency_decimal_mark :   (comma) ',' = 0,01   or   (decimal) '.' = 0.01
169
-     *
170
-     * @return string
171
-     * @throws EE_Error
172
-     * @throws ReflectionException
173
-     */
174
-    public function currency_decimal_mark(): string
175
-    {
176
-        return (string) $this->get('CNT_cur_dec_mrk');
177
-    }
178
-
179
-
180
-    /**
181
-     * currency thousands separator:   (comma) ',' = 1,000   or   (decimal) '.' = 1.000
182
-     *
183
-     * @return string
184
-     * @throws EE_Error
185
-     * @throws ReflectionException
186
-     */
187
-    public function currency_thousands_separator(): string
188
-    {
189
-        return (string) $this->get('CNT_cur_thsnds');
190
-    }
191
-
192
-
193
-    /**
194
-     * @return bool
195
-     * @throws EE_Error
196
-     * @throws ReflectionException
197
-     * @since 4.10.30.p
198
-     */
199
-    public function isEU(): bool
200
-    {
201
-        return (bool) $this->get('CNT_is_EU');
202
-    }
203
-
204
-
205
-    /**
206
-     * Country Telephone Code: +1
207
-     *
208
-     * @return string
209
-     * @throws EE_Error
210
-     * @throws ReflectionException
211
-     * @since 4.10.30.p
212
-     */
213
-    public function telephoneCode(): string
214
-    {
215
-        return (string) $this->get('CNT_tel_code');
216
-    }
217
-
218
-
219
-    /**
220
-     * @return bool
221
-     * @throws EE_Error
222
-     * @throws ReflectionException
223
-     * @deprecated 4.10.30.p
224
-     */
225
-    public function is_active(): bool
226
-    {
227
-        return $this->isActive();
228
-    }
12
+	/**
13
+	 * @param array $props_n_values
14
+	 * @return EE_Country|mixed
15
+	 * @throws EE_Error
16
+	 * @throws ReflectionException
17
+	 */
18
+	public static function new_instance($props_n_values = [])
19
+	{
20
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
21
+		return $has_object ?: new self($props_n_values);
22
+	}
23
+
24
+
25
+	/**
26
+	 * @param array $props_n_values
27
+	 * @return EE_Country
28
+	 * @throws EE_Error
29
+	 * @throws ReflectionException
30
+	 */
31
+	public static function new_instance_from_db($props_n_values = []): EE_Country
32
+	{
33
+		return new self($props_n_values, true);
34
+	}
35
+
36
+
37
+	/**
38
+	 * Gets the country name
39
+	 *
40
+	 * @return string
41
+	 * @throws EE_Error
42
+	 * @throws ReflectionException
43
+	 */
44
+	public function name(): string
45
+	{
46
+		return (string) $this->get('CNT_name');
47
+	}
48
+
49
+
50
+	/**
51
+	 * Whether the country is active/enabled
52
+	 *
53
+	 * @return bool
54
+	 * @throws EE_Error
55
+	 * @throws ReflectionException
56
+	 */
57
+	public function isActive(): bool
58
+	{
59
+		return (bool) $this->get('CNT_active');
60
+	}
61
+
62
+
63
+	/**
64
+	 * Gets the country ISO code
65
+	 *
66
+	 * @return string
67
+	 * @throws EE_Error
68
+	 * @throws ReflectionException
69
+	 */
70
+	public function ISO(): string
71
+	{
72
+		return (string) $this->get('CNT_ISO');
73
+	}
74
+
75
+
76
+	/**
77
+	 * Gets the country ISO3 code
78
+	 *
79
+	 * @return string
80
+	 * @throws EE_Error
81
+	 * @throws ReflectionException
82
+	 */
83
+	public function ISO3(): string
84
+	{
85
+		return (string) $this->get('CNT_ISO3');
86
+	}
87
+
88
+
89
+	/**
90
+	 * gets the country's currency code
91
+	 *
92
+	 * @return string
93
+	 * @throws EE_Error
94
+	 * @throws ReflectionException
95
+	 */
96
+	public function currency_code(): string
97
+	{
98
+		return (string) $this->get('CNT_cur_code');
99
+	}
100
+
101
+
102
+	/**
103
+	 * gets the country's currency sign/symbol
104
+	 *
105
+	 * @return string
106
+	 * @throws EE_Error
107
+	 * @throws ReflectionException
108
+	 */
109
+	public function currency_sign(): string
110
+	{
111
+		return (string) $this->get('CNT_cur_sign');
112
+	}
113
+
114
+
115
+	/**
116
+	 * Currency name singular
117
+	 *
118
+	 * @return string
119
+	 * @throws EE_Error
120
+	 * @throws ReflectionException
121
+	 */
122
+	public function currency_name_single(): string
123
+	{
124
+		return (string) $this->get('CNT_cur_single');
125
+	}
126
+
127
+
128
+	/**
129
+	 * Currency name plural
130
+	 *
131
+	 * @return string
132
+	 * @throws EE_Error
133
+	 * @throws ReflectionException
134
+	 */
135
+	public function currency_name_plural(): string
136
+	{
137
+		return (string) $this->get('CNT_cur_plural');
138
+	}
139
+
140
+
141
+	/**
142
+	 * currency_sign_before - ie: $TRUE  or  FALSE$
143
+	 *
144
+	 * @return boolean
145
+	 * @throws EE_Error
146
+	 * @throws ReflectionException
147
+	 */
148
+	public function currency_sign_before(): bool
149
+	{
150
+		return (bool) $this->get('CNT_cur_sign_b4');
151
+	}
152
+
153
+
154
+	/**
155
+	 * currency_decimal_places : 2 = 0.00   3 = 0.000
156
+	 *
157
+	 * @return integer
158
+	 * @throws EE_Error
159
+	 * @throws ReflectionException
160
+	 */
161
+	public function currency_decimal_places(): int
162
+	{
163
+		return (int) $this->get('CNT_cur_dec_plc');
164
+	}
165
+
166
+
167
+	/**
168
+	 * currency_decimal_mark :   (comma) ',' = 0,01   or   (decimal) '.' = 0.01
169
+	 *
170
+	 * @return string
171
+	 * @throws EE_Error
172
+	 * @throws ReflectionException
173
+	 */
174
+	public function currency_decimal_mark(): string
175
+	{
176
+		return (string) $this->get('CNT_cur_dec_mrk');
177
+	}
178
+
179
+
180
+	/**
181
+	 * currency thousands separator:   (comma) ',' = 1,000   or   (decimal) '.' = 1.000
182
+	 *
183
+	 * @return string
184
+	 * @throws EE_Error
185
+	 * @throws ReflectionException
186
+	 */
187
+	public function currency_thousands_separator(): string
188
+	{
189
+		return (string) $this->get('CNT_cur_thsnds');
190
+	}
191
+
192
+
193
+	/**
194
+	 * @return bool
195
+	 * @throws EE_Error
196
+	 * @throws ReflectionException
197
+	 * @since 4.10.30.p
198
+	 */
199
+	public function isEU(): bool
200
+	{
201
+		return (bool) $this->get('CNT_is_EU');
202
+	}
203
+
204
+
205
+	/**
206
+	 * Country Telephone Code: +1
207
+	 *
208
+	 * @return string
209
+	 * @throws EE_Error
210
+	 * @throws ReflectionException
211
+	 * @since 4.10.30.p
212
+	 */
213
+	public function telephoneCode(): string
214
+	{
215
+		return (string) $this->get('CNT_tel_code');
216
+	}
217
+
218
+
219
+	/**
220
+	 * @return bool
221
+	 * @throws EE_Error
222
+	 * @throws ReflectionException
223
+	 * @deprecated 4.10.30.p
224
+	 */
225
+	public function is_active(): bool
226
+	{
227
+		return $this->isActive();
228
+	}
229 229
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +3362 added lines, -3362 removed lines patch added patch discarded remove patch
@@ -15,3377 +15,3377 @@
 block discarded – undo
15 15
  */
16 16
 abstract class EE_Base_Class
17 17
 {
18
-    /**
19
-     * @var EEM_Base|null
20
-     */
21
-    protected $_model = null;
22
-
23
-    /**
24
-     * This is an array of the original properties and values provided during construction
25
-     * of this model object. (keys are model field names, values are their values).
26
-     * This list is important to remember so that when we are merging data from the db, we know
27
-     * which values to override and which to not override.
28
-     */
29
-    protected ?array $_props_n_values_provided_in_constructor = null;
30
-
31
-    /**
32
-     * Timezone
33
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
34
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
35
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
36
-     * access to it.
37
-     */
38
-    protected string $_timezone = '';
39
-
40
-    /**
41
-     * date format
42
-     * pattern or format for displaying dates
43
-     */
44
-    protected string $_dt_frmt = '';
45
-
46
-    /**
47
-     * time format
48
-     * pattern or format for displaying time
49
-     */
50
-    protected string $_tm_frmt = '';
51
-
52
-    /**
53
-     * This property is for holding a cached array of object properties indexed by property name as the key.
54
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
55
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
56
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
57
-     */
58
-    protected array $_cached_properties = [];
59
-
60
-    /**
61
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
62
-     * single
63
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
64
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
65
-     * all others have an array)
66
-     */
67
-    protected array $_model_relations = [];
68
-
69
-    /**
70
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
71
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
72
-     */
73
-    protected array $_fields = [];
74
-
75
-    /**
76
-     * indicating whether or not this model object is intended to ever be saved
77
-     * For example, we might create model objects intended to only be used for the duration
78
-     * of this request and to be thrown away, and if they were accidentally saved
79
-     * it would be a bug.
80
-     */
81
-    protected bool $_allow_persist = true;
82
-
83
-    /**
84
-     * indicating whether or not this model object's properties have changed since construction
85
-     */
86
-    protected bool $_has_changes = false;
87
-
88
-    /**
89
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
90
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
91
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
92
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
93
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
94
-     * array as:
95
-     * array(
96
-     *  'Registration_Count' => 24
97
-     * );
98
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
99
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
100
-     * info)
101
-     */
102
-    protected array $custom_selection_results = [];
103
-
104
-
105
-    /**
106
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
107
-     * play nice
108
-     *
109
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
110
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
111
-     *                                                         TXN_amount, QST_name, etc) and values are their values
112
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
113
-     *                                                         corresponding db model or not.
114
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
115
-     *                                                         be in when instantiating a EE_Base_Class object.
116
-     * @param array   $date_formats                            An array of date formats to set on construct where first
117
-     *                                                         value is the date_format and second value is the time
118
-     *                                                         format.
119
-     * @throws InvalidArgumentException
120
-     * @throws InvalidInterfaceException
121
-     * @throws InvalidDataTypeException
122
-     * @throws EE_Error
123
-     * @throws ReflectionException
124
-     */
125
-    protected function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
126
-    {
127
-        $className = get_class($this);
128
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
129
-        $model        = $this->get_model();
130
-        $model_fields = $model->field_settings();
131
-        // ensure $fieldValues is an array
132
-        $fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
133
-        // verify client code has not passed any invalid field names
134
-        foreach ($fieldValues as $field_name => $field_value) {
135
-            if (! isset($model_fields[ $field_name ])) {
136
-                throw new EE_Error(
137
-                    sprintf(
138
-                        esc_html__(
139
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
140
-                            'event_espresso'
141
-                        ),
142
-                        $field_name,
143
-                        get_class($this),
144
-                        implode(', ', array_keys($model_fields))
145
-                    )
146
-                );
147
-            }
148
-        }
149
-
150
-        $date_format     = null;
151
-        $time_format     = null;
152
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
153
-        if (! empty($date_formats) && is_array($date_formats)) {
154
-            [$date_format, $time_format] = $date_formats;
155
-        }
156
-        $this->set_date_format($date_format);
157
-        $this->set_time_format($time_format);
158
-        // if db model is instantiating
159
-        foreach ($model_fields as $fieldName => $field) {
160
-            if ($bydb) {
161
-                // client code has indicated these field values are from the database
162
-                $this->set_from_db(
163
-                    $fieldName,
164
-                    $fieldValues[ $fieldName ] ?? null
165
-                );
166
-            } else {
167
-                // we're constructing a brand new instance of the model object.
168
-                // Generally, this means we'll need to do more field validation
169
-                $this->set(
170
-                    $fieldName,
171
-                    $fieldValues[ $fieldName ] ?? null,
172
-                    true
173
-                );
174
-            }
175
-        }
176
-        // remember what values were passed to this constructor
177
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
178
-        // remember in entity mapper
179
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
180
-            $model->add_to_entity_map($this);
181
-        }
182
-        // setup all the relations
183
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
184
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
185
-                $this->_model_relations[ $relation_name ] = null;
186
-            } else {
187
-                $this->_model_relations[ $relation_name ] = [];
188
-            }
189
-        }
190
-        /**
191
-         * Action done at the end of each model object construction
192
-         *
193
-         * @param EE_Base_Class $this the model object just created
194
-         */
195
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
196
-    }
197
-
198
-
199
-    /**
200
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
201
-     *
202
-     * @return boolean
203
-     */
204
-    public function allow_persist()
205
-    {
206
-        return $this->_allow_persist;
207
-    }
208
-
209
-
210
-    /**
211
-     * Sets whether or not this model object should be allowed to be saved to the DB.
212
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
213
-     * you got new information that somehow made you change your mind.
214
-     *
215
-     * @param boolean $allow_persist
216
-     * @return boolean
217
-     */
218
-    public function set_allow_persist($allow_persist)
219
-    {
220
-        return $this->_allow_persist = $allow_persist;
221
-    }
222
-
223
-
224
-    /**
225
-     * Gets the field's original value when this object was constructed during this request.
226
-     * This can be helpful when determining if a model object has changed or not
227
-     *
228
-     * @param string $field_name
229
-     * @return mixed|null
230
-     * @throws ReflectionException
231
-     * @throws InvalidArgumentException
232
-     * @throws InvalidInterfaceException
233
-     * @throws InvalidDataTypeException
234
-     * @throws EE_Error
235
-     */
236
-    public function get_original($field_name)
237
-    {
238
-        if (
239
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
240
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
241
-        ) {
242
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
243
-        }
244
-        return null;
245
-    }
246
-
247
-
248
-    /**
249
-     * @param EE_Base_Class $obj
250
-     * @return string
251
-     */
252
-    public function get_class($obj)
253
-    {
254
-        return get_class($obj);
255
-    }
256
-
257
-
258
-    /**
259
-     * Overrides parent because parent expects old models.
260
-     * This also doesn't do any validation, and won't work for serialized arrays
261
-     *
262
-     * @param string $field_name
263
-     * @param mixed  $field_value
264
-     * @param bool   $use_default
265
-     * @throws InvalidArgumentException
266
-     * @throws InvalidInterfaceException
267
-     * @throws InvalidDataTypeException
268
-     * @throws EE_Error
269
-     * @throws ReflectionException
270
-     * @throws Exception
271
-     */
272
-    public function set(string $field_name, $field_value, bool $use_default = false)
273
-    {
274
-        // if not using default and nothing has changed, and object has already been setup (has ID),
275
-        // then don't do anything
276
-        if (
277
-            ! $use_default
278
-            && $this->_fields[ $field_name ] === $field_value
279
-            && $this->ID()
280
-        ) {
281
-            return;
282
-        }
283
-        $model              = $this->get_model();
284
-        $this->_has_changes = true;
285
-        $field_obj          = $model->field_settings_for($field_name);
286
-        if (! $field_obj instanceof EE_Model_Field_Base) {
287
-            throw new EE_Error(
288
-                sprintf(
289
-                    esc_html__(
290
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
291
-                        'event_espresso'
292
-                    ),
293
-                    $field_name
294
-                )
295
-            );
296
-        }
297
-        // if ( method_exists( $field_obj, 'set_timezone' )) {
298
-        if ($field_obj instanceof EE_Datetime_Field) {
299
-            $field_obj->set_timezone($this->_timezone);
300
-            $field_obj->set_date_format($this->_dt_frmt);
301
-            $field_obj->set_time_format($this->_tm_frmt);
302
-        }
303
-
304
-        // should the value be null?
305
-        $value = $field_value === null && ($use_default || ! $field_obj->is_nullable())
306
-            ? $field_obj->get_default_value()
307
-            : $field_value;
308
-
309
-        $this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
310
-
311
-        // if we're not in the constructor...
312
-        // now check if what we set was a primary key
313
-        if (
314
-            // note: props_n_values_provided_in_constructor is only set at the END of the constructor
315
-            $this->_props_n_values_provided_in_constructor
316
-            && $field_value
317
-            && $field_name === $model->primary_key_name()
318
-        ) {
319
-            // if so, we want all this object's fields to be filled either with
320
-            // what we've explicitly set on this model
321
-            // or what we have in the db
322
-            // echo "setting primary key!";
323
-            $fields_on_model = self::_get_model(get_class($this))->field_settings();
324
-            $obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
325
-            foreach ($fields_on_model as $field_obj) {
326
-                if (
327
-                    ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
328
-                    && $field_obj->get_name() !== $field_name
329
-                ) {
330
-                    $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
331
-                }
332
-            }
333
-            // oh this model object has an ID? well make sure its in the entity mapper
334
-            $model->add_to_entity_map($this);
335
-        }
336
-        // let's unset any cache for this field_name from the $_cached_properties property.
337
-        $this->_clear_cached_property($field_name);
338
-    }
339
-
340
-
341
-    /**
342
-     * Overrides parent because parent expects old models.
343
-     * This also doesn't do any validation, and won't work for serialized arrays
344
-     *
345
-     * @param string $field_name
346
-     * @param mixed  $field_value_from_db
347
-     * @throws ReflectionException
348
-     * @throws InvalidArgumentException
349
-     * @throws InvalidInterfaceException
350
-     * @throws InvalidDataTypeException
351
-     * @throws EE_Error
352
-     */
353
-    public function set_from_db(string $field_name, $field_value_from_db)
354
-    {
355
-        $field_obj = $this->get_model()->field_settings_for($field_name);
356
-        if ($field_obj instanceof EE_Model_Field_Base) {
357
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
358
-            // eg, a CPT model object could have an entry in the posts table, but no
359
-            // entry in the meta table. Meaning that all its columns in the meta table
360
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
361
-            if ($field_value_from_db === null) {
362
-                if ($field_obj->is_nullable()) {
363
-                    // if the field allows nulls, then let it be null
364
-                    $field_value = null;
365
-                } else {
366
-                    $field_value = $field_obj->get_default_value();
367
-                }
368
-            } else {
369
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
370
-            }
371
-            $this->_fields[ $field_name ] = $field_value;
372
-            $this->_clear_cached_property($field_name);
373
-        }
374
-    }
375
-
376
-
377
-    /**
378
-     * Set custom select values for model.
379
-     *
380
-     * @param array $custom_select_values
381
-     */
382
-    public function setCustomSelectsValues(array $custom_select_values)
383
-    {
384
-        $this->custom_selection_results = $custom_select_values;
385
-    }
386
-
387
-
388
-    /**
389
-     * Returns the custom select value for the provided alias if its set.
390
-     * If not set, returns null.
391
-     *
392
-     * @param string $alias
393
-     * @return string|int|float|null
394
-     */
395
-    public function getCustomSelect($alias)
396
-    {
397
-        return $this->custom_selection_results[ $alias ] ?? null;
398
-    }
399
-
400
-
401
-    /**
402
-     * This sets the field value on the db column if it exists for the given $column_name or
403
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
404
-     *
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
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
414
-     */
415
-    public function set_field_or_extra_meta($field_name, $field_value)
416
-    {
417
-        if ($this->get_model()->has_field($field_name)) {
418
-            $this->set($field_name, $field_value);
419
-            return true;
420
-        }
421
-        // ensure this object is saved first so that extra meta can be properly related.
422
-        $this->save();
423
-        return $this->update_extra_meta($field_name, $field_value);
424
-    }
425
-
426
-
427
-    /**
428
-     * This retrieves the value of the db column set on this class or if that's not present
429
-     * it will attempt to retrieve from extra_meta if found.
430
-     * Example Usage:
431
-     * Via EE_Message child class:
432
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
433
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
434
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
435
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
436
-     * value for those extra fields dynamically via the EE_message object.
437
-     *
438
-     * @param string $field_name expecting the fully qualified field name.
439
-     * @return mixed|null  value for the field if found.  null if not found.
440
-     * @throws ReflectionException
441
-     * @throws InvalidArgumentException
442
-     * @throws InvalidInterfaceException
443
-     * @throws InvalidDataTypeException
444
-     * @throws EE_Error
445
-     */
446
-    public function get_field_or_extra_meta($field_name)
447
-    {
448
-        if ($this->get_model()->has_field($field_name)) {
449
-            $column_value = $this->get($field_name);
450
-        } else {
451
-            // This isn't a column in the main table, let's see if it is in the extra meta.
452
-            $column_value = $this->get_extra_meta($field_name, true, null);
453
-        }
454
-        return $column_value;
455
-    }
456
-
457
-
458
-    /**
459
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
460
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
461
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
462
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
463
-     *
464
-     * @access public
465
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
466
-     * @return void
467
-     * @throws InvalidArgumentException
468
-     * @throws InvalidInterfaceException
469
-     * @throws InvalidDataTypeException
470
-     * @throws EE_Error
471
-     * @throws ReflectionException
472
-     * @throws Exception
473
-     */
474
-    public function set_timezone($timezone = '')
475
-    {
476
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
477
-        // make sure we clear all cached properties because they won't be relevant now
478
-        $this->_clear_cached_properties();
479
-        // make sure we update field settings and the date for all EE_Datetime_Fields
480
-        $model_fields = $this->get_model()->field_settings(false);
481
-        foreach ($model_fields as $field_name => $field_obj) {
482
-            if ($field_obj instanceof EE_Datetime_Field) {
483
-                $field_obj->set_timezone($this->_timezone);
484
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
485
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
486
-                }
487
-            }
488
-        }
489
-    }
490
-
491
-
492
-    /**
493
-     * This just returns whatever is set for the current timezone.
494
-     *
495
-     * @access public
496
-     * @return string timezone string
497
-     */
498
-    public function get_timezone()
499
-    {
500
-        return $this->_timezone;
501
-    }
502
-
503
-
504
-    /**
505
-     * This sets the internal date format to what is sent in to be used as the new default for the class
506
-     * internally instead of wp set date format options
507
-     *
508
-     * @param string|null $format should be a format recognizable by PHP date() functions.
509
-     * @since 4.6
510
-     */
511
-    public function set_date_format(?string $format)
512
-    {
513
-        $this->_dt_frmt = new DateFormat($format);
514
-        // clear cached_properties because they won't be relevant now.
515
-        $this->_clear_cached_properties();
516
-    }
517
-
518
-
519
-    /**
520
-     * This sets the internal time format string to what is sent in to be used as the new default for the
521
-     * class internally instead of wp set time format options.
522
-     *
523
-     * @param string|null $format should be a format recognizable by PHP date() functions.
524
-     * @since 4.6
525
-     */
526
-    public function set_time_format(?string $format)
527
-    {
528
-        $this->_tm_frmt = new TimeFormat($format);
529
-        // clear cached_properties because they won't be relevant now.
530
-        $this->_clear_cached_properties();
531
-    }
532
-
533
-
534
-    /**
535
-     * This returns the current internal set format for the date and time formats.
536
-     *
537
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
538
-     *                             where the first value is the date format and the second value is the time format.
539
-     * @return string|array
540
-     */
541
-    public function get_format($full = true)
542
-    {
543
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
544
-    }
545
-
546
-
547
-    /**
548
-     * cache
549
-     * stores the passed model object on the current model object.
550
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
551
-     *
552
-     * @param string        $relation_name   one of the keys in the _model_relations array on the model. Eg
553
-     *                                       'Registration' associated with this model object
554
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
555
-     *                                       that could be a payment or a registration)
556
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
557
-     *                                       items which will be stored in an array on this object
558
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
559
-     *                                       related thing, no array)
560
-     * @throws InvalidArgumentException
561
-     * @throws InvalidInterfaceException
562
-     * @throws InvalidDataTypeException
563
-     * @throws EE_Error
564
-     * @throws ReflectionException
565
-     */
566
-    public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
567
-    {
568
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
569
-        if (! $object_to_cache instanceof EE_Base_Class) {
570
-            return false;
571
-        }
572
-        // also get "how" the object is related, or throw an error
573
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
574
-            throw new EE_Error(
575
-                sprintf(
576
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
577
-                    $relation_name,
578
-                    get_class($this)
579
-                )
580
-            );
581
-        }
582
-        // how many things are related ?
583
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
584
-            // if it's a "belongs to" relationship, then there's only one related model object
585
-            // eg, if this is a registration, there's only 1 attendee for it
586
-            // so for these model objects just set it to be cached
587
-            $this->_model_relations[ $relation_name ] = $object_to_cache;
588
-            $return                                   = true;
589
-        } else {
590
-            // otherwise, this is the "many" side of a one to many relationship,
591
-            // so we'll add the object to the array of related objects for that type.
592
-            // eg: if this is an event, there are many registrations for that event,
593
-            // so we cache the registrations in an array
594
-            if (! is_array($this->_model_relations[ $relation_name ])) {
595
-                // if for some reason, the cached item is a model object,
596
-                // then stick that in the array, otherwise start with an empty array
597
-                $this->_model_relations[ $relation_name ] =
598
-                    $this->_model_relations[ $relation_name ] instanceof EE_Base_Class
599
-                        ? [$this->_model_relations[ $relation_name ]]
600
-                        : [];
601
-            }
602
-            // first check for a cache_id which is normally empty
603
-            if (! empty($cache_id)) {
604
-                // if the cache_id exists, then it means we are purposely trying to cache this
605
-                // with a known key that can then be used to retrieve the object later on
606
-                $this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
607
-                $return                                                = $cache_id;
608
-            } elseif ($object_to_cache->ID()) {
609
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
610
-                $this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
611
-                $return                                                             = $object_to_cache->ID();
612
-            } else {
613
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
614
-                $this->_model_relations[ $relation_name ][] = $object_to_cache;
615
-                // move the internal pointer to the end of the array
616
-                end($this->_model_relations[ $relation_name ]);
617
-                // and grab the key so that we can return it
618
-                $return = key($this->_model_relations[ $relation_name ]);
619
-            }
620
-        }
621
-        return $return;
622
-    }
623
-
624
-
625
-    /**
626
-     * For adding an item to the cached_properties property.
627
-     *
628
-     * @access protected
629
-     * @param string      $fieldname the property item the corresponding value is for.
630
-     * @param mixed       $value     The value we are caching.
631
-     * @param string|null $cache_type
632
-     * @return void
633
-     * @throws ReflectionException
634
-     * @throws InvalidArgumentException
635
-     * @throws InvalidInterfaceException
636
-     * @throws InvalidDataTypeException
637
-     * @throws EE_Error
638
-     */
639
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
640
-    {
641
-        // first make sure this property exists
642
-        $this->get_model()->field_settings_for($fieldname);
643
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
644
-
645
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
646
-    }
647
-
648
-
649
-    /**
650
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
651
-     * This also SETS the cache if we return the actual property!
652
-     *
653
-     * @param string $fieldname        the name of the property we're trying to retrieve
654
-     * @param bool   $pretty
655
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
656
-     *                                 (in cases where the same property may be used for different outputs
657
-     *                                 - i.e. datetime, money etc.)
658
-     *                                 It can also accept certain pre-defined "schema" strings
659
-     *                                 to define how to output the property.
660
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
661
-     * @return mixed                   whatever the value for the property is we're retrieving
662
-     * @throws ReflectionException
663
-     * @throws InvalidArgumentException
664
-     * @throws InvalidInterfaceException
665
-     * @throws InvalidDataTypeException
666
-     * @throws EE_Error
667
-     */
668
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
669
-    {
670
-        // verify the field exists
671
-        $model = $this->get_model();
672
-        $model->field_settings_for($fieldname);
673
-        $cache_type = $pretty ? 'pretty' : 'standard';
674
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
675
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
676
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
677
-        }
678
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
679
-        $this->_set_cached_property($fieldname, $value, $cache_type);
680
-        return $value;
681
-    }
682
-
683
-
684
-    /**
685
-     * If the cache didn't fetch the needed item, this fetches it.
686
-     *
687
-     * @param string $fieldname
688
-     * @param bool   $pretty
689
-     * @param string $extra_cache_ref
690
-     * @return mixed
691
-     * @throws InvalidArgumentException
692
-     * @throws InvalidInterfaceException
693
-     * @throws InvalidDataTypeException
694
-     * @throws EE_Error
695
-     * @throws ReflectionException
696
-     */
697
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
698
-    {
699
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
700
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
701
-        if ($field_obj instanceof EE_Datetime_Field) {
702
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
703
-        }
704
-        if (! isset($this->_fields[ $fieldname ])) {
705
-            $this->_fields[ $fieldname ] = null;
706
-        }
707
-        return $pretty
708
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
709
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
710
-    }
711
-
712
-
713
-    /**
714
-     * set timezone, formats, and output for EE_Datetime_Field objects
715
-     *
716
-     * @param EE_Datetime_Field $datetime_field
717
-     * @param bool              $pretty
718
-     * @param null              $date_or_time
719
-     * @return void
720
-     * @throws InvalidArgumentException
721
-     * @throws InvalidInterfaceException
722
-     * @throws InvalidDataTypeException
723
-     */
724
-    protected function _prepare_datetime_field(
725
-        EE_Datetime_Field $datetime_field,
726
-        $pretty = false,
727
-        $date_or_time = null
728
-    ) {
729
-        $datetime_field->set_timezone($this->_timezone);
730
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
731
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
732
-        // set the output returned
733
-        switch ($date_or_time) {
734
-            case 'D':
735
-                $datetime_field->set_date_time_output('date');
736
-                break;
737
-            case 'T':
738
-                $datetime_field->set_date_time_output('time');
739
-                break;
740
-            default:
741
-                $datetime_field->set_date_time_output();
742
-        }
743
-    }
744
-
745
-
746
-    /**
747
-     * This just takes care of clearing out the cached_properties
748
-     *
749
-     * @return void
750
-     */
751
-    protected function _clear_cached_properties()
752
-    {
753
-        $this->_cached_properties = [];
754
-    }
755
-
756
-
757
-    /**
758
-     * This just clears out ONE property if it exists in the cache
759
-     *
760
-     * @param string $property_name the property to remove if it exists (from the _cached_properties array)
761
-     * @return void
762
-     */
763
-    protected function _clear_cached_property($property_name)
764
-    {
765
-        if (isset($this->_cached_properties[ $property_name ])) {
766
-            unset($this->_cached_properties[ $property_name ]);
767
-        }
768
-    }
769
-
770
-
771
-    /**
772
-     * Ensures that this related thing is a model object.
773
-     *
774
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
775
-     * @param string $model_name   name of the related thing, eg 'Attendee',
776
-     * @return EE_Base_Class
777
-     * @throws ReflectionException
778
-     * @throws InvalidArgumentException
779
-     * @throws InvalidInterfaceException
780
-     * @throws InvalidDataTypeException
781
-     * @throws EE_Error
782
-     */
783
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
784
-    {
785
-        $other_model_instance = self::_get_model_instance_with_name(
786
-            self::_get_model_classname($model_name),
787
-            $this->_timezone
788
-        );
789
-        return $other_model_instance->ensure_is_obj($object_or_id);
790
-    }
791
-
792
-
793
-    /**
794
-     * Forgets the cached model of the given relation Name. So the next time we request it,
795
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
796
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
797
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
798
-     *
799
-     * @param string $relation_name                        one of the keys in the _model_relations array on the model.
800
-     *                                                     Eg 'Registration'
801
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
802
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
803
-     *                                                     has 1 object anyway (ie, it's a BelongsToRelation)
804
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
805
-     *                                                     this is HasMany or HABTM.
806
-     * @return EE_Base_Class|bool                          entity that was cleared from the cache,
807
-     *                                                     or true if we requested to remove a relation from all
808
-     *                                                     or false if entity was never cached anyway.
809
-     * @throws InvalidArgumentException
810
-     * @throws InvalidInterfaceException
811
-     * @throws InvalidDataTypeException
812
-     * @throws EE_Error
813
-     * @throws ReflectionException
814
-     */
815
-    public function clear_cache($relation_name, $object_to_remove_or_index_into_array = null, $clear_all = false)
816
-    {
817
-        $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
818
-        $index_in_cache        = '';
819
-        if (! $relationship_to_model) {
820
-            throw new EE_Error(
821
-                sprintf(
822
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
823
-                    $relation_name,
824
-                    get_class($this)
825
-                )
826
-            );
827
-        }
828
-        if ($clear_all) {
829
-            $obj_removed                              = true;
830
-            $this->_model_relations[ $relation_name ] = null;
831
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
-            $obj_removed                              = $this->_model_relations[ $relation_name ];
833
-            $this->_model_relations[ $relation_name ] = null;
834
-        } else {
835
-            if (
836
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
837
-                && $object_to_remove_or_index_into_array->ID()
838
-            ) {
839
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
840
-                if (
841
-                    is_array($this->_model_relations[ $relation_name ])
842
-                    && ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
843
-                ) {
844
-                    $index_found_at = null;
845
-                    // find this object in the array even though it has a different key
846
-                    foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
847
-                        /** @noinspection TypeUnsafeComparisonInspection */
848
-                        if (
849
-                            $obj instanceof EE_Base_Class
850
-                            && (
851
-                                $obj == $object_to_remove_or_index_into_array
852
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
853
-                            )
854
-                        ) {
855
-                            $index_found_at = $index;
856
-                            break;
857
-                        }
858
-                    }
859
-                    if ($index_found_at) {
860
-                        $index_in_cache = $index_found_at;
861
-                    } else {
862
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
863
-                        // if it wasn't in it to begin with. So we're done
864
-                        return $object_to_remove_or_index_into_array;
865
-                    }
866
-                }
867
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
868
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
869
-                foreach ($this->get_all_from_cache($relation_name) as $index => $potentially_obj_we_want) {
870
-                    /** @noinspection TypeUnsafeComparisonInspection */
871
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
872
-                        $index_in_cache = $index;
873
-                    }
874
-                }
875
-            } else {
876
-                $index_in_cache = $object_to_remove_or_index_into_array;
877
-            }
878
-            // supposedly we've found it. But it could just be that the client code
879
-            // provided a bad index/object
880
-            if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
881
-                $obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
882
-                unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
883
-            } else {
884
-                // that thing was never cached anyway.
885
-                $obj_removed = false;
886
-            }
887
-        }
888
-        return $obj_removed;
889
-    }
890
-
891
-
892
-    /**
893
-     * update_cache_after_object_save
894
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
895
-     * obtained after being saved to the db
896
-     *
897
-     * @param string        $relation_name      - the type of object that is cached
898
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
899
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
900
-     * @return boolean TRUE on success, FALSE on fail
901
-     * @throws ReflectionException
902
-     * @throws InvalidArgumentException
903
-     * @throws InvalidInterfaceException
904
-     * @throws InvalidDataTypeException
905
-     * @throws EE_Error
906
-     */
907
-    public function update_cache_after_object_save(
908
-        $relation_name,
909
-        EE_Base_Class $newly_saved_object,
910
-        $current_cache_id = ''
911
-    ) {
912
-        // verify that incoming object is of the correct type
913
-        $obj_class = 'EE_' . $relation_name;
914
-        if ($newly_saved_object instanceof $obj_class) {
915
-            /* @type EE_Base_Class $newly_saved_object */
916
-            // now get the type of relation
917
-            $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
918
-            // if this is a 1:1 relationship
919
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
920
-                // then just replace the cached object with the newly saved object
921
-                $this->_model_relations[ $relation_name ] = $newly_saved_object;
922
-                return true;
923
-                // or if it's some kind of sordid feral polyamorous relationship...
924
-            }
925
-            if (
926
-                is_array($this->_model_relations[ $relation_name ])
927
-                && isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
928
-            ) {
929
-                // then remove the current cached item
930
-                unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
931
-                // and cache the newly saved object using it's new ID
932
-                $this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
933
-                return true;
934
-            }
935
-        }
936
-        return false;
937
-    }
938
-
939
-
940
-    /**
941
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
942
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
943
-     *
944
-     * @param string $relation_name
945
-     * @return EE_Base_Class
946
-     */
947
-    public function get_one_from_cache($relation_name)
948
-    {
949
-        $cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
950
-        if (is_array($cached_array_or_object)) {
951
-            return array_shift($cached_array_or_object);
952
-        }
953
-        return $cached_array_or_object;
954
-    }
955
-
956
-
957
-    /**
958
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
959
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
960
-     *
961
-     * @param string $relation_name
962
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
963
-     * @throws InvalidArgumentException
964
-     * @throws InvalidInterfaceException
965
-     * @throws InvalidDataTypeException
966
-     * @throws EE_Error
967
-     * @throws ReflectionException
968
-     */
969
-    public function get_all_from_cache($relation_name)
970
-    {
971
-        $objects = $this->_model_relations[ $relation_name ] ?? [];
972
-        // if the result is not an array, but exists, make it an array
973
-        $objects = is_array($objects)
974
-            ? $objects
975
-            : [$objects];
976
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
977
-        // basically, if this model object was stored in the session, and these cached model objects
978
-        // already have IDs, let's make sure they're in their model's entity mapper
979
-        // otherwise we will have duplicates next time we call
980
-        // EE_Registry::instance()->load_model( $relation_name )->get_one_by_ID( $result->ID() );
981
-        $model = EE_Registry::instance()->load_model($relation_name);
982
-        foreach ($objects as $model_object) {
983
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
984
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
985
-                if ($model_object->ID()) {
986
-                    $model->add_to_entity_map($model_object);
987
-                }
988
-            } else {
989
-                throw new EE_Error(
990
-                    sprintf(
991
-                        esc_html__(
992
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
993
-                            'event_espresso'
994
-                        ),
995
-                        $relation_name,
996
-                        gettype($model_object)
997
-                    )
998
-                );
999
-            }
1000
-        }
1001
-        return $objects;
1002
-    }
1003
-
1004
-
1005
-    /**
1006
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1007
-     * matching the given query conditions.
1008
-     *
1009
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1010
-     * @param int   $limit              How many objects to return.
1011
-     * @param array $query_params       Any additional conditions on the query.
1012
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1013
-     *                                  you can indicate just the columns you want returned
1014
-     * @return array|EE_Base_Class[]
1015
-     * @throws ReflectionException
1016
-     * @throws InvalidArgumentException
1017
-     * @throws InvalidInterfaceException
1018
-     * @throws InvalidDataTypeException
1019
-     * @throws EE_Error
1020
-     */
1021
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = [], $columns_to_select = null)
1022
-    {
1023
-        $model         = $this->get_model();
1024
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1025
-            ? $model->get_primary_key_field()->get_name()
1026
-            : $field_to_order_by;
1027
-        $current_value = ! empty($field)
1028
-            ? $this->get($field)
1029
-            : null;
1030
-        if (empty($field) || empty($current_value)) {
1031
-            return [];
1032
-        }
1033
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1039
-     * matching the given query conditions.
1040
-     *
1041
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1042
-     * @param int   $limit              How many objects to return.
1043
-     * @param array $query_params       Any additional conditions on the query.
1044
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1045
-     *                                  you can indicate just the columns you want returned
1046
-     * @return array|EE_Base_Class[]
1047
-     * @throws ReflectionException
1048
-     * @throws InvalidArgumentException
1049
-     * @throws InvalidInterfaceException
1050
-     * @throws InvalidDataTypeException
1051
-     * @throws EE_Error
1052
-     */
1053
-    public function previous_x(
1054
-        $field_to_order_by = null,
1055
-        $limit = 1,
1056
-        $query_params = [],
1057
-        $columns_to_select = null
1058
-    ) {
1059
-        $model         = $this->get_model();
1060
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1061
-            ? $model->get_primary_key_field()->get_name()
1062
-            : $field_to_order_by;
1063
-        $current_value = ! empty($field) ? $this->get($field) : null;
1064
-        if (empty($field) || empty($current_value)) {
1065
-            return [];
1066
-        }
1067
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1068
-    }
1069
-
1070
-
1071
-    /**
1072
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1073
-     * matching the given query conditions.
1074
-     *
1075
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1076
-     * @param array $query_params       Any additional conditions on the query.
1077
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1078
-     *                                  you can indicate just the columns you want returned
1079
-     * @return array|EE_Base_Class
1080
-     * @throws ReflectionException
1081
-     * @throws InvalidArgumentException
1082
-     * @throws InvalidInterfaceException
1083
-     * @throws InvalidDataTypeException
1084
-     * @throws EE_Error
1085
-     */
1086
-    public function next($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1087
-    {
1088
-        $model         = $this->get_model();
1089
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1090
-            ? $model->get_primary_key_field()->get_name()
1091
-            : $field_to_order_by;
1092
-        $current_value = ! empty($field) ? $this->get($field) : null;
1093
-        if (empty($field) || empty($current_value)) {
1094
-            return [];
1095
-        }
1096
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1097
-    }
1098
-
1099
-
1100
-    /**
1101
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1102
-     * matching the given query conditions.
1103
-     *
1104
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1105
-     * @param array $query_params       Any additional conditions on the query.
1106
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1107
-     *                                  you can indicate just the column you want returned
1108
-     * @return array|EE_Base_Class
1109
-     * @throws ReflectionException
1110
-     * @throws InvalidArgumentException
1111
-     * @throws InvalidInterfaceException
1112
-     * @throws InvalidDataTypeException
1113
-     * @throws EE_Error
1114
-     */
1115
-    public function previous($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1116
-    {
1117
-        $model         = $this->get_model();
1118
-        $field         = empty($field_to_order_by) && $model->has_primary_key_field()
1119
-            ? $model->get_primary_key_field()->get_name()
1120
-            : $field_to_order_by;
1121
-        $current_value = ! empty($field) ? $this->get($field) : null;
1122
-        if (empty($field) || empty($current_value)) {
1123
-            return [];
1124
-        }
1125
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * verifies that the specified field is of the correct type
1131
-     *
1132
-     * @param string $field_name
1133
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1134
-     *                                (in cases where the same property may be used for different outputs
1135
-     *                                - i.e. datetime, money etc.)
1136
-     * @return mixed
1137
-     * @throws ReflectionException
1138
-     * @throws InvalidArgumentException
1139
-     * @throws InvalidInterfaceException
1140
-     * @throws InvalidDataTypeException
1141
-     * @throws EE_Error
1142
-     */
1143
-    public function get($field_name, $extra_cache_ref = null)
1144
-    {
1145
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1146
-    }
1147
-
1148
-
1149
-    /**
1150
-     * This method simply returns the RAW unprocessed value for the given property in this class
1151
-     *
1152
-     * @param string $field_name A valid fieldname
1153
-     * @return mixed              Whatever the raw value stored on the property is.
1154
-     * @throws ReflectionException
1155
-     * @throws InvalidArgumentException
1156
-     * @throws InvalidInterfaceException
1157
-     * @throws InvalidDataTypeException
1158
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1159
-     */
1160
-    public function get_raw($field_name)
1161
-    {
1162
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1163
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1164
-            ? $this->_fields[ $field_name ]->format('U')
1165
-            : $this->_fields[ $field_name ];
1166
-    }
1167
-
1168
-
1169
-    /**
1170
-     * This is used to return the internal DateTime object used for a field that is a
1171
-     * EE_Datetime_Field.
1172
-     *
1173
-     * @param string $field_name               The field name retrieving the DateTime object.
1174
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1175
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1176
-     *                                         EE_Datetime_Field and but the field value is null, then
1177
-     *                                         just null is returned (because that indicates that likely
1178
-     *                                         this field is nullable).
1179
-     * @throws InvalidArgumentException
1180
-     * @throws InvalidDataTypeException
1181
-     * @throws InvalidInterfaceException
1182
-     * @throws ReflectionException
1183
-     */
1184
-    public function get_DateTime_object($field_name)
1185
-    {
1186
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1187
-        if (! $field_settings instanceof EE_Datetime_Field) {
1188
-            EE_Error::add_error(
1189
-                sprintf(
1190
-                    esc_html__(
1191
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1192
-                        'event_espresso'
1193
-                    ),
1194
-                    $field_name
1195
-                ),
1196
-                __FILE__,
1197
-                __FUNCTION__,
1198
-                __LINE__
1199
-            );
1200
-            return false;
1201
-        }
1202
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1203
-            ? clone $this->_fields[ $field_name ]
1204
-            : null;
1205
-    }
1206
-
1207
-
1208
-    /**
1209
-     * To be used in template to immediately echo out the value, and format it for output.
1210
-     * Eg, should call stripslashes and whatnot before echoing
1211
-     *
1212
-     * @param string $field_name      the name of the field as it appears in the DB
1213
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1214
-     *                                (in cases where the same property may be used for different outputs
1215
-     *                                - i.e. datetime, money etc.)
1216
-     * @return void
1217
-     * @throws ReflectionException
1218
-     * @throws InvalidArgumentException
1219
-     * @throws InvalidInterfaceException
1220
-     * @throws InvalidDataTypeException
1221
-     * @throws EE_Error
1222
-     */
1223
-    public function e($field_name, $extra_cache_ref = null)
1224
-    {
1225
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1231
-     * can be easily used as the value of form input.
1232
-     *
1233
-     * @param string $field_name
1234
-     * @return void
1235
-     * @throws ReflectionException
1236
-     * @throws InvalidArgumentException
1237
-     * @throws InvalidInterfaceException
1238
-     * @throws InvalidDataTypeException
1239
-     * @throws EE_Error
1240
-     */
1241
-    public function f($field_name)
1242
-    {
1243
-        $this->e($field_name, 'form_input');
1244
-    }
1245
-
1246
-
1247
-    /**
1248
-     * Same as `f()` but just returns the value instead of echoing it
1249
-     *
1250
-     * @param string $field_name
1251
-     * @return string
1252
-     * @throws ReflectionException
1253
-     * @throws InvalidArgumentException
1254
-     * @throws InvalidInterfaceException
1255
-     * @throws InvalidDataTypeException
1256
-     * @throws EE_Error
1257
-     */
1258
-    public function get_f($field_name)
1259
-    {
1260
-        return (string) $this->get_pretty($field_name, 'form_input');
1261
-    }
1262
-
1263
-
1264
-    /**
1265
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1266
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1267
-     * to see what options are available.
1268
-     *
1269
-     * @param string $field_name
1270
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1271
-     *                                (in cases where the same property may be used for different outputs
1272
-     *                                - i.e. datetime, money etc.)
1273
-     * @return mixed
1274
-     * @throws ReflectionException
1275
-     * @throws InvalidArgumentException
1276
-     * @throws InvalidInterfaceException
1277
-     * @throws InvalidDataTypeException
1278
-     * @throws EE_Error
1279
-     */
1280
-    public function get_pretty($field_name, $extra_cache_ref = null)
1281
-    {
1282
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1283
-    }
1284
-
1285
-
1286
-    /**
1287
-     * This simply returns the datetime for the given field name
1288
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1289
-     * (and the equivalent e_date, e_time, e_datetime).
1290
-     *
1291
-     * @access   protected
1292
-     * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1293
-     * @param string|null $date_format  valid datetime format used for date
1294
-     *                                  (if '' then we just use the default on the field,
1295
-     *                                  if NULL we use the last-used format)
1296
-     * @param string|null $time_format  Same as above except this is for time format
1297
-     * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1298
-     * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1299
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1300
-     *                                  if field is not a valid dtt field, or void if echoing
1301
-     * @throws EE_Error
1302
-     * @throws ReflectionException
1303
-     */
1304
-    protected function _get_datetime(
1305
-        string $field_name,
1306
-        ?string $date_format = '',
1307
-        ?string $time_format = '',
1308
-        ?string $date_or_time = '',
1309
-        ?bool $echo = false
1310
-    ) {
1311
-        // clear cached property
1312
-        $this->_clear_cached_property($field_name);
1313
-        // reset format properties because they are used in get()
1314
-        $this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1315
-        $this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1316
-        if ($echo) {
1317
-            $this->e($field_name, $date_or_time);
1318
-            return '';
1319
-        }
1320
-        return $this->get($field_name, $date_or_time);
1321
-    }
1322
-
1323
-
1324
-    /**
1325
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1326
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1327
-     * other echoes the pretty value for dtt)
1328
-     *
1329
-     * @param string $field_name name of model object datetime field holding the value
1330
-     * @param string $format     format for the date returned (if NULL we use default in dt_frmt property)
1331
-     * @return string            datetime value formatted
1332
-     * @throws ReflectionException
1333
-     * @throws InvalidArgumentException
1334
-     * @throws InvalidInterfaceException
1335
-     * @throws InvalidDataTypeException
1336
-     * @throws EE_Error
1337
-     */
1338
-    public function get_date($field_name, $format = '')
1339
-    {
1340
-        return $this->_get_datetime($field_name, $format, null, 'D');
1341
-    }
1342
-
1343
-
1344
-    /**
1345
-     * @param        $field_name
1346
-     * @param string $format
1347
-     * @throws ReflectionException
1348
-     * @throws InvalidArgumentException
1349
-     * @throws InvalidInterfaceException
1350
-     * @throws InvalidDataTypeException
1351
-     * @throws EE_Error
1352
-     */
1353
-    public function e_date($field_name, $format = '')
1354
-    {
1355
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1356
-    }
1357
-
1358
-
1359
-    /**
1360
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1361
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1362
-     * other echoes the pretty value for dtt)
1363
-     *
1364
-     * @param string $field_name name of model object datetime field holding the value
1365
-     * @param string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1366
-     * @return string             datetime value formatted
1367
-     * @throws ReflectionException
1368
-     * @throws InvalidArgumentException
1369
-     * @throws InvalidInterfaceException
1370
-     * @throws InvalidDataTypeException
1371
-     * @throws EE_Error
1372
-     */
1373
-    public function get_time($field_name, $format = '')
1374
-    {
1375
-        return $this->_get_datetime($field_name, null, $format, 'T');
1376
-    }
1377
-
1378
-
1379
-    /**
1380
-     * @param        $field_name
1381
-     * @param string $format
1382
-     * @throws ReflectionException
1383
-     * @throws InvalidArgumentException
1384
-     * @throws InvalidInterfaceException
1385
-     * @throws InvalidDataTypeException
1386
-     * @throws EE_Error
1387
-     */
1388
-    public function e_time($field_name, $format = '')
1389
-    {
1390
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1391
-    }
1392
-
1393
-
1394
-    /**
1395
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1396
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1397
-     * other echoes the pretty value for dtt)
1398
-     *
1399
-     * @param string $field_name  name of model object datetime field holding the value
1400
-     * @param string $date_format format for the date returned (if NULL we use default in dt_frmt property)
1401
-     * @param string $time_format format for the time returned (if NULL we use default in tm_frmt property)
1402
-     * @return string             datetime value formatted
1403
-     * @throws ReflectionException
1404
-     * @throws InvalidArgumentException
1405
-     * @throws InvalidInterfaceException
1406
-     * @throws InvalidDataTypeException
1407
-     * @throws EE_Error
1408
-     */
1409
-    public function get_datetime($field_name, $date_format = '', $time_format = '')
1410
-    {
1411
-        return $this->_get_datetime($field_name, $date_format, $time_format);
1412
-    }
1413
-
1414
-
1415
-    /**
1416
-     * @param string $field_name
1417
-     * @param string $date_format
1418
-     * @param string $time_format
1419
-     * @throws ReflectionException
1420
-     * @throws InvalidArgumentException
1421
-     * @throws InvalidInterfaceException
1422
-     * @throws InvalidDataTypeException
1423
-     * @throws EE_Error
1424
-     */
1425
-    public function e_datetime($field_name, $date_format = '', $time_format = '')
1426
-    {
1427
-        $this->_get_datetime($field_name, $date_format, $time_format, null, true);
1428
-    }
1429
-
1430
-
1431
-    /**
1432
-     * Get the i8ln value for a date using the WordPress @param string $field_name The EE_Datetime_Field reference for
1433
-     *                           the date being retrieved.
1434
-     *
1435
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1436
-     *                           on the object will be used.
1437
-     * @return string Date and time string in set locale or false if no field exists for the given
1438
-     * @throws ReflectionException
1439
-     * @throws InvalidArgumentException
1440
-     * @throws InvalidInterfaceException
1441
-     * @throws InvalidDataTypeException
1442
-     * @throws EE_Error
1443
-     *                           field name.
1444
-     * @see date_i18n function.
1445
-     */
1446
-    public function get_i18n_datetime(string $field_name, string $format = ''): string
1447
-    {
1448
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1449
-        return date_i18n(
1450
-            $format,
1451
-            EEH_DTT_Helper::get_timestamp_with_offset(
1452
-                $this->get_raw($field_name),
1453
-                $this->_timezone
1454
-            )
1455
-        );
1456
-    }
1457
-
1458
-
1459
-    /**
1460
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1461
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1462
-     * thrown.
1463
-     *
1464
-     * @param string $field_name The field name being checked
1465
-     * @return EE_Datetime_Field
1466
-     * @throws InvalidArgumentException
1467
-     * @throws InvalidInterfaceException
1468
-     * @throws InvalidDataTypeException
1469
-     * @throws EE_Error
1470
-     * @throws ReflectionException
1471
-     */
1472
-    protected function _get_dtt_field_settings($field_name)
1473
-    {
1474
-        $field = $this->get_model()->field_settings_for($field_name);
1475
-        // check if field is dtt
1476
-        if ($field instanceof EE_Datetime_Field) {
1477
-            return $field;
1478
-        }
1479
-        throw new EE_Error(
1480
-            sprintf(
1481
-                esc_html__(
1482
-                    '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',
1483
-                    'event_espresso'
1484
-                ),
1485
-                $field_name,
1486
-                self::_get_model_classname(get_class($this))
1487
-            )
1488
-        );
1489
-    }
1490
-
1491
-
1492
-
1493
-
1494
-    /**
1495
-     * NOTE ABOUT BELOW:
1496
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1497
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1498
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1499
-     * method and make sure you send the entire datetime value for setting.
1500
-     */
1501
-    /**
1502
-     * sets the time on a datetime property
1503
-     *
1504
-     * @access protected
1505
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1506
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1507
-     * @throws ReflectionException
1508
-     * @throws InvalidArgumentException
1509
-     * @throws InvalidInterfaceException
1510
-     * @throws InvalidDataTypeException
1511
-     * @throws EE_Error
1512
-     */
1513
-    protected function _set_time_for($time, $fieldname)
1514
-    {
1515
-        $this->_set_date_time('T', $time, $fieldname);
1516
-    }
1517
-
1518
-
1519
-    /**
1520
-     * sets the date on a datetime property
1521
-     *
1522
-     * @access protected
1523
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1524
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1525
-     * @throws ReflectionException
1526
-     * @throws InvalidArgumentException
1527
-     * @throws InvalidInterfaceException
1528
-     * @throws InvalidDataTypeException
1529
-     * @throws EE_Error
1530
-     */
1531
-    protected function _set_date_for($date, $fieldname)
1532
-    {
1533
-        $this->_set_date_time('D', $date, $fieldname);
1534
-    }
1535
-
1536
-
1537
-    /**
1538
-     * This takes care of setting a date or time independently on a given model object property. This method also
1539
-     * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1540
-     *
1541
-     * @access protected
1542
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1543
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1544
-     * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1545
-     *                                        EE_Datetime_Field property)
1546
-     * @throws ReflectionException
1547
-     * @throws InvalidArgumentException
1548
-     * @throws InvalidInterfaceException
1549
-     * @throws InvalidDataTypeException
1550
-     * @throws EE_Error
1551
-     */
1552
-    protected function _set_date_time(string $what, $datetime_value, string $field_name)
1553
-    {
1554
-        $field = $this->_get_dtt_field_settings($field_name);
1555
-        $field->set_timezone($this->_timezone);
1556
-        $field->set_date_format($this->_dt_frmt);
1557
-        $field->set_time_format($this->_tm_frmt);
1558
-        switch ($what) {
1559
-            case 'T':
1560
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1561
-                    $datetime_value,
1562
-                    $this->_fields[ $field_name ]
1563
-                );
1564
-                $this->_has_changes           = true;
1565
-                break;
1566
-            case 'D':
1567
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1568
-                    $datetime_value,
1569
-                    $this->_fields[ $field_name ]
1570
-                );
1571
-                $this->_has_changes           = true;
1572
-                break;
1573
-            case 'B':
1574
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1575
-                $this->_has_changes           = true;
1576
-                break;
1577
-        }
1578
-        $this->_clear_cached_property($field_name);
1579
-    }
1580
-
1581
-
1582
-    /**
1583
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1584
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1585
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1586
-     * that could lead to some unexpected results!
1587
-     *
1588
-     * @access public
1589
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1590
-     *                                         value being returned.
1591
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1592
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1593
-     * @param string $prepend                  You can include something to prepend on the timestamp
1594
-     * @param string $append                   You can include something to append on the timestamp
1595
-     * @return string timestamp
1596
-     * @throws ReflectionException
1597
-     * @throws InvalidArgumentException
1598
-     * @throws InvalidInterfaceException
1599
-     * @throws InvalidDataTypeException
1600
-     * @throws EE_Error
1601
-     */
1602
-    public function display_in_my_timezone(
1603
-        $field_name,
1604
-        $callback = 'get_datetime',
1605
-        $args = null,
1606
-        $prepend = '',
1607
-        $append = ''
1608
-    ) {
1609
-        $timezone = EEH_DTT_Helper::get_timezone();
1610
-        if ($timezone === $this->_timezone) {
1611
-            return '';
1612
-        }
1613
-        $original_timezone = $this->_timezone;
1614
-        $this->set_timezone($timezone);
1615
-        $fn   = (array) $field_name;
1616
-        $args = array_merge($fn, (array) $args);
1617
-        if (! method_exists($this, $callback)) {
1618
-            throw new EE_Error(
1619
-                sprintf(
1620
-                    esc_html__(
1621
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1622
-                        'event_espresso'
1623
-                    ),
1624
-                    $callback
1625
-                )
1626
-            );
1627
-        }
1628
-        $args   = (array) $args;
1629
-        $return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1630
-        $this->set_timezone($original_timezone);
1631
-        return $return;
1632
-    }
1633
-
1634
-
1635
-    /**
1636
-     * Deletes this model object.
1637
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1638
-     * override
1639
-     * `EE_Base_Class::_delete` NOT this class.
1640
-     *
1641
-     * @return int
1642
-     * @throws ReflectionException
1643
-     * @throws InvalidArgumentException
1644
-     * @throws InvalidInterfaceException
1645
-     * @throws InvalidDataTypeException
1646
-     * @throws EE_Error
1647
-     */
1648
-    public function delete()
1649
-    {
1650
-        /**
1651
-         * Called just before the `EE_Base_Class::_delete` method call.
1652
-         * Note:
1653
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1654
-         * should be aware that `_delete` may not always result in a permanent delete.
1655
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1656
-         * soft deletes (trash) the object and does not permanently delete it.
1657
-         *
1658
-         * @param EE_Base_Class $model_object about to be 'deleted'
1659
-         */
1660
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1661
-        $deleted = $this->_delete();
1662
-        /**
1663
-         * Called just after the `EE_Base_Class::_delete` method call.
1664
-         * Note:
1665
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1666
-         * should be aware that `_delete` may not always result in a permanent delete.
1667
-         * For example `EE_Soft_Base_Class::_delete`
1668
-         * soft deletes (trash) the object and does not permanently delete it.
1669
-         *
1670
-         * @param EE_Base_Class $model_object that was just 'deleted'
1671
-         * @param boolean       $deleted
1672
-         */
1673
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $deleted);
1674
-        return $deleted;
1675
-    }
1676
-
1677
-
1678
-    /**
1679
-     * Calls the specific delete method for the instantiated class.
1680
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1681
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1682
-     * `EE_Base_Class::delete`
1683
-     *
1684
-     * @return int
1685
-     * @throws ReflectionException
1686
-     * @throws InvalidArgumentException
1687
-     * @throws InvalidInterfaceException
1688
-     * @throws InvalidDataTypeException
1689
-     * @throws EE_Error
1690
-     */
1691
-    protected function _delete(): int
1692
-    {
1693
-        return $this->delete_permanently();
1694
-    }
1695
-
1696
-
1697
-    /**
1698
-     * Deletes this model object permanently from db
1699
-     * (but keep in mind related models may block the delete and return an error)
1700
-     *
1701
-     * @return int
1702
-     * @throws ReflectionException
1703
-     * @throws InvalidArgumentException
1704
-     * @throws InvalidInterfaceException
1705
-     * @throws InvalidDataTypeException
1706
-     * @throws EE_Error
1707
-     */
1708
-    public function delete_permanently(): int
1709
-    {
1710
-        /**
1711
-         * Called just before HARD deleting a model object
1712
-         *
1713
-         * @param EE_Base_Class $model_object about to be 'deleted'
1714
-         */
1715
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1716
-        $model  = $this->get_model();
1717
-        $result = $model->delete_permanently_by_ID($this->ID());
1718
-        $this->refresh_cache_of_related_objects();
1719
-        /**
1720
-         * Called just after HARD deleting a model object
1721
-         *
1722
-         * @param EE_Base_Class $model_object that was just 'deleted'
1723
-         * @param boolean       $result
1724
-         */
1725
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1726
-        return $result;
1727
-    }
1728
-
1729
-
1730
-    /**
1731
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1732
-     * related model objects
1733
-     *
1734
-     * @throws ReflectionException
1735
-     * @throws InvalidArgumentException
1736
-     * @throws InvalidInterfaceException
1737
-     * @throws InvalidDataTypeException
1738
-     * @throws EE_Error
1739
-     */
1740
-    public function refresh_cache_of_related_objects()
1741
-    {
1742
-        $model = $this->get_model();
1743
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1744
-            if (! empty($this->_model_relations[ $relation_name ])) {
1745
-                $related_objects = $this->_model_relations[ $relation_name ];
1746
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1747
-                    // this relation only stores a single model object, not an array
1748
-                    // but let's make it consistent
1749
-                    $related_objects = [$related_objects];
1750
-                }
1751
-                foreach ($related_objects as $related_object) {
1752
-                    // only refresh their cache if they're in memory
1753
-                    if ($related_object instanceof EE_Base_Class) {
1754
-                        $related_object->clear_cache(
1755
-                            $model->get_this_model_name(),
1756
-                            $this
1757
-                        );
1758
-                    }
1759
-                }
1760
-            }
1761
-        }
1762
-    }
1763
-
1764
-
1765
-    /**
1766
-     *        Saves this object to the database. An array may be supplied to set some values on this
1767
-     * object just before saving.
1768
-     *
1769
-     * @access public
1770
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1771
-     *                                 if provided during the save() method (often client code will change the fields'
1772
-     *                                 values before calling save)
1773
-     * @return bool|int|string         1 on a successful update
1774
-     *                                 the ID of the new entry on insert
1775
-     *                                 0 on failure or if the model object isn't allowed to persist
1776
-     *                                 (as determined by EE_Base_Class::allow_persist())
1777
-     * @throws InvalidInterfaceException
1778
-     * @throws InvalidDataTypeException
1779
-     * @throws EE_Error
1780
-     * @throws InvalidArgumentException
1781
-     * @throws ReflectionException
1782
-     */
1783
-    public function save($set_cols_n_values = [])
1784
-    {
1785
-        $model = $this->get_model();
1786
-        /**
1787
-         * Filters the fields we're about to save on the model object
1788
-         *
1789
-         * @param array         $set_cols_n_values
1790
-         * @param EE_Base_Class $model_object
1791
-         */
1792
-        $set_cols_n_values = (array) apply_filters(
1793
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1794
-            $set_cols_n_values,
1795
-            $this
1796
-        );
1797
-        // set attributes as provided in $set_cols_n_values
1798
-        foreach ($set_cols_n_values as $column => $value) {
1799
-            $this->set($column, $value);
1800
-        }
1801
-        // no changes ? then don't do anything
1802
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1803
-            return 0;
1804
-        }
1805
-        /**
1806
-         * Saving a model object.
1807
-         * Before we perform a save, this action is fired.
1808
-         *
1809
-         * @param EE_Base_Class $model_object the model object about to be saved.
1810
-         */
1811
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1812
-        if (! $this->allow_persist()) {
1813
-            return 0;
1814
-        }
1815
-        // now get current attribute values
1816
-        $save_cols_n_values = $this->_fields;
1817
-        // if the object already has an ID, update it. Otherwise, insert it
1818
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1819
-        // They have been
1820
-        $old_assumption_concerning_value_preparation = $model
1821
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1822
-        $model->assume_values_already_prepared_by_model_object(true);
1823
-        // does this model have an autoincrement PK?
1824
-        if ($model->has_primary_key_field()) {
1825
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1826
-                // ok check if it's set, if so: update; if not, insert
1827
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1828
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1829
-                } else {
1830
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1831
-                    $results = $model->insert($save_cols_n_values);
1832
-                    if ($results) {
1833
-                        // if successful, set the primary key
1834
-                        // but don't use the normal SET method, because it will check if
1835
-                        // an item with the same ID exists in the mapper & db, then
1836
-                        // will find it in the db (because we just added it) and THAT object
1837
-                        // will get added to the mapper before we can add this one!
1838
-                        // but if we just avoid using the SET method, all that headache can be avoided
1839
-                        $pk_field_name                   = $model->primary_key_name();
1840
-                        $this->_fields[ $pk_field_name ] = $results;
1841
-                        $this->_clear_cached_property($pk_field_name);
1842
-                        $model->add_to_entity_map($this);
1843
-                        $this->_update_cached_related_model_objs_fks();
1844
-                    }
1845
-                }
1846
-            } else {// PK is NOT auto-increment
1847
-                // so check if one like it already exists in the db
1848
-                if ($model->exists_by_ID($this->ID())) {
1849
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1850
-                        throw new EE_Error(
1851
-                            sprintf(
1852
-                                esc_html__(
1853
-                                    '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',
1854
-                                    'event_espresso'
1855
-                                ),
1856
-                                get_class($this),
1857
-                                get_class($model) . '::instance()->add_to_entity_map()',
1858
-                                get_class($model) . '::instance()->get_one_by_ID()',
1859
-                                '<br />'
1860
-                            )
1861
-                        );
1862
-                    }
1863
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1864
-                } else {
1865
-                    $results = $model->insert($save_cols_n_values);
1866
-                    $this->_update_cached_related_model_objs_fks();
1867
-                }
1868
-            }
1869
-        } else {// there is NO primary key
1870
-            $already_in_db = false;
1871
-            foreach ($model->unique_indexes() as $index) {
1872
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1873
-                if ($model->exists([$uniqueness_where_params])) {
1874
-                    $already_in_db = true;
1875
-                }
1876
-            }
1877
-            if ($already_in_db) {
1878
-                $combined_pk_fields_n_values = array_intersect_key(
1879
-                    $save_cols_n_values,
1880
-                    $model->get_combined_primary_key_fields()
1881
-                );
1882
-                $results                     = $model->update(
1883
-                    $save_cols_n_values,
1884
-                    $combined_pk_fields_n_values
1885
-                );
1886
-            } else {
1887
-                $results = $model->insert($save_cols_n_values);
1888
-            }
1889
-        }
1890
-        // restore the old assumption about values being prepared by the model object
1891
-        $model->assume_values_already_prepared_by_model_object(
1892
-            $old_assumption_concerning_value_preparation
1893
-        );
1894
-        /**
1895
-         * After saving the model object this action is called
1896
-         *
1897
-         * @param EE_Base_Class $model_object which was just saved
1898
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1899
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1900
-         */
1901
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1902
-        $this->_has_changes = false;
1903
-        return $results;
1904
-    }
1905
-
1906
-
1907
-    /**
1908
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1909
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1910
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1911
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1912
-     * 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
1913
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1914
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1915
-     *
1916
-     * @return void
1917
-     * @throws ReflectionException
1918
-     * @throws InvalidArgumentException
1919
-     * @throws InvalidInterfaceException
1920
-     * @throws InvalidDataTypeException
1921
-     * @throws EE_Error
1922
-     */
1923
-    protected function _update_cached_related_model_objs_fks()
1924
-    {
1925
-        $model = $this->get_model();
1926
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1927
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1928
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1929
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1930
-                        $model->get_this_model_name()
1931
-                    );
1932
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1933
-                    if ($related_model_obj_in_cache->ID()) {
1934
-                        $related_model_obj_in_cache->save();
1935
-                    }
1936
-                }
1937
-            }
1938
-        }
1939
-    }
1940
-
1941
-
1942
-    /**
1943
-     * Saves this model object and its NEW cached relations to the database.
1944
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1945
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1946
-     * because otherwise, there's a potential for infinite looping of saving
1947
-     * Saves the cached related model objects, and ensures the relation between them
1948
-     * and this object and properly setup
1949
-     *
1950
-     * @return int ID of new model object on save; 0 on failure+
1951
-     * @throws ReflectionException
1952
-     * @throws InvalidArgumentException
1953
-     * @throws InvalidInterfaceException
1954
-     * @throws InvalidDataTypeException
1955
-     * @throws EE_Error
1956
-     */
1957
-    public function save_new_cached_related_model_objs()
1958
-    {
1959
-        // make sure this has been saved
1960
-        if (! $this->ID()) {
1961
-            $id = $this->save();
1962
-        } else {
1963
-            $id = $this->ID();
1964
-        }
1965
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1966
-        foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1967
-            if ($this->_model_relations[ $relation_name ]) {
1968
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1969
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1970
-                /* @var $related_model_obj EE_Base_Class */
1971
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1972
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
1973
-                    // but ONLY if it DOES NOT exist in the DB
1974
-                    $related_model_obj = $this->_model_relations[ $relation_name ];
1975
-                    // if( ! $related_model_obj->ID()){
1976
-                    $this->_add_relation_to($related_model_obj, $relation_name);
1977
-                    $related_model_obj->save_new_cached_related_model_objs();
1978
-                    // }
1979
-                } else {
1980
-                    foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1981
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
1982
-                        // but ONLY if it DOES NOT exist in the DB
1983
-                        // if( ! $related_model_obj->ID()){
1984
-                        $this->_add_relation_to($related_model_obj, $relation_name);
1985
-                        $related_model_obj->save_new_cached_related_model_objs();
1986
-                        // }
1987
-                    }
1988
-                }
1989
-            }
1990
-        }
1991
-        return $id;
1992
-    }
1993
-
1994
-
1995
-    /**
1996
-     * for getting a model while instantiated.
1997
-     *
1998
-     * @return EEM_Base | EEM_CPT_Base
1999
-     * @throws ReflectionException
2000
-     * @throws InvalidArgumentException
2001
-     * @throws InvalidInterfaceException
2002
-     * @throws InvalidDataTypeException
2003
-     * @throws EE_Error
2004
-     */
2005
-    public function get_model()
2006
-    {
2007
-        if (! $this->_model) {
2008
-            $modelName    = self::_get_model_classname(get_class($this));
2009
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2010
-        } else {
2011
-            $this->_model->set_timezone($this->_timezone);
2012
-        }
2013
-        return $this->_model;
2014
-    }
2015
-
2016
-
2017
-    /**
2018
-     * @param $props_n_values
2019
-     * @param $classname
2020
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2021
-     * @throws ReflectionException
2022
-     * @throws InvalidArgumentException
2023
-     * @throws InvalidInterfaceException
2024
-     * @throws InvalidDataTypeException
2025
-     * @throws EE_Error
2026
-     */
2027
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2028
-    {
2029
-        // TODO: will not work for Term_Relationships because they have no PK!
2030
-        $primary_id_ref = self::_get_primary_key_name($classname);
2031
-        if (
2032
-            array_key_exists($primary_id_ref, $props_n_values)
2033
-            && ! empty($props_n_values[ $primary_id_ref ])
2034
-        ) {
2035
-            $id = $props_n_values[ $primary_id_ref ];
2036
-            return self::_get_model($classname)->get_from_entity_map($id);
2037
-        }
2038
-        return false;
2039
-    }
2040
-
2041
-
2042
-    /**
2043
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2044
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2045
-     * 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
2046
-     * we return false.
2047
-     *
2048
-     * @param array  $props_n_values    incoming array of properties and their values
2049
-     * @param string $classname         the classname of the child class
2050
-     * @param null   $timezone
2051
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the
2052
-     *                                  date_format and the second value is the time format
2053
-     * @return mixed (EE_Base_Class|bool)
2054
-     * @throws InvalidArgumentException
2055
-     * @throws InvalidInterfaceException
2056
-     * @throws InvalidDataTypeException
2057
-     * @throws EE_Error
2058
-     * @throws ReflectionException
2059
-     */
2060
-    protected static function _check_for_object($props_n_values, $classname, $timezone = '', $date_formats = [])
2061
-    {
2062
-        $existing = null;
2063
-        $model    = self::_get_model($classname, $timezone);
2064
-        if ($model->has_primary_key_field()) {
2065
-            $primary_id_ref = self::_get_primary_key_name($classname);
2066
-            if (
2067
-                array_key_exists($primary_id_ref, $props_n_values)
2068
-                && ! empty($props_n_values[ $primary_id_ref ])
2069
-            ) {
2070
-                $existing = $model->get_one_by_ID(
2071
-                    $props_n_values[ $primary_id_ref ]
2072
-                );
2073
-            }
2074
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2075
-            // no primary key on this model, but there's still a matching item in the DB
2076
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2077
-                self::_get_model($classname, $timezone)
2078
-                    ->get_index_primary_key_string($props_n_values)
2079
-            );
2080
-        }
2081
-        if ($existing) {
2082
-            // set date formats if present before setting values
2083
-            if (! empty($date_formats) && is_array($date_formats)) {
2084
-                $existing->set_date_format($date_formats[0]);
2085
-                $existing->set_time_format($date_formats[1]);
2086
-            } else {
2087
-                // set default formats for date and time
2088
-                $existing->set_date_format(get_option('date_format'));
2089
-                $existing->set_time_format(get_option('time_format'));
2090
-            }
2091
-            foreach ($props_n_values as $property => $field_value) {
2092
-                $existing->set($property, $field_value);
2093
-            }
2094
-            return $existing;
2095
-        }
2096
-        return false;
2097
-    }
2098
-
2099
-
2100
-    /**
2101
-     * Gets the EEM_*_Model for this class
2102
-     *
2103
-     * @access public now, as this is more convenient
2104
-     * @param      $classname
2105
-     * @param null $timezone
2106
-     * @return EEM_Base
2107
-     * @throws InvalidArgumentException
2108
-     * @throws InvalidInterfaceException
2109
-     * @throws InvalidDataTypeException
2110
-     * @throws EE_Error
2111
-     * @throws ReflectionException
2112
-     */
2113
-    protected static function _get_model($classname, $timezone = '')
2114
-    {
2115
-        // find model for this class
2116
-        if (! $classname) {
2117
-            throw new EE_Error(
2118
-                sprintf(
2119
-                    esc_html__(
2120
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2121
-                        'event_espresso'
2122
-                    ),
2123
-                    $classname
2124
-                )
2125
-            );
2126
-        }
2127
-        $modelName = self::_get_model_classname($classname);
2128
-        return self::_get_model_instance_with_name($modelName, $timezone);
2129
-    }
2130
-
2131
-
2132
-    /**
2133
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2134
-     *
2135
-     * @param string $model_classname
2136
-     * @param null   $timezone
2137
-     * @return EEM_Base
2138
-     * @throws ReflectionException
2139
-     * @throws InvalidArgumentException
2140
-     * @throws InvalidInterfaceException
2141
-     * @throws InvalidDataTypeException
2142
-     * @throws EE_Error
2143
-     */
2144
-    protected static function _get_model_instance_with_name($model_classname, $timezone = '')
2145
-    {
2146
-        $model_classname = str_replace('EEM_', '', $model_classname);
2147
-        $model           = EE_Registry::instance()->load_model($model_classname);
2148
-        $model->set_timezone($timezone);
2149
-        return $model;
2150
-    }
2151
-
2152
-
2153
-    /**
2154
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2155
-     * Also works if a model class's classname is provided (eg EE_Registration).
2156
-     *
2157
-     * @param string|null $model_name
2158
-     * @return string like EEM_Attendee
2159
-     */
2160
-    private static function _get_model_classname($model_name = '')
2161
-    {
2162
-        return strpos((string) $model_name, 'EE_') === 0
2163
-            ? str_replace('EE_', 'EEM_', $model_name)
2164
-            : 'EEM_' . $model_name;
2165
-    }
2166
-
2167
-
2168
-    /**
2169
-     * returns the name of the primary key attribute
2170
-     *
2171
-     * @param null $classname
2172
-     * @return string
2173
-     * @throws InvalidArgumentException
2174
-     * @throws InvalidInterfaceException
2175
-     * @throws InvalidDataTypeException
2176
-     * @throws EE_Error
2177
-     * @throws ReflectionException
2178
-     */
2179
-    protected static function _get_primary_key_name($classname = null)
2180
-    {
2181
-        if (! $classname) {
2182
-            throw new EE_Error(
2183
-                sprintf(
2184
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2185
-                    $classname
2186
-                )
2187
-            );
2188
-        }
2189
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2190
-    }
2191
-
2192
-
2193
-    /**
2194
-     * Gets the value of the primary key.
2195
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2196
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2197
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2198
-     *
2199
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2200
-     * @throws ReflectionException
2201
-     * @throws InvalidArgumentException
2202
-     * @throws InvalidInterfaceException
2203
-     * @throws InvalidDataTypeException
2204
-     * @throws EE_Error
2205
-     */
2206
-    public function ID()
2207
-    {
2208
-        $model = $this->get_model();
2209
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2210
-        if ($model->has_primary_key_field()) {
2211
-            return $this->_fields[ $model->primary_key_name() ];
2212
-        }
2213
-        return $model->get_index_primary_key_string($this->_fields);
2214
-    }
2215
-
2216
-
2217
-    /**
2218
-     * @param EE_Base_Class|int|string $otherModelObjectOrID
2219
-     * @param string                   $relation_name
2220
-     * @return bool
2221
-     * @throws EE_Error
2222
-     * @throws ReflectionException
2223
-     * @since   5.0.0.p
2224
-     */
2225
-    public function hasRelation($otherModelObjectOrID, string $relation_name): bool
2226
-    {
2227
-        $other_model = self::_get_model_instance_with_name(
2228
-            self::_get_model_classname($relation_name),
2229
-            $this->_timezone
2230
-        );
2231
-        $primary_key = $other_model->primary_key_name();
2232
-        /** @var EE_Base_Class $otherModelObject */
2233
-        $otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relation_name);
2234
-        return $this->count_related($relation_name, [[$primary_key => $otherModelObject->ID()]]) > 0;
2235
-    }
2236
-
2237
-
2238
-    /**
2239
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2240
-     * model is related to a group of events, the $relation_name should be 'Event', and should be a key in the EE
2241
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2242
-     *
2243
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2244
-     * @param string $relation_name                    eg 'Events','Question',etc.
2245
-     *                                                 an attendee to a group, you also want to specify which role they
2246
-     *                                                 will have in that group. So you would use this parameter to
2247
-     *                                                 specify array('role-column-name'=>'role-id')
2248
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2249
-     *                                                 allow you to further constrict the relation to being added.
2250
-     *                                                 However, keep in mind that the columns (keys) given must match a
2251
-     *                                                 column on the JOIN table and currently only the HABTM models
2252
-     *                                                 accept these additional conditions.  Also remember that if an
2253
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2254
-     *                                                 NEW row is created in the join table.
2255
-     * @param null   $cache_id
2256
-     * @return EE_Base_Class the object the relation was added to
2257
-     * @throws ReflectionException
2258
-     * @throws InvalidArgumentException
2259
-     * @throws InvalidInterfaceException
2260
-     * @throws InvalidDataTypeException
2261
-     * @throws EE_Error
2262
-     */
2263
-    public function _add_relation_to(
2264
-        $otherObjectModelObjectOrID,
2265
-        $relation_name,
2266
-        $extra_join_model_fields_n_values = [],
2267
-        $cache_id = null
2268
-    ) {
2269
-        $model = $this->get_model();
2270
-        // if this thing exists in the DB, save the relation to the DB
2271
-        if ($this->ID()) {
2272
-            $otherObject = $model->add_relationship_to(
2273
-                $this,
2274
-                $otherObjectModelObjectOrID,
2275
-                $relation_name,
2276
-                $extra_join_model_fields_n_values
2277
-            );
2278
-            // clear cache so future get_many_related and get_first_related() return new results.
2279
-            $this->clear_cache($relation_name, $otherObject, true);
2280
-            if ($otherObject instanceof EE_Base_Class) {
2281
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2282
-            }
2283
-        } else {
2284
-            // this thing doesn't exist in the DB,  so just cache it
2285
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2286
-                throw new EE_Error(
2287
-                    sprintf(
2288
-                        esc_html__(
2289
-                            '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',
2290
-                            'event_espresso'
2291
-                        ),
2292
-                        $otherObjectModelObjectOrID,
2293
-                        get_class($this)
2294
-                    )
2295
-                );
2296
-            }
2297
-            $otherObject = $otherObjectModelObjectOrID;
2298
-            $this->cache($relation_name, $otherObjectModelObjectOrID, $cache_id);
2299
-        }
2300
-        if ($otherObject instanceof EE_Base_Class) {
2301
-            // fix the reciprocal relation too
2302
-            if ($otherObject->ID()) {
2303
-                // its saved so assumed relations exist in the DB, so we can just
2304
-                // clear the cache so future queries use the updated info in the DB
2305
-                $otherObject->clear_cache(
2306
-                    $model->get_this_model_name(),
2307
-                    null,
2308
-                    true
2309
-                );
2310
-            } else {
2311
-                // it's not saved, so it caches relations like this
2312
-                $otherObject->cache($model->get_this_model_name(), $this);
2313
-            }
2314
-        }
2315
-        return $otherObject;
2316
-    }
2317
-
2318
-
2319
-    /**
2320
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2321
-     * model is related to a group of events, the $relation_name should be 'Events', and should be a key in the EE
2322
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2323
-     * from the cache
2324
-     *
2325
-     * @param mixed  $otherObjectModelObjectOrID
2326
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2327
-     *                to the DB yet
2328
-     * @param string $relation_name
2329
-     * @param array  $where_query
2330
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2331
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2332
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2333
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2334
-     *                deleted.
2335
-     * @return EE_Base_Class|bool   the related entity that was removed
2336
-     *                              or true if multiple entities removed
2337
-     *                              or false if nothing was cached
2338
-     * @throws ReflectionException
2339
-     * @throws InvalidArgumentException
2340
-     * @throws InvalidInterfaceException
2341
-     * @throws InvalidDataTypeException
2342
-     * @throws EE_Error
2343
-     */
2344
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relation_name, $where_query = [])
2345
-    {
2346
-        if ($this->ID()) {
2347
-            // if this exists in the DB, save the relation change to the DB too
2348
-            $otherObject = $this->get_model()->remove_relationship_to(
2349
-                $this,
2350
-                $otherObjectModelObjectOrID,
2351
-                $relation_name,
2352
-                $where_query
2353
-            );
2354
-            $this->clear_cache(
2355
-                $relation_name,
2356
-                $otherObject
2357
-            );
2358
-        } else {
2359
-            // this doesn't exist in the DB, just remove it from the cache
2360
-            $otherObject = $this->clear_cache(
2361
-                $relation_name,
2362
-                $otherObjectModelObjectOrID
2363
-            );
2364
-        }
2365
-        if ($otherObject instanceof EE_Base_Class) {
2366
-            $otherObject->clear_cache(
2367
-                $this->get_model()->get_this_model_name(),
2368
-                $this
2369
-            );
2370
-        }
2371
-        return $otherObject;
2372
-    }
2373
-
2374
-
2375
-    /**
2376
-     * Removes ALL the related things for the $relation_name.
2377
-     *
2378
-     * @param string $relation_name
2379
-     * @param array  $where_query_params @see
2380
-     *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2381
-     * @return EE_Base_Class
2382
-     * @throws ReflectionException
2383
-     * @throws InvalidArgumentException
2384
-     * @throws InvalidInterfaceException
2385
-     * @throws InvalidDataTypeException
2386
-     * @throws EE_Error
2387
-     */
2388
-    public function _remove_relations($relation_name, $where_query_params = [])
2389
-    {
2390
-        if ($this->ID()) {
2391
-            // if this exists in the DB, save the relation change to the DB too
2392
-            $otherObjects = $this->get_model()->remove_relations(
2393
-                $this,
2394
-                $relation_name,
2395
-                $where_query_params
2396
-            );
2397
-            $this->clear_cache(
2398
-                $relation_name,
2399
-                null,
2400
-                true
2401
-            );
2402
-        } else {
2403
-            // this doesn't exist in the DB, just remove it from the cache
2404
-            $otherObjects = $this->clear_cache(
2405
-                $relation_name,
2406
-                null,
2407
-                true
2408
-            );
2409
-        }
2410
-        if (is_array($otherObjects)) {
2411
-            foreach ($otherObjects as $otherObject) {
2412
-                $otherObject->clear_cache(
2413
-                    $this->get_model()->get_this_model_name(),
2414
-                    $this
2415
-                );
2416
-            }
2417
-        }
2418
-        return $otherObjects;
2419
-    }
2420
-
2421
-
2422
-    /**
2423
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2424
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2425
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2426
-     * because we want to get even deleted items etc.
2427
-     *
2428
-     * @param string      $relation_name key in the model's _model_relations array
2429
-     * @param array|null  $query_params  @see
2430
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2431
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2432
-     *                              keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2433
-     *                              results if you want IDs
2434
-     * @throws ReflectionException
2435
-     * @throws InvalidArgumentException
2436
-     * @throws InvalidInterfaceException
2437
-     * @throws InvalidDataTypeException
2438
-     * @throws EE_Error
2439
-     */
2440
-    public function get_many_related($relation_name, $query_params = [])
2441
-    {
2442
-        if ($this->ID()) {
2443
-            // this exists in the DB, so get the related things from either the cache or the DB
2444
-            // if there are query parameters, forget about caching the related model objects.
2445
-            if ($query_params) {
2446
-                $related_model_objects = $this->get_model()->get_all_related(
2447
-                    $this,
2448
-                    $relation_name,
2449
-                    $query_params
2450
-                );
2451
-            } else {
2452
-                // did we already cache the result of this query?
2453
-                $cached_results = $this->get_all_from_cache($relation_name);
2454
-                if (! $cached_results) {
2455
-                    $related_model_objects = $this->get_model()->get_all_related(
2456
-                        $this,
2457
-                        $relation_name,
2458
-                        $query_params
2459
-                    );
2460
-                    // if no query parameters were passed, then we got all the related model objects
2461
-                    // for that relation. We can cache them then.
2462
-                    foreach ($related_model_objects as $related_model_object) {
2463
-                        $this->cache($relation_name, $related_model_object);
2464
-                    }
2465
-                } else {
2466
-                    $related_model_objects = $cached_results;
2467
-                }
2468
-            }
2469
-        } else {
2470
-            // this doesn't exist in the DB, so just get the related things from the cache
2471
-            $related_model_objects = $this->get_all_from_cache($relation_name);
2472
-        }
2473
-        return $related_model_objects;
2474
-    }
2475
-
2476
-
2477
-    /**
2478
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2479
-     * unless otherwise specified in the $query_params
2480
-     *
2481
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2482
-     * @param array  $query_params   @see
2483
-     *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2484
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2485
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2486
-     *                               that by the setting $distinct to TRUE;
2487
-     * @return int
2488
-     * @throws ReflectionException
2489
-     * @throws InvalidArgumentException
2490
-     * @throws InvalidInterfaceException
2491
-     * @throws InvalidDataTypeException
2492
-     * @throws EE_Error
2493
-     */
2494
-    public function count_related($relation_name, $query_params = [], $field_to_count = null, $distinct = false)
2495
-    {
2496
-        return $this->get_model()->count_related(
2497
-            $this,
2498
-            $relation_name,
2499
-            $query_params,
2500
-            $field_to_count,
2501
-            $distinct
2502
-        );
2503
-    }
2504
-
2505
-
2506
-    /**
2507
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2508
-     * Note: ignores default_where_conditions by default, 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
2512
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2513
-     * @param string $field_to_sum  name of field to count by.
2514
-     *                              By default, uses primary key
2515
-     *                              (which doesn't make much sense, so you should probably change it)
2516
-     * @return int
2517
-     * @throws ReflectionException
2518
-     * @throws InvalidArgumentException
2519
-     * @throws InvalidInterfaceException
2520
-     * @throws InvalidDataTypeException
2521
-     * @throws EE_Error
2522
-     */
2523
-    public function sum_related($relation_name, $query_params = [], $field_to_sum = null)
2524
-    {
2525
-        return $this->get_model()->sum_related(
2526
-            $this,
2527
-            $relation_name,
2528
-            $query_params,
2529
-            $field_to_sum
2530
-        );
2531
-    }
2532
-
2533
-
2534
-    /**
2535
-     * Gets the first (ie, one) related model object of the specified type.
2536
-     *
2537
-     * @param string $relation_name key in the model's _model_relations array
2538
-     * @param array  $query_params  @see
2539
-     *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2540
-     * @return EE_Base_Class|null (not an array, a single object)
2541
-     * @throws ReflectionException
2542
-     * @throws InvalidArgumentException
2543
-     * @throws InvalidInterfaceException
2544
-     * @throws InvalidDataTypeException
2545
-     * @throws EE_Error
2546
-     */
2547
-    public function get_first_related(string $relation_name, array $query_params = []): ?EE_Base_Class
2548
-    {
2549
-        $model = $this->get_model();
2550
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2551
-            // if they've provided some query parameters, don't bother trying to cache the result
2552
-            // also make sure we're not caching the result of get_first_related
2553
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2554
-            if (
2555
-                $query_params
2556
-                || ! $model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation
2557
-            ) {
2558
-                $related_model_object = $model->get_first_related(
2559
-                    $this,
2560
-                    $relation_name,
2561
-                    $query_params
2562
-                );
2563
-            } else {
2564
-                // first, check if we've already cached the result of this query
2565
-                $cached_result = $this->get_one_from_cache($relation_name);
2566
-                if (! $cached_result) {
2567
-                    $related_model_object = $model->get_first_related(
2568
-                        $this,
2569
-                        $relation_name,
2570
-                        $query_params
2571
-                    );
2572
-                    $this->cache($relation_name, $related_model_object);
2573
-                } else {
2574
-                    $related_model_object = $cached_result;
2575
-                }
2576
-            }
2577
-        } else {
2578
-            $related_model_object = null;
2579
-            // this doesn't exist in the Db,
2580
-            // but maybe the relation is of type belongs to, and so the related thing might
2581
-            if ($model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation) {
2582
-                $related_model_object = $model->get_first_related(
2583
-                    $this,
2584
-                    $relation_name,
2585
-                    $query_params
2586
-                );
2587
-            }
2588
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2589
-            // just get what's cached on this object
2590
-            if (! $related_model_object) {
2591
-                $related_model_object = $this->get_one_from_cache($relation_name);
2592
-            }
2593
-        }
2594
-        return $related_model_object;
2595
-    }
2596
-
2597
-
2598
-    /**
2599
-     * Does a delete on all related objects of type $relation_name and removes
2600
-     * the current model object's relation to them. If they can't be deleted (because
2601
-     * of blocking related model objects) does nothing. If the related model objects are
2602
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2603
-     * If this model object doesn't exist yet in the DB, just removes its related things
2604
-     *
2605
-     * @param string $relation_name
2606
-     * @param array  $query_params @see
2607
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2608
-     * @return int how many deleted
2609
-     * @throws ReflectionException
2610
-     * @throws InvalidArgumentException
2611
-     * @throws InvalidInterfaceException
2612
-     * @throws InvalidDataTypeException
2613
-     * @throws EE_Error
2614
-     */
2615
-    public function delete_related($relation_name, $query_params = [])
2616
-    {
2617
-        if ($this->ID()) {
2618
-            $count = $this->get_model()->delete_related(
2619
-                $this,
2620
-                $relation_name,
2621
-                $query_params
2622
-            );
2623
-        } else {
2624
-            $count = count($this->get_all_from_cache($relation_name));
2625
-            $this->clear_cache($relation_name, null, true);
2626
-        }
2627
-        return $count;
2628
-    }
2629
-
2630
-
2631
-    /**
2632
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relation_name and removes
2633
-     * the current model object's relation to them. If they can't be deleted (because
2634
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2635
-     * If the related thing isn't a soft-deletable model object, this function is identical
2636
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2637
-     *
2638
-     * @param string $relation_name
2639
-     * @param array  $query_params @see
2640
-     *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2641
-     * @return int how many deleted (including those soft deleted)
2642
-     * @throws ReflectionException
2643
-     * @throws InvalidArgumentException
2644
-     * @throws InvalidInterfaceException
2645
-     * @throws InvalidDataTypeException
2646
-     * @throws EE_Error
2647
-     */
2648
-    public function delete_related_permanently($relation_name, $query_params = [])
2649
-    {
2650
-        $count = $this->ID()
2651
-            ? $this->get_model()->delete_related_permanently(
2652
-                $this,
2653
-                $relation_name,
2654
-                $query_params
2655
-            )
2656
-            : count($this->get_all_from_cache($relation_name));
2657
-
2658
-        $this->clear_cache($relation_name, null, true);
2659
-        return $count;
2660
-    }
2661
-
2662
-
2663
-    /**
2664
-     * is_set
2665
-     * Just a simple utility function children can use for checking if property exists
2666
-     *
2667
-     * @access  public
2668
-     * @param string $field_name property to check
2669
-     * @return bool                              TRUE if existing,FALSE if not.
2670
-     */
2671
-    public function is_set($field_name)
2672
-    {
2673
-        return isset($this->_fields[ $field_name ]);
2674
-    }
2675
-
2676
-
2677
-    /**
2678
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2679
-     * EE_Error exception if they don't
2680
-     *
2681
-     * @param mixed (string|array) $properties properties to check
2682
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2683
-     * @throws EE_Error
2684
-     */
2685
-    protected function _property_exists($properties)
2686
-    {
2687
-        foreach ((array) $properties as $property_name) {
2688
-            // first make sure this property exists
2689
-            if (! $this->_fields[ $property_name ]) {
2690
-                throw new EE_Error(
2691
-                    sprintf(
2692
-                        esc_html__(
2693
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2694
-                            'event_espresso'
2695
-                        ),
2696
-                        $property_name
2697
-                    )
2698
-                );
2699
-            }
2700
-        }
2701
-        return true;
2702
-    }
2703
-
2704
-
2705
-    /**
2706
-     * This simply returns an array of model fields for this object
2707
-     *
2708
-     * @return array
2709
-     * @throws ReflectionException
2710
-     * @throws InvalidArgumentException
2711
-     * @throws InvalidInterfaceException
2712
-     * @throws InvalidDataTypeException
2713
-     * @throws EE_Error
2714
-     */
2715
-    public function model_field_array()
2716
-    {
2717
-        $fields     = $this->get_model()->field_settings(false);
2718
-        $properties = [];
2719
-        // remove prepended underscore
2720
-        foreach ($fields as $field_name => $settings) {
2721
-            $properties[ $field_name ] = $this->get($field_name);
2722
-        }
2723
-        return $properties;
2724
-    }
2725
-
2726
-
2727
-    /**
2728
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2729
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2730
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2731
-     * Instead of requiring a plugin to extend the EE_Base_Class
2732
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2733
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2734
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2735
-     * and accepts 2 arguments: the object on which the function was called,
2736
-     * and an array of the original arguments passed to the function.
2737
-     * Whatever their callback function returns will be returned by this function.
2738
-     * Example: in functions.php (or in a plugin):
2739
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2740
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2741
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2742
-     *          return $previousReturnValue.$returnString;
2743
-     *      }
2744
-     * require('EE_Answer.class.php');
2745
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2746
-     *      ->my_callback('monkeys',100);
2747
-     * // will output "you called my_callback! and passed args:monkeys,100"
2748
-     *
2749
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2750
-     * @param array  $args       array of original arguments passed to the function
2751
-     * @return mixed whatever the plugin which calls add_filter decides
2752
-     * @throws EE_Error
2753
-     */
2754
-    public function __call($methodName, $args)
2755
-    {
2756
-        $className = get_class($this);
2757
-        $tagName   = "FHEE__{$className}__{$methodName}";
2758
-        if (! has_filter($tagName)) {
2759
-            throw new EE_Error(
2760
-                sprintf(
2761
-                    esc_html__(
2762
-                        "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;}",
2763
-                        'event_espresso'
2764
-                    ),
2765
-                    $methodName,
2766
-                    $className,
2767
-                    $tagName
2768
-                )
2769
-            );
2770
-        }
2771
-        return apply_filters($tagName, null, $this, $args);
2772
-    }
2773
-
2774
-
2775
-    /**
2776
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2777
-     * A $previous_value can be specified in case there are many meta rows with the same key
2778
-     *
2779
-     * @param string $meta_key
2780
-     * @param mixed  $meta_value
2781
-     * @param mixed  $previous_value
2782
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2783
-     *                  NOTE: if the values haven't changed, returns 0
2784
-     * @throws InvalidArgumentException
2785
-     * @throws InvalidInterfaceException
2786
-     * @throws InvalidDataTypeException
2787
-     * @throws EE_Error
2788
-     * @throws ReflectionException
2789
-     */
2790
-    public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2791
-    {
2792
-        $query_params = [
2793
-            [
2794
-                'EXM_key'  => $meta_key,
2795
-                'OBJ_ID'   => $this->ID(),
2796
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2797
-            ],
2798
-        ];
2799
-        if ($previous_value !== null) {
2800
-            $query_params[0]['EXM_value'] = $meta_value;
2801
-        }
2802
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2803
-        if (! $existing_rows_like_that) {
2804
-            return $this->add_extra_meta($meta_key, $meta_value);
2805
-        }
2806
-        foreach ($existing_rows_like_that as $existing_row) {
2807
-            $existing_row->save(['EXM_value' => $meta_value]);
2808
-        }
2809
-        return count($existing_rows_like_that);
2810
-    }
2811
-
2812
-
2813
-    /**
2814
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2815
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2816
-     * extra meta row was entered, false if not
2817
-     *
2818
-     * @param string $meta_key
2819
-     * @param mixed  $meta_value
2820
-     * @param bool   $unique
2821
-     * @return bool
2822
-     * @throws InvalidArgumentException
2823
-     * @throws InvalidInterfaceException
2824
-     * @throws InvalidDataTypeException
2825
-     * @throws EE_Error
2826
-     * @throws ReflectionException
2827
-     */
2828
-    public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2829
-    {
2830
-        if ($unique) {
2831
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2832
-                [
2833
-                    [
2834
-                        'EXM_key'  => $meta_key,
2835
-                        'OBJ_ID'   => $this->ID(),
2836
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2837
-                    ],
2838
-                ]
2839
-            );
2840
-            if ($existing_extra_meta) {
2841
-                return false;
2842
-            }
2843
-        }
2844
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2845
-            [
2846
-                'EXM_key'   => $meta_key,
2847
-                'EXM_value' => $meta_value,
2848
-                'OBJ_ID'    => $this->ID(),
2849
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2850
-            ]
2851
-        );
2852
-        $new_extra_meta->save();
2853
-        return true;
2854
-    }
2855
-
2856
-
2857
-    /**
2858
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2859
-     * is specified, only deletes extra meta records with that value.
2860
-     *
2861
-     * @param string $meta_key
2862
-     * @param mixed  $meta_value
2863
-     * @return int number of extra meta rows deleted
2864
-     * @throws InvalidArgumentException
2865
-     * @throws InvalidInterfaceException
2866
-     * @throws InvalidDataTypeException
2867
-     * @throws EE_Error
2868
-     * @throws ReflectionException
2869
-     */
2870
-    public function delete_extra_meta(string $meta_key, $meta_value = null)
2871
-    {
2872
-        $query_params = [
2873
-            [
2874
-                'EXM_key'  => $meta_key,
2875
-                'OBJ_ID'   => $this->ID(),
2876
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2877
-            ],
2878
-        ];
2879
-        if ($meta_value !== null) {
2880
-            $query_params[0]['EXM_value'] = $meta_value;
2881
-        }
2882
-        return EEM_Extra_Meta::instance()->delete($query_params);
2883
-    }
2884
-
2885
-
2886
-    /**
2887
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2888
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2889
-     * You can specify $default is case you haven't found the extra meta
2890
-     *
2891
-     * @param string     $meta_key
2892
-     * @param bool       $single
2893
-     * @param mixed      $default if we don't find anything, what should we return?
2894
-     * @param array|null $extra_where
2895
-     * @return mixed single value if $single; array if ! $single
2896
-     * @throws ReflectionException
2897
-     * @throws EE_Error
2898
-     */
2899
-    public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2900
-    {
2901
-        $query_params = [$extra_where + ['EXM_key' => $meta_key]];
2902
-        if ($single) {
2903
-            $result = $this->get_first_related('Extra_Meta', $query_params);
2904
-            if ($result instanceof EE_Extra_Meta) {
2905
-                return $result->value();
2906
-            }
2907
-        } else {
2908
-            $results = $this->get_many_related('Extra_Meta', $query_params);
2909
-            if ($results) {
2910
-                $values = [];
2911
-                foreach ($results as $result) {
2912
-                    if ($result instanceof EE_Extra_Meta) {
2913
-                        $values[ $result->ID() ] = $result->value();
2914
-                    }
2915
-                }
2916
-                return $values;
2917
-            }
2918
-        }
2919
-        // if nothing discovered yet return default.
2920
-        return apply_filters(
2921
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2922
-            $default,
2923
-            $meta_key,
2924
-            $single,
2925
-            $this
2926
-        );
2927
-    }
2928
-
2929
-
2930
-    /**
2931
-     * Returns a simple array of all the extra meta associated with this model object.
2932
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2933
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2934
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2935
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2936
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2937
-     * finally the extra meta's value as each sub-value. (eg
2938
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2939
-     *
2940
-     * @param bool $one_of_each_key
2941
-     * @return array
2942
-     * @throws ReflectionException
2943
-     * @throws InvalidArgumentException
2944
-     * @throws InvalidInterfaceException
2945
-     * @throws InvalidDataTypeException
2946
-     * @throws EE_Error
2947
-     */
2948
-    public function all_extra_meta_array(bool $one_of_each_key = true): array
2949
-    {
2950
-        $return_array = [];
2951
-        if ($one_of_each_key) {
2952
-            $extra_meta_objs = $this->get_many_related(
2953
-                'Extra_Meta',
2954
-                ['group_by' => 'EXM_key']
2955
-            );
2956
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2957
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2958
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2959
-                }
2960
-            }
2961
-        } else {
2962
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2963
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2964
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2965
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2966
-                        $return_array[ $extra_meta_obj->key() ] = [];
2967
-                    }
2968
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2969
-                }
2970
-            }
2971
-        }
2972
-        return $return_array;
2973
-    }
2974
-
2975
-
2976
-    /**
2977
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2978
-     *
2979
-     * @return string
2980
-     * @throws ReflectionException
2981
-     * @throws InvalidArgumentException
2982
-     * @throws InvalidInterfaceException
2983
-     * @throws InvalidDataTypeException
2984
-     * @throws EE_Error
2985
-     */
2986
-    public function name()
2987
-    {
2988
-        // find a field that's not a text field
2989
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2990
-        if ($field_we_can_use) {
2991
-            return $this->get($field_we_can_use->get_name());
2992
-        }
2993
-        $first_few_properties = $this->model_field_array();
2994
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
2995
-        $name_parts           = [];
2996
-        foreach ($first_few_properties as $name => $value) {
2997
-            $name_parts[] = "$name:$value";
2998
-        }
2999
-        return implode(',', $name_parts);
3000
-    }
3001
-
3002
-
3003
-    /**
3004
-     * in_entity_map
3005
-     * Checks if this model object has been proven to already be in the entity map
3006
-     *
3007
-     * @return boolean
3008
-     * @throws ReflectionException
3009
-     * @throws InvalidArgumentException
3010
-     * @throws InvalidInterfaceException
3011
-     * @throws InvalidDataTypeException
3012
-     * @throws EE_Error
3013
-     */
3014
-    public function in_entity_map()
3015
-    {
3016
-        // well, if we looked, did we find it in the entity map?
3017
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3018
-    }
3019
-
3020
-
3021
-    /**
3022
-     * refresh_from_db
3023
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3024
-     *
3025
-     * @throws ReflectionException
3026
-     * @throws InvalidArgumentException
3027
-     * @throws InvalidInterfaceException
3028
-     * @throws InvalidDataTypeException
3029
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3030
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3031
-     */
3032
-    public function refresh_from_db()
3033
-    {
3034
-        if ($this->ID() && $this->in_entity_map()) {
3035
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3036
-        } else {
3037
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3038
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3039
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3040
-            // absolutely nothing in it for this ID
3041
-            if (WP_DEBUG) {
3042
-                throw new EE_Error(
3043
-                    sprintf(
3044
-                        esc_html__(
3045
-                            '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.',
3046
-                            'event_espresso'
3047
-                        ),
3048
-                        $this->ID(),
3049
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3050
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3051
-                    )
3052
-                );
3053
-            }
3054
-        }
3055
-    }
3056
-
3057
-
3058
-    /**
3059
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3060
-     *
3061
-     * @param EE_Model_Field_Base[] $fields
3062
-     * @param string                $new_value_sql
3063
-     *          example: 'column_name=123',
3064
-     *          or 'column_name=column_name+1',
3065
-     *          or 'column_name= CASE
3066
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3067
-     *          THEN `column_name` + 5
3068
-     *          ELSE `column_name`
3069
-     *          END'
3070
-     *          Also updates $field on this model object with the latest value from the database.
3071
-     * @return bool
3072
-     * @throws EE_Error
3073
-     * @throws InvalidArgumentException
3074
-     * @throws InvalidDataTypeException
3075
-     * @throws InvalidInterfaceException
3076
-     * @throws ReflectionException
3077
-     * @since 4.9.80.p
3078
-     */
3079
-    protected function updateFieldsInDB($fields, $new_value_sql)
3080
-    {
3081
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3082
-        // if it wasn't even there to start off.
3083
-        if (! $this->ID()) {
3084
-            $this->save();
3085
-        }
3086
-        global $wpdb;
3087
-        if (empty($fields)) {
3088
-            throw new InvalidArgumentException(
3089
-                esc_html__(
3090
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3091
-                    'event_espresso'
3092
-                )
3093
-            );
3094
-        }
3095
-        $first_field = reset($fields);
3096
-        $table_alias = $first_field->get_table_alias();
3097
-        foreach ($fields as $field) {
3098
-            if ($table_alias !== $field->get_table_alias()) {
3099
-                throw new InvalidArgumentException(
3100
-                    sprintf(
3101
-                        esc_html__(
3102
-                        // @codingStandardsIgnoreStart
3103
-                            '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.',
3104
-                            // @codingStandardsIgnoreEnd
3105
-                            'event_espresso'
3106
-                        ),
3107
-                        $table_alias,
3108
-                        $field->get_table_alias()
3109
-                    )
3110
-                );
3111
-            }
3112
-        }
3113
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3114
-        $table_obj      = $this->get_model()->get_table_obj_by_alias($table_alias);
3115
-        $table_pk_value = $this->ID();
3116
-        $table_name     = $table_obj->get_table_name();
3117
-        if ($table_obj instanceof EE_Secondary_Table) {
3118
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3119
-        } else {
3120
-            $table_pk_field_name = $table_obj->get_pk_column();
3121
-        }
3122
-
3123
-        $query  =
3124
-            "UPDATE `{$table_name}`
18
+	/**
19
+	 * @var EEM_Base|null
20
+	 */
21
+	protected $_model = null;
22
+
23
+	/**
24
+	 * This is an array of the original properties and values provided during construction
25
+	 * of this model object. (keys are model field names, values are their values).
26
+	 * This list is important to remember so that when we are merging data from the db, we know
27
+	 * which values to override and which to not override.
28
+	 */
29
+	protected ?array $_props_n_values_provided_in_constructor = null;
30
+
31
+	/**
32
+	 * Timezone
33
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
34
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
35
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
36
+	 * access to it.
37
+	 */
38
+	protected string $_timezone = '';
39
+
40
+	/**
41
+	 * date format
42
+	 * pattern or format for displaying dates
43
+	 */
44
+	protected string $_dt_frmt = '';
45
+
46
+	/**
47
+	 * time format
48
+	 * pattern or format for displaying time
49
+	 */
50
+	protected string $_tm_frmt = '';
51
+
52
+	/**
53
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
54
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
55
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
56
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
57
+	 */
58
+	protected array $_cached_properties = [];
59
+
60
+	/**
61
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
62
+	 * single
63
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
64
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
65
+	 * all others have an array)
66
+	 */
67
+	protected array $_model_relations = [];
68
+
69
+	/**
70
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
71
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
72
+	 */
73
+	protected array $_fields = [];
74
+
75
+	/**
76
+	 * indicating whether or not this model object is intended to ever be saved
77
+	 * For example, we might create model objects intended to only be used for the duration
78
+	 * of this request and to be thrown away, and if they were accidentally saved
79
+	 * it would be a bug.
80
+	 */
81
+	protected bool $_allow_persist = true;
82
+
83
+	/**
84
+	 * indicating whether or not this model object's properties have changed since construction
85
+	 */
86
+	protected bool $_has_changes = false;
87
+
88
+	/**
89
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
90
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
91
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
92
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
93
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
94
+	 * array as:
95
+	 * array(
96
+	 *  'Registration_Count' => 24
97
+	 * );
98
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
99
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
100
+	 * info)
101
+	 */
102
+	protected array $custom_selection_results = [];
103
+
104
+
105
+	/**
106
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
107
+	 * play nice
108
+	 *
109
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
110
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
111
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
112
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
113
+	 *                                                         corresponding db model or not.
114
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
115
+	 *                                                         be in when instantiating a EE_Base_Class object.
116
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
117
+	 *                                                         value is the date_format and second value is the time
118
+	 *                                                         format.
119
+	 * @throws InvalidArgumentException
120
+	 * @throws InvalidInterfaceException
121
+	 * @throws InvalidDataTypeException
122
+	 * @throws EE_Error
123
+	 * @throws ReflectionException
124
+	 */
125
+	protected function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
126
+	{
127
+		$className = get_class($this);
128
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
129
+		$model        = $this->get_model();
130
+		$model_fields = $model->field_settings();
131
+		// ensure $fieldValues is an array
132
+		$fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
133
+		// verify client code has not passed any invalid field names
134
+		foreach ($fieldValues as $field_name => $field_value) {
135
+			if (! isset($model_fields[ $field_name ])) {
136
+				throw new EE_Error(
137
+					sprintf(
138
+						esc_html__(
139
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
140
+							'event_espresso'
141
+						),
142
+						$field_name,
143
+						get_class($this),
144
+						implode(', ', array_keys($model_fields))
145
+					)
146
+				);
147
+			}
148
+		}
149
+
150
+		$date_format     = null;
151
+		$time_format     = null;
152
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
153
+		if (! empty($date_formats) && is_array($date_formats)) {
154
+			[$date_format, $time_format] = $date_formats;
155
+		}
156
+		$this->set_date_format($date_format);
157
+		$this->set_time_format($time_format);
158
+		// if db model is instantiating
159
+		foreach ($model_fields as $fieldName => $field) {
160
+			if ($bydb) {
161
+				// client code has indicated these field values are from the database
162
+				$this->set_from_db(
163
+					$fieldName,
164
+					$fieldValues[ $fieldName ] ?? null
165
+				);
166
+			} else {
167
+				// we're constructing a brand new instance of the model object.
168
+				// Generally, this means we'll need to do more field validation
169
+				$this->set(
170
+					$fieldName,
171
+					$fieldValues[ $fieldName ] ?? null,
172
+					true
173
+				);
174
+			}
175
+		}
176
+		// remember what values were passed to this constructor
177
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
178
+		// remember in entity mapper
179
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
180
+			$model->add_to_entity_map($this);
181
+		}
182
+		// setup all the relations
183
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
184
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
185
+				$this->_model_relations[ $relation_name ] = null;
186
+			} else {
187
+				$this->_model_relations[ $relation_name ] = [];
188
+			}
189
+		}
190
+		/**
191
+		 * Action done at the end of each model object construction
192
+		 *
193
+		 * @param EE_Base_Class $this the model object just created
194
+		 */
195
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
196
+	}
197
+
198
+
199
+	/**
200
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
201
+	 *
202
+	 * @return boolean
203
+	 */
204
+	public function allow_persist()
205
+	{
206
+		return $this->_allow_persist;
207
+	}
208
+
209
+
210
+	/**
211
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
212
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
213
+	 * you got new information that somehow made you change your mind.
214
+	 *
215
+	 * @param boolean $allow_persist
216
+	 * @return boolean
217
+	 */
218
+	public function set_allow_persist($allow_persist)
219
+	{
220
+		return $this->_allow_persist = $allow_persist;
221
+	}
222
+
223
+
224
+	/**
225
+	 * Gets the field's original value when this object was constructed during this request.
226
+	 * This can be helpful when determining if a model object has changed or not
227
+	 *
228
+	 * @param string $field_name
229
+	 * @return mixed|null
230
+	 * @throws ReflectionException
231
+	 * @throws InvalidArgumentException
232
+	 * @throws InvalidInterfaceException
233
+	 * @throws InvalidDataTypeException
234
+	 * @throws EE_Error
235
+	 */
236
+	public function get_original($field_name)
237
+	{
238
+		if (
239
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
240
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
241
+		) {
242
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
243
+		}
244
+		return null;
245
+	}
246
+
247
+
248
+	/**
249
+	 * @param EE_Base_Class $obj
250
+	 * @return string
251
+	 */
252
+	public function get_class($obj)
253
+	{
254
+		return get_class($obj);
255
+	}
256
+
257
+
258
+	/**
259
+	 * Overrides parent because parent expects old models.
260
+	 * This also doesn't do any validation, and won't work for serialized arrays
261
+	 *
262
+	 * @param string $field_name
263
+	 * @param mixed  $field_value
264
+	 * @param bool   $use_default
265
+	 * @throws InvalidArgumentException
266
+	 * @throws InvalidInterfaceException
267
+	 * @throws InvalidDataTypeException
268
+	 * @throws EE_Error
269
+	 * @throws ReflectionException
270
+	 * @throws Exception
271
+	 */
272
+	public function set(string $field_name, $field_value, bool $use_default = false)
273
+	{
274
+		// if not using default and nothing has changed, and object has already been setup (has ID),
275
+		// then don't do anything
276
+		if (
277
+			! $use_default
278
+			&& $this->_fields[ $field_name ] === $field_value
279
+			&& $this->ID()
280
+		) {
281
+			return;
282
+		}
283
+		$model              = $this->get_model();
284
+		$this->_has_changes = true;
285
+		$field_obj          = $model->field_settings_for($field_name);
286
+		if (! $field_obj instanceof EE_Model_Field_Base) {
287
+			throw new EE_Error(
288
+				sprintf(
289
+					esc_html__(
290
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
291
+						'event_espresso'
292
+					),
293
+					$field_name
294
+				)
295
+			);
296
+		}
297
+		// if ( method_exists( $field_obj, 'set_timezone' )) {
298
+		if ($field_obj instanceof EE_Datetime_Field) {
299
+			$field_obj->set_timezone($this->_timezone);
300
+			$field_obj->set_date_format($this->_dt_frmt);
301
+			$field_obj->set_time_format($this->_tm_frmt);
302
+		}
303
+
304
+		// should the value be null?
305
+		$value = $field_value === null && ($use_default || ! $field_obj->is_nullable())
306
+			? $field_obj->get_default_value()
307
+			: $field_value;
308
+
309
+		$this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
310
+
311
+		// if we're not in the constructor...
312
+		// now check if what we set was a primary key
313
+		if (
314
+			// note: props_n_values_provided_in_constructor is only set at the END of the constructor
315
+			$this->_props_n_values_provided_in_constructor
316
+			&& $field_value
317
+			&& $field_name === $model->primary_key_name()
318
+		) {
319
+			// if so, we want all this object's fields to be filled either with
320
+			// what we've explicitly set on this model
321
+			// or what we have in the db
322
+			// echo "setting primary key!";
323
+			$fields_on_model = self::_get_model(get_class($this))->field_settings();
324
+			$obj_in_db       = self::_get_model(get_class($this))->get_one_by_ID($field_value);
325
+			foreach ($fields_on_model as $field_obj) {
326
+				if (
327
+					! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
328
+					&& $field_obj->get_name() !== $field_name
329
+				) {
330
+					$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
331
+				}
332
+			}
333
+			// oh this model object has an ID? well make sure its in the entity mapper
334
+			$model->add_to_entity_map($this);
335
+		}
336
+		// let's unset any cache for this field_name from the $_cached_properties property.
337
+		$this->_clear_cached_property($field_name);
338
+	}
339
+
340
+
341
+	/**
342
+	 * Overrides parent because parent expects old models.
343
+	 * This also doesn't do any validation, and won't work for serialized arrays
344
+	 *
345
+	 * @param string $field_name
346
+	 * @param mixed  $field_value_from_db
347
+	 * @throws ReflectionException
348
+	 * @throws InvalidArgumentException
349
+	 * @throws InvalidInterfaceException
350
+	 * @throws InvalidDataTypeException
351
+	 * @throws EE_Error
352
+	 */
353
+	public function set_from_db(string $field_name, $field_value_from_db)
354
+	{
355
+		$field_obj = $this->get_model()->field_settings_for($field_name);
356
+		if ($field_obj instanceof EE_Model_Field_Base) {
357
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
358
+			// eg, a CPT model object could have an entry in the posts table, but no
359
+			// entry in the meta table. Meaning that all its columns in the meta table
360
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
361
+			if ($field_value_from_db === null) {
362
+				if ($field_obj->is_nullable()) {
363
+					// if the field allows nulls, then let it be null
364
+					$field_value = null;
365
+				} else {
366
+					$field_value = $field_obj->get_default_value();
367
+				}
368
+			} else {
369
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
370
+			}
371
+			$this->_fields[ $field_name ] = $field_value;
372
+			$this->_clear_cached_property($field_name);
373
+		}
374
+	}
375
+
376
+
377
+	/**
378
+	 * Set custom select values for model.
379
+	 *
380
+	 * @param array $custom_select_values
381
+	 */
382
+	public function setCustomSelectsValues(array $custom_select_values)
383
+	{
384
+		$this->custom_selection_results = $custom_select_values;
385
+	}
386
+
387
+
388
+	/**
389
+	 * Returns the custom select value for the provided alias if its set.
390
+	 * If not set, returns null.
391
+	 *
392
+	 * @param string $alias
393
+	 * @return string|int|float|null
394
+	 */
395
+	public function getCustomSelect($alias)
396
+	{
397
+		return $this->custom_selection_results[ $alias ] ?? null;
398
+	}
399
+
400
+
401
+	/**
402
+	 * This sets the field value on the db column if it exists for the given $column_name or
403
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
404
+	 *
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
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
414
+	 */
415
+	public function set_field_or_extra_meta($field_name, $field_value)
416
+	{
417
+		if ($this->get_model()->has_field($field_name)) {
418
+			$this->set($field_name, $field_value);
419
+			return true;
420
+		}
421
+		// ensure this object is saved first so that extra meta can be properly related.
422
+		$this->save();
423
+		return $this->update_extra_meta($field_name, $field_value);
424
+	}
425
+
426
+
427
+	/**
428
+	 * This retrieves the value of the db column set on this class or if that's not present
429
+	 * it will attempt to retrieve from extra_meta if found.
430
+	 * Example Usage:
431
+	 * Via EE_Message child class:
432
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
433
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
434
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
435
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
436
+	 * value for those extra fields dynamically via the EE_message object.
437
+	 *
438
+	 * @param string $field_name expecting the fully qualified field name.
439
+	 * @return mixed|null  value for the field if found.  null if not found.
440
+	 * @throws ReflectionException
441
+	 * @throws InvalidArgumentException
442
+	 * @throws InvalidInterfaceException
443
+	 * @throws InvalidDataTypeException
444
+	 * @throws EE_Error
445
+	 */
446
+	public function get_field_or_extra_meta($field_name)
447
+	{
448
+		if ($this->get_model()->has_field($field_name)) {
449
+			$column_value = $this->get($field_name);
450
+		} else {
451
+			// This isn't a column in the main table, let's see if it is in the extra meta.
452
+			$column_value = $this->get_extra_meta($field_name, true, null);
453
+		}
454
+		return $column_value;
455
+	}
456
+
457
+
458
+	/**
459
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
460
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
461
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
462
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
463
+	 *
464
+	 * @access public
465
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
466
+	 * @return void
467
+	 * @throws InvalidArgumentException
468
+	 * @throws InvalidInterfaceException
469
+	 * @throws InvalidDataTypeException
470
+	 * @throws EE_Error
471
+	 * @throws ReflectionException
472
+	 * @throws Exception
473
+	 */
474
+	public function set_timezone($timezone = '')
475
+	{
476
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
477
+		// make sure we clear all cached properties because they won't be relevant now
478
+		$this->_clear_cached_properties();
479
+		// make sure we update field settings and the date for all EE_Datetime_Fields
480
+		$model_fields = $this->get_model()->field_settings(false);
481
+		foreach ($model_fields as $field_name => $field_obj) {
482
+			if ($field_obj instanceof EE_Datetime_Field) {
483
+				$field_obj->set_timezone($this->_timezone);
484
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
485
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
486
+				}
487
+			}
488
+		}
489
+	}
490
+
491
+
492
+	/**
493
+	 * This just returns whatever is set for the current timezone.
494
+	 *
495
+	 * @access public
496
+	 * @return string timezone string
497
+	 */
498
+	public function get_timezone()
499
+	{
500
+		return $this->_timezone;
501
+	}
502
+
503
+
504
+	/**
505
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
506
+	 * internally instead of wp set date format options
507
+	 *
508
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
509
+	 * @since 4.6
510
+	 */
511
+	public function set_date_format(?string $format)
512
+	{
513
+		$this->_dt_frmt = new DateFormat($format);
514
+		// clear cached_properties because they won't be relevant now.
515
+		$this->_clear_cached_properties();
516
+	}
517
+
518
+
519
+	/**
520
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
521
+	 * class internally instead of wp set time format options.
522
+	 *
523
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
524
+	 * @since 4.6
525
+	 */
526
+	public function set_time_format(?string $format)
527
+	{
528
+		$this->_tm_frmt = new TimeFormat($format);
529
+		// clear cached_properties because they won't be relevant now.
530
+		$this->_clear_cached_properties();
531
+	}
532
+
533
+
534
+	/**
535
+	 * This returns the current internal set format for the date and time formats.
536
+	 *
537
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
538
+	 *                             where the first value is the date format and the second value is the time format.
539
+	 * @return string|array
540
+	 */
541
+	public function get_format($full = true)
542
+	{
543
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
544
+	}
545
+
546
+
547
+	/**
548
+	 * cache
549
+	 * stores the passed model object on the current model object.
550
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
551
+	 *
552
+	 * @param string        $relation_name   one of the keys in the _model_relations array on the model. Eg
553
+	 *                                       'Registration' associated with this model object
554
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
555
+	 *                                       that could be a payment or a registration)
556
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
557
+	 *                                       items which will be stored in an array on this object
558
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
559
+	 *                                       related thing, no array)
560
+	 * @throws InvalidArgumentException
561
+	 * @throws InvalidInterfaceException
562
+	 * @throws InvalidDataTypeException
563
+	 * @throws EE_Error
564
+	 * @throws ReflectionException
565
+	 */
566
+	public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
567
+	{
568
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
569
+		if (! $object_to_cache instanceof EE_Base_Class) {
570
+			return false;
571
+		}
572
+		// also get "how" the object is related, or throw an error
573
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
574
+			throw new EE_Error(
575
+				sprintf(
576
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
577
+					$relation_name,
578
+					get_class($this)
579
+				)
580
+			);
581
+		}
582
+		// how many things are related ?
583
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
584
+			// if it's a "belongs to" relationship, then there's only one related model object
585
+			// eg, if this is a registration, there's only 1 attendee for it
586
+			// so for these model objects just set it to be cached
587
+			$this->_model_relations[ $relation_name ] = $object_to_cache;
588
+			$return                                   = true;
589
+		} else {
590
+			// otherwise, this is the "many" side of a one to many relationship,
591
+			// so we'll add the object to the array of related objects for that type.
592
+			// eg: if this is an event, there are many registrations for that event,
593
+			// so we cache the registrations in an array
594
+			if (! is_array($this->_model_relations[ $relation_name ])) {
595
+				// if for some reason, the cached item is a model object,
596
+				// then stick that in the array, otherwise start with an empty array
597
+				$this->_model_relations[ $relation_name ] =
598
+					$this->_model_relations[ $relation_name ] instanceof EE_Base_Class
599
+						? [$this->_model_relations[ $relation_name ]]
600
+						: [];
601
+			}
602
+			// first check for a cache_id which is normally empty
603
+			if (! empty($cache_id)) {
604
+				// if the cache_id exists, then it means we are purposely trying to cache this
605
+				// with a known key that can then be used to retrieve the object later on
606
+				$this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
607
+				$return                                                = $cache_id;
608
+			} elseif ($object_to_cache->ID()) {
609
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
610
+				$this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
611
+				$return                                                             = $object_to_cache->ID();
612
+			} else {
613
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
614
+				$this->_model_relations[ $relation_name ][] = $object_to_cache;
615
+				// move the internal pointer to the end of the array
616
+				end($this->_model_relations[ $relation_name ]);
617
+				// and grab the key so that we can return it
618
+				$return = key($this->_model_relations[ $relation_name ]);
619
+			}
620
+		}
621
+		return $return;
622
+	}
623
+
624
+
625
+	/**
626
+	 * For adding an item to the cached_properties property.
627
+	 *
628
+	 * @access protected
629
+	 * @param string      $fieldname the property item the corresponding value is for.
630
+	 * @param mixed       $value     The value we are caching.
631
+	 * @param string|null $cache_type
632
+	 * @return void
633
+	 * @throws ReflectionException
634
+	 * @throws InvalidArgumentException
635
+	 * @throws InvalidInterfaceException
636
+	 * @throws InvalidDataTypeException
637
+	 * @throws EE_Error
638
+	 */
639
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
640
+	{
641
+		// first make sure this property exists
642
+		$this->get_model()->field_settings_for($fieldname);
643
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
644
+
645
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
646
+	}
647
+
648
+
649
+	/**
650
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
651
+	 * This also SETS the cache if we return the actual property!
652
+	 *
653
+	 * @param string $fieldname        the name of the property we're trying to retrieve
654
+	 * @param bool   $pretty
655
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
656
+	 *                                 (in cases where the same property may be used for different outputs
657
+	 *                                 - i.e. datetime, money etc.)
658
+	 *                                 It can also accept certain pre-defined "schema" strings
659
+	 *                                 to define how to output the property.
660
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
661
+	 * @return mixed                   whatever the value for the property is we're retrieving
662
+	 * @throws ReflectionException
663
+	 * @throws InvalidArgumentException
664
+	 * @throws InvalidInterfaceException
665
+	 * @throws InvalidDataTypeException
666
+	 * @throws EE_Error
667
+	 */
668
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
669
+	{
670
+		// verify the field exists
671
+		$model = $this->get_model();
672
+		$model->field_settings_for($fieldname);
673
+		$cache_type = $pretty ? 'pretty' : 'standard';
674
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
675
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
676
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
677
+		}
678
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
679
+		$this->_set_cached_property($fieldname, $value, $cache_type);
680
+		return $value;
681
+	}
682
+
683
+
684
+	/**
685
+	 * If the cache didn't fetch the needed item, this fetches it.
686
+	 *
687
+	 * @param string $fieldname
688
+	 * @param bool   $pretty
689
+	 * @param string $extra_cache_ref
690
+	 * @return mixed
691
+	 * @throws InvalidArgumentException
692
+	 * @throws InvalidInterfaceException
693
+	 * @throws InvalidDataTypeException
694
+	 * @throws EE_Error
695
+	 * @throws ReflectionException
696
+	 */
697
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
698
+	{
699
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
700
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
701
+		if ($field_obj instanceof EE_Datetime_Field) {
702
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
703
+		}
704
+		if (! isset($this->_fields[ $fieldname ])) {
705
+			$this->_fields[ $fieldname ] = null;
706
+		}
707
+		return $pretty
708
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
709
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
710
+	}
711
+
712
+
713
+	/**
714
+	 * set timezone, formats, and output for EE_Datetime_Field objects
715
+	 *
716
+	 * @param EE_Datetime_Field $datetime_field
717
+	 * @param bool              $pretty
718
+	 * @param null              $date_or_time
719
+	 * @return void
720
+	 * @throws InvalidArgumentException
721
+	 * @throws InvalidInterfaceException
722
+	 * @throws InvalidDataTypeException
723
+	 */
724
+	protected function _prepare_datetime_field(
725
+		EE_Datetime_Field $datetime_field,
726
+		$pretty = false,
727
+		$date_or_time = null
728
+	) {
729
+		$datetime_field->set_timezone($this->_timezone);
730
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
731
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
732
+		// set the output returned
733
+		switch ($date_or_time) {
734
+			case 'D':
735
+				$datetime_field->set_date_time_output('date');
736
+				break;
737
+			case 'T':
738
+				$datetime_field->set_date_time_output('time');
739
+				break;
740
+			default:
741
+				$datetime_field->set_date_time_output();
742
+		}
743
+	}
744
+
745
+
746
+	/**
747
+	 * This just takes care of clearing out the cached_properties
748
+	 *
749
+	 * @return void
750
+	 */
751
+	protected function _clear_cached_properties()
752
+	{
753
+		$this->_cached_properties = [];
754
+	}
755
+
756
+
757
+	/**
758
+	 * This just clears out ONE property if it exists in the cache
759
+	 *
760
+	 * @param string $property_name the property to remove if it exists (from the _cached_properties array)
761
+	 * @return void
762
+	 */
763
+	protected function _clear_cached_property($property_name)
764
+	{
765
+		if (isset($this->_cached_properties[ $property_name ])) {
766
+			unset($this->_cached_properties[ $property_name ]);
767
+		}
768
+	}
769
+
770
+
771
+	/**
772
+	 * Ensures that this related thing is a model object.
773
+	 *
774
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
775
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
776
+	 * @return EE_Base_Class
777
+	 * @throws ReflectionException
778
+	 * @throws InvalidArgumentException
779
+	 * @throws InvalidInterfaceException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws EE_Error
782
+	 */
783
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
784
+	{
785
+		$other_model_instance = self::_get_model_instance_with_name(
786
+			self::_get_model_classname($model_name),
787
+			$this->_timezone
788
+		);
789
+		return $other_model_instance->ensure_is_obj($object_or_id);
790
+	}
791
+
792
+
793
+	/**
794
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
795
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
796
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
797
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
798
+	 *
799
+	 * @param string $relation_name                        one of the keys in the _model_relations array on the model.
800
+	 *                                                     Eg 'Registration'
801
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
802
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
803
+	 *                                                     has 1 object anyway (ie, it's a BelongsToRelation)
804
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
805
+	 *                                                     this is HasMany or HABTM.
806
+	 * @return EE_Base_Class|bool                          entity that was cleared from the cache,
807
+	 *                                                     or true if we requested to remove a relation from all
808
+	 *                                                     or false if entity was never cached anyway.
809
+	 * @throws InvalidArgumentException
810
+	 * @throws InvalidInterfaceException
811
+	 * @throws InvalidDataTypeException
812
+	 * @throws EE_Error
813
+	 * @throws ReflectionException
814
+	 */
815
+	public function clear_cache($relation_name, $object_to_remove_or_index_into_array = null, $clear_all = false)
816
+	{
817
+		$relationship_to_model = $this->get_model()->related_settings_for($relation_name);
818
+		$index_in_cache        = '';
819
+		if (! $relationship_to_model) {
820
+			throw new EE_Error(
821
+				sprintf(
822
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
823
+					$relation_name,
824
+					get_class($this)
825
+				)
826
+			);
827
+		}
828
+		if ($clear_all) {
829
+			$obj_removed                              = true;
830
+			$this->_model_relations[ $relation_name ] = null;
831
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
+			$obj_removed                              = $this->_model_relations[ $relation_name ];
833
+			$this->_model_relations[ $relation_name ] = null;
834
+		} else {
835
+			if (
836
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
837
+				&& $object_to_remove_or_index_into_array->ID()
838
+			) {
839
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
840
+				if (
841
+					is_array($this->_model_relations[ $relation_name ])
842
+					&& ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
843
+				) {
844
+					$index_found_at = null;
845
+					// find this object in the array even though it has a different key
846
+					foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
847
+						/** @noinspection TypeUnsafeComparisonInspection */
848
+						if (
849
+							$obj instanceof EE_Base_Class
850
+							&& (
851
+								$obj == $object_to_remove_or_index_into_array
852
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
853
+							)
854
+						) {
855
+							$index_found_at = $index;
856
+							break;
857
+						}
858
+					}
859
+					if ($index_found_at) {
860
+						$index_in_cache = $index_found_at;
861
+					} else {
862
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
863
+						// if it wasn't in it to begin with. So we're done
864
+						return $object_to_remove_or_index_into_array;
865
+					}
866
+				}
867
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
868
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
869
+				foreach ($this->get_all_from_cache($relation_name) as $index => $potentially_obj_we_want) {
870
+					/** @noinspection TypeUnsafeComparisonInspection */
871
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
872
+						$index_in_cache = $index;
873
+					}
874
+				}
875
+			} else {
876
+				$index_in_cache = $object_to_remove_or_index_into_array;
877
+			}
878
+			// supposedly we've found it. But it could just be that the client code
879
+			// provided a bad index/object
880
+			if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
881
+				$obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
882
+				unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
883
+			} else {
884
+				// that thing was never cached anyway.
885
+				$obj_removed = false;
886
+			}
887
+		}
888
+		return $obj_removed;
889
+	}
890
+
891
+
892
+	/**
893
+	 * update_cache_after_object_save
894
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
895
+	 * obtained after being saved to the db
896
+	 *
897
+	 * @param string        $relation_name      - the type of object that is cached
898
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
899
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
900
+	 * @return boolean TRUE on success, FALSE on fail
901
+	 * @throws ReflectionException
902
+	 * @throws InvalidArgumentException
903
+	 * @throws InvalidInterfaceException
904
+	 * @throws InvalidDataTypeException
905
+	 * @throws EE_Error
906
+	 */
907
+	public function update_cache_after_object_save(
908
+		$relation_name,
909
+		EE_Base_Class $newly_saved_object,
910
+		$current_cache_id = ''
911
+	) {
912
+		// verify that incoming object is of the correct type
913
+		$obj_class = 'EE_' . $relation_name;
914
+		if ($newly_saved_object instanceof $obj_class) {
915
+			/* @type EE_Base_Class $newly_saved_object */
916
+			// now get the type of relation
917
+			$relationship_to_model = $this->get_model()->related_settings_for($relation_name);
918
+			// if this is a 1:1 relationship
919
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
920
+				// then just replace the cached object with the newly saved object
921
+				$this->_model_relations[ $relation_name ] = $newly_saved_object;
922
+				return true;
923
+				// or if it's some kind of sordid feral polyamorous relationship...
924
+			}
925
+			if (
926
+				is_array($this->_model_relations[ $relation_name ])
927
+				&& isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
928
+			) {
929
+				// then remove the current cached item
930
+				unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
931
+				// and cache the newly saved object using it's new ID
932
+				$this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
933
+				return true;
934
+			}
935
+		}
936
+		return false;
937
+	}
938
+
939
+
940
+	/**
941
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
942
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
943
+	 *
944
+	 * @param string $relation_name
945
+	 * @return EE_Base_Class
946
+	 */
947
+	public function get_one_from_cache($relation_name)
948
+	{
949
+		$cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
950
+		if (is_array($cached_array_or_object)) {
951
+			return array_shift($cached_array_or_object);
952
+		}
953
+		return $cached_array_or_object;
954
+	}
955
+
956
+
957
+	/**
958
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
959
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
960
+	 *
961
+	 * @param string $relation_name
962
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
963
+	 * @throws InvalidArgumentException
964
+	 * @throws InvalidInterfaceException
965
+	 * @throws InvalidDataTypeException
966
+	 * @throws EE_Error
967
+	 * @throws ReflectionException
968
+	 */
969
+	public function get_all_from_cache($relation_name)
970
+	{
971
+		$objects = $this->_model_relations[ $relation_name ] ?? [];
972
+		// if the result is not an array, but exists, make it an array
973
+		$objects = is_array($objects)
974
+			? $objects
975
+			: [$objects];
976
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
977
+		// basically, if this model object was stored in the session, and these cached model objects
978
+		// already have IDs, let's make sure they're in their model's entity mapper
979
+		// otherwise we will have duplicates next time we call
980
+		// EE_Registry::instance()->load_model( $relation_name )->get_one_by_ID( $result->ID() );
981
+		$model = EE_Registry::instance()->load_model($relation_name);
982
+		foreach ($objects as $model_object) {
983
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
984
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
985
+				if ($model_object->ID()) {
986
+					$model->add_to_entity_map($model_object);
987
+				}
988
+			} else {
989
+				throw new EE_Error(
990
+					sprintf(
991
+						esc_html__(
992
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
993
+							'event_espresso'
994
+						),
995
+						$relation_name,
996
+						gettype($model_object)
997
+					)
998
+				);
999
+			}
1000
+		}
1001
+		return $objects;
1002
+	}
1003
+
1004
+
1005
+	/**
1006
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1007
+	 * matching the given query conditions.
1008
+	 *
1009
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1010
+	 * @param int   $limit              How many objects to return.
1011
+	 * @param array $query_params       Any additional conditions on the query.
1012
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1013
+	 *                                  you can indicate just the columns you want returned
1014
+	 * @return array|EE_Base_Class[]
1015
+	 * @throws ReflectionException
1016
+	 * @throws InvalidArgumentException
1017
+	 * @throws InvalidInterfaceException
1018
+	 * @throws InvalidDataTypeException
1019
+	 * @throws EE_Error
1020
+	 */
1021
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = [], $columns_to_select = null)
1022
+	{
1023
+		$model         = $this->get_model();
1024
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1025
+			? $model->get_primary_key_field()->get_name()
1026
+			: $field_to_order_by;
1027
+		$current_value = ! empty($field)
1028
+			? $this->get($field)
1029
+			: null;
1030
+		if (empty($field) || empty($current_value)) {
1031
+			return [];
1032
+		}
1033
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1039
+	 * matching the given query conditions.
1040
+	 *
1041
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1042
+	 * @param int   $limit              How many objects to return.
1043
+	 * @param array $query_params       Any additional conditions on the query.
1044
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1045
+	 *                                  you can indicate just the columns you want returned
1046
+	 * @return array|EE_Base_Class[]
1047
+	 * @throws ReflectionException
1048
+	 * @throws InvalidArgumentException
1049
+	 * @throws InvalidInterfaceException
1050
+	 * @throws InvalidDataTypeException
1051
+	 * @throws EE_Error
1052
+	 */
1053
+	public function previous_x(
1054
+		$field_to_order_by = null,
1055
+		$limit = 1,
1056
+		$query_params = [],
1057
+		$columns_to_select = null
1058
+	) {
1059
+		$model         = $this->get_model();
1060
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1061
+			? $model->get_primary_key_field()->get_name()
1062
+			: $field_to_order_by;
1063
+		$current_value = ! empty($field) ? $this->get($field) : null;
1064
+		if (empty($field) || empty($current_value)) {
1065
+			return [];
1066
+		}
1067
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1068
+	}
1069
+
1070
+
1071
+	/**
1072
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1073
+	 * matching the given query conditions.
1074
+	 *
1075
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1076
+	 * @param array $query_params       Any additional conditions on the query.
1077
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1078
+	 *                                  you can indicate just the columns you want returned
1079
+	 * @return array|EE_Base_Class
1080
+	 * @throws ReflectionException
1081
+	 * @throws InvalidArgumentException
1082
+	 * @throws InvalidInterfaceException
1083
+	 * @throws InvalidDataTypeException
1084
+	 * @throws EE_Error
1085
+	 */
1086
+	public function next($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1087
+	{
1088
+		$model         = $this->get_model();
1089
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1090
+			? $model->get_primary_key_field()->get_name()
1091
+			: $field_to_order_by;
1092
+		$current_value = ! empty($field) ? $this->get($field) : null;
1093
+		if (empty($field) || empty($current_value)) {
1094
+			return [];
1095
+		}
1096
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1097
+	}
1098
+
1099
+
1100
+	/**
1101
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1102
+	 * matching the given query conditions.
1103
+	 *
1104
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1105
+	 * @param array $query_params       Any additional conditions on the query.
1106
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1107
+	 *                                  you can indicate just the column you want returned
1108
+	 * @return array|EE_Base_Class
1109
+	 * @throws ReflectionException
1110
+	 * @throws InvalidArgumentException
1111
+	 * @throws InvalidInterfaceException
1112
+	 * @throws InvalidDataTypeException
1113
+	 * @throws EE_Error
1114
+	 */
1115
+	public function previous($field_to_order_by = null, $query_params = [], $columns_to_select = null)
1116
+	{
1117
+		$model         = $this->get_model();
1118
+		$field         = empty($field_to_order_by) && $model->has_primary_key_field()
1119
+			? $model->get_primary_key_field()->get_name()
1120
+			: $field_to_order_by;
1121
+		$current_value = ! empty($field) ? $this->get($field) : null;
1122
+		if (empty($field) || empty($current_value)) {
1123
+			return [];
1124
+		}
1125
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * verifies that the specified field is of the correct type
1131
+	 *
1132
+	 * @param string $field_name
1133
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1134
+	 *                                (in cases where the same property may be used for different outputs
1135
+	 *                                - i.e. datetime, money etc.)
1136
+	 * @return mixed
1137
+	 * @throws ReflectionException
1138
+	 * @throws InvalidArgumentException
1139
+	 * @throws InvalidInterfaceException
1140
+	 * @throws InvalidDataTypeException
1141
+	 * @throws EE_Error
1142
+	 */
1143
+	public function get($field_name, $extra_cache_ref = null)
1144
+	{
1145
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1146
+	}
1147
+
1148
+
1149
+	/**
1150
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1151
+	 *
1152
+	 * @param string $field_name A valid fieldname
1153
+	 * @return mixed              Whatever the raw value stored on the property is.
1154
+	 * @throws ReflectionException
1155
+	 * @throws InvalidArgumentException
1156
+	 * @throws InvalidInterfaceException
1157
+	 * @throws InvalidDataTypeException
1158
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1159
+	 */
1160
+	public function get_raw($field_name)
1161
+	{
1162
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1163
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1164
+			? $this->_fields[ $field_name ]->format('U')
1165
+			: $this->_fields[ $field_name ];
1166
+	}
1167
+
1168
+
1169
+	/**
1170
+	 * This is used to return the internal DateTime object used for a field that is a
1171
+	 * EE_Datetime_Field.
1172
+	 *
1173
+	 * @param string $field_name               The field name retrieving the DateTime object.
1174
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1175
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1176
+	 *                                         EE_Datetime_Field and but the field value is null, then
1177
+	 *                                         just null is returned (because that indicates that likely
1178
+	 *                                         this field is nullable).
1179
+	 * @throws InvalidArgumentException
1180
+	 * @throws InvalidDataTypeException
1181
+	 * @throws InvalidInterfaceException
1182
+	 * @throws ReflectionException
1183
+	 */
1184
+	public function get_DateTime_object($field_name)
1185
+	{
1186
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1187
+		if (! $field_settings instanceof EE_Datetime_Field) {
1188
+			EE_Error::add_error(
1189
+				sprintf(
1190
+					esc_html__(
1191
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1192
+						'event_espresso'
1193
+					),
1194
+					$field_name
1195
+				),
1196
+				__FILE__,
1197
+				__FUNCTION__,
1198
+				__LINE__
1199
+			);
1200
+			return false;
1201
+		}
1202
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1203
+			? clone $this->_fields[ $field_name ]
1204
+			: null;
1205
+	}
1206
+
1207
+
1208
+	/**
1209
+	 * To be used in template to immediately echo out the value, and format it for output.
1210
+	 * Eg, should call stripslashes and whatnot before echoing
1211
+	 *
1212
+	 * @param string $field_name      the name of the field as it appears in the DB
1213
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1214
+	 *                                (in cases where the same property may be used for different outputs
1215
+	 *                                - i.e. datetime, money etc.)
1216
+	 * @return void
1217
+	 * @throws ReflectionException
1218
+	 * @throws InvalidArgumentException
1219
+	 * @throws InvalidInterfaceException
1220
+	 * @throws InvalidDataTypeException
1221
+	 * @throws EE_Error
1222
+	 */
1223
+	public function e($field_name, $extra_cache_ref = null)
1224
+	{
1225
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1231
+	 * can be easily used as the value of form input.
1232
+	 *
1233
+	 * @param string $field_name
1234
+	 * @return void
1235
+	 * @throws ReflectionException
1236
+	 * @throws InvalidArgumentException
1237
+	 * @throws InvalidInterfaceException
1238
+	 * @throws InvalidDataTypeException
1239
+	 * @throws EE_Error
1240
+	 */
1241
+	public function f($field_name)
1242
+	{
1243
+		$this->e($field_name, 'form_input');
1244
+	}
1245
+
1246
+
1247
+	/**
1248
+	 * Same as `f()` but just returns the value instead of echoing it
1249
+	 *
1250
+	 * @param string $field_name
1251
+	 * @return string
1252
+	 * @throws ReflectionException
1253
+	 * @throws InvalidArgumentException
1254
+	 * @throws InvalidInterfaceException
1255
+	 * @throws InvalidDataTypeException
1256
+	 * @throws EE_Error
1257
+	 */
1258
+	public function get_f($field_name)
1259
+	{
1260
+		return (string) $this->get_pretty($field_name, 'form_input');
1261
+	}
1262
+
1263
+
1264
+	/**
1265
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1266
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1267
+	 * to see what options are available.
1268
+	 *
1269
+	 * @param string $field_name
1270
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1271
+	 *                                (in cases where the same property may be used for different outputs
1272
+	 *                                - i.e. datetime, money etc.)
1273
+	 * @return mixed
1274
+	 * @throws ReflectionException
1275
+	 * @throws InvalidArgumentException
1276
+	 * @throws InvalidInterfaceException
1277
+	 * @throws InvalidDataTypeException
1278
+	 * @throws EE_Error
1279
+	 */
1280
+	public function get_pretty($field_name, $extra_cache_ref = null)
1281
+	{
1282
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1283
+	}
1284
+
1285
+
1286
+	/**
1287
+	 * This simply returns the datetime for the given field name
1288
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1289
+	 * (and the equivalent e_date, e_time, e_datetime).
1290
+	 *
1291
+	 * @access   protected
1292
+	 * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1293
+	 * @param string|null $date_format  valid datetime format used for date
1294
+	 *                                  (if '' then we just use the default on the field,
1295
+	 *                                  if NULL we use the last-used format)
1296
+	 * @param string|null $time_format  Same as above except this is for time format
1297
+	 * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1298
+	 * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1299
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1300
+	 *                                  if field is not a valid dtt field, or void if echoing
1301
+	 * @throws EE_Error
1302
+	 * @throws ReflectionException
1303
+	 */
1304
+	protected function _get_datetime(
1305
+		string $field_name,
1306
+		?string $date_format = '',
1307
+		?string $time_format = '',
1308
+		?string $date_or_time = '',
1309
+		?bool $echo = false
1310
+	) {
1311
+		// clear cached property
1312
+		$this->_clear_cached_property($field_name);
1313
+		// reset format properties because they are used in get()
1314
+		$this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1315
+		$this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1316
+		if ($echo) {
1317
+			$this->e($field_name, $date_or_time);
1318
+			return '';
1319
+		}
1320
+		return $this->get($field_name, $date_or_time);
1321
+	}
1322
+
1323
+
1324
+	/**
1325
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1326
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1327
+	 * other echoes the pretty value for dtt)
1328
+	 *
1329
+	 * @param string $field_name name of model object datetime field holding the value
1330
+	 * @param string $format     format for the date returned (if NULL we use default in dt_frmt property)
1331
+	 * @return string            datetime value formatted
1332
+	 * @throws ReflectionException
1333
+	 * @throws InvalidArgumentException
1334
+	 * @throws InvalidInterfaceException
1335
+	 * @throws InvalidDataTypeException
1336
+	 * @throws EE_Error
1337
+	 */
1338
+	public function get_date($field_name, $format = '')
1339
+	{
1340
+		return $this->_get_datetime($field_name, $format, null, 'D');
1341
+	}
1342
+
1343
+
1344
+	/**
1345
+	 * @param        $field_name
1346
+	 * @param string $format
1347
+	 * @throws ReflectionException
1348
+	 * @throws InvalidArgumentException
1349
+	 * @throws InvalidInterfaceException
1350
+	 * @throws InvalidDataTypeException
1351
+	 * @throws EE_Error
1352
+	 */
1353
+	public function e_date($field_name, $format = '')
1354
+	{
1355
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1356
+	}
1357
+
1358
+
1359
+	/**
1360
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1361
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1362
+	 * other echoes the pretty value for dtt)
1363
+	 *
1364
+	 * @param string $field_name name of model object datetime field holding the value
1365
+	 * @param string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1366
+	 * @return string             datetime value formatted
1367
+	 * @throws ReflectionException
1368
+	 * @throws InvalidArgumentException
1369
+	 * @throws InvalidInterfaceException
1370
+	 * @throws InvalidDataTypeException
1371
+	 * @throws EE_Error
1372
+	 */
1373
+	public function get_time($field_name, $format = '')
1374
+	{
1375
+		return $this->_get_datetime($field_name, null, $format, 'T');
1376
+	}
1377
+
1378
+
1379
+	/**
1380
+	 * @param        $field_name
1381
+	 * @param string $format
1382
+	 * @throws ReflectionException
1383
+	 * @throws InvalidArgumentException
1384
+	 * @throws InvalidInterfaceException
1385
+	 * @throws InvalidDataTypeException
1386
+	 * @throws EE_Error
1387
+	 */
1388
+	public function e_time($field_name, $format = '')
1389
+	{
1390
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1391
+	}
1392
+
1393
+
1394
+	/**
1395
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1396
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1397
+	 * other echoes the pretty value for dtt)
1398
+	 *
1399
+	 * @param string $field_name  name of model object datetime field holding the value
1400
+	 * @param string $date_format format for the date returned (if NULL we use default in dt_frmt property)
1401
+	 * @param string $time_format format for the time returned (if NULL we use default in tm_frmt property)
1402
+	 * @return string             datetime value formatted
1403
+	 * @throws ReflectionException
1404
+	 * @throws InvalidArgumentException
1405
+	 * @throws InvalidInterfaceException
1406
+	 * @throws InvalidDataTypeException
1407
+	 * @throws EE_Error
1408
+	 */
1409
+	public function get_datetime($field_name, $date_format = '', $time_format = '')
1410
+	{
1411
+		return $this->_get_datetime($field_name, $date_format, $time_format);
1412
+	}
1413
+
1414
+
1415
+	/**
1416
+	 * @param string $field_name
1417
+	 * @param string $date_format
1418
+	 * @param string $time_format
1419
+	 * @throws ReflectionException
1420
+	 * @throws InvalidArgumentException
1421
+	 * @throws InvalidInterfaceException
1422
+	 * @throws InvalidDataTypeException
1423
+	 * @throws EE_Error
1424
+	 */
1425
+	public function e_datetime($field_name, $date_format = '', $time_format = '')
1426
+	{
1427
+		$this->_get_datetime($field_name, $date_format, $time_format, null, true);
1428
+	}
1429
+
1430
+
1431
+	/**
1432
+	 * Get the i8ln value for a date using the WordPress @param string $field_name The EE_Datetime_Field reference for
1433
+	 *                           the date being retrieved.
1434
+	 *
1435
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1436
+	 *                           on the object will be used.
1437
+	 * @return string Date and time string in set locale or false if no field exists for the given
1438
+	 * @throws ReflectionException
1439
+	 * @throws InvalidArgumentException
1440
+	 * @throws InvalidInterfaceException
1441
+	 * @throws InvalidDataTypeException
1442
+	 * @throws EE_Error
1443
+	 *                           field name.
1444
+	 * @see date_i18n function.
1445
+	 */
1446
+	public function get_i18n_datetime(string $field_name, string $format = ''): string
1447
+	{
1448
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1449
+		return date_i18n(
1450
+			$format,
1451
+			EEH_DTT_Helper::get_timestamp_with_offset(
1452
+				$this->get_raw($field_name),
1453
+				$this->_timezone
1454
+			)
1455
+		);
1456
+	}
1457
+
1458
+
1459
+	/**
1460
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1461
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1462
+	 * thrown.
1463
+	 *
1464
+	 * @param string $field_name The field name being checked
1465
+	 * @return EE_Datetime_Field
1466
+	 * @throws InvalidArgumentException
1467
+	 * @throws InvalidInterfaceException
1468
+	 * @throws InvalidDataTypeException
1469
+	 * @throws EE_Error
1470
+	 * @throws ReflectionException
1471
+	 */
1472
+	protected function _get_dtt_field_settings($field_name)
1473
+	{
1474
+		$field = $this->get_model()->field_settings_for($field_name);
1475
+		// check if field is dtt
1476
+		if ($field instanceof EE_Datetime_Field) {
1477
+			return $field;
1478
+		}
1479
+		throw new EE_Error(
1480
+			sprintf(
1481
+				esc_html__(
1482
+					'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',
1483
+					'event_espresso'
1484
+				),
1485
+				$field_name,
1486
+				self::_get_model_classname(get_class($this))
1487
+			)
1488
+		);
1489
+	}
1490
+
1491
+
1492
+
1493
+
1494
+	/**
1495
+	 * NOTE ABOUT BELOW:
1496
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1497
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1498
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1499
+	 * method and make sure you send the entire datetime value for setting.
1500
+	 */
1501
+	/**
1502
+	 * sets the time on a datetime property
1503
+	 *
1504
+	 * @access protected
1505
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1506
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1507
+	 * @throws ReflectionException
1508
+	 * @throws InvalidArgumentException
1509
+	 * @throws InvalidInterfaceException
1510
+	 * @throws InvalidDataTypeException
1511
+	 * @throws EE_Error
1512
+	 */
1513
+	protected function _set_time_for($time, $fieldname)
1514
+	{
1515
+		$this->_set_date_time('T', $time, $fieldname);
1516
+	}
1517
+
1518
+
1519
+	/**
1520
+	 * sets the date on a datetime property
1521
+	 *
1522
+	 * @access protected
1523
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1524
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1525
+	 * @throws ReflectionException
1526
+	 * @throws InvalidArgumentException
1527
+	 * @throws InvalidInterfaceException
1528
+	 * @throws InvalidDataTypeException
1529
+	 * @throws EE_Error
1530
+	 */
1531
+	protected function _set_date_for($date, $fieldname)
1532
+	{
1533
+		$this->_set_date_time('D', $date, $fieldname);
1534
+	}
1535
+
1536
+
1537
+	/**
1538
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1539
+	 * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1540
+	 *
1541
+	 * @access protected
1542
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1543
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1544
+	 * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1545
+	 *                                        EE_Datetime_Field property)
1546
+	 * @throws ReflectionException
1547
+	 * @throws InvalidArgumentException
1548
+	 * @throws InvalidInterfaceException
1549
+	 * @throws InvalidDataTypeException
1550
+	 * @throws EE_Error
1551
+	 */
1552
+	protected function _set_date_time(string $what, $datetime_value, string $field_name)
1553
+	{
1554
+		$field = $this->_get_dtt_field_settings($field_name);
1555
+		$field->set_timezone($this->_timezone);
1556
+		$field->set_date_format($this->_dt_frmt);
1557
+		$field->set_time_format($this->_tm_frmt);
1558
+		switch ($what) {
1559
+			case 'T':
1560
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1561
+					$datetime_value,
1562
+					$this->_fields[ $field_name ]
1563
+				);
1564
+				$this->_has_changes           = true;
1565
+				break;
1566
+			case 'D':
1567
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1568
+					$datetime_value,
1569
+					$this->_fields[ $field_name ]
1570
+				);
1571
+				$this->_has_changes           = true;
1572
+				break;
1573
+			case 'B':
1574
+				$this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1575
+				$this->_has_changes           = true;
1576
+				break;
1577
+		}
1578
+		$this->_clear_cached_property($field_name);
1579
+	}
1580
+
1581
+
1582
+	/**
1583
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1584
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1585
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1586
+	 * that could lead to some unexpected results!
1587
+	 *
1588
+	 * @access public
1589
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1590
+	 *                                         value being returned.
1591
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1592
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1593
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1594
+	 * @param string $append                   You can include something to append on the timestamp
1595
+	 * @return string timestamp
1596
+	 * @throws ReflectionException
1597
+	 * @throws InvalidArgumentException
1598
+	 * @throws InvalidInterfaceException
1599
+	 * @throws InvalidDataTypeException
1600
+	 * @throws EE_Error
1601
+	 */
1602
+	public function display_in_my_timezone(
1603
+		$field_name,
1604
+		$callback = 'get_datetime',
1605
+		$args = null,
1606
+		$prepend = '',
1607
+		$append = ''
1608
+	) {
1609
+		$timezone = EEH_DTT_Helper::get_timezone();
1610
+		if ($timezone === $this->_timezone) {
1611
+			return '';
1612
+		}
1613
+		$original_timezone = $this->_timezone;
1614
+		$this->set_timezone($timezone);
1615
+		$fn   = (array) $field_name;
1616
+		$args = array_merge($fn, (array) $args);
1617
+		if (! method_exists($this, $callback)) {
1618
+			throw new EE_Error(
1619
+				sprintf(
1620
+					esc_html__(
1621
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1622
+						'event_espresso'
1623
+					),
1624
+					$callback
1625
+				)
1626
+			);
1627
+		}
1628
+		$args   = (array) $args;
1629
+		$return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1630
+		$this->set_timezone($original_timezone);
1631
+		return $return;
1632
+	}
1633
+
1634
+
1635
+	/**
1636
+	 * Deletes this model object.
1637
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1638
+	 * override
1639
+	 * `EE_Base_Class::_delete` NOT this class.
1640
+	 *
1641
+	 * @return int
1642
+	 * @throws ReflectionException
1643
+	 * @throws InvalidArgumentException
1644
+	 * @throws InvalidInterfaceException
1645
+	 * @throws InvalidDataTypeException
1646
+	 * @throws EE_Error
1647
+	 */
1648
+	public function delete()
1649
+	{
1650
+		/**
1651
+		 * Called just before the `EE_Base_Class::_delete` method call.
1652
+		 * Note:
1653
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1654
+		 * should be aware that `_delete` may not always result in a permanent delete.
1655
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1656
+		 * soft deletes (trash) the object and does not permanently delete it.
1657
+		 *
1658
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1659
+		 */
1660
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1661
+		$deleted = $this->_delete();
1662
+		/**
1663
+		 * Called just after the `EE_Base_Class::_delete` method call.
1664
+		 * Note:
1665
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1666
+		 * should be aware that `_delete` may not always result in a permanent delete.
1667
+		 * For example `EE_Soft_Base_Class::_delete`
1668
+		 * soft deletes (trash) the object and does not permanently delete it.
1669
+		 *
1670
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1671
+		 * @param boolean       $deleted
1672
+		 */
1673
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $deleted);
1674
+		return $deleted;
1675
+	}
1676
+
1677
+
1678
+	/**
1679
+	 * Calls the specific delete method for the instantiated class.
1680
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1681
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1682
+	 * `EE_Base_Class::delete`
1683
+	 *
1684
+	 * @return int
1685
+	 * @throws ReflectionException
1686
+	 * @throws InvalidArgumentException
1687
+	 * @throws InvalidInterfaceException
1688
+	 * @throws InvalidDataTypeException
1689
+	 * @throws EE_Error
1690
+	 */
1691
+	protected function _delete(): int
1692
+	{
1693
+		return $this->delete_permanently();
1694
+	}
1695
+
1696
+
1697
+	/**
1698
+	 * Deletes this model object permanently from db
1699
+	 * (but keep in mind related models may block the delete and return an error)
1700
+	 *
1701
+	 * @return int
1702
+	 * @throws ReflectionException
1703
+	 * @throws InvalidArgumentException
1704
+	 * @throws InvalidInterfaceException
1705
+	 * @throws InvalidDataTypeException
1706
+	 * @throws EE_Error
1707
+	 */
1708
+	public function delete_permanently(): int
1709
+	{
1710
+		/**
1711
+		 * Called just before HARD deleting a model object
1712
+		 *
1713
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1714
+		 */
1715
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1716
+		$model  = $this->get_model();
1717
+		$result = $model->delete_permanently_by_ID($this->ID());
1718
+		$this->refresh_cache_of_related_objects();
1719
+		/**
1720
+		 * Called just after HARD deleting a model object
1721
+		 *
1722
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1723
+		 * @param boolean       $result
1724
+		 */
1725
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1726
+		return $result;
1727
+	}
1728
+
1729
+
1730
+	/**
1731
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1732
+	 * related model objects
1733
+	 *
1734
+	 * @throws ReflectionException
1735
+	 * @throws InvalidArgumentException
1736
+	 * @throws InvalidInterfaceException
1737
+	 * @throws InvalidDataTypeException
1738
+	 * @throws EE_Error
1739
+	 */
1740
+	public function refresh_cache_of_related_objects()
1741
+	{
1742
+		$model = $this->get_model();
1743
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1744
+			if (! empty($this->_model_relations[ $relation_name ])) {
1745
+				$related_objects = $this->_model_relations[ $relation_name ];
1746
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1747
+					// this relation only stores a single model object, not an array
1748
+					// but let's make it consistent
1749
+					$related_objects = [$related_objects];
1750
+				}
1751
+				foreach ($related_objects as $related_object) {
1752
+					// only refresh their cache if they're in memory
1753
+					if ($related_object instanceof EE_Base_Class) {
1754
+						$related_object->clear_cache(
1755
+							$model->get_this_model_name(),
1756
+							$this
1757
+						);
1758
+					}
1759
+				}
1760
+			}
1761
+		}
1762
+	}
1763
+
1764
+
1765
+	/**
1766
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1767
+	 * object just before saving.
1768
+	 *
1769
+	 * @access public
1770
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1771
+	 *                                 if provided during the save() method (often client code will change the fields'
1772
+	 *                                 values before calling save)
1773
+	 * @return bool|int|string         1 on a successful update
1774
+	 *                                 the ID of the new entry on insert
1775
+	 *                                 0 on failure or if the model object isn't allowed to persist
1776
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1777
+	 * @throws InvalidInterfaceException
1778
+	 * @throws InvalidDataTypeException
1779
+	 * @throws EE_Error
1780
+	 * @throws InvalidArgumentException
1781
+	 * @throws ReflectionException
1782
+	 */
1783
+	public function save($set_cols_n_values = [])
1784
+	{
1785
+		$model = $this->get_model();
1786
+		/**
1787
+		 * Filters the fields we're about to save on the model object
1788
+		 *
1789
+		 * @param array         $set_cols_n_values
1790
+		 * @param EE_Base_Class $model_object
1791
+		 */
1792
+		$set_cols_n_values = (array) apply_filters(
1793
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1794
+			$set_cols_n_values,
1795
+			$this
1796
+		);
1797
+		// set attributes as provided in $set_cols_n_values
1798
+		foreach ($set_cols_n_values as $column => $value) {
1799
+			$this->set($column, $value);
1800
+		}
1801
+		// no changes ? then don't do anything
1802
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1803
+			return 0;
1804
+		}
1805
+		/**
1806
+		 * Saving a model object.
1807
+		 * Before we perform a save, this action is fired.
1808
+		 *
1809
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1810
+		 */
1811
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1812
+		if (! $this->allow_persist()) {
1813
+			return 0;
1814
+		}
1815
+		// now get current attribute values
1816
+		$save_cols_n_values = $this->_fields;
1817
+		// if the object already has an ID, update it. Otherwise, insert it
1818
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1819
+		// They have been
1820
+		$old_assumption_concerning_value_preparation = $model
1821
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1822
+		$model->assume_values_already_prepared_by_model_object(true);
1823
+		// does this model have an autoincrement PK?
1824
+		if ($model->has_primary_key_field()) {
1825
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1826
+				// ok check if it's set, if so: update; if not, insert
1827
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1828
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1829
+				} else {
1830
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1831
+					$results = $model->insert($save_cols_n_values);
1832
+					if ($results) {
1833
+						// if successful, set the primary key
1834
+						// but don't use the normal SET method, because it will check if
1835
+						// an item with the same ID exists in the mapper & db, then
1836
+						// will find it in the db (because we just added it) and THAT object
1837
+						// will get added to the mapper before we can add this one!
1838
+						// but if we just avoid using the SET method, all that headache can be avoided
1839
+						$pk_field_name                   = $model->primary_key_name();
1840
+						$this->_fields[ $pk_field_name ] = $results;
1841
+						$this->_clear_cached_property($pk_field_name);
1842
+						$model->add_to_entity_map($this);
1843
+						$this->_update_cached_related_model_objs_fks();
1844
+					}
1845
+				}
1846
+			} else {// PK is NOT auto-increment
1847
+				// so check if one like it already exists in the db
1848
+				if ($model->exists_by_ID($this->ID())) {
1849
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1850
+						throw new EE_Error(
1851
+							sprintf(
1852
+								esc_html__(
1853
+									'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',
1854
+									'event_espresso'
1855
+								),
1856
+								get_class($this),
1857
+								get_class($model) . '::instance()->add_to_entity_map()',
1858
+								get_class($model) . '::instance()->get_one_by_ID()',
1859
+								'<br />'
1860
+							)
1861
+						);
1862
+					}
1863
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1864
+				} else {
1865
+					$results = $model->insert($save_cols_n_values);
1866
+					$this->_update_cached_related_model_objs_fks();
1867
+				}
1868
+			}
1869
+		} else {// there is NO primary key
1870
+			$already_in_db = false;
1871
+			foreach ($model->unique_indexes() as $index) {
1872
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1873
+				if ($model->exists([$uniqueness_where_params])) {
1874
+					$already_in_db = true;
1875
+				}
1876
+			}
1877
+			if ($already_in_db) {
1878
+				$combined_pk_fields_n_values = array_intersect_key(
1879
+					$save_cols_n_values,
1880
+					$model->get_combined_primary_key_fields()
1881
+				);
1882
+				$results                     = $model->update(
1883
+					$save_cols_n_values,
1884
+					$combined_pk_fields_n_values
1885
+				);
1886
+			} else {
1887
+				$results = $model->insert($save_cols_n_values);
1888
+			}
1889
+		}
1890
+		// restore the old assumption about values being prepared by the model object
1891
+		$model->assume_values_already_prepared_by_model_object(
1892
+			$old_assumption_concerning_value_preparation
1893
+		);
1894
+		/**
1895
+		 * After saving the model object this action is called
1896
+		 *
1897
+		 * @param EE_Base_Class $model_object which was just saved
1898
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1899
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1900
+		 */
1901
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1902
+		$this->_has_changes = false;
1903
+		return $results;
1904
+	}
1905
+
1906
+
1907
+	/**
1908
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1909
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1910
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1911
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1912
+	 * 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
1913
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1914
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1915
+	 *
1916
+	 * @return void
1917
+	 * @throws ReflectionException
1918
+	 * @throws InvalidArgumentException
1919
+	 * @throws InvalidInterfaceException
1920
+	 * @throws InvalidDataTypeException
1921
+	 * @throws EE_Error
1922
+	 */
1923
+	protected function _update_cached_related_model_objs_fks()
1924
+	{
1925
+		$model = $this->get_model();
1926
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1927
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1928
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1929
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1930
+						$model->get_this_model_name()
1931
+					);
1932
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1933
+					if ($related_model_obj_in_cache->ID()) {
1934
+						$related_model_obj_in_cache->save();
1935
+					}
1936
+				}
1937
+			}
1938
+		}
1939
+	}
1940
+
1941
+
1942
+	/**
1943
+	 * Saves this model object and its NEW cached relations to the database.
1944
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1945
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1946
+	 * because otherwise, there's a potential for infinite looping of saving
1947
+	 * Saves the cached related model objects, and ensures the relation between them
1948
+	 * and this object and properly setup
1949
+	 *
1950
+	 * @return int ID of new model object on save; 0 on failure+
1951
+	 * @throws ReflectionException
1952
+	 * @throws InvalidArgumentException
1953
+	 * @throws InvalidInterfaceException
1954
+	 * @throws InvalidDataTypeException
1955
+	 * @throws EE_Error
1956
+	 */
1957
+	public function save_new_cached_related_model_objs()
1958
+	{
1959
+		// make sure this has been saved
1960
+		if (! $this->ID()) {
1961
+			$id = $this->save();
1962
+		} else {
1963
+			$id = $this->ID();
1964
+		}
1965
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1966
+		foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1967
+			if ($this->_model_relations[ $relation_name ]) {
1968
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1969
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1970
+				/* @var $related_model_obj EE_Base_Class */
1971
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1972
+					// add a relation to that relation type (which saves the appropriate thing in the process)
1973
+					// but ONLY if it DOES NOT exist in the DB
1974
+					$related_model_obj = $this->_model_relations[ $relation_name ];
1975
+					// if( ! $related_model_obj->ID()){
1976
+					$this->_add_relation_to($related_model_obj, $relation_name);
1977
+					$related_model_obj->save_new_cached_related_model_objs();
1978
+					// }
1979
+				} else {
1980
+					foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1981
+						// add a relation to that relation type (which saves the appropriate thing in the process)
1982
+						// but ONLY if it DOES NOT exist in the DB
1983
+						// if( ! $related_model_obj->ID()){
1984
+						$this->_add_relation_to($related_model_obj, $relation_name);
1985
+						$related_model_obj->save_new_cached_related_model_objs();
1986
+						// }
1987
+					}
1988
+				}
1989
+			}
1990
+		}
1991
+		return $id;
1992
+	}
1993
+
1994
+
1995
+	/**
1996
+	 * for getting a model while instantiated.
1997
+	 *
1998
+	 * @return EEM_Base | EEM_CPT_Base
1999
+	 * @throws ReflectionException
2000
+	 * @throws InvalidArgumentException
2001
+	 * @throws InvalidInterfaceException
2002
+	 * @throws InvalidDataTypeException
2003
+	 * @throws EE_Error
2004
+	 */
2005
+	public function get_model()
2006
+	{
2007
+		if (! $this->_model) {
2008
+			$modelName    = self::_get_model_classname(get_class($this));
2009
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2010
+		} else {
2011
+			$this->_model->set_timezone($this->_timezone);
2012
+		}
2013
+		return $this->_model;
2014
+	}
2015
+
2016
+
2017
+	/**
2018
+	 * @param $props_n_values
2019
+	 * @param $classname
2020
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2021
+	 * @throws ReflectionException
2022
+	 * @throws InvalidArgumentException
2023
+	 * @throws InvalidInterfaceException
2024
+	 * @throws InvalidDataTypeException
2025
+	 * @throws EE_Error
2026
+	 */
2027
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2028
+	{
2029
+		// TODO: will not work for Term_Relationships because they have no PK!
2030
+		$primary_id_ref = self::_get_primary_key_name($classname);
2031
+		if (
2032
+			array_key_exists($primary_id_ref, $props_n_values)
2033
+			&& ! empty($props_n_values[ $primary_id_ref ])
2034
+		) {
2035
+			$id = $props_n_values[ $primary_id_ref ];
2036
+			return self::_get_model($classname)->get_from_entity_map($id);
2037
+		}
2038
+		return false;
2039
+	}
2040
+
2041
+
2042
+	/**
2043
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2044
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2045
+	 * 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
2046
+	 * we return false.
2047
+	 *
2048
+	 * @param array  $props_n_values    incoming array of properties and their values
2049
+	 * @param string $classname         the classname of the child class
2050
+	 * @param null   $timezone
2051
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the
2052
+	 *                                  date_format and the second value is the time format
2053
+	 * @return mixed (EE_Base_Class|bool)
2054
+	 * @throws InvalidArgumentException
2055
+	 * @throws InvalidInterfaceException
2056
+	 * @throws InvalidDataTypeException
2057
+	 * @throws EE_Error
2058
+	 * @throws ReflectionException
2059
+	 */
2060
+	protected static function _check_for_object($props_n_values, $classname, $timezone = '', $date_formats = [])
2061
+	{
2062
+		$existing = null;
2063
+		$model    = self::_get_model($classname, $timezone);
2064
+		if ($model->has_primary_key_field()) {
2065
+			$primary_id_ref = self::_get_primary_key_name($classname);
2066
+			if (
2067
+				array_key_exists($primary_id_ref, $props_n_values)
2068
+				&& ! empty($props_n_values[ $primary_id_ref ])
2069
+			) {
2070
+				$existing = $model->get_one_by_ID(
2071
+					$props_n_values[ $primary_id_ref ]
2072
+				);
2073
+			}
2074
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2075
+			// no primary key on this model, but there's still a matching item in the DB
2076
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2077
+				self::_get_model($classname, $timezone)
2078
+					->get_index_primary_key_string($props_n_values)
2079
+			);
2080
+		}
2081
+		if ($existing) {
2082
+			// set date formats if present before setting values
2083
+			if (! empty($date_formats) && is_array($date_formats)) {
2084
+				$existing->set_date_format($date_formats[0]);
2085
+				$existing->set_time_format($date_formats[1]);
2086
+			} else {
2087
+				// set default formats for date and time
2088
+				$existing->set_date_format(get_option('date_format'));
2089
+				$existing->set_time_format(get_option('time_format'));
2090
+			}
2091
+			foreach ($props_n_values as $property => $field_value) {
2092
+				$existing->set($property, $field_value);
2093
+			}
2094
+			return $existing;
2095
+		}
2096
+		return false;
2097
+	}
2098
+
2099
+
2100
+	/**
2101
+	 * Gets the EEM_*_Model for this class
2102
+	 *
2103
+	 * @access public now, as this is more convenient
2104
+	 * @param      $classname
2105
+	 * @param null $timezone
2106
+	 * @return EEM_Base
2107
+	 * @throws InvalidArgumentException
2108
+	 * @throws InvalidInterfaceException
2109
+	 * @throws InvalidDataTypeException
2110
+	 * @throws EE_Error
2111
+	 * @throws ReflectionException
2112
+	 */
2113
+	protected static function _get_model($classname, $timezone = '')
2114
+	{
2115
+		// find model for this class
2116
+		if (! $classname) {
2117
+			throw new EE_Error(
2118
+				sprintf(
2119
+					esc_html__(
2120
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2121
+						'event_espresso'
2122
+					),
2123
+					$classname
2124
+				)
2125
+			);
2126
+		}
2127
+		$modelName = self::_get_model_classname($classname);
2128
+		return self::_get_model_instance_with_name($modelName, $timezone);
2129
+	}
2130
+
2131
+
2132
+	/**
2133
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2134
+	 *
2135
+	 * @param string $model_classname
2136
+	 * @param null   $timezone
2137
+	 * @return EEM_Base
2138
+	 * @throws ReflectionException
2139
+	 * @throws InvalidArgumentException
2140
+	 * @throws InvalidInterfaceException
2141
+	 * @throws InvalidDataTypeException
2142
+	 * @throws EE_Error
2143
+	 */
2144
+	protected static function _get_model_instance_with_name($model_classname, $timezone = '')
2145
+	{
2146
+		$model_classname = str_replace('EEM_', '', $model_classname);
2147
+		$model           = EE_Registry::instance()->load_model($model_classname);
2148
+		$model->set_timezone($timezone);
2149
+		return $model;
2150
+	}
2151
+
2152
+
2153
+	/**
2154
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2155
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2156
+	 *
2157
+	 * @param string|null $model_name
2158
+	 * @return string like EEM_Attendee
2159
+	 */
2160
+	private static function _get_model_classname($model_name = '')
2161
+	{
2162
+		return strpos((string) $model_name, 'EE_') === 0
2163
+			? str_replace('EE_', 'EEM_', $model_name)
2164
+			: 'EEM_' . $model_name;
2165
+	}
2166
+
2167
+
2168
+	/**
2169
+	 * returns the name of the primary key attribute
2170
+	 *
2171
+	 * @param null $classname
2172
+	 * @return string
2173
+	 * @throws InvalidArgumentException
2174
+	 * @throws InvalidInterfaceException
2175
+	 * @throws InvalidDataTypeException
2176
+	 * @throws EE_Error
2177
+	 * @throws ReflectionException
2178
+	 */
2179
+	protected static function _get_primary_key_name($classname = null)
2180
+	{
2181
+		if (! $classname) {
2182
+			throw new EE_Error(
2183
+				sprintf(
2184
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2185
+					$classname
2186
+				)
2187
+			);
2188
+		}
2189
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2190
+	}
2191
+
2192
+
2193
+	/**
2194
+	 * Gets the value of the primary key.
2195
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2196
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2197
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2198
+	 *
2199
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2200
+	 * @throws ReflectionException
2201
+	 * @throws InvalidArgumentException
2202
+	 * @throws InvalidInterfaceException
2203
+	 * @throws InvalidDataTypeException
2204
+	 * @throws EE_Error
2205
+	 */
2206
+	public function ID()
2207
+	{
2208
+		$model = $this->get_model();
2209
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2210
+		if ($model->has_primary_key_field()) {
2211
+			return $this->_fields[ $model->primary_key_name() ];
2212
+		}
2213
+		return $model->get_index_primary_key_string($this->_fields);
2214
+	}
2215
+
2216
+
2217
+	/**
2218
+	 * @param EE_Base_Class|int|string $otherModelObjectOrID
2219
+	 * @param string                   $relation_name
2220
+	 * @return bool
2221
+	 * @throws EE_Error
2222
+	 * @throws ReflectionException
2223
+	 * @since   5.0.0.p
2224
+	 */
2225
+	public function hasRelation($otherModelObjectOrID, string $relation_name): bool
2226
+	{
2227
+		$other_model = self::_get_model_instance_with_name(
2228
+			self::_get_model_classname($relation_name),
2229
+			$this->_timezone
2230
+		);
2231
+		$primary_key = $other_model->primary_key_name();
2232
+		/** @var EE_Base_Class $otherModelObject */
2233
+		$otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relation_name);
2234
+		return $this->count_related($relation_name, [[$primary_key => $otherModelObject->ID()]]) > 0;
2235
+	}
2236
+
2237
+
2238
+	/**
2239
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2240
+	 * model is related to a group of events, the $relation_name should be 'Event', and should be a key in the EE
2241
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2242
+	 *
2243
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2244
+	 * @param string $relation_name                    eg 'Events','Question',etc.
2245
+	 *                                                 an attendee to a group, you also want to specify which role they
2246
+	 *                                                 will have in that group. So you would use this parameter to
2247
+	 *                                                 specify array('role-column-name'=>'role-id')
2248
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2249
+	 *                                                 allow you to further constrict the relation to being added.
2250
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2251
+	 *                                                 column on the JOIN table and currently only the HABTM models
2252
+	 *                                                 accept these additional conditions.  Also remember that if an
2253
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2254
+	 *                                                 NEW row is created in the join table.
2255
+	 * @param null   $cache_id
2256
+	 * @return EE_Base_Class the object the relation was added to
2257
+	 * @throws ReflectionException
2258
+	 * @throws InvalidArgumentException
2259
+	 * @throws InvalidInterfaceException
2260
+	 * @throws InvalidDataTypeException
2261
+	 * @throws EE_Error
2262
+	 */
2263
+	public function _add_relation_to(
2264
+		$otherObjectModelObjectOrID,
2265
+		$relation_name,
2266
+		$extra_join_model_fields_n_values = [],
2267
+		$cache_id = null
2268
+	) {
2269
+		$model = $this->get_model();
2270
+		// if this thing exists in the DB, save the relation to the DB
2271
+		if ($this->ID()) {
2272
+			$otherObject = $model->add_relationship_to(
2273
+				$this,
2274
+				$otherObjectModelObjectOrID,
2275
+				$relation_name,
2276
+				$extra_join_model_fields_n_values
2277
+			);
2278
+			// clear cache so future get_many_related and get_first_related() return new results.
2279
+			$this->clear_cache($relation_name, $otherObject, true);
2280
+			if ($otherObject instanceof EE_Base_Class) {
2281
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2282
+			}
2283
+		} else {
2284
+			// this thing doesn't exist in the DB,  so just cache it
2285
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2286
+				throw new EE_Error(
2287
+					sprintf(
2288
+						esc_html__(
2289
+							'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',
2290
+							'event_espresso'
2291
+						),
2292
+						$otherObjectModelObjectOrID,
2293
+						get_class($this)
2294
+					)
2295
+				);
2296
+			}
2297
+			$otherObject = $otherObjectModelObjectOrID;
2298
+			$this->cache($relation_name, $otherObjectModelObjectOrID, $cache_id);
2299
+		}
2300
+		if ($otherObject instanceof EE_Base_Class) {
2301
+			// fix the reciprocal relation too
2302
+			if ($otherObject->ID()) {
2303
+				// its saved so assumed relations exist in the DB, so we can just
2304
+				// clear the cache so future queries use the updated info in the DB
2305
+				$otherObject->clear_cache(
2306
+					$model->get_this_model_name(),
2307
+					null,
2308
+					true
2309
+				);
2310
+			} else {
2311
+				// it's not saved, so it caches relations like this
2312
+				$otherObject->cache($model->get_this_model_name(), $this);
2313
+			}
2314
+		}
2315
+		return $otherObject;
2316
+	}
2317
+
2318
+
2319
+	/**
2320
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2321
+	 * model is related to a group of events, the $relation_name should be 'Events', and should be a key in the EE
2322
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2323
+	 * from the cache
2324
+	 *
2325
+	 * @param mixed  $otherObjectModelObjectOrID
2326
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2327
+	 *                to the DB yet
2328
+	 * @param string $relation_name
2329
+	 * @param array  $where_query
2330
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2331
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2332
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2333
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2334
+	 *                deleted.
2335
+	 * @return EE_Base_Class|bool   the related entity that was removed
2336
+	 *                              or true if multiple entities removed
2337
+	 *                              or false if nothing was cached
2338
+	 * @throws ReflectionException
2339
+	 * @throws InvalidArgumentException
2340
+	 * @throws InvalidInterfaceException
2341
+	 * @throws InvalidDataTypeException
2342
+	 * @throws EE_Error
2343
+	 */
2344
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relation_name, $where_query = [])
2345
+	{
2346
+		if ($this->ID()) {
2347
+			// if this exists in the DB, save the relation change to the DB too
2348
+			$otherObject = $this->get_model()->remove_relationship_to(
2349
+				$this,
2350
+				$otherObjectModelObjectOrID,
2351
+				$relation_name,
2352
+				$where_query
2353
+			);
2354
+			$this->clear_cache(
2355
+				$relation_name,
2356
+				$otherObject
2357
+			);
2358
+		} else {
2359
+			// this doesn't exist in the DB, just remove it from the cache
2360
+			$otherObject = $this->clear_cache(
2361
+				$relation_name,
2362
+				$otherObjectModelObjectOrID
2363
+			);
2364
+		}
2365
+		if ($otherObject instanceof EE_Base_Class) {
2366
+			$otherObject->clear_cache(
2367
+				$this->get_model()->get_this_model_name(),
2368
+				$this
2369
+			);
2370
+		}
2371
+		return $otherObject;
2372
+	}
2373
+
2374
+
2375
+	/**
2376
+	 * Removes ALL the related things for the $relation_name.
2377
+	 *
2378
+	 * @param string $relation_name
2379
+	 * @param array  $where_query_params @see
2380
+	 *                                   https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2381
+	 * @return EE_Base_Class
2382
+	 * @throws ReflectionException
2383
+	 * @throws InvalidArgumentException
2384
+	 * @throws InvalidInterfaceException
2385
+	 * @throws InvalidDataTypeException
2386
+	 * @throws EE_Error
2387
+	 */
2388
+	public function _remove_relations($relation_name, $where_query_params = [])
2389
+	{
2390
+		if ($this->ID()) {
2391
+			// if this exists in the DB, save the relation change to the DB too
2392
+			$otherObjects = $this->get_model()->remove_relations(
2393
+				$this,
2394
+				$relation_name,
2395
+				$where_query_params
2396
+			);
2397
+			$this->clear_cache(
2398
+				$relation_name,
2399
+				null,
2400
+				true
2401
+			);
2402
+		} else {
2403
+			// this doesn't exist in the DB, just remove it from the cache
2404
+			$otherObjects = $this->clear_cache(
2405
+				$relation_name,
2406
+				null,
2407
+				true
2408
+			);
2409
+		}
2410
+		if (is_array($otherObjects)) {
2411
+			foreach ($otherObjects as $otherObject) {
2412
+				$otherObject->clear_cache(
2413
+					$this->get_model()->get_this_model_name(),
2414
+					$this
2415
+				);
2416
+			}
2417
+		}
2418
+		return $otherObjects;
2419
+	}
2420
+
2421
+
2422
+	/**
2423
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2424
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2425
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2426
+	 * because we want to get even deleted items etc.
2427
+	 *
2428
+	 * @param string      $relation_name key in the model's _model_relations array
2429
+	 * @param array|null  $query_params  @see
2430
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2431
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2432
+	 *                              keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2433
+	 *                              results if you want IDs
2434
+	 * @throws ReflectionException
2435
+	 * @throws InvalidArgumentException
2436
+	 * @throws InvalidInterfaceException
2437
+	 * @throws InvalidDataTypeException
2438
+	 * @throws EE_Error
2439
+	 */
2440
+	public function get_many_related($relation_name, $query_params = [])
2441
+	{
2442
+		if ($this->ID()) {
2443
+			// this exists in the DB, so get the related things from either the cache or the DB
2444
+			// if there are query parameters, forget about caching the related model objects.
2445
+			if ($query_params) {
2446
+				$related_model_objects = $this->get_model()->get_all_related(
2447
+					$this,
2448
+					$relation_name,
2449
+					$query_params
2450
+				);
2451
+			} else {
2452
+				// did we already cache the result of this query?
2453
+				$cached_results = $this->get_all_from_cache($relation_name);
2454
+				if (! $cached_results) {
2455
+					$related_model_objects = $this->get_model()->get_all_related(
2456
+						$this,
2457
+						$relation_name,
2458
+						$query_params
2459
+					);
2460
+					// if no query parameters were passed, then we got all the related model objects
2461
+					// for that relation. We can cache them then.
2462
+					foreach ($related_model_objects as $related_model_object) {
2463
+						$this->cache($relation_name, $related_model_object);
2464
+					}
2465
+				} else {
2466
+					$related_model_objects = $cached_results;
2467
+				}
2468
+			}
2469
+		} else {
2470
+			// this doesn't exist in the DB, so just get the related things from the cache
2471
+			$related_model_objects = $this->get_all_from_cache($relation_name);
2472
+		}
2473
+		return $related_model_objects;
2474
+	}
2475
+
2476
+
2477
+	/**
2478
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2479
+	 * unless otherwise specified in the $query_params
2480
+	 *
2481
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2482
+	 * @param array  $query_params   @see
2483
+	 *                               https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2484
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2485
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2486
+	 *                               that by the setting $distinct to TRUE;
2487
+	 * @return int
2488
+	 * @throws ReflectionException
2489
+	 * @throws InvalidArgumentException
2490
+	 * @throws InvalidInterfaceException
2491
+	 * @throws InvalidDataTypeException
2492
+	 * @throws EE_Error
2493
+	 */
2494
+	public function count_related($relation_name, $query_params = [], $field_to_count = null, $distinct = false)
2495
+	{
2496
+		return $this->get_model()->count_related(
2497
+			$this,
2498
+			$relation_name,
2499
+			$query_params,
2500
+			$field_to_count,
2501
+			$distinct
2502
+		);
2503
+	}
2504
+
2505
+
2506
+	/**
2507
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2508
+	 * Note: ignores default_where_conditions by default, 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
2512
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2513
+	 * @param string $field_to_sum  name of field to count by.
2514
+	 *                              By default, uses primary key
2515
+	 *                              (which doesn't make much sense, so you should probably change it)
2516
+	 * @return int
2517
+	 * @throws ReflectionException
2518
+	 * @throws InvalidArgumentException
2519
+	 * @throws InvalidInterfaceException
2520
+	 * @throws InvalidDataTypeException
2521
+	 * @throws EE_Error
2522
+	 */
2523
+	public function sum_related($relation_name, $query_params = [], $field_to_sum = null)
2524
+	{
2525
+		return $this->get_model()->sum_related(
2526
+			$this,
2527
+			$relation_name,
2528
+			$query_params,
2529
+			$field_to_sum
2530
+		);
2531
+	}
2532
+
2533
+
2534
+	/**
2535
+	 * Gets the first (ie, one) related model object of the specified type.
2536
+	 *
2537
+	 * @param string $relation_name key in the model's _model_relations array
2538
+	 * @param array  $query_params  @see
2539
+	 *                              https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2540
+	 * @return EE_Base_Class|null (not an array, a single object)
2541
+	 * @throws ReflectionException
2542
+	 * @throws InvalidArgumentException
2543
+	 * @throws InvalidInterfaceException
2544
+	 * @throws InvalidDataTypeException
2545
+	 * @throws EE_Error
2546
+	 */
2547
+	public function get_first_related(string $relation_name, array $query_params = []): ?EE_Base_Class
2548
+	{
2549
+		$model = $this->get_model();
2550
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2551
+			// if they've provided some query parameters, don't bother trying to cache the result
2552
+			// also make sure we're not caching the result of get_first_related
2553
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2554
+			if (
2555
+				$query_params
2556
+				|| ! $model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation
2557
+			) {
2558
+				$related_model_object = $model->get_first_related(
2559
+					$this,
2560
+					$relation_name,
2561
+					$query_params
2562
+				);
2563
+			} else {
2564
+				// first, check if we've already cached the result of this query
2565
+				$cached_result = $this->get_one_from_cache($relation_name);
2566
+				if (! $cached_result) {
2567
+					$related_model_object = $model->get_first_related(
2568
+						$this,
2569
+						$relation_name,
2570
+						$query_params
2571
+					);
2572
+					$this->cache($relation_name, $related_model_object);
2573
+				} else {
2574
+					$related_model_object = $cached_result;
2575
+				}
2576
+			}
2577
+		} else {
2578
+			$related_model_object = null;
2579
+			// this doesn't exist in the Db,
2580
+			// but maybe the relation is of type belongs to, and so the related thing might
2581
+			if ($model->related_settings_for($relation_name) instanceof EE_Belongs_To_Relation) {
2582
+				$related_model_object = $model->get_first_related(
2583
+					$this,
2584
+					$relation_name,
2585
+					$query_params
2586
+				);
2587
+			}
2588
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2589
+			// just get what's cached on this object
2590
+			if (! $related_model_object) {
2591
+				$related_model_object = $this->get_one_from_cache($relation_name);
2592
+			}
2593
+		}
2594
+		return $related_model_object;
2595
+	}
2596
+
2597
+
2598
+	/**
2599
+	 * Does a delete on all related objects of type $relation_name and removes
2600
+	 * the current model object's relation to them. If they can't be deleted (because
2601
+	 * of blocking related model objects) does nothing. If the related model objects are
2602
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2603
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2604
+	 *
2605
+	 * @param string $relation_name
2606
+	 * @param array  $query_params @see
2607
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2608
+	 * @return int how many deleted
2609
+	 * @throws ReflectionException
2610
+	 * @throws InvalidArgumentException
2611
+	 * @throws InvalidInterfaceException
2612
+	 * @throws InvalidDataTypeException
2613
+	 * @throws EE_Error
2614
+	 */
2615
+	public function delete_related($relation_name, $query_params = [])
2616
+	{
2617
+		if ($this->ID()) {
2618
+			$count = $this->get_model()->delete_related(
2619
+				$this,
2620
+				$relation_name,
2621
+				$query_params
2622
+			);
2623
+		} else {
2624
+			$count = count($this->get_all_from_cache($relation_name));
2625
+			$this->clear_cache($relation_name, null, true);
2626
+		}
2627
+		return $count;
2628
+	}
2629
+
2630
+
2631
+	/**
2632
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relation_name and removes
2633
+	 * the current model object's relation to them. If they can't be deleted (because
2634
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2635
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2636
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2637
+	 *
2638
+	 * @param string $relation_name
2639
+	 * @param array  $query_params @see
2640
+	 *                             https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2641
+	 * @return int how many deleted (including those soft deleted)
2642
+	 * @throws ReflectionException
2643
+	 * @throws InvalidArgumentException
2644
+	 * @throws InvalidInterfaceException
2645
+	 * @throws InvalidDataTypeException
2646
+	 * @throws EE_Error
2647
+	 */
2648
+	public function delete_related_permanently($relation_name, $query_params = [])
2649
+	{
2650
+		$count = $this->ID()
2651
+			? $this->get_model()->delete_related_permanently(
2652
+				$this,
2653
+				$relation_name,
2654
+				$query_params
2655
+			)
2656
+			: count($this->get_all_from_cache($relation_name));
2657
+
2658
+		$this->clear_cache($relation_name, null, true);
2659
+		return $count;
2660
+	}
2661
+
2662
+
2663
+	/**
2664
+	 * is_set
2665
+	 * Just a simple utility function children can use for checking if property exists
2666
+	 *
2667
+	 * @access  public
2668
+	 * @param string $field_name property to check
2669
+	 * @return bool                              TRUE if existing,FALSE if not.
2670
+	 */
2671
+	public function is_set($field_name)
2672
+	{
2673
+		return isset($this->_fields[ $field_name ]);
2674
+	}
2675
+
2676
+
2677
+	/**
2678
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2679
+	 * EE_Error exception if they don't
2680
+	 *
2681
+	 * @param mixed (string|array) $properties properties to check
2682
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2683
+	 * @throws EE_Error
2684
+	 */
2685
+	protected function _property_exists($properties)
2686
+	{
2687
+		foreach ((array) $properties as $property_name) {
2688
+			// first make sure this property exists
2689
+			if (! $this->_fields[ $property_name ]) {
2690
+				throw new EE_Error(
2691
+					sprintf(
2692
+						esc_html__(
2693
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2694
+							'event_espresso'
2695
+						),
2696
+						$property_name
2697
+					)
2698
+				);
2699
+			}
2700
+		}
2701
+		return true;
2702
+	}
2703
+
2704
+
2705
+	/**
2706
+	 * This simply returns an array of model fields for this object
2707
+	 *
2708
+	 * @return array
2709
+	 * @throws ReflectionException
2710
+	 * @throws InvalidArgumentException
2711
+	 * @throws InvalidInterfaceException
2712
+	 * @throws InvalidDataTypeException
2713
+	 * @throws EE_Error
2714
+	 */
2715
+	public function model_field_array()
2716
+	{
2717
+		$fields     = $this->get_model()->field_settings(false);
2718
+		$properties = [];
2719
+		// remove prepended underscore
2720
+		foreach ($fields as $field_name => $settings) {
2721
+			$properties[ $field_name ] = $this->get($field_name);
2722
+		}
2723
+		return $properties;
2724
+	}
2725
+
2726
+
2727
+	/**
2728
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2729
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2730
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2731
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2732
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2733
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2734
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2735
+	 * and accepts 2 arguments: the object on which the function was called,
2736
+	 * and an array of the original arguments passed to the function.
2737
+	 * Whatever their callback function returns will be returned by this function.
2738
+	 * Example: in functions.php (or in a plugin):
2739
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2740
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2741
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2742
+	 *          return $previousReturnValue.$returnString;
2743
+	 *      }
2744
+	 * require('EE_Answer.class.php');
2745
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2746
+	 *      ->my_callback('monkeys',100);
2747
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2748
+	 *
2749
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2750
+	 * @param array  $args       array of original arguments passed to the function
2751
+	 * @return mixed whatever the plugin which calls add_filter decides
2752
+	 * @throws EE_Error
2753
+	 */
2754
+	public function __call($methodName, $args)
2755
+	{
2756
+		$className = get_class($this);
2757
+		$tagName   = "FHEE__{$className}__{$methodName}";
2758
+		if (! has_filter($tagName)) {
2759
+			throw new EE_Error(
2760
+				sprintf(
2761
+					esc_html__(
2762
+						"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;}",
2763
+						'event_espresso'
2764
+					),
2765
+					$methodName,
2766
+					$className,
2767
+					$tagName
2768
+				)
2769
+			);
2770
+		}
2771
+		return apply_filters($tagName, null, $this, $args);
2772
+	}
2773
+
2774
+
2775
+	/**
2776
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2777
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2778
+	 *
2779
+	 * @param string $meta_key
2780
+	 * @param mixed  $meta_value
2781
+	 * @param mixed  $previous_value
2782
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2783
+	 *                  NOTE: if the values haven't changed, returns 0
2784
+	 * @throws InvalidArgumentException
2785
+	 * @throws InvalidInterfaceException
2786
+	 * @throws InvalidDataTypeException
2787
+	 * @throws EE_Error
2788
+	 * @throws ReflectionException
2789
+	 */
2790
+	public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2791
+	{
2792
+		$query_params = [
2793
+			[
2794
+				'EXM_key'  => $meta_key,
2795
+				'OBJ_ID'   => $this->ID(),
2796
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2797
+			],
2798
+		];
2799
+		if ($previous_value !== null) {
2800
+			$query_params[0]['EXM_value'] = $meta_value;
2801
+		}
2802
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2803
+		if (! $existing_rows_like_that) {
2804
+			return $this->add_extra_meta($meta_key, $meta_value);
2805
+		}
2806
+		foreach ($existing_rows_like_that as $existing_row) {
2807
+			$existing_row->save(['EXM_value' => $meta_value]);
2808
+		}
2809
+		return count($existing_rows_like_that);
2810
+	}
2811
+
2812
+
2813
+	/**
2814
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2815
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2816
+	 * extra meta row was entered, false if not
2817
+	 *
2818
+	 * @param string $meta_key
2819
+	 * @param mixed  $meta_value
2820
+	 * @param bool   $unique
2821
+	 * @return bool
2822
+	 * @throws InvalidArgumentException
2823
+	 * @throws InvalidInterfaceException
2824
+	 * @throws InvalidDataTypeException
2825
+	 * @throws EE_Error
2826
+	 * @throws ReflectionException
2827
+	 */
2828
+	public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2829
+	{
2830
+		if ($unique) {
2831
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2832
+				[
2833
+					[
2834
+						'EXM_key'  => $meta_key,
2835
+						'OBJ_ID'   => $this->ID(),
2836
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2837
+					],
2838
+				]
2839
+			);
2840
+			if ($existing_extra_meta) {
2841
+				return false;
2842
+			}
2843
+		}
2844
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2845
+			[
2846
+				'EXM_key'   => $meta_key,
2847
+				'EXM_value' => $meta_value,
2848
+				'OBJ_ID'    => $this->ID(),
2849
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2850
+			]
2851
+		);
2852
+		$new_extra_meta->save();
2853
+		return true;
2854
+	}
2855
+
2856
+
2857
+	/**
2858
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2859
+	 * is specified, only deletes extra meta records with that value.
2860
+	 *
2861
+	 * @param string $meta_key
2862
+	 * @param mixed  $meta_value
2863
+	 * @return int number of extra meta rows deleted
2864
+	 * @throws InvalidArgumentException
2865
+	 * @throws InvalidInterfaceException
2866
+	 * @throws InvalidDataTypeException
2867
+	 * @throws EE_Error
2868
+	 * @throws ReflectionException
2869
+	 */
2870
+	public function delete_extra_meta(string $meta_key, $meta_value = null)
2871
+	{
2872
+		$query_params = [
2873
+			[
2874
+				'EXM_key'  => $meta_key,
2875
+				'OBJ_ID'   => $this->ID(),
2876
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2877
+			],
2878
+		];
2879
+		if ($meta_value !== null) {
2880
+			$query_params[0]['EXM_value'] = $meta_value;
2881
+		}
2882
+		return EEM_Extra_Meta::instance()->delete($query_params);
2883
+	}
2884
+
2885
+
2886
+	/**
2887
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2888
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2889
+	 * You can specify $default is case you haven't found the extra meta
2890
+	 *
2891
+	 * @param string     $meta_key
2892
+	 * @param bool       $single
2893
+	 * @param mixed      $default if we don't find anything, what should we return?
2894
+	 * @param array|null $extra_where
2895
+	 * @return mixed single value if $single; array if ! $single
2896
+	 * @throws ReflectionException
2897
+	 * @throws EE_Error
2898
+	 */
2899
+	public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2900
+	{
2901
+		$query_params = [$extra_where + ['EXM_key' => $meta_key]];
2902
+		if ($single) {
2903
+			$result = $this->get_first_related('Extra_Meta', $query_params);
2904
+			if ($result instanceof EE_Extra_Meta) {
2905
+				return $result->value();
2906
+			}
2907
+		} else {
2908
+			$results = $this->get_many_related('Extra_Meta', $query_params);
2909
+			if ($results) {
2910
+				$values = [];
2911
+				foreach ($results as $result) {
2912
+					if ($result instanceof EE_Extra_Meta) {
2913
+						$values[ $result->ID() ] = $result->value();
2914
+					}
2915
+				}
2916
+				return $values;
2917
+			}
2918
+		}
2919
+		// if nothing discovered yet return default.
2920
+		return apply_filters(
2921
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2922
+			$default,
2923
+			$meta_key,
2924
+			$single,
2925
+			$this
2926
+		);
2927
+	}
2928
+
2929
+
2930
+	/**
2931
+	 * Returns a simple array of all the extra meta associated with this model object.
2932
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2933
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2934
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2935
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2936
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2937
+	 * finally the extra meta's value as each sub-value. (eg
2938
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2939
+	 *
2940
+	 * @param bool $one_of_each_key
2941
+	 * @return array
2942
+	 * @throws ReflectionException
2943
+	 * @throws InvalidArgumentException
2944
+	 * @throws InvalidInterfaceException
2945
+	 * @throws InvalidDataTypeException
2946
+	 * @throws EE_Error
2947
+	 */
2948
+	public function all_extra_meta_array(bool $one_of_each_key = true): array
2949
+	{
2950
+		$return_array = [];
2951
+		if ($one_of_each_key) {
2952
+			$extra_meta_objs = $this->get_many_related(
2953
+				'Extra_Meta',
2954
+				['group_by' => 'EXM_key']
2955
+			);
2956
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2957
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2958
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2959
+				}
2960
+			}
2961
+		} else {
2962
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2963
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2964
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2965
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2966
+						$return_array[ $extra_meta_obj->key() ] = [];
2967
+					}
2968
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2969
+				}
2970
+			}
2971
+		}
2972
+		return $return_array;
2973
+	}
2974
+
2975
+
2976
+	/**
2977
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2978
+	 *
2979
+	 * @return string
2980
+	 * @throws ReflectionException
2981
+	 * @throws InvalidArgumentException
2982
+	 * @throws InvalidInterfaceException
2983
+	 * @throws InvalidDataTypeException
2984
+	 * @throws EE_Error
2985
+	 */
2986
+	public function name()
2987
+	{
2988
+		// find a field that's not a text field
2989
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2990
+		if ($field_we_can_use) {
2991
+			return $this->get($field_we_can_use->get_name());
2992
+		}
2993
+		$first_few_properties = $this->model_field_array();
2994
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
2995
+		$name_parts           = [];
2996
+		foreach ($first_few_properties as $name => $value) {
2997
+			$name_parts[] = "$name:$value";
2998
+		}
2999
+		return implode(',', $name_parts);
3000
+	}
3001
+
3002
+
3003
+	/**
3004
+	 * in_entity_map
3005
+	 * Checks if this model object has been proven to already be in the entity map
3006
+	 *
3007
+	 * @return boolean
3008
+	 * @throws ReflectionException
3009
+	 * @throws InvalidArgumentException
3010
+	 * @throws InvalidInterfaceException
3011
+	 * @throws InvalidDataTypeException
3012
+	 * @throws EE_Error
3013
+	 */
3014
+	public function in_entity_map()
3015
+	{
3016
+		// well, if we looked, did we find it in the entity map?
3017
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3018
+	}
3019
+
3020
+
3021
+	/**
3022
+	 * refresh_from_db
3023
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3024
+	 *
3025
+	 * @throws ReflectionException
3026
+	 * @throws InvalidArgumentException
3027
+	 * @throws InvalidInterfaceException
3028
+	 * @throws InvalidDataTypeException
3029
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3030
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3031
+	 */
3032
+	public function refresh_from_db()
3033
+	{
3034
+		if ($this->ID() && $this->in_entity_map()) {
3035
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3036
+		} else {
3037
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3038
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3039
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3040
+			// absolutely nothing in it for this ID
3041
+			if (WP_DEBUG) {
3042
+				throw new EE_Error(
3043
+					sprintf(
3044
+						esc_html__(
3045
+							'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.',
3046
+							'event_espresso'
3047
+						),
3048
+						$this->ID(),
3049
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3050
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3051
+					)
3052
+				);
3053
+			}
3054
+		}
3055
+	}
3056
+
3057
+
3058
+	/**
3059
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3060
+	 *
3061
+	 * @param EE_Model_Field_Base[] $fields
3062
+	 * @param string                $new_value_sql
3063
+	 *          example: 'column_name=123',
3064
+	 *          or 'column_name=column_name+1',
3065
+	 *          or 'column_name= CASE
3066
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3067
+	 *          THEN `column_name` + 5
3068
+	 *          ELSE `column_name`
3069
+	 *          END'
3070
+	 *          Also updates $field on this model object with the latest value from the database.
3071
+	 * @return bool
3072
+	 * @throws EE_Error
3073
+	 * @throws InvalidArgumentException
3074
+	 * @throws InvalidDataTypeException
3075
+	 * @throws InvalidInterfaceException
3076
+	 * @throws ReflectionException
3077
+	 * @since 4.9.80.p
3078
+	 */
3079
+	protected function updateFieldsInDB($fields, $new_value_sql)
3080
+	{
3081
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3082
+		// if it wasn't even there to start off.
3083
+		if (! $this->ID()) {
3084
+			$this->save();
3085
+		}
3086
+		global $wpdb;
3087
+		if (empty($fields)) {
3088
+			throw new InvalidArgumentException(
3089
+				esc_html__(
3090
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3091
+					'event_espresso'
3092
+				)
3093
+			);
3094
+		}
3095
+		$first_field = reset($fields);
3096
+		$table_alias = $first_field->get_table_alias();
3097
+		foreach ($fields as $field) {
3098
+			if ($table_alias !== $field->get_table_alias()) {
3099
+				throw new InvalidArgumentException(
3100
+					sprintf(
3101
+						esc_html__(
3102
+						// @codingStandardsIgnoreStart
3103
+							'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.',
3104
+							// @codingStandardsIgnoreEnd
3105
+							'event_espresso'
3106
+						),
3107
+						$table_alias,
3108
+						$field->get_table_alias()
3109
+					)
3110
+				);
3111
+			}
3112
+		}
3113
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3114
+		$table_obj      = $this->get_model()->get_table_obj_by_alias($table_alias);
3115
+		$table_pk_value = $this->ID();
3116
+		$table_name     = $table_obj->get_table_name();
3117
+		if ($table_obj instanceof EE_Secondary_Table) {
3118
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3119
+		} else {
3120
+			$table_pk_field_name = $table_obj->get_pk_column();
3121
+		}
3122
+
3123
+		$query  =
3124
+			"UPDATE `{$table_name}`
3125 3125
             SET "
3126
-            . $new_value_sql
3127
-            . $wpdb->prepare(
3128
-                "
3126
+			. $new_value_sql
3127
+			. $wpdb->prepare(
3128
+				"
3129 3129
             WHERE `{$table_pk_field_name}` = %d;",
3130
-                $table_pk_value
3131
-            );
3132
-        $result = $wpdb->query($query);
3133
-        foreach ($fields as $field) {
3134
-            // If it was successful, we'd like to know the new value.
3135
-            // If it failed, we'd also like to know the new value.
3136
-            $new_value = $this->get_model()->get_var(
3137
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3138
-                    $this->get_model()->get_index_primary_key_string(
3139
-                        $this->model_field_array()
3140
-                    ),
3141
-                    [
3142
-                        'default_where_conditions' => 'minimum',
3143
-                    ]
3144
-                ),
3145
-                $field->get_name()
3146
-            );
3147
-            $this->set_from_db(
3148
-                $field->get_name(),
3149
-                $new_value
3150
-            );
3151
-        }
3152
-        return (bool) $result;
3153
-    }
3154
-
3155
-
3156
-    /**
3157
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3158
-     * Does not allow negative values, however.
3159
-     *
3160
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3161
-     *                                   (positive or negative). One important gotcha: all these values must be
3162
-     *                                   on the same table (eg don't pass in one field for the posts table and
3163
-     *                                   another for the event meta table.)
3164
-     * @return bool
3165
-     * @throws EE_Error
3166
-     * @throws InvalidArgumentException
3167
-     * @throws InvalidDataTypeException
3168
-     * @throws InvalidInterfaceException
3169
-     * @throws ReflectionException
3170
-     * @since 4.9.80.p
3171
-     */
3172
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3173
-    {
3174
-        global $wpdb;
3175
-        if (empty($fields_n_quantities)) {
3176
-            // No fields to update? Well sure, we updated them to that value just fine.
3177
-            return true;
3178
-        }
3179
-        $fields             = [];
3180
-        $set_sql_statements = [];
3181
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3182
-            $field       = $this->get_model()->field_settings_for($field_name, true);
3183
-            $fields[]    = $field;
3184
-            $column_name = $field->get_table_column();
3185
-
3186
-            $abs_qty = absint($quantity);
3187
-            if ($quantity > 0) {
3188
-                // don't let the value be negative as often these fields are unsigned
3189
-                $set_sql_statements[] = $wpdb->prepare(
3190
-                    "`{$column_name}` = `{$column_name}` + %d",
3191
-                    $abs_qty
3192
-                );
3193
-            } else {
3194
-                $set_sql_statements[] = $wpdb->prepare(
3195
-                    "`{$column_name}` = CASE
3130
+				$table_pk_value
3131
+			);
3132
+		$result = $wpdb->query($query);
3133
+		foreach ($fields as $field) {
3134
+			// If it was successful, we'd like to know the new value.
3135
+			// If it failed, we'd also like to know the new value.
3136
+			$new_value = $this->get_model()->get_var(
3137
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3138
+					$this->get_model()->get_index_primary_key_string(
3139
+						$this->model_field_array()
3140
+					),
3141
+					[
3142
+						'default_where_conditions' => 'minimum',
3143
+					]
3144
+				),
3145
+				$field->get_name()
3146
+			);
3147
+			$this->set_from_db(
3148
+				$field->get_name(),
3149
+				$new_value
3150
+			);
3151
+		}
3152
+		return (bool) $result;
3153
+	}
3154
+
3155
+
3156
+	/**
3157
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3158
+	 * Does not allow negative values, however.
3159
+	 *
3160
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3161
+	 *                                   (positive or negative). One important gotcha: all these values must be
3162
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3163
+	 *                                   another for the event meta table.)
3164
+	 * @return bool
3165
+	 * @throws EE_Error
3166
+	 * @throws InvalidArgumentException
3167
+	 * @throws InvalidDataTypeException
3168
+	 * @throws InvalidInterfaceException
3169
+	 * @throws ReflectionException
3170
+	 * @since 4.9.80.p
3171
+	 */
3172
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3173
+	{
3174
+		global $wpdb;
3175
+		if (empty($fields_n_quantities)) {
3176
+			// No fields to update? Well sure, we updated them to that value just fine.
3177
+			return true;
3178
+		}
3179
+		$fields             = [];
3180
+		$set_sql_statements = [];
3181
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3182
+			$field       = $this->get_model()->field_settings_for($field_name, true);
3183
+			$fields[]    = $field;
3184
+			$column_name = $field->get_table_column();
3185
+
3186
+			$abs_qty = absint($quantity);
3187
+			if ($quantity > 0) {
3188
+				// don't let the value be negative as often these fields are unsigned
3189
+				$set_sql_statements[] = $wpdb->prepare(
3190
+					"`{$column_name}` = `{$column_name}` + %d",
3191
+					$abs_qty
3192
+				);
3193
+			} else {
3194
+				$set_sql_statements[] = $wpdb->prepare(
3195
+					"`{$column_name}` = CASE
3196 3196
                        WHEN (`{$column_name}` >= %d)
3197 3197
                        THEN `{$column_name}` - %d
3198 3198
                        ELSE 0
3199 3199
                     END",
3200
-                    $abs_qty,
3201
-                    $abs_qty
3202
-                );
3203
-            }
3204
-        }
3205
-        return $this->updateFieldsInDB(
3206
-            $fields,
3207
-            implode(', ', $set_sql_statements)
3208
-        );
3209
-    }
3210
-
3211
-
3212
-    /**
3213
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3214
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3215
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3216
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3217
-     * Otherwise returns false.
3218
-     *
3219
-     * @param string $field_name_to_bump
3220
-     * @param string $field_name_affecting_total
3221
-     * @param string $limit_field_name
3222
-     * @param int    $quantity
3223
-     * @return bool
3224
-     * @throws EE_Error
3225
-     * @throws InvalidArgumentException
3226
-     * @throws InvalidDataTypeException
3227
-     * @throws InvalidInterfaceException
3228
-     * @throws ReflectionException
3229
-     * @since 4.9.80.p
3230
-     */
3231
-    public function incrementFieldConditionallyInDb(
3232
-        $field_name_to_bump,
3233
-        $field_name_affecting_total,
3234
-        $limit_field_name,
3235
-        $quantity
3236
-    ) {
3237
-        global $wpdb;
3238
-        $field       = $this->get_model()->field_settings_for($field_name_to_bump, true);
3239
-        $column_name = $field->get_table_column();
3240
-
3241
-        $field_affecting_total  = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3242
-        $column_affecting_total = $field_affecting_total->get_table_column();
3243
-
3244
-        $limiting_field  = $this->get_model()->field_settings_for($limit_field_name, true);
3245
-        $limiting_column = $limiting_field->get_table_column();
3246
-        return $this->updateFieldsInDB(
3247
-            [$field],
3248
-            $wpdb->prepare(
3249
-                "`{$column_name}` =
3200
+					$abs_qty,
3201
+					$abs_qty
3202
+				);
3203
+			}
3204
+		}
3205
+		return $this->updateFieldsInDB(
3206
+			$fields,
3207
+			implode(', ', $set_sql_statements)
3208
+		);
3209
+	}
3210
+
3211
+
3212
+	/**
3213
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3214
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3215
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3216
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3217
+	 * Otherwise returns false.
3218
+	 *
3219
+	 * @param string $field_name_to_bump
3220
+	 * @param string $field_name_affecting_total
3221
+	 * @param string $limit_field_name
3222
+	 * @param int    $quantity
3223
+	 * @return bool
3224
+	 * @throws EE_Error
3225
+	 * @throws InvalidArgumentException
3226
+	 * @throws InvalidDataTypeException
3227
+	 * @throws InvalidInterfaceException
3228
+	 * @throws ReflectionException
3229
+	 * @since 4.9.80.p
3230
+	 */
3231
+	public function incrementFieldConditionallyInDb(
3232
+		$field_name_to_bump,
3233
+		$field_name_affecting_total,
3234
+		$limit_field_name,
3235
+		$quantity
3236
+	) {
3237
+		global $wpdb;
3238
+		$field       = $this->get_model()->field_settings_for($field_name_to_bump, true);
3239
+		$column_name = $field->get_table_column();
3240
+
3241
+		$field_affecting_total  = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3242
+		$column_affecting_total = $field_affecting_total->get_table_column();
3243
+
3244
+		$limiting_field  = $this->get_model()->field_settings_for($limit_field_name, true);
3245
+		$limiting_column = $limiting_field->get_table_column();
3246
+		return $this->updateFieldsInDB(
3247
+			[$field],
3248
+			$wpdb->prepare(
3249
+				"`{$column_name}` =
3250 3250
             CASE
3251 3251
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3252 3252
                THEN `{$column_name}` + %d
3253 3253
                ELSE `{$column_name}`
3254 3254
             END",
3255
-                $quantity,
3256
-                EE_INF_IN_DB,
3257
-                $quantity
3258
-            )
3259
-        );
3260
-    }
3261
-
3262
-
3263
-    /**
3264
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3265
-     * (probably a bad assumption they have made, oh well)
3266
-     *
3267
-     * @return string
3268
-     */
3269
-    public function __toString()
3270
-    {
3271
-        try {
3272
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3273
-        } catch (Exception $e) {
3274
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3275
-            return '';
3276
-        }
3277
-    }
3278
-
3279
-
3280
-    /**
3281
-     * Clear related model objects if they're already in the DB, because otherwise when we
3282
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3283
-     * This means if we have made changes to those related model objects, and want to unserialize
3284
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3285
-     * Instead, those related model objects should be directly serialized and stored.
3286
-     * Eg, the following won't work:
3287
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3288
-     * $att = $reg->attendee();
3289
-     * $att->set( 'ATT_fname', 'Dirk' );
3290
-     * update_option( 'my_option', serialize( $reg ) );
3291
-     * //END REQUEST
3292
-     * //START NEXT REQUEST
3293
-     * $reg = get_option( 'my_option' );
3294
-     * $reg->attendee()->save();
3295
-     * And would need to be replace with:
3296
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3297
-     * $att = $reg->attendee();
3298
-     * $att->set( 'ATT_fname', 'Dirk' );
3299
-     * update_option( 'my_option', serialize( $reg ) );
3300
-     * //END REQUEST
3301
-     * //START NEXT REQUEST
3302
-     * $att = get_option( 'my_option' );
3303
-     * $att->save();
3304
-     *
3305
-     * @return array
3306
-     * @throws ReflectionException
3307
-     * @throws InvalidArgumentException
3308
-     * @throws InvalidInterfaceException
3309
-     * @throws InvalidDataTypeException
3310
-     * @throws EE_Error
3311
-     */
3312
-    public function __sleep()
3313
-    {
3314
-        $model = $this->get_model();
3315
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3316
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3317
-                $classname = 'EE_' . $model->get_this_model_name();
3318
-                if (
3319
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3320
-                    && $this->get_one_from_cache($relation_name)->ID()
3321
-                ) {
3322
-                    $this->clear_cache(
3323
-                        $relation_name,
3324
-                        $this->get_one_from_cache($relation_name)->ID()
3325
-                    );
3326
-                }
3327
-            }
3328
-        }
3329
-        $this->_props_n_values_provided_in_constructor = [];
3330
-        $properties_to_serialize                       = get_object_vars($this);
3331
-        // don't serialize the model. It's big and that risks recursion
3332
-        unset($properties_to_serialize['_model']);
3333
-        return array_keys($properties_to_serialize);
3334
-    }
3335
-
3336
-
3337
-    /**
3338
-     * restore _props_n_values_provided_in_constructor
3339
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3340
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3341
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3342
-     */
3343
-    public function __wakeup()
3344
-    {
3345
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3346
-    }
3347
-
3348
-
3349
-    /**
3350
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3351
-     * distinct with the clone host instance are also cloned.
3352
-     */
3353
-    public function __clone()
3354
-    {
3355
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3356
-        foreach ($this->_fields as $field => $value) {
3357
-            if ($value instanceof DateTime) {
3358
-                $this->_fields[ $field ] = clone $value;
3359
-            }
3360
-        }
3361
-    }
3362
-
3363
-
3364
-    public function debug()
3365
-    {
3366
-        $this->echoProperty(get_class($this), get_object_vars($this));
3367
-        echo "\n\n";
3368
-    }
3369
-
3370
-
3371
-    private function echoProperty($field, $value, int $indent = 0)
3372
-    {
3373
-        $bullets = str_repeat(' -', $indent) . ' ';
3374
-        $field = strpos($field, '_') === 0 ? substr($field, 1) : $field;
3375
-        echo "\n$bullets$field: ";
3376
-        if ($value instanceof EEM_Base) {
3377
-            $value = get_class($value);
3378
-        } elseif (is_object($value)) {
3379
-            $value = get_object_vars($value);
3380
-        }
3381
-        if (is_array($value)) {
3382
-            foreach ($value as $f => $v) {
3383
-                $this->echoProperty($f, $v, $indent + 1);
3384
-            }
3385
-            return;
3386
-        }
3387
-        ob_start();
3388
-        var_dump($value);
3389
-        echo rtrim(ob_get_clean(), "\n");
3390
-    }
3255
+				$quantity,
3256
+				EE_INF_IN_DB,
3257
+				$quantity
3258
+			)
3259
+		);
3260
+	}
3261
+
3262
+
3263
+	/**
3264
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3265
+	 * (probably a bad assumption they have made, oh well)
3266
+	 *
3267
+	 * @return string
3268
+	 */
3269
+	public function __toString()
3270
+	{
3271
+		try {
3272
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3273
+		} catch (Exception $e) {
3274
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3275
+			return '';
3276
+		}
3277
+	}
3278
+
3279
+
3280
+	/**
3281
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3282
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3283
+	 * This means if we have made changes to those related model objects, and want to unserialize
3284
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3285
+	 * Instead, those related model objects should be directly serialized and stored.
3286
+	 * Eg, the following won't work:
3287
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3288
+	 * $att = $reg->attendee();
3289
+	 * $att->set( 'ATT_fname', 'Dirk' );
3290
+	 * update_option( 'my_option', serialize( $reg ) );
3291
+	 * //END REQUEST
3292
+	 * //START NEXT REQUEST
3293
+	 * $reg = get_option( 'my_option' );
3294
+	 * $reg->attendee()->save();
3295
+	 * And would need to be replace with:
3296
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3297
+	 * $att = $reg->attendee();
3298
+	 * $att->set( 'ATT_fname', 'Dirk' );
3299
+	 * update_option( 'my_option', serialize( $reg ) );
3300
+	 * //END REQUEST
3301
+	 * //START NEXT REQUEST
3302
+	 * $att = get_option( 'my_option' );
3303
+	 * $att->save();
3304
+	 *
3305
+	 * @return array
3306
+	 * @throws ReflectionException
3307
+	 * @throws InvalidArgumentException
3308
+	 * @throws InvalidInterfaceException
3309
+	 * @throws InvalidDataTypeException
3310
+	 * @throws EE_Error
3311
+	 */
3312
+	public function __sleep()
3313
+	{
3314
+		$model = $this->get_model();
3315
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3316
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3317
+				$classname = 'EE_' . $model->get_this_model_name();
3318
+				if (
3319
+					$this->get_one_from_cache($relation_name) instanceof $classname
3320
+					&& $this->get_one_from_cache($relation_name)->ID()
3321
+				) {
3322
+					$this->clear_cache(
3323
+						$relation_name,
3324
+						$this->get_one_from_cache($relation_name)->ID()
3325
+					);
3326
+				}
3327
+			}
3328
+		}
3329
+		$this->_props_n_values_provided_in_constructor = [];
3330
+		$properties_to_serialize                       = get_object_vars($this);
3331
+		// don't serialize the model. It's big and that risks recursion
3332
+		unset($properties_to_serialize['_model']);
3333
+		return array_keys($properties_to_serialize);
3334
+	}
3335
+
3336
+
3337
+	/**
3338
+	 * restore _props_n_values_provided_in_constructor
3339
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3340
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3341
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3342
+	 */
3343
+	public function __wakeup()
3344
+	{
3345
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3346
+	}
3347
+
3348
+
3349
+	/**
3350
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3351
+	 * distinct with the clone host instance are also cloned.
3352
+	 */
3353
+	public function __clone()
3354
+	{
3355
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3356
+		foreach ($this->_fields as $field => $value) {
3357
+			if ($value instanceof DateTime) {
3358
+				$this->_fields[ $field ] = clone $value;
3359
+			}
3360
+		}
3361
+	}
3362
+
3363
+
3364
+	public function debug()
3365
+	{
3366
+		$this->echoProperty(get_class($this), get_object_vars($this));
3367
+		echo "\n\n";
3368
+	}
3369
+
3370
+
3371
+	private function echoProperty($field, $value, int $indent = 0)
3372
+	{
3373
+		$bullets = str_repeat(' -', $indent) . ' ';
3374
+		$field = strpos($field, '_') === 0 ? substr($field, 1) : $field;
3375
+		echo "\n$bullets$field: ";
3376
+		if ($value instanceof EEM_Base) {
3377
+			$value = get_class($value);
3378
+		} elseif (is_object($value)) {
3379
+			$value = get_object_vars($value);
3380
+		}
3381
+		if (is_array($value)) {
3382
+			foreach ($value as $f => $v) {
3383
+				$this->echoProperty($f, $v, $indent + 1);
3384
+			}
3385
+			return;
3386
+		}
3387
+		ob_start();
3388
+		var_dump($value);
3389
+		echo rtrim(ob_get_clean(), "\n");
3390
+	}
3391 3391
 }
Please login to merge, or discard this patch.
Spacing   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
         $fieldValues = is_array($fieldValues) ? $fieldValues : [$fieldValues];
133 133
         // verify client code has not passed any invalid field names
134 134
         foreach ($fieldValues as $field_name => $field_value) {
135
-            if (! isset($model_fields[ $field_name ])) {
135
+            if ( ! isset($model_fields[$field_name])) {
136 136
                 throw new EE_Error(
137 137
                     sprintf(
138 138
                         esc_html__(
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
         $date_format     = null;
151 151
         $time_format     = null;
152 152
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
153
-        if (! empty($date_formats) && is_array($date_formats)) {
153
+        if ( ! empty($date_formats) && is_array($date_formats)) {
154 154
             [$date_format, $time_format] = $date_formats;
155 155
         }
156 156
         $this->set_date_format($date_format);
@@ -161,14 +161,14 @@  discard block
 block discarded – undo
161 161
                 // client code has indicated these field values are from the database
162 162
                 $this->set_from_db(
163 163
                     $fieldName,
164
-                    $fieldValues[ $fieldName ] ?? null
164
+                    $fieldValues[$fieldName] ?? null
165 165
                 );
166 166
             } else {
167 167
                 // we're constructing a brand new instance of the model object.
168 168
                 // Generally, this means we'll need to do more field validation
169 169
                 $this->set(
170 170
                     $fieldName,
171
-                    $fieldValues[ $fieldName ] ?? null,
171
+                    $fieldValues[$fieldName] ?? null,
172 172
                     true
173 173
                 );
174 174
             }
@@ -176,15 +176,15 @@  discard block
 block discarded – undo
176 176
         // remember what values were passed to this constructor
177 177
         $this->_props_n_values_provided_in_constructor = $fieldValues;
178 178
         // remember in entity mapper
179
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
179
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
180 180
             $model->add_to_entity_map($this);
181 181
         }
182 182
         // setup all the relations
183 183
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
184 184
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
185
-                $this->_model_relations[ $relation_name ] = null;
185
+                $this->_model_relations[$relation_name] = null;
186 186
             } else {
187
-                $this->_model_relations[ $relation_name ] = [];
187
+                $this->_model_relations[$relation_name] = [];
188 188
             }
189 189
         }
190 190
         /**
@@ -236,10 +236,10 @@  discard block
 block discarded – undo
236 236
     public function get_original($field_name)
237 237
     {
238 238
         if (
239
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
239
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
240 240
             && $field_settings = $this->get_model()->field_settings_for($field_name)
241 241
         ) {
242
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
242
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
243 243
         }
244 244
         return null;
245 245
     }
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
         // then don't do anything
276 276
         if (
277 277
             ! $use_default
278
-            && $this->_fields[ $field_name ] === $field_value
278
+            && $this->_fields[$field_name] === $field_value
279 279
             && $this->ID()
280 280
         ) {
281 281
             return;
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
         $model              = $this->get_model();
284 284
         $this->_has_changes = true;
285 285
         $field_obj          = $model->field_settings_for($field_name);
286
-        if (! $field_obj instanceof EE_Model_Field_Base) {
286
+        if ( ! $field_obj instanceof EE_Model_Field_Base) {
287 287
             throw new EE_Error(
288 288
                 sprintf(
289 289
                     esc_html__(
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
             ? $field_obj->get_default_value()
307 307
             : $field_value;
308 308
 
309
-        $this->_fields[ $field_name ] = $field_obj->prepare_for_set($value);
309
+        $this->_fields[$field_name] = $field_obj->prepare_for_set($value);
310 310
 
311 311
         // if we're not in the constructor...
312 312
         // now check if what we set was a primary key
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
             } else {
369 369
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
370 370
             }
371
-            $this->_fields[ $field_name ] = $field_value;
371
+            $this->_fields[$field_name] = $field_value;
372 372
             $this->_clear_cached_property($field_name);
373 373
         }
374 374
     }
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
      */
395 395
     public function getCustomSelect($alias)
396 396
     {
397
-        return $this->custom_selection_results[ $alias ] ?? null;
397
+        return $this->custom_selection_results[$alias] ?? null;
398 398
     }
399 399
 
400 400
 
@@ -481,8 +481,8 @@  discard block
 block discarded – undo
481 481
         foreach ($model_fields as $field_name => $field_obj) {
482 482
             if ($field_obj instanceof EE_Datetime_Field) {
483 483
                 $field_obj->set_timezone($this->_timezone);
484
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
485
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
484
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
485
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
486 486
                 }
487 487
             }
488 488
         }
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
      */
541 541
     public function get_format($full = true)
542 542
     {
543
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
543
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : [$this->_dt_frmt, $this->_tm_frmt];
544 544
     }
545 545
 
546 546
 
@@ -566,11 +566,11 @@  discard block
 block discarded – undo
566 566
     public function cache($relation_name = '', $object_to_cache = null, $cache_id = null)
567 567
     {
568 568
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
569
-        if (! $object_to_cache instanceof EE_Base_Class) {
569
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
570 570
             return false;
571 571
         }
572 572
         // also get "how" the object is related, or throw an error
573
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
573
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relation_name)) {
574 574
             throw new EE_Error(
575 575
                 sprintf(
576 576
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -584,38 +584,38 @@  discard block
 block discarded – undo
584 584
             // if it's a "belongs to" relationship, then there's only one related model object
585 585
             // eg, if this is a registration, there's only 1 attendee for it
586 586
             // so for these model objects just set it to be cached
587
-            $this->_model_relations[ $relation_name ] = $object_to_cache;
587
+            $this->_model_relations[$relation_name] = $object_to_cache;
588 588
             $return                                   = true;
589 589
         } else {
590 590
             // otherwise, this is the "many" side of a one to many relationship,
591 591
             // so we'll add the object to the array of related objects for that type.
592 592
             // eg: if this is an event, there are many registrations for that event,
593 593
             // so we cache the registrations in an array
594
-            if (! is_array($this->_model_relations[ $relation_name ])) {
594
+            if ( ! is_array($this->_model_relations[$relation_name])) {
595 595
                 // if for some reason, the cached item is a model object,
596 596
                 // then stick that in the array, otherwise start with an empty array
597
-                $this->_model_relations[ $relation_name ] =
598
-                    $this->_model_relations[ $relation_name ] instanceof EE_Base_Class
599
-                        ? [$this->_model_relations[ $relation_name ]]
597
+                $this->_model_relations[$relation_name] =
598
+                    $this->_model_relations[$relation_name] instanceof EE_Base_Class
599
+                        ? [$this->_model_relations[$relation_name]]
600 600
                         : [];
601 601
             }
602 602
             // first check for a cache_id which is normally empty
603
-            if (! empty($cache_id)) {
603
+            if ( ! empty($cache_id)) {
604 604
                 // if the cache_id exists, then it means we are purposely trying to cache this
605 605
                 // with a known key that can then be used to retrieve the object later on
606
-                $this->_model_relations[ $relation_name ][ $cache_id ] = $object_to_cache;
606
+                $this->_model_relations[$relation_name][$cache_id] = $object_to_cache;
607 607
                 $return                                                = $cache_id;
608 608
             } elseif ($object_to_cache->ID()) {
609 609
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
610
-                $this->_model_relations[ $relation_name ][ $object_to_cache->ID() ] = $object_to_cache;
610
+                $this->_model_relations[$relation_name][$object_to_cache->ID()] = $object_to_cache;
611 611
                 $return                                                             = $object_to_cache->ID();
612 612
             } else {
613 613
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
614
-                $this->_model_relations[ $relation_name ][] = $object_to_cache;
614
+                $this->_model_relations[$relation_name][] = $object_to_cache;
615 615
                 // move the internal pointer to the end of the array
616
-                end($this->_model_relations[ $relation_name ]);
616
+                end($this->_model_relations[$relation_name]);
617 617
                 // and grab the key so that we can return it
618
-                $return = key($this->_model_relations[ $relation_name ]);
618
+                $return = key($this->_model_relations[$relation_name]);
619 619
             }
620 620
         }
621 621
         return $return;
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
         $this->get_model()->field_settings_for($fieldname);
643 643
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
644 644
 
645
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
645
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
646 646
     }
647 647
 
648 648
 
@@ -671,9 +671,9 @@  discard block
 block discarded – undo
671 671
         $model = $this->get_model();
672 672
         $model->field_settings_for($fieldname);
673 673
         $cache_type = $pretty ? 'pretty' : 'standard';
674
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
675
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
676
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
674
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
675
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
676
+            return $this->_cached_properties[$fieldname][$cache_type];
677 677
         }
678 678
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
679 679
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -701,12 +701,12 @@  discard block
 block discarded – undo
701 701
         if ($field_obj instanceof EE_Datetime_Field) {
702 702
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
703 703
         }
704
-        if (! isset($this->_fields[ $fieldname ])) {
705
-            $this->_fields[ $fieldname ] = null;
704
+        if ( ! isset($this->_fields[$fieldname])) {
705
+            $this->_fields[$fieldname] = null;
706 706
         }
707 707
         return $pretty
708
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
709
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
708
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
709
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
710 710
     }
711 711
 
712 712
 
@@ -762,8 +762,8 @@  discard block
 block discarded – undo
762 762
      */
763 763
     protected function _clear_cached_property($property_name)
764 764
     {
765
-        if (isset($this->_cached_properties[ $property_name ])) {
766
-            unset($this->_cached_properties[ $property_name ]);
765
+        if (isset($this->_cached_properties[$property_name])) {
766
+            unset($this->_cached_properties[$property_name]);
767 767
         }
768 768
     }
769 769
 
@@ -816,7 +816,7 @@  discard block
 block discarded – undo
816 816
     {
817 817
         $relationship_to_model = $this->get_model()->related_settings_for($relation_name);
818 818
         $index_in_cache        = '';
819
-        if (! $relationship_to_model) {
819
+        if ( ! $relationship_to_model) {
820 820
             throw new EE_Error(
821 821
                 sprintf(
822 822
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -827,10 +827,10 @@  discard block
 block discarded – undo
827 827
         }
828 828
         if ($clear_all) {
829 829
             $obj_removed                              = true;
830
-            $this->_model_relations[ $relation_name ] = null;
830
+            $this->_model_relations[$relation_name] = null;
831 831
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
832
-            $obj_removed                              = $this->_model_relations[ $relation_name ];
833
-            $this->_model_relations[ $relation_name ] = null;
832
+            $obj_removed                              = $this->_model_relations[$relation_name];
833
+            $this->_model_relations[$relation_name] = null;
834 834
         } else {
835 835
             if (
836 836
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -838,12 +838,12 @@  discard block
 block discarded – undo
838 838
             ) {
839 839
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
840 840
                 if (
841
-                    is_array($this->_model_relations[ $relation_name ])
842
-                    && ! isset($this->_model_relations[ $relation_name ][ $index_in_cache ])
841
+                    is_array($this->_model_relations[$relation_name])
842
+                    && ! isset($this->_model_relations[$relation_name][$index_in_cache])
843 843
                 ) {
844 844
                     $index_found_at = null;
845 845
                     // find this object in the array even though it has a different key
846
-                    foreach ($this->_model_relations[ $relation_name ] as $index => $obj) {
846
+                    foreach ($this->_model_relations[$relation_name] as $index => $obj) {
847 847
                         /** @noinspection TypeUnsafeComparisonInspection */
848 848
                         if (
849 849
                             $obj instanceof EE_Base_Class
@@ -877,9 +877,9 @@  discard block
 block discarded – undo
877 877
             }
878 878
             // supposedly we've found it. But it could just be that the client code
879 879
             // provided a bad index/object
880
-            if (isset($this->_model_relations[ $relation_name ][ $index_in_cache ])) {
881
-                $obj_removed = $this->_model_relations[ $relation_name ][ $index_in_cache ];
882
-                unset($this->_model_relations[ $relation_name ][ $index_in_cache ]);
880
+            if (isset($this->_model_relations[$relation_name][$index_in_cache])) {
881
+                $obj_removed = $this->_model_relations[$relation_name][$index_in_cache];
882
+                unset($this->_model_relations[$relation_name][$index_in_cache]);
883 883
             } else {
884 884
                 // that thing was never cached anyway.
885 885
                 $obj_removed = false;
@@ -910,7 +910,7 @@  discard block
 block discarded – undo
910 910
         $current_cache_id = ''
911 911
     ) {
912 912
         // verify that incoming object is of the correct type
913
-        $obj_class = 'EE_' . $relation_name;
913
+        $obj_class = 'EE_'.$relation_name;
914 914
         if ($newly_saved_object instanceof $obj_class) {
915 915
             /* @type EE_Base_Class $newly_saved_object */
916 916
             // now get the type of relation
@@ -918,18 +918,18 @@  discard block
 block discarded – undo
918 918
             // if this is a 1:1 relationship
919 919
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
920 920
                 // then just replace the cached object with the newly saved object
921
-                $this->_model_relations[ $relation_name ] = $newly_saved_object;
921
+                $this->_model_relations[$relation_name] = $newly_saved_object;
922 922
                 return true;
923 923
                 // or if it's some kind of sordid feral polyamorous relationship...
924 924
             }
925 925
             if (
926
-                is_array($this->_model_relations[ $relation_name ])
927
-                && isset($this->_model_relations[ $relation_name ][ $current_cache_id ])
926
+                is_array($this->_model_relations[$relation_name])
927
+                && isset($this->_model_relations[$relation_name][$current_cache_id])
928 928
             ) {
929 929
                 // then remove the current cached item
930
-                unset($this->_model_relations[ $relation_name ][ $current_cache_id ]);
930
+                unset($this->_model_relations[$relation_name][$current_cache_id]);
931 931
                 // and cache the newly saved object using it's new ID
932
-                $this->_model_relations[ $relation_name ][ $newly_saved_object->ID() ] = $newly_saved_object;
932
+                $this->_model_relations[$relation_name][$newly_saved_object->ID()] = $newly_saved_object;
933 933
                 return true;
934 934
             }
935 935
         }
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
      */
947 947
     public function get_one_from_cache($relation_name)
948 948
     {
949
-        $cached_array_or_object = $this->_model_relations[ $relation_name ] ?? null;
949
+        $cached_array_or_object = $this->_model_relations[$relation_name] ?? null;
950 950
         if (is_array($cached_array_or_object)) {
951 951
             return array_shift($cached_array_or_object);
952 952
         }
@@ -968,7 +968,7 @@  discard block
 block discarded – undo
968 968
      */
969 969
     public function get_all_from_cache($relation_name)
970 970
     {
971
-        $objects = $this->_model_relations[ $relation_name ] ?? [];
971
+        $objects = $this->_model_relations[$relation_name] ?? [];
972 972
         // if the result is not an array, but exists, make it an array
973 973
         $objects = is_array($objects)
974 974
             ? $objects
@@ -1160,9 +1160,9 @@  discard block
 block discarded – undo
1160 1160
     public function get_raw($field_name)
1161 1161
     {
1162 1162
         $field_settings = $this->get_model()->field_settings_for($field_name);
1163
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1164
-            ? $this->_fields[ $field_name ]->format('U')
1165
-            : $this->_fields[ $field_name ];
1163
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1164
+            ? $this->_fields[$field_name]->format('U')
1165
+            : $this->_fields[$field_name];
1166 1166
     }
1167 1167
 
1168 1168
 
@@ -1184,7 +1184,7 @@  discard block
 block discarded – undo
1184 1184
     public function get_DateTime_object($field_name)
1185 1185
     {
1186 1186
         $field_settings = $this->get_model()->field_settings_for($field_name);
1187
-        if (! $field_settings instanceof EE_Datetime_Field) {
1187
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1188 1188
             EE_Error::add_error(
1189 1189
                 sprintf(
1190 1190
                     esc_html__(
@@ -1199,8 +1199,8 @@  discard block
 block discarded – undo
1199 1199
             );
1200 1200
             return false;
1201 1201
         }
1202
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1203
-            ? clone $this->_fields[ $field_name ]
1202
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1203
+            ? clone $this->_fields[$field_name]
1204 1204
             : null;
1205 1205
     }
1206 1206
 
@@ -1445,7 +1445,7 @@  discard block
 block discarded – undo
1445 1445
      */
1446 1446
     public function get_i18n_datetime(string $field_name, string $format = ''): string
1447 1447
     {
1448
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1448
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1449 1449
         return date_i18n(
1450 1450
             $format,
1451 1451
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1557,21 +1557,21 @@  discard block
 block discarded – undo
1557 1557
         $field->set_time_format($this->_tm_frmt);
1558 1558
         switch ($what) {
1559 1559
             case 'T':
1560
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1560
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_time(
1561 1561
                     $datetime_value,
1562
-                    $this->_fields[ $field_name ]
1562
+                    $this->_fields[$field_name]
1563 1563
                 );
1564 1564
                 $this->_has_changes           = true;
1565 1565
                 break;
1566 1566
             case 'D':
1567
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1567
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_date(
1568 1568
                     $datetime_value,
1569
-                    $this->_fields[ $field_name ]
1569
+                    $this->_fields[$field_name]
1570 1570
                 );
1571 1571
                 $this->_has_changes           = true;
1572 1572
                 break;
1573 1573
             case 'B':
1574
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1574
+                $this->_fields[$field_name] = $field->prepare_for_set($datetime_value);
1575 1575
                 $this->_has_changes           = true;
1576 1576
                 break;
1577 1577
         }
@@ -1614,7 +1614,7 @@  discard block
 block discarded – undo
1614 1614
         $this->set_timezone($timezone);
1615 1615
         $fn   = (array) $field_name;
1616 1616
         $args = array_merge($fn, (array) $args);
1617
-        if (! method_exists($this, $callback)) {
1617
+        if ( ! method_exists($this, $callback)) {
1618 1618
             throw new EE_Error(
1619 1619
                 sprintf(
1620 1620
                     esc_html__(
@@ -1626,7 +1626,7 @@  discard block
 block discarded – undo
1626 1626
             );
1627 1627
         }
1628 1628
         $args   = (array) $args;
1629
-        $return = $prepend . call_user_func_array([$this, $callback], $args) . $append;
1629
+        $return = $prepend.call_user_func_array([$this, $callback], $args).$append;
1630 1630
         $this->set_timezone($original_timezone);
1631 1631
         return $return;
1632 1632
     }
@@ -1741,8 +1741,8 @@  discard block
 block discarded – undo
1741 1741
     {
1742 1742
         $model = $this->get_model();
1743 1743
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1744
-            if (! empty($this->_model_relations[ $relation_name ])) {
1745
-                $related_objects = $this->_model_relations[ $relation_name ];
1744
+            if ( ! empty($this->_model_relations[$relation_name])) {
1745
+                $related_objects = $this->_model_relations[$relation_name];
1746 1746
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1747 1747
                     // this relation only stores a single model object, not an array
1748 1748
                     // but let's make it consistent
@@ -1799,7 +1799,7 @@  discard block
 block discarded – undo
1799 1799
             $this->set($column, $value);
1800 1800
         }
1801 1801
         // no changes ? then don't do anything
1802
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1802
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1803 1803
             return 0;
1804 1804
         }
1805 1805
         /**
@@ -1809,7 +1809,7 @@  discard block
 block discarded – undo
1809 1809
          * @param EE_Base_Class $model_object the model object about to be saved.
1810 1810
          */
1811 1811
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1812
-        if (! $this->allow_persist()) {
1812
+        if ( ! $this->allow_persist()) {
1813 1813
             return 0;
1814 1814
         }
1815 1815
         // now get current attribute values
@@ -1824,10 +1824,10 @@  discard block
 block discarded – undo
1824 1824
         if ($model->has_primary_key_field()) {
1825 1825
             if ($model->get_primary_key_field()->is_auto_increment()) {
1826 1826
                 // ok check if it's set, if so: update; if not, insert
1827
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1827
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1828 1828
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1829 1829
                 } else {
1830
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1830
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1831 1831
                     $results = $model->insert($save_cols_n_values);
1832 1832
                     if ($results) {
1833 1833
                         // if successful, set the primary key
@@ -1837,7 +1837,7 @@  discard block
 block discarded – undo
1837 1837
                         // will get added to the mapper before we can add this one!
1838 1838
                         // but if we just avoid using the SET method, all that headache can be avoided
1839 1839
                         $pk_field_name                   = $model->primary_key_name();
1840
-                        $this->_fields[ $pk_field_name ] = $results;
1840
+                        $this->_fields[$pk_field_name] = $results;
1841 1841
                         $this->_clear_cached_property($pk_field_name);
1842 1842
                         $model->add_to_entity_map($this);
1843 1843
                         $this->_update_cached_related_model_objs_fks();
@@ -1854,8 +1854,8 @@  discard block
 block discarded – undo
1854 1854
                                     'event_espresso'
1855 1855
                                 ),
1856 1856
                                 get_class($this),
1857
-                                get_class($model) . '::instance()->add_to_entity_map()',
1858
-                                get_class($model) . '::instance()->get_one_by_ID()',
1857
+                                get_class($model).'::instance()->add_to_entity_map()',
1858
+                                get_class($model).'::instance()->get_one_by_ID()',
1859 1859
                                 '<br />'
1860 1860
                             )
1861 1861
                         );
@@ -1879,7 +1879,7 @@  discard block
 block discarded – undo
1879 1879
                     $save_cols_n_values,
1880 1880
                     $model->get_combined_primary_key_fields()
1881 1881
                 );
1882
-                $results                     = $model->update(
1882
+                $results = $model->update(
1883 1883
                     $save_cols_n_values,
1884 1884
                     $combined_pk_fields_n_values
1885 1885
                 );
@@ -1957,27 +1957,27 @@  discard block
 block discarded – undo
1957 1957
     public function save_new_cached_related_model_objs()
1958 1958
     {
1959 1959
         // make sure this has been saved
1960
-        if (! $this->ID()) {
1960
+        if ( ! $this->ID()) {
1961 1961
             $id = $this->save();
1962 1962
         } else {
1963 1963
             $id = $this->ID();
1964 1964
         }
1965 1965
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1966 1966
         foreach ($this->get_model()->relation_settings() as $relation_name => $relationObj) {
1967
-            if ($this->_model_relations[ $relation_name ]) {
1967
+            if ($this->_model_relations[$relation_name]) {
1968 1968
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1969 1969
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1970 1970
                 /* @var $related_model_obj EE_Base_Class */
1971 1971
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
1972 1972
                     // add a relation to that relation type (which saves the appropriate thing in the process)
1973 1973
                     // but ONLY if it DOES NOT exist in the DB
1974
-                    $related_model_obj = $this->_model_relations[ $relation_name ];
1974
+                    $related_model_obj = $this->_model_relations[$relation_name];
1975 1975
                     // if( ! $related_model_obj->ID()){
1976 1976
                     $this->_add_relation_to($related_model_obj, $relation_name);
1977 1977
                     $related_model_obj->save_new_cached_related_model_objs();
1978 1978
                     // }
1979 1979
                 } else {
1980
-                    foreach ($this->_model_relations[ $relation_name ] as $related_model_obj) {
1980
+                    foreach ($this->_model_relations[$relation_name] as $related_model_obj) {
1981 1981
                         // add a relation to that relation type (which saves the appropriate thing in the process)
1982 1982
                         // but ONLY if it DOES NOT exist in the DB
1983 1983
                         // if( ! $related_model_obj->ID()){
@@ -2004,7 +2004,7 @@  discard block
 block discarded – undo
2004 2004
      */
2005 2005
     public function get_model()
2006 2006
     {
2007
-        if (! $this->_model) {
2007
+        if ( ! $this->_model) {
2008 2008
             $modelName    = self::_get_model_classname(get_class($this));
2009 2009
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2010 2010
         } else {
@@ -2030,9 +2030,9 @@  discard block
 block discarded – undo
2030 2030
         $primary_id_ref = self::_get_primary_key_name($classname);
2031 2031
         if (
2032 2032
             array_key_exists($primary_id_ref, $props_n_values)
2033
-            && ! empty($props_n_values[ $primary_id_ref ])
2033
+            && ! empty($props_n_values[$primary_id_ref])
2034 2034
         ) {
2035
-            $id = $props_n_values[ $primary_id_ref ];
2035
+            $id = $props_n_values[$primary_id_ref];
2036 2036
             return self::_get_model($classname)->get_from_entity_map($id);
2037 2037
         }
2038 2038
         return false;
@@ -2065,10 +2065,10 @@  discard block
 block discarded – undo
2065 2065
             $primary_id_ref = self::_get_primary_key_name($classname);
2066 2066
             if (
2067 2067
                 array_key_exists($primary_id_ref, $props_n_values)
2068
-                && ! empty($props_n_values[ $primary_id_ref ])
2068
+                && ! empty($props_n_values[$primary_id_ref])
2069 2069
             ) {
2070 2070
                 $existing = $model->get_one_by_ID(
2071
-                    $props_n_values[ $primary_id_ref ]
2071
+                    $props_n_values[$primary_id_ref]
2072 2072
                 );
2073 2073
             }
2074 2074
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
         }
2081 2081
         if ($existing) {
2082 2082
             // set date formats if present before setting values
2083
-            if (! empty($date_formats) && is_array($date_formats)) {
2083
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2084 2084
                 $existing->set_date_format($date_formats[0]);
2085 2085
                 $existing->set_time_format($date_formats[1]);
2086 2086
             } else {
@@ -2113,7 +2113,7 @@  discard block
 block discarded – undo
2113 2113
     protected static function _get_model($classname, $timezone = '')
2114 2114
     {
2115 2115
         // find model for this class
2116
-        if (! $classname) {
2116
+        if ( ! $classname) {
2117 2117
             throw new EE_Error(
2118 2118
                 sprintf(
2119 2119
                     esc_html__(
@@ -2161,7 +2161,7 @@  discard block
 block discarded – undo
2161 2161
     {
2162 2162
         return strpos((string) $model_name, 'EE_') === 0
2163 2163
             ? str_replace('EE_', 'EEM_', $model_name)
2164
-            : 'EEM_' . $model_name;
2164
+            : 'EEM_'.$model_name;
2165 2165
     }
2166 2166
 
2167 2167
 
@@ -2178,7 +2178,7 @@  discard block
 block discarded – undo
2178 2178
      */
2179 2179
     protected static function _get_primary_key_name($classname = null)
2180 2180
     {
2181
-        if (! $classname) {
2181
+        if ( ! $classname) {
2182 2182
             throw new EE_Error(
2183 2183
                 sprintf(
2184 2184
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2208,7 +2208,7 @@  discard block
 block discarded – undo
2208 2208
         $model = $this->get_model();
2209 2209
         // now that we know the name of the variable, use a variable variable to get its value and return its
2210 2210
         if ($model->has_primary_key_field()) {
2211
-            return $this->_fields[ $model->primary_key_name() ];
2211
+            return $this->_fields[$model->primary_key_name()];
2212 2212
         }
2213 2213
         return $model->get_index_primary_key_string($this->_fields);
2214 2214
     }
@@ -2282,7 +2282,7 @@  discard block
 block discarded – undo
2282 2282
             }
2283 2283
         } else {
2284 2284
             // this thing doesn't exist in the DB,  so just cache it
2285
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2285
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2286 2286
                 throw new EE_Error(
2287 2287
                     sprintf(
2288 2288
                         esc_html__(
@@ -2451,7 +2451,7 @@  discard block
 block discarded – undo
2451 2451
             } else {
2452 2452
                 // did we already cache the result of this query?
2453 2453
                 $cached_results = $this->get_all_from_cache($relation_name);
2454
-                if (! $cached_results) {
2454
+                if ( ! $cached_results) {
2455 2455
                     $related_model_objects = $this->get_model()->get_all_related(
2456 2456
                         $this,
2457 2457
                         $relation_name,
@@ -2563,7 +2563,7 @@  discard block
 block discarded – undo
2563 2563
             } else {
2564 2564
                 // first, check if we've already cached the result of this query
2565 2565
                 $cached_result = $this->get_one_from_cache($relation_name);
2566
-                if (! $cached_result) {
2566
+                if ( ! $cached_result) {
2567 2567
                     $related_model_object = $model->get_first_related(
2568 2568
                         $this,
2569 2569
                         $relation_name,
@@ -2587,7 +2587,7 @@  discard block
 block discarded – undo
2587 2587
             }
2588 2588
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2589 2589
             // just get what's cached on this object
2590
-            if (! $related_model_object) {
2590
+            if ( ! $related_model_object) {
2591 2591
                 $related_model_object = $this->get_one_from_cache($relation_name);
2592 2592
             }
2593 2593
         }
@@ -2670,7 +2670,7 @@  discard block
 block discarded – undo
2670 2670
      */
2671 2671
     public function is_set($field_name)
2672 2672
     {
2673
-        return isset($this->_fields[ $field_name ]);
2673
+        return isset($this->_fields[$field_name]);
2674 2674
     }
2675 2675
 
2676 2676
 
@@ -2686,7 +2686,7 @@  discard block
 block discarded – undo
2686 2686
     {
2687 2687
         foreach ((array) $properties as $property_name) {
2688 2688
             // first make sure this property exists
2689
-            if (! $this->_fields[ $property_name ]) {
2689
+            if ( ! $this->_fields[$property_name]) {
2690 2690
                 throw new EE_Error(
2691 2691
                     sprintf(
2692 2692
                         esc_html__(
@@ -2718,7 +2718,7 @@  discard block
 block discarded – undo
2718 2718
         $properties = [];
2719 2719
         // remove prepended underscore
2720 2720
         foreach ($fields as $field_name => $settings) {
2721
-            $properties[ $field_name ] = $this->get($field_name);
2721
+            $properties[$field_name] = $this->get($field_name);
2722 2722
         }
2723 2723
         return $properties;
2724 2724
     }
@@ -2755,7 +2755,7 @@  discard block
 block discarded – undo
2755 2755
     {
2756 2756
         $className = get_class($this);
2757 2757
         $tagName   = "FHEE__{$className}__{$methodName}";
2758
-        if (! has_filter($tagName)) {
2758
+        if ( ! has_filter($tagName)) {
2759 2759
             throw new EE_Error(
2760 2760
                 sprintf(
2761 2761
                     esc_html__(
@@ -2800,7 +2800,7 @@  discard block
 block discarded – undo
2800 2800
             $query_params[0]['EXM_value'] = $meta_value;
2801 2801
         }
2802 2802
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2803
-        if (! $existing_rows_like_that) {
2803
+        if ( ! $existing_rows_like_that) {
2804 2804
             return $this->add_extra_meta($meta_key, $meta_value);
2805 2805
         }
2806 2806
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2910,7 +2910,7 @@  discard block
 block discarded – undo
2910 2910
                 $values = [];
2911 2911
                 foreach ($results as $result) {
2912 2912
                     if ($result instanceof EE_Extra_Meta) {
2913
-                        $values[ $result->ID() ] = $result->value();
2913
+                        $values[$result->ID()] = $result->value();
2914 2914
                     }
2915 2915
                 }
2916 2916
                 return $values;
@@ -2955,17 +2955,17 @@  discard block
 block discarded – undo
2955 2955
             );
2956 2956
             foreach ($extra_meta_objs as $extra_meta_obj) {
2957 2957
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2958
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2958
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2959 2959
                 }
2960 2960
             }
2961 2961
         } else {
2962 2962
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2963 2963
             foreach ($extra_meta_objs as $extra_meta_obj) {
2964 2964
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2965
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2966
-                        $return_array[ $extra_meta_obj->key() ] = [];
2965
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2966
+                        $return_array[$extra_meta_obj->key()] = [];
2967 2967
                     }
2968
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2968
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2969 2969
                 }
2970 2970
             }
2971 2971
         }
@@ -3046,8 +3046,8 @@  discard block
 block discarded – undo
3046 3046
                             'event_espresso'
3047 3047
                         ),
3048 3048
                         $this->ID(),
3049
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3050
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3049
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3050
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3051 3051
                     )
3052 3052
                 );
3053 3053
             }
@@ -3080,7 +3080,7 @@  discard block
 block discarded – undo
3080 3080
     {
3081 3081
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3082 3082
         // if it wasn't even there to start off.
3083
-        if (! $this->ID()) {
3083
+        if ( ! $this->ID()) {
3084 3084
             $this->save();
3085 3085
         }
3086 3086
         global $wpdb;
@@ -3120,7 +3120,7 @@  discard block
 block discarded – undo
3120 3120
             $table_pk_field_name = $table_obj->get_pk_column();
3121 3121
         }
3122 3122
 
3123
-        $query  =
3123
+        $query =
3124 3124
             "UPDATE `{$table_name}`
3125 3125
             SET "
3126 3126
             . $new_value_sql
@@ -3314,7 +3314,7 @@  discard block
 block discarded – undo
3314 3314
         $model = $this->get_model();
3315 3315
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3316 3316
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3317
-                $classname = 'EE_' . $model->get_this_model_name();
3317
+                $classname = 'EE_'.$model->get_this_model_name();
3318 3318
                 if (
3319 3319
                     $this->get_one_from_cache($relation_name) instanceof $classname
3320 3320
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3355,7 +3355,7 @@  discard block
 block discarded – undo
3355 3355
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3356 3356
         foreach ($this->_fields as $field => $value) {
3357 3357
             if ($value instanceof DateTime) {
3358
-                $this->_fields[ $field ] = clone $value;
3358
+                $this->_fields[$field] = clone $value;
3359 3359
             }
3360 3360
         }
3361 3361
     }
@@ -3370,7 +3370,7 @@  discard block
 block discarded – undo
3370 3370
 
3371 3371
     private function echoProperty($field, $value, int $indent = 0)
3372 3372
     {
3373
-        $bullets = str_repeat(' -', $indent) . ' ';
3373
+        $bullets = str_repeat(' -', $indent).' ';
3374 3374
         $field = strpos($field, '_') === 0 ? substr($field, 1) : $field;
3375 3375
         echo "\n$bullets$field: ";
3376 3376
         if ($value instanceof EEM_Base) {
Please login to merge, or discard this patch.
core/db_classes/EE_Export.class.php 2 patches
Indentation   +771 added lines, -771 removed lines patch added patch discarded remove patch
@@ -18,775 +18,775 @@
 block discarded – undo
18 18
  */
19 19
 class EE_Export
20 20
 {
21
-    const option_prefix = 'ee_report_job_';
22
-
23
-    /**
24
-     * instance of the EE_Export object
25
-     */
26
-    private static $_instance = null;
27
-
28
-    /**
29
-     * instance of the EE_CSV object
30
-     * @var EE_CSV
31
-     */
32
-    public $EE_CSV = null;
33
-
34
-
35
-    private $_req_data = array();
36
-
37
-
38
-    /**
39
-     * private constructor to prevent direct creation
40
-     *
41
-     * @param array $request_data
42
-     */
43
-    private function __construct($request_data = array())
44
-    {
45
-        $this->_req_data = $request_data;
46
-        $this->today = date("Y-m-d", time());
47
-        require_once(EE_CLASSES . 'EE_CSV.class.php');
48
-        $this->EE_CSV = EE_CSV::instance();
49
-    }
50
-
51
-
52
-    /**
53
-     * singleton method used to instantiate class object
54
-     *
55
-     * @param array $request_data
56
-     * @return EE_Export
57
-     */
58
-    public static function instance($request_data = array())
59
-    {
60
-        // check if class object is instantiated
61
-        if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_Export)) {
62
-            self::$_instance = new self($request_data);
63
-        }
64
-        return self::$_instance;
65
-    }
66
-
67
-
68
-    /**
69
-     * Export Event Espresso data - routes export requests
70
-     * @return void | bool
71
-     */
72
-    public function export()
73
-    {
74
-        // in case of bulk exports, the "actual" action will be in action2, but first check regular action for "export" keyword
75
-        if (isset($this->_req_data['action']) && strpos($this->_req_data['action'], 'export') === false) {
76
-            // check if action2 has export action
77
-            if (isset($this->_req_data['action2']) && strpos($this->_req_data['action2'], 'export') !== false) {
78
-                // whoop! there it is!
79
-                $this->_req_data['action'] = $this->_req_data['action2'];
80
-            }
81
-        }
82
-
83
-        $this->_req_data['export'] = isset($this->_req_data['export']) ? $this->_req_data['export'] : '';
84
-
85
-        switch ($this->_req_data['export']) {
86
-            case 'report':
87
-                switch ($this->_req_data['action']) {
88
-                    case "event":
89
-                    case "export_events":
90
-                    case 'all_event_data':
91
-                        $this->export_all_event_data();
92
-                        break;
93
-
94
-                    case 'registrations_report_for_event':
95
-                        $this->report_registrations_for_event($this->_req_data['EVT_ID']);
96
-                        break;
97
-
98
-                    case 'attendees':
99
-                        $this->export_attendees();
100
-                        break;
101
-
102
-                    case 'categories':
103
-                        $this->export_categories();
104
-                        break;
105
-
106
-                    default:
107
-                        EE_Error::add_error(
108
-                            esc_html__('An error occurred! The requested export report could not be found.', 'event_espresso'),
109
-                            __FILE__,
110
-                            __FUNCTION__,
111
-                            __LINE__
112
-                        );
113
-                        return false;
114
-                        break;
115
-                }
116
-                break; // end of switch export : report
117
-            default:
118
-                break;
119
-        } // end of switch export
120
-
121
-        exit;
122
-    }
123
-
124
-    /**
125
-     * Downloads a CSV file with all the columns, but no data. This should be used for importing
126
-     *
127
-     * @return void kills execution
128
-     * @throws EE_Error
129
-     * @throws ReflectionException
130
-     */
131
-    public function export_sample()
132
-    {
133
-        $event = EEM_Event::instance()->get_one();
134
-        $this->_req_data['EVT_ID'] = $event->ID();
135
-        $this->export_all_event_data();
136
-    }
137
-
138
-
139
-    /**
140
-     * Export data for ALL events
141
-     * @return void
142
-     * @throws EE_Error
143
-     * @throws ReflectionException
144
-     */
145
-    public function export_all_event_data()
146
-    {
147
-        // are any Event IDs set?
148
-        $event_query_params = array();
149
-        $related_models_query_params = array();
150
-        $related_through_reg_query_params = array();
151
-        $datetime_ticket_query_params = array();
152
-        $price_query_params = array();
153
-        $price_type_query_params = array();
154
-        $term_query_params = array();
155
-        $state_country_query_params = array();
156
-        $question_group_query_params = array();
157
-        $question_query_params = array();
158
-        if (isset($this->_req_data['EVT_ID'])) {
159
-            // do we have an array of IDs ?
160
-
161
-            if (is_array($this->_req_data['EVT_ID'])) {
162
-                $EVT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_ID']);
163
-                $value_to_equal = array('IN', $EVT_IDs);
164
-                $filename = 'events';
165
-            } else {
166
-                // generate regular where = clause
167
-                $EVT_ID = absint($this->_req_data['EVT_ID']);
168
-                $value_to_equal = $EVT_ID;
169
-                $event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
170
-
171
-                $filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : esc_html__('unknown', 'event_espresso'));
172
-            }
173
-            $event_query_params[0]['EVT_ID'] = $value_to_equal;
174
-            $related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
175
-            $related_through_reg_query_params[0]['Registration.EVT_ID'] = $value_to_equal;
176
-            $datetime_ticket_query_params[0]['Datetime.EVT_ID'] = $value_to_equal;
177
-            $price_query_params[0]['Ticket.Datetime.EVT_ID'] = $value_to_equal;
178
-            $price_type_query_params[0]['Price.Ticket.Datetime.EVT_ID'] = $value_to_equal;
179
-            $term_query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $value_to_equal;
180
-            $state_country_query_params[0]['Venue.Event.EVT_ID'] = $value_to_equal;
181
-            $question_group_query_params[0]['Event.EVT_ID'] = $value_to_equal;
182
-            $question_query_params[0]['Question_Group.Event.EVT_ID'] = $value_to_equal;
183
-        } else {
184
-            $filename = 'all-events';
185
-        }
186
-
187
-
188
-        // array in the format:  table name =>  query where clause
189
-        $models_to_export = array(
190
-            'Event'                   => $event_query_params,
191
-            'Datetime'                => $related_models_query_params,
192
-            'Ticket_Template'         => $price_query_params,
193
-            'Ticket'                  => $datetime_ticket_query_params,
194
-            'Datetime_Ticket'         => $datetime_ticket_query_params,
195
-            'Price_Type'              => $price_type_query_params,
196
-            'Price'                   => $price_query_params,
197
-            'Ticket_Price'            => $price_query_params,
198
-            'Term'                    => $term_query_params,
199
-            'Term_Taxonomy'           => $related_models_query_params,
200
-            'Term_Relationship'       => $related_models_query_params, // model has NO primary key...
201
-            'Country'                 => $state_country_query_params,
202
-            'State'                   => $state_country_query_params,
203
-            'Venue'                   => $related_models_query_params,
204
-            'Event_Venue'             => $related_models_query_params,
205
-            'Question_Group'          => $question_group_query_params,
206
-            'Event_Question_Group'    => $question_group_query_params,
207
-            'Question'                => $question_query_params,
208
-            'Question_Group_Question' => $question_query_params,
209
-            // 'Transaction'=>$related_through_reg_query_params,
210
-            // 'Registration'=>$related_models_query_params,
211
-            // 'Attendee'=>$related_through_reg_query_params,
212
-            // 'Line_Item'=>
213
-
214
-        );
215
-
216
-        $model_data = $this->_get_export_data_for_models($models_to_export);
217
-
218
-        $filename = $this->generate_filename($filename);
219
-
220
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
221
-            EE_Error::add_error(
222
-                esc_html__(
223
-                    "'An error occurred and the Event details could not be exported from the database.'",
224
-                    "event_espresso"
225
-                ),
226
-                __FILE__,
227
-                __FUNCTION__,
228
-                __LINE__
229
-            );
230
-        }
231
-    }
232
-
233
-    public function report_attendees()
234
-    {
235
-        $attendee_rows = EEM_Attendee::instance()->get_all_wpdb_results(
236
-            array(
237
-                'force_join' => array('State', 'Country'),
238
-                'caps'       => EEM_Base::caps_read_admin,
239
-            )
240
-        );
241
-        $csv_data = array();
242
-        foreach ($attendee_rows as $attendee_row) {
243
-            $csv_row = array();
244
-            foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
245
-                if ($field_name == 'STA_ID') {
246
-                    $state_name_field = EEM_State::instance()->field_settings_for('STA_name');
247
-                    $csv_row[ esc_html__('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
248
-                    ) ];
249
-                } elseif ($field_name == 'CNT_ISO') {
250
-                    $country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
251
-                    $csv_row[ esc_html__(
252
-                        'Country',
253
-                        'event_espresso'
254
-                    ) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
255
-                } else {
256
-                    $csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
257
-                }
258
-            }
259
-            $csv_data[] = $csv_row;
260
-        }
261
-
262
-        $filename = $this->generate_filename('contact-list-report');
263
-
264
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
265
-        $this->EE_CSV->write_data_array_to_csv($handle, $csv_data);
266
-        $this->EE_CSV->end_sending_csv($handle);
267
-    }
268
-
269
-
270
-    /**
271
-     * Export data for ALL attendees
272
-     * @return void
273
-     * @throws EE_Error
274
-     */
275
-    public function export_attendees()
276
-    {
277
-
278
-        $states_that_have_an_attendee = EEM_State::instance()->get_all(
279
-            array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
280
-        );
281
-        $countries_that_have_an_attendee = EEM_Country::instance()->get_all(
282
-            array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
283
-        );
284
-        // $states_to_export_query_params
285
-        $models_to_export = array(
286
-            'Country'  => array(array('CNT_ISO' => array('IN', array_keys($countries_that_have_an_attendee)))),
287
-            'State'    => array(array('STA_ID' => array('IN', array_keys($states_that_have_an_attendee)))),
288
-            'Attendee' => array(),
289
-        );
290
-
291
-
292
-        $model_data = $this->_get_export_data_for_models($models_to_export);
293
-        $filename = $this->generate_filename('all-attendees');
294
-
295
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
296
-            EE_Error::add_error(
297
-                esc_html__(
298
-                    'An error occurred and the Attendee data could not be exported from the database.',
299
-                    'event_espresso'
300
-                ),
301
-                __FILE__,
302
-                __FUNCTION__,
303
-                __LINE__
304
-            );
305
-        }
306
-    }
307
-
308
-    /**
309
-     * Shortcut for preparing a database result for display
310
-     *
311
-     * @param EEM_Base $model
312
-     * @param string $field_name
313
-     * @param string $raw_db_value
314
-     * @param bool|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to
315
-     *                                      NOT display pretty
316
-     * @return string
317
-     * @throws EE_Error
318
-     */
319
-    protected function _prepare_value_from_db_for_display($model, $field_name, $raw_db_value, $pretty_schema = true)
320
-    {
321
-        $field_obj = $model->field_settings_for($field_name);
322
-        $value_on_model_obj = $field_obj->prepare_for_set_from_db($raw_db_value);
323
-        if ($field_obj instanceof EE_Datetime_Field) {
324
-            $field_obj->set_date_format(
325
-                EE_CSV::instance()->get_date_format_for_csv($field_obj->get_date_format($pretty_schema)),
326
-                $pretty_schema
327
-            );
328
-            $field_obj->set_time_format(
329
-                EE_CSV::instance()->get_time_format_for_csv($field_obj->get_time_format($pretty_schema)),
330
-                $pretty_schema
331
-            );
332
-        }
333
-        if ($pretty_schema === true) {
334
-            return $field_obj->prepare_for_pretty_echoing($value_on_model_obj);
335
-        } elseif (is_string($pretty_schema)) {
336
-            return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema);
337
-        } else {
338
-            return $field_obj->prepare_for_get($value_on_model_obj);
339
-        }
340
-    }
341
-
342
-    /**
343
-     * Export a custom CSV of registration info including: A bunch of the reg fields, the time of the event, the price
344
-     * name, and the questions associated with the registrations
345
-     *
346
-     * @param int $event_id
347
-     * @throws EE_Error
348
-     * @throws ReflectionException
349
-     */
350
-    public function report_registrations_for_event($event_id = null)
351
-    {
352
-        $reg_fields_to_include = array(
353
-            'TXN_ID',
354
-            'ATT_ID',
355
-            'REG_ID',
356
-            'REG_date',
357
-            'REG_code',
358
-            'REG_count',
359
-            'REG_final_price',
360
-
361
-        );
362
-        $att_fields_to_include = array(
363
-            'ATT_fname',
364
-            'ATT_lname',
365
-            'ATT_email',
366
-            'ATT_address',
367
-            'ATT_address2',
368
-            'ATT_city',
369
-            'STA_ID',
370
-            'CNT_ISO',
371
-            'ATT_zip',
372
-            'ATT_phone',
373
-        );
374
-
375
-        $registrations_csv_ready_array = array();
376
-        $reg_model = EE_Registry::instance()->load_model('Registration');
377
-        $query_params = apply_filters(
378
-            'FHEE__EE_Export__report_registration_for_event',
379
-            array(
380
-                array(
381
-                    'OR'                 => array(
382
-                        // don't include registrations from failed or abandoned transactions...
383
-                        'Transaction.STS_ID' => array(
384
-                            'NOT IN',
385
-                            array(EEM_Transaction::failed_status_code, EEM_Transaction::abandoned_status_code),
386
-                        ),
387
-                        // unless the registration is approved, in which case include it regardless of transaction status
388
-                        'STS_ID'             => RegStatus::APPROVED,
389
-                    ),
390
-                    'Ticket.TKT_deleted' => array('IN', array(true, false)),
391
-                ),
392
-                'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
393
-                'force_join' => array('Transaction', 'Ticket', 'Attendee'),
394
-                'caps'       => EEM_Base::caps_read_admin,
395
-            ),
396
-            $event_id
397
-        );
398
-        if ($event_id) {
399
-            $query_params[0]['EVT_ID'] = $event_id;
400
-        } else {
401
-            $query_params['force_join'][] = 'Event';
402
-        }
403
-        $registration_rows = $reg_model->get_all_wpdb_results($query_params);
404
-        // get all questions which relate to someone in this group
405
-        $registration_ids = array();
406
-        foreach ($registration_rows as $reg_row) {
407
-            $registration_ids[] = intval($reg_row['Registration.REG_ID']);
408
-        }
409
-        // EEM_Question::instance()->show_next_x_db_queries();
410
-        $questions_for_these_regs_rows = EEM_Question::instance()->get_all_wpdb_results(
411
-            array(array('Answer.REG_ID' => array('IN', $registration_ids)))
412
-        );
413
-        foreach ($registration_rows as $reg_row) {
414
-            if (is_array($reg_row)) {
415
-                $reg_csv_array = array();
416
-                if (! $event_id) {
417
-                    // get the event's name and Id
418
-                    $reg_csv_array[ esc_html__('Event', 'event_espresso') ] = sprintf(
419
-                        esc_html__('%1$s (%2$s)', 'event_espresso'),
420
-                        $this->_prepare_value_from_db_for_display(
421
-                            EEM_Event::instance(),
422
-                            'EVT_name',
423
-                            $reg_row['Event_CPT.post_title']
424
-                        ),
425
-                        $reg_row['Event_CPT.ID']
426
-                    );
427
-                }
428
-                $is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
429
-                /*@var $reg_row EE_Registration */
430
-                foreach ($reg_fields_to_include as $field_name) {
431
-                    $field = $reg_model->field_settings_for($field_name);
432
-                    if ($field_name == 'REG_final_price') {
433
-                        $value = $this->_prepare_value_from_db_for_display(
434
-                            $reg_model,
435
-                            $field_name,
436
-                            $reg_row['Registration.REG_final_price'],
437
-                            'localized_float'
438
-                        );
439
-                    } elseif ($field_name == 'REG_count') {
440
-                        $value = sprintf(
441
-                            esc_html__('%s of %s', 'event_espresso'),
442
-                            $this->_prepare_value_from_db_for_display(
443
-                                $reg_model,
444
-                                'REG_count',
445
-                                $reg_row['Registration.REG_count']
446
-                            ),
447
-                            $this->_prepare_value_from_db_for_display(
448
-                                $reg_model,
449
-                                'REG_group_size',
450
-                                $reg_row['Registration.REG_group_size']
451
-                            )
452
-                        );
453
-                    } elseif ($field_name == 'REG_date') {
454
-                        $value = $this->_prepare_value_from_db_for_display(
455
-                            $reg_model,
456
-                            $field_name,
457
-                            $reg_row['Registration.REG_date'],
458
-                            'no_html'
459
-                        );
460
-                    } else {
461
-                        $value = $this->_prepare_value_from_db_for_display(
462
-                            $reg_model,
463
-                            $field_name,
464
-                            $reg_row[ $field->get_qualified_column() ]
465
-                        );
466
-                    }
467
-                    $reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
468
-                    if ($field_name == 'REG_final_price') {
469
-                        // add a column named Currency after the final price
470
-                        $reg_csv_array[ esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
471
-                    }
472
-                }
473
-                // get pretty status
474
-                $stati = EEM_Status::instance()->localized_status(
475
-                    array(
476
-                        $reg_row['Registration.STS_ID']     => esc_html__('unknown', 'event_espresso'),
477
-                        $reg_row['TransactionTable.STS_ID'] => esc_html__('unknown', 'event_espresso'),
478
-                    ),
479
-                    false,
480
-                    'sentence'
481
-                );
482
-                $reg_csv_array[ esc_html__(
483
-                    "Registration Status",
484
-                    'event_espresso'
485
-                ) ] = $stati[ $reg_row['Registration.STS_ID'] ];
486
-                // get pretty trnasaction status
487
-                $reg_csv_array[ esc_html__(
488
-                    "Transaction Status",
489
-                    'event_espresso'
490
-                ) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
491
-                $reg_csv_array[ esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
492
-                    ? $this->_prepare_value_from_db_for_display(
493
-                        EEM_Transaction::instance(),
494
-                        'TXN_total',
495
-                        $reg_row['TransactionTable.TXN_total'],
496
-                        'localized_float'
497
-                    ) : '0.00';
498
-                $reg_csv_array[ esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
499
-                    ? $this->_prepare_value_from_db_for_display(
500
-                        EEM_Transaction::instance(),
501
-                        'TXN_paid',
502
-                        $reg_row['TransactionTable.TXN_paid'],
503
-                        'localized_float'
504
-                    ) : '0.00';
505
-                $payment_methods = array();
506
-                $gateway_txn_ids_etc = array();
507
-                $payment_times = array();
508
-                if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
509
-                    $payments_info = EEM_Payment::instance()->get_all_wpdb_results(
510
-                        array(
511
-                            array(
512
-                                'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
513
-                                'STS_ID' => EEM_Payment::status_id_approved,
514
-                            ),
515
-                            'force_join' => array('Payment_Method'),
516
-                        ),
517
-                        ARRAY_A,
518
-                        'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
519
-                    );
520
-                    list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
521
-                }
522
-                $reg_csv_array[ esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
523
-                $reg_csv_array[ esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
524
-                $reg_csv_array[ esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
525
-                    ',',
526
-                    $gateway_txn_ids_etc
527
-                );
528
-
529
-                // get whether or not the user has checked in
530
-                $reg_csv_array[ esc_html__("Check-Ins", "event_espresso") ] = $reg_model->count_related(
531
-                    $reg_row['Registration.REG_ID'],
532
-                    'Checkin'
533
-                );
534
-                // get ticket of registration and its price
535
-                $ticket_model = EE_Registry::instance()->load_model('Ticket');
536
-                if ($reg_row['Ticket.TKT_ID']) {
537
-                    $ticket_name = $this->_prepare_value_from_db_for_display(
538
-                        $ticket_model,
539
-                        'TKT_name',
540
-                        $reg_row['Ticket.TKT_name']
541
-                    );
542
-                    $datetimes_strings = array();
543
-                    foreach (
544
-                        EEM_Datetime::instance()->get_all_wpdb_results(
545
-                            array(
546
-                            array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
547
-                            'order_by'                 => array('DTT_EVT_start' => 'ASC'),
548
-                            'default_where_conditions' => 'none',
549
-                            )
550
-                        ) as $datetime
551
-                    ) {
552
-                        $datetimes_strings[] = $this->_prepare_value_from_db_for_display(
553
-                            EEM_Datetime::instance(),
554
-                            'DTT_EVT_start',
555
-                            $datetime['Datetime.DTT_EVT_start']
556
-                        );
557
-                    }
558
-                } else {
559
-                    $ticket_name = esc_html__('Unknown', 'event_espresso');
560
-                    $datetimes_strings = array(esc_html__('Unknown', 'event_espresso'));
561
-                }
562
-                $reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
563
-                $reg_csv_array[ esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
564
-                // get datetime(s) of registration
565
-
566
-                // add attendee columns
567
-                foreach ($att_fields_to_include as $att_field_name) {
568
-                    $field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
569
-                    if ($reg_row['Attendee_CPT.ID']) {
570
-                        if ($att_field_name == 'STA_ID') {
571
-                            $value = EEM_State::instance()->get_var(
572
-                                array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
573
-                                'STA_name'
574
-                            );
575
-                        } elseif ($att_field_name == 'CNT_ISO') {
576
-                            $value = EEM_Country::instance()->get_var(
577
-                                array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
578
-                                'CNT_name'
579
-                            );
580
-                        } else {
581
-                            $value = $this->_prepare_value_from_db_for_display(
582
-                                EEM_Attendee::instance(),
583
-                                $att_field_name,
584
-                                $reg_row[ $field_obj->get_qualified_column() ]
585
-                            );
586
-                        }
587
-                    } else {
588
-                        $value = '';
589
-                    }
590
-
591
-                    $reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
592
-                }
593
-
594
-                // make sure each registration has the same questions in the same order
595
-                foreach ($questions_for_these_regs_rows as $question_row) {
596
-                    if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
597
-                        $reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
598
-                    }
599
-                }
600
-                // now fill out the questions THEY answered
601
-                foreach (
602
-                    EEM_Answer::instance()->get_all_wpdb_results(
603
-                        array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
604
-                    ) as $answer_row
605
-                ) {
606
-                    /* @var $answer EE_Answer */
607
-                    if ($answer_row['Question.QST_ID']) {
608
-                        $question_label = $this->_prepare_value_from_db_for_display(
609
-                            EEM_Question::instance(),
610
-                            'QST_admin_label',
611
-                            $answer_row['Question.QST_admin_label']
612
-                        );
613
-                    } else {
614
-                        $question_label = sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
615
-                    }
616
-                    if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
617
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
618
-                            (int) $answer_row['Answer.ANS_value']
619
-                        );
620
-                    } else {
621
-                        $reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
622
-                            EEM_Answer::instance(),
623
-                            'ANS_value',
624
-                            $answer_row['Answer.ANS_value']
625
-                        );
626
-                    }
627
-                }
628
-                $registrations_csv_ready_array[] = apply_filters(
629
-                    'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport__reg_csv_array',
630
-                    $reg_csv_array,
631
-                    $reg_row
632
-                );
633
-            }
634
-        }
635
-
636
-        // if we couldn't export anything, we want to at least show the column headers
637
-        if (empty($registrations_csv_ready_array)) {
638
-            $reg_csv_array = array();
639
-            $model_and_fields_to_include = array(
640
-                'Registration' => $reg_fields_to_include,
641
-                'Attendee'     => $att_fields_to_include,
642
-            );
643
-            foreach ($model_and_fields_to_include as $model_name => $field_list) {
644
-                $model = EE_Registry::instance()->load_model($model_name);
645
-                foreach ($field_list as $field_name) {
646
-                    $field = $model->field_settings_for($field_name);
647
-                    $reg_csv_array[ $this->_get_column_name_for_field(
648
-                        $field
649
-                    ) ] = null;// $registration->get($field->get_name());
650
-                }
651
-            }
652
-            $registrations_csv_ready_array [] = $reg_csv_array;
653
-        }
654
-        if ($event_id) {
655
-            $event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
656
-            if (! $event_slug) {
657
-                $event_slug = esc_html__('unknown', 'event_espresso');
658
-            }
659
-        } else {
660
-            $event_slug = esc_html__('all', 'event_espresso');
661
-        }
662
-        $filename = sprintf("registrations-for-%s", $event_slug);
663
-
664
-        $handle = $this->EE_CSV->begin_sending_csv($filename);
665
-        $this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
666
-        $this->EE_CSV->end_sending_csv($handle);
667
-    }
668
-
669
-    /**
670
-     * Gets the 'normal' column named for fields
671
-     *
672
-     * @param EE_Model_Field_Base $field
673
-     * @return string
674
-     * @throws EE_Error
675
-     */
676
-    protected function _get_column_name_for_field(EE_Model_Field_Base $field)
677
-    {
678
-        return $field->get_nicename() . "[" . $field->get_name() . "]";
679
-    }
680
-
681
-
682
-    /**
683
-     * Export data for ALL events
684
-     * @return void
685
-     */
686
-    public function export_categories()
687
-    {
688
-        // are any Event IDs set?
689
-        $query_params = array();
690
-        if (isset($this->_req_data['EVT_CAT_ID'])) {
691
-            // do we have an array of IDs ?
692
-            if (is_array($this->_req_data['EVT_CAT_ID'])) {
693
-                // generate an "IN (CSV)" where clause
694
-                $EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
695
-                $filename = 'event-categories';
696
-                $query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
697
-            } else {
698
-                // generate regular where = clause
699
-                $EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
700
-                $filename = 'event-category#' . $EVT_CAT_ID;
701
-                $query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
702
-            }
703
-        } else {
704
-            // no IDs means we will d/l the entire table
705
-            $filename = 'all-categories';
706
-        }
707
-
708
-        $tables_to_export = array(
709
-            'Term_Taxonomy' => $query_params,
710
-        );
711
-
712
-        $table_data = $this->_get_export_data_for_models($tables_to_export);
713
-        $filename = $this->generate_filename($filename);
714
-
715
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
716
-            EE_Error::add_error(
717
-                esc_html__(
718
-                    'An error occurred and the Category details could not be exported from the database.',
719
-                    'event_espresso'
720
-                ),
721
-                __FILE__,
722
-                __FUNCTION__,
723
-                __LINE__
724
-            );
725
-        }
726
-    }
727
-
728
-
729
-    /**
730
-     * process export name to create a suitable filename
731
-     * @param string - export_name
732
-     * @return string on success, FALSE on fail
733
-     */
734
-    private function generate_filename($export_name = '')
735
-    {
736
-        if ($export_name != '') {
737
-            $filename = get_bloginfo('name') . '-' . $export_name;
738
-            $filename = sanitize_key($filename) . '-' . $this->today;
739
-            return $filename;
740
-        } else {
741
-            EE_Error::add_error(esc_html__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
742
-        }
743
-        return false;
744
-    }
745
-
746
-
747
-    /**
748
-     * recursive function for exporting table data and merging the results with the next results
749
-     * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
750
-     *                                query params @return bool on success, FALSE on fail
751
-     * @throws EE_Error
752
-     * @throws ReflectionException
753
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
754
-     */
755
-    private function _get_export_data_for_models($models_to_export = array())
756
-    {
757
-        $table_data = false;
758
-        if (is_array($models_to_export)) {
759
-            foreach ($models_to_export as $model_name => $query_params) {
760
-                // check for a numerically-indexed array. in that case, $model_name is the value!!
761
-                if (is_int($model_name)) {
762
-                    $model_name = $query_params;
763
-                    $query_params = array();
764
-                }
765
-                $model = EE_Registry::instance()->load_model($model_name);
766
-                $model_objects = $model->get_all($query_params);
767
-
768
-                $table_data[ $model_name ] = array();
769
-                foreach ($model_objects as $model_object) {
770
-                    $model_data_array = array();
771
-                    $fields = $model->field_settings();
772
-                    foreach ($fields as $field) {
773
-                        $column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
774
-                        if ($field instanceof EE_Datetime_Field) {
775
-                            // $field->set_date_format('Y-m-d');
776
-                            // $field->set_time_format('H:i:s');
777
-                            $model_data_array[ $column_name ] = $model_object->get_datetime(
778
-                                $field->get_name(),
779
-                                'Y-m-d',
780
-                                'H:i:s'
781
-                            );
782
-                        } else {
783
-                            $model_data_array[ $column_name ] = $model_object->get($field->get_name());
784
-                        }
785
-                    }
786
-                    $table_data[ $model_name ][] = $model_data_array;
787
-                }
788
-            }
789
-        }
790
-        return $table_data;
791
-    }
21
+	const option_prefix = 'ee_report_job_';
22
+
23
+	/**
24
+	 * instance of the EE_Export object
25
+	 */
26
+	private static $_instance = null;
27
+
28
+	/**
29
+	 * instance of the EE_CSV object
30
+	 * @var EE_CSV
31
+	 */
32
+	public $EE_CSV = null;
33
+
34
+
35
+	private $_req_data = array();
36
+
37
+
38
+	/**
39
+	 * private constructor to prevent direct creation
40
+	 *
41
+	 * @param array $request_data
42
+	 */
43
+	private function __construct($request_data = array())
44
+	{
45
+		$this->_req_data = $request_data;
46
+		$this->today = date("Y-m-d", time());
47
+		require_once(EE_CLASSES . 'EE_CSV.class.php');
48
+		$this->EE_CSV = EE_CSV::instance();
49
+	}
50
+
51
+
52
+	/**
53
+	 * singleton method used to instantiate class object
54
+	 *
55
+	 * @param array $request_data
56
+	 * @return EE_Export
57
+	 */
58
+	public static function instance($request_data = array())
59
+	{
60
+		// check if class object is instantiated
61
+		if (self::$_instance === null or ! is_object(self::$_instance) or ! (self::$_instance instanceof EE_Export)) {
62
+			self::$_instance = new self($request_data);
63
+		}
64
+		return self::$_instance;
65
+	}
66
+
67
+
68
+	/**
69
+	 * Export Event Espresso data - routes export requests
70
+	 * @return void | bool
71
+	 */
72
+	public function export()
73
+	{
74
+		// in case of bulk exports, the "actual" action will be in action2, but first check regular action for "export" keyword
75
+		if (isset($this->_req_data['action']) && strpos($this->_req_data['action'], 'export') === false) {
76
+			// check if action2 has export action
77
+			if (isset($this->_req_data['action2']) && strpos($this->_req_data['action2'], 'export') !== false) {
78
+				// whoop! there it is!
79
+				$this->_req_data['action'] = $this->_req_data['action2'];
80
+			}
81
+		}
82
+
83
+		$this->_req_data['export'] = isset($this->_req_data['export']) ? $this->_req_data['export'] : '';
84
+
85
+		switch ($this->_req_data['export']) {
86
+			case 'report':
87
+				switch ($this->_req_data['action']) {
88
+					case "event":
89
+					case "export_events":
90
+					case 'all_event_data':
91
+						$this->export_all_event_data();
92
+						break;
93
+
94
+					case 'registrations_report_for_event':
95
+						$this->report_registrations_for_event($this->_req_data['EVT_ID']);
96
+						break;
97
+
98
+					case 'attendees':
99
+						$this->export_attendees();
100
+						break;
101
+
102
+					case 'categories':
103
+						$this->export_categories();
104
+						break;
105
+
106
+					default:
107
+						EE_Error::add_error(
108
+							esc_html__('An error occurred! The requested export report could not be found.', 'event_espresso'),
109
+							__FILE__,
110
+							__FUNCTION__,
111
+							__LINE__
112
+						);
113
+						return false;
114
+						break;
115
+				}
116
+				break; // end of switch export : report
117
+			default:
118
+				break;
119
+		} // end of switch export
120
+
121
+		exit;
122
+	}
123
+
124
+	/**
125
+	 * Downloads a CSV file with all the columns, but no data. This should be used for importing
126
+	 *
127
+	 * @return void kills execution
128
+	 * @throws EE_Error
129
+	 * @throws ReflectionException
130
+	 */
131
+	public function export_sample()
132
+	{
133
+		$event = EEM_Event::instance()->get_one();
134
+		$this->_req_data['EVT_ID'] = $event->ID();
135
+		$this->export_all_event_data();
136
+	}
137
+
138
+
139
+	/**
140
+	 * Export data for ALL events
141
+	 * @return void
142
+	 * @throws EE_Error
143
+	 * @throws ReflectionException
144
+	 */
145
+	public function export_all_event_data()
146
+	{
147
+		// are any Event IDs set?
148
+		$event_query_params = array();
149
+		$related_models_query_params = array();
150
+		$related_through_reg_query_params = array();
151
+		$datetime_ticket_query_params = array();
152
+		$price_query_params = array();
153
+		$price_type_query_params = array();
154
+		$term_query_params = array();
155
+		$state_country_query_params = array();
156
+		$question_group_query_params = array();
157
+		$question_query_params = array();
158
+		if (isset($this->_req_data['EVT_ID'])) {
159
+			// do we have an array of IDs ?
160
+
161
+			if (is_array($this->_req_data['EVT_ID'])) {
162
+				$EVT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_ID']);
163
+				$value_to_equal = array('IN', $EVT_IDs);
164
+				$filename = 'events';
165
+			} else {
166
+				// generate regular where = clause
167
+				$EVT_ID = absint($this->_req_data['EVT_ID']);
168
+				$value_to_equal = $EVT_ID;
169
+				$event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
170
+
171
+				$filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : esc_html__('unknown', 'event_espresso'));
172
+			}
173
+			$event_query_params[0]['EVT_ID'] = $value_to_equal;
174
+			$related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
175
+			$related_through_reg_query_params[0]['Registration.EVT_ID'] = $value_to_equal;
176
+			$datetime_ticket_query_params[0]['Datetime.EVT_ID'] = $value_to_equal;
177
+			$price_query_params[0]['Ticket.Datetime.EVT_ID'] = $value_to_equal;
178
+			$price_type_query_params[0]['Price.Ticket.Datetime.EVT_ID'] = $value_to_equal;
179
+			$term_query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $value_to_equal;
180
+			$state_country_query_params[0]['Venue.Event.EVT_ID'] = $value_to_equal;
181
+			$question_group_query_params[0]['Event.EVT_ID'] = $value_to_equal;
182
+			$question_query_params[0]['Question_Group.Event.EVT_ID'] = $value_to_equal;
183
+		} else {
184
+			$filename = 'all-events';
185
+		}
186
+
187
+
188
+		// array in the format:  table name =>  query where clause
189
+		$models_to_export = array(
190
+			'Event'                   => $event_query_params,
191
+			'Datetime'                => $related_models_query_params,
192
+			'Ticket_Template'         => $price_query_params,
193
+			'Ticket'                  => $datetime_ticket_query_params,
194
+			'Datetime_Ticket'         => $datetime_ticket_query_params,
195
+			'Price_Type'              => $price_type_query_params,
196
+			'Price'                   => $price_query_params,
197
+			'Ticket_Price'            => $price_query_params,
198
+			'Term'                    => $term_query_params,
199
+			'Term_Taxonomy'           => $related_models_query_params,
200
+			'Term_Relationship'       => $related_models_query_params, // model has NO primary key...
201
+			'Country'                 => $state_country_query_params,
202
+			'State'                   => $state_country_query_params,
203
+			'Venue'                   => $related_models_query_params,
204
+			'Event_Venue'             => $related_models_query_params,
205
+			'Question_Group'          => $question_group_query_params,
206
+			'Event_Question_Group'    => $question_group_query_params,
207
+			'Question'                => $question_query_params,
208
+			'Question_Group_Question' => $question_query_params,
209
+			// 'Transaction'=>$related_through_reg_query_params,
210
+			// 'Registration'=>$related_models_query_params,
211
+			// 'Attendee'=>$related_through_reg_query_params,
212
+			// 'Line_Item'=>
213
+
214
+		);
215
+
216
+		$model_data = $this->_get_export_data_for_models($models_to_export);
217
+
218
+		$filename = $this->generate_filename($filename);
219
+
220
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
221
+			EE_Error::add_error(
222
+				esc_html__(
223
+					"'An error occurred and the Event details could not be exported from the database.'",
224
+					"event_espresso"
225
+				),
226
+				__FILE__,
227
+				__FUNCTION__,
228
+				__LINE__
229
+			);
230
+		}
231
+	}
232
+
233
+	public function report_attendees()
234
+	{
235
+		$attendee_rows = EEM_Attendee::instance()->get_all_wpdb_results(
236
+			array(
237
+				'force_join' => array('State', 'Country'),
238
+				'caps'       => EEM_Base::caps_read_admin,
239
+			)
240
+		);
241
+		$csv_data = array();
242
+		foreach ($attendee_rows as $attendee_row) {
243
+			$csv_row = array();
244
+			foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
245
+				if ($field_name == 'STA_ID') {
246
+					$state_name_field = EEM_State::instance()->field_settings_for('STA_name');
247
+					$csv_row[ esc_html__('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
248
+					) ];
249
+				} elseif ($field_name == 'CNT_ISO') {
250
+					$country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
251
+					$csv_row[ esc_html__(
252
+						'Country',
253
+						'event_espresso'
254
+					) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
255
+				} else {
256
+					$csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
257
+				}
258
+			}
259
+			$csv_data[] = $csv_row;
260
+		}
261
+
262
+		$filename = $this->generate_filename('contact-list-report');
263
+
264
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
265
+		$this->EE_CSV->write_data_array_to_csv($handle, $csv_data);
266
+		$this->EE_CSV->end_sending_csv($handle);
267
+	}
268
+
269
+
270
+	/**
271
+	 * Export data for ALL attendees
272
+	 * @return void
273
+	 * @throws EE_Error
274
+	 */
275
+	public function export_attendees()
276
+	{
277
+
278
+		$states_that_have_an_attendee = EEM_State::instance()->get_all(
279
+			array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
280
+		);
281
+		$countries_that_have_an_attendee = EEM_Country::instance()->get_all(
282
+			array(0 => array('Attendee.ATT_ID' => array('IS NOT NULL')))
283
+		);
284
+		// $states_to_export_query_params
285
+		$models_to_export = array(
286
+			'Country'  => array(array('CNT_ISO' => array('IN', array_keys($countries_that_have_an_attendee)))),
287
+			'State'    => array(array('STA_ID' => array('IN', array_keys($states_that_have_an_attendee)))),
288
+			'Attendee' => array(),
289
+		);
290
+
291
+
292
+		$model_data = $this->_get_export_data_for_models($models_to_export);
293
+		$filename = $this->generate_filename('all-attendees');
294
+
295
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
296
+			EE_Error::add_error(
297
+				esc_html__(
298
+					'An error occurred and the Attendee data could not be exported from the database.',
299
+					'event_espresso'
300
+				),
301
+				__FILE__,
302
+				__FUNCTION__,
303
+				__LINE__
304
+			);
305
+		}
306
+	}
307
+
308
+	/**
309
+	 * Shortcut for preparing a database result for display
310
+	 *
311
+	 * @param EEM_Base $model
312
+	 * @param string $field_name
313
+	 * @param string $raw_db_value
314
+	 * @param bool|string $pretty_schema true to display pretty, a string to use a specific "Schema", or false to
315
+	 *                                      NOT display pretty
316
+	 * @return string
317
+	 * @throws EE_Error
318
+	 */
319
+	protected function _prepare_value_from_db_for_display($model, $field_name, $raw_db_value, $pretty_schema = true)
320
+	{
321
+		$field_obj = $model->field_settings_for($field_name);
322
+		$value_on_model_obj = $field_obj->prepare_for_set_from_db($raw_db_value);
323
+		if ($field_obj instanceof EE_Datetime_Field) {
324
+			$field_obj->set_date_format(
325
+				EE_CSV::instance()->get_date_format_for_csv($field_obj->get_date_format($pretty_schema)),
326
+				$pretty_schema
327
+			);
328
+			$field_obj->set_time_format(
329
+				EE_CSV::instance()->get_time_format_for_csv($field_obj->get_time_format($pretty_schema)),
330
+				$pretty_schema
331
+			);
332
+		}
333
+		if ($pretty_schema === true) {
334
+			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj);
335
+		} elseif (is_string($pretty_schema)) {
336
+			return $field_obj->prepare_for_pretty_echoing($value_on_model_obj, $pretty_schema);
337
+		} else {
338
+			return $field_obj->prepare_for_get($value_on_model_obj);
339
+		}
340
+	}
341
+
342
+	/**
343
+	 * Export a custom CSV of registration info including: A bunch of the reg fields, the time of the event, the price
344
+	 * name, and the questions associated with the registrations
345
+	 *
346
+	 * @param int $event_id
347
+	 * @throws EE_Error
348
+	 * @throws ReflectionException
349
+	 */
350
+	public function report_registrations_for_event($event_id = null)
351
+	{
352
+		$reg_fields_to_include = array(
353
+			'TXN_ID',
354
+			'ATT_ID',
355
+			'REG_ID',
356
+			'REG_date',
357
+			'REG_code',
358
+			'REG_count',
359
+			'REG_final_price',
360
+
361
+		);
362
+		$att_fields_to_include = array(
363
+			'ATT_fname',
364
+			'ATT_lname',
365
+			'ATT_email',
366
+			'ATT_address',
367
+			'ATT_address2',
368
+			'ATT_city',
369
+			'STA_ID',
370
+			'CNT_ISO',
371
+			'ATT_zip',
372
+			'ATT_phone',
373
+		);
374
+
375
+		$registrations_csv_ready_array = array();
376
+		$reg_model = EE_Registry::instance()->load_model('Registration');
377
+		$query_params = apply_filters(
378
+			'FHEE__EE_Export__report_registration_for_event',
379
+			array(
380
+				array(
381
+					'OR'                 => array(
382
+						// don't include registrations from failed or abandoned transactions...
383
+						'Transaction.STS_ID' => array(
384
+							'NOT IN',
385
+							array(EEM_Transaction::failed_status_code, EEM_Transaction::abandoned_status_code),
386
+						),
387
+						// unless the registration is approved, in which case include it regardless of transaction status
388
+						'STS_ID'             => RegStatus::APPROVED,
389
+					),
390
+					'Ticket.TKT_deleted' => array('IN', array(true, false)),
391
+				),
392
+				'order_by'   => array('Transaction.TXN_ID' => 'asc', 'REG_count' => 'asc'),
393
+				'force_join' => array('Transaction', 'Ticket', 'Attendee'),
394
+				'caps'       => EEM_Base::caps_read_admin,
395
+			),
396
+			$event_id
397
+		);
398
+		if ($event_id) {
399
+			$query_params[0]['EVT_ID'] = $event_id;
400
+		} else {
401
+			$query_params['force_join'][] = 'Event';
402
+		}
403
+		$registration_rows = $reg_model->get_all_wpdb_results($query_params);
404
+		// get all questions which relate to someone in this group
405
+		$registration_ids = array();
406
+		foreach ($registration_rows as $reg_row) {
407
+			$registration_ids[] = intval($reg_row['Registration.REG_ID']);
408
+		}
409
+		// EEM_Question::instance()->show_next_x_db_queries();
410
+		$questions_for_these_regs_rows = EEM_Question::instance()->get_all_wpdb_results(
411
+			array(array('Answer.REG_ID' => array('IN', $registration_ids)))
412
+		);
413
+		foreach ($registration_rows as $reg_row) {
414
+			if (is_array($reg_row)) {
415
+				$reg_csv_array = array();
416
+				if (! $event_id) {
417
+					// get the event's name and Id
418
+					$reg_csv_array[ esc_html__('Event', 'event_espresso') ] = sprintf(
419
+						esc_html__('%1$s (%2$s)', 'event_espresso'),
420
+						$this->_prepare_value_from_db_for_display(
421
+							EEM_Event::instance(),
422
+							'EVT_name',
423
+							$reg_row['Event_CPT.post_title']
424
+						),
425
+						$reg_row['Event_CPT.ID']
426
+					);
427
+				}
428
+				$is_primary_reg = $reg_row['Registration.REG_count'] == '1' ? true : false;
429
+				/*@var $reg_row EE_Registration */
430
+				foreach ($reg_fields_to_include as $field_name) {
431
+					$field = $reg_model->field_settings_for($field_name);
432
+					if ($field_name == 'REG_final_price') {
433
+						$value = $this->_prepare_value_from_db_for_display(
434
+							$reg_model,
435
+							$field_name,
436
+							$reg_row['Registration.REG_final_price'],
437
+							'localized_float'
438
+						);
439
+					} elseif ($field_name == 'REG_count') {
440
+						$value = sprintf(
441
+							esc_html__('%s of %s', 'event_espresso'),
442
+							$this->_prepare_value_from_db_for_display(
443
+								$reg_model,
444
+								'REG_count',
445
+								$reg_row['Registration.REG_count']
446
+							),
447
+							$this->_prepare_value_from_db_for_display(
448
+								$reg_model,
449
+								'REG_group_size',
450
+								$reg_row['Registration.REG_group_size']
451
+							)
452
+						);
453
+					} elseif ($field_name == 'REG_date') {
454
+						$value = $this->_prepare_value_from_db_for_display(
455
+							$reg_model,
456
+							$field_name,
457
+							$reg_row['Registration.REG_date'],
458
+							'no_html'
459
+						);
460
+					} else {
461
+						$value = $this->_prepare_value_from_db_for_display(
462
+							$reg_model,
463
+							$field_name,
464
+							$reg_row[ $field->get_qualified_column() ]
465
+						);
466
+					}
467
+					$reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
468
+					if ($field_name == 'REG_final_price') {
469
+						// add a column named Currency after the final price
470
+						$reg_csv_array[ esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
471
+					}
472
+				}
473
+				// get pretty status
474
+				$stati = EEM_Status::instance()->localized_status(
475
+					array(
476
+						$reg_row['Registration.STS_ID']     => esc_html__('unknown', 'event_espresso'),
477
+						$reg_row['TransactionTable.STS_ID'] => esc_html__('unknown', 'event_espresso'),
478
+					),
479
+					false,
480
+					'sentence'
481
+				);
482
+				$reg_csv_array[ esc_html__(
483
+					"Registration Status",
484
+					'event_espresso'
485
+				) ] = $stati[ $reg_row['Registration.STS_ID'] ];
486
+				// get pretty trnasaction status
487
+				$reg_csv_array[ esc_html__(
488
+					"Transaction Status",
489
+					'event_espresso'
490
+				) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
491
+				$reg_csv_array[ esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
492
+					? $this->_prepare_value_from_db_for_display(
493
+						EEM_Transaction::instance(),
494
+						'TXN_total',
495
+						$reg_row['TransactionTable.TXN_total'],
496
+						'localized_float'
497
+					) : '0.00';
498
+				$reg_csv_array[ esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
499
+					? $this->_prepare_value_from_db_for_display(
500
+						EEM_Transaction::instance(),
501
+						'TXN_paid',
502
+						$reg_row['TransactionTable.TXN_paid'],
503
+						'localized_float'
504
+					) : '0.00';
505
+				$payment_methods = array();
506
+				$gateway_txn_ids_etc = array();
507
+				$payment_times = array();
508
+				if ($is_primary_reg && $reg_row['TransactionTable.TXN_ID']) {
509
+					$payments_info = EEM_Payment::instance()->get_all_wpdb_results(
510
+						array(
511
+							array(
512
+								'TXN_ID' => $reg_row['TransactionTable.TXN_ID'],
513
+								'STS_ID' => EEM_Payment::status_id_approved,
514
+							),
515
+							'force_join' => array('Payment_Method'),
516
+						),
517
+						ARRAY_A,
518
+						'Payment_Method.PMD_admin_name as name, Payment.PAY_txn_id_chq_nmbr as gateway_txn_id, Payment.PAY_timestamp as payment_time'
519
+					);
520
+					list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
521
+				}
522
+				$reg_csv_array[ esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
523
+				$reg_csv_array[ esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
524
+				$reg_csv_array[ esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
525
+					',',
526
+					$gateway_txn_ids_etc
527
+				);
528
+
529
+				// get whether or not the user has checked in
530
+				$reg_csv_array[ esc_html__("Check-Ins", "event_espresso") ] = $reg_model->count_related(
531
+					$reg_row['Registration.REG_ID'],
532
+					'Checkin'
533
+				);
534
+				// get ticket of registration and its price
535
+				$ticket_model = EE_Registry::instance()->load_model('Ticket');
536
+				if ($reg_row['Ticket.TKT_ID']) {
537
+					$ticket_name = $this->_prepare_value_from_db_for_display(
538
+						$ticket_model,
539
+						'TKT_name',
540
+						$reg_row['Ticket.TKT_name']
541
+					);
542
+					$datetimes_strings = array();
543
+					foreach (
544
+						EEM_Datetime::instance()->get_all_wpdb_results(
545
+							array(
546
+							array('Ticket.TKT_ID' => $reg_row['Ticket.TKT_ID']),
547
+							'order_by'                 => array('DTT_EVT_start' => 'ASC'),
548
+							'default_where_conditions' => 'none',
549
+							)
550
+						) as $datetime
551
+					) {
552
+						$datetimes_strings[] = $this->_prepare_value_from_db_for_display(
553
+							EEM_Datetime::instance(),
554
+							'DTT_EVT_start',
555
+							$datetime['Datetime.DTT_EVT_start']
556
+						);
557
+					}
558
+				} else {
559
+					$ticket_name = esc_html__('Unknown', 'event_espresso');
560
+					$datetimes_strings = array(esc_html__('Unknown', 'event_espresso'));
561
+				}
562
+				$reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
563
+				$reg_csv_array[ esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
564
+				// get datetime(s) of registration
565
+
566
+				// add attendee columns
567
+				foreach ($att_fields_to_include as $att_field_name) {
568
+					$field_obj = EEM_Attendee::instance()->field_settings_for($att_field_name);
569
+					if ($reg_row['Attendee_CPT.ID']) {
570
+						if ($att_field_name == 'STA_ID') {
571
+							$value = EEM_State::instance()->get_var(
572
+								array(array('STA_ID' => $reg_row['Attendee_Meta.STA_ID'])),
573
+								'STA_name'
574
+							);
575
+						} elseif ($att_field_name == 'CNT_ISO') {
576
+							$value = EEM_Country::instance()->get_var(
577
+								array(array('CNT_ISO' => $reg_row['Attendee_Meta.CNT_ISO'])),
578
+								'CNT_name'
579
+							);
580
+						} else {
581
+							$value = $this->_prepare_value_from_db_for_display(
582
+								EEM_Attendee::instance(),
583
+								$att_field_name,
584
+								$reg_row[ $field_obj->get_qualified_column() ]
585
+							);
586
+						}
587
+					} else {
588
+						$value = '';
589
+					}
590
+
591
+					$reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
592
+				}
593
+
594
+				// make sure each registration has the same questions in the same order
595
+				foreach ($questions_for_these_regs_rows as $question_row) {
596
+					if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
597
+						$reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
598
+					}
599
+				}
600
+				// now fill out the questions THEY answered
601
+				foreach (
602
+					EEM_Answer::instance()->get_all_wpdb_results(
603
+						array(array('REG_ID' => $reg_row['Registration.REG_ID']), 'force_join' => array('Question'))
604
+					) as $answer_row
605
+				) {
606
+					/* @var $answer EE_Answer */
607
+					if ($answer_row['Question.QST_ID']) {
608
+						$question_label = $this->_prepare_value_from_db_for_display(
609
+							EEM_Question::instance(),
610
+							'QST_admin_label',
611
+							$answer_row['Question.QST_admin_label']
612
+						);
613
+					} else {
614
+						$question_label = sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
615
+					}
616
+					if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
617
+						$reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
618
+							(int) $answer_row['Answer.ANS_value']
619
+						);
620
+					} else {
621
+						$reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
622
+							EEM_Answer::instance(),
623
+							'ANS_value',
624
+							$answer_row['Answer.ANS_value']
625
+						);
626
+					}
627
+				}
628
+				$registrations_csv_ready_array[] = apply_filters(
629
+					'FHEE__EventEspressoBatchRequest__JobHandlers__RegistrationsReport__reg_csv_array',
630
+					$reg_csv_array,
631
+					$reg_row
632
+				);
633
+			}
634
+		}
635
+
636
+		// if we couldn't export anything, we want to at least show the column headers
637
+		if (empty($registrations_csv_ready_array)) {
638
+			$reg_csv_array = array();
639
+			$model_and_fields_to_include = array(
640
+				'Registration' => $reg_fields_to_include,
641
+				'Attendee'     => $att_fields_to_include,
642
+			);
643
+			foreach ($model_and_fields_to_include as $model_name => $field_list) {
644
+				$model = EE_Registry::instance()->load_model($model_name);
645
+				foreach ($field_list as $field_name) {
646
+					$field = $model->field_settings_for($field_name);
647
+					$reg_csv_array[ $this->_get_column_name_for_field(
648
+						$field
649
+					) ] = null;// $registration->get($field->get_name());
650
+				}
651
+			}
652
+			$registrations_csv_ready_array [] = $reg_csv_array;
653
+		}
654
+		if ($event_id) {
655
+			$event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
656
+			if (! $event_slug) {
657
+				$event_slug = esc_html__('unknown', 'event_espresso');
658
+			}
659
+		} else {
660
+			$event_slug = esc_html__('all', 'event_espresso');
661
+		}
662
+		$filename = sprintf("registrations-for-%s", $event_slug);
663
+
664
+		$handle = $this->EE_CSV->begin_sending_csv($filename);
665
+		$this->EE_CSV->write_data_array_to_csv($handle, $registrations_csv_ready_array);
666
+		$this->EE_CSV->end_sending_csv($handle);
667
+	}
668
+
669
+	/**
670
+	 * Gets the 'normal' column named for fields
671
+	 *
672
+	 * @param EE_Model_Field_Base $field
673
+	 * @return string
674
+	 * @throws EE_Error
675
+	 */
676
+	protected function _get_column_name_for_field(EE_Model_Field_Base $field)
677
+	{
678
+		return $field->get_nicename() . "[" . $field->get_name() . "]";
679
+	}
680
+
681
+
682
+	/**
683
+	 * Export data for ALL events
684
+	 * @return void
685
+	 */
686
+	public function export_categories()
687
+	{
688
+		// are any Event IDs set?
689
+		$query_params = array();
690
+		if (isset($this->_req_data['EVT_CAT_ID'])) {
691
+			// do we have an array of IDs ?
692
+			if (is_array($this->_req_data['EVT_CAT_ID'])) {
693
+				// generate an "IN (CSV)" where clause
694
+				$EVT_CAT_IDs = array_map('sanitize_text_field', $this->_req_data['EVT_CAT_ID']);
695
+				$filename = 'event-categories';
696
+				$query_params[0]['term_taxonomy_id'] = array('IN', $EVT_CAT_IDs);
697
+			} else {
698
+				// generate regular where = clause
699
+				$EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
700
+				$filename = 'event-category#' . $EVT_CAT_ID;
701
+				$query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
702
+			}
703
+		} else {
704
+			// no IDs means we will d/l the entire table
705
+			$filename = 'all-categories';
706
+		}
707
+
708
+		$tables_to_export = array(
709
+			'Term_Taxonomy' => $query_params,
710
+		);
711
+
712
+		$table_data = $this->_get_export_data_for_models($tables_to_export);
713
+		$filename = $this->generate_filename($filename);
714
+
715
+		if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
716
+			EE_Error::add_error(
717
+				esc_html__(
718
+					'An error occurred and the Category details could not be exported from the database.',
719
+					'event_espresso'
720
+				),
721
+				__FILE__,
722
+				__FUNCTION__,
723
+				__LINE__
724
+			);
725
+		}
726
+	}
727
+
728
+
729
+	/**
730
+	 * process export name to create a suitable filename
731
+	 * @param string - export_name
732
+	 * @return string on success, FALSE on fail
733
+	 */
734
+	private function generate_filename($export_name = '')
735
+	{
736
+		if ($export_name != '') {
737
+			$filename = get_bloginfo('name') . '-' . $export_name;
738
+			$filename = sanitize_key($filename) . '-' . $this->today;
739
+			return $filename;
740
+		} else {
741
+			EE_Error::add_error(esc_html__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
742
+		}
743
+		return false;
744
+	}
745
+
746
+
747
+	/**
748
+	 * recursive function for exporting table data and merging the results with the next results
749
+	 * @param array $models_to_export keys are model names (eg 'Event', 'Attendee', etc.) and values are arrays of
750
+	 *                                query params @return bool on success, FALSE on fail
751
+	 * @throws EE_Error
752
+	 * @throws ReflectionException
753
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
754
+	 */
755
+	private function _get_export_data_for_models($models_to_export = array())
756
+	{
757
+		$table_data = false;
758
+		if (is_array($models_to_export)) {
759
+			foreach ($models_to_export as $model_name => $query_params) {
760
+				// check for a numerically-indexed array. in that case, $model_name is the value!!
761
+				if (is_int($model_name)) {
762
+					$model_name = $query_params;
763
+					$query_params = array();
764
+				}
765
+				$model = EE_Registry::instance()->load_model($model_name);
766
+				$model_objects = $model->get_all($query_params);
767
+
768
+				$table_data[ $model_name ] = array();
769
+				foreach ($model_objects as $model_object) {
770
+					$model_data_array = array();
771
+					$fields = $model->field_settings();
772
+					foreach ($fields as $field) {
773
+						$column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
774
+						if ($field instanceof EE_Datetime_Field) {
775
+							// $field->set_date_format('Y-m-d');
776
+							// $field->set_time_format('H:i:s');
777
+							$model_data_array[ $column_name ] = $model_object->get_datetime(
778
+								$field->get_name(),
779
+								'Y-m-d',
780
+								'H:i:s'
781
+							);
782
+						} else {
783
+							$model_data_array[ $column_name ] = $model_object->get($field->get_name());
784
+						}
785
+					}
786
+					$table_data[ $model_name ][] = $model_data_array;
787
+				}
788
+			}
789
+		}
790
+		return $table_data;
791
+	}
792 792
 }
Please login to merge, or discard this patch.
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
     {
45 45
         $this->_req_data = $request_data;
46 46
         $this->today = date("Y-m-d", time());
47
-        require_once(EE_CLASSES . 'EE_CSV.class.php');
47
+        require_once(EE_CLASSES.'EE_CSV.class.php');
48 48
         $this->EE_CSV = EE_CSV::instance();
49 49
     }
50 50
 
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
                 $value_to_equal = $EVT_ID;
169 169
                 $event = EE_Registry::instance()->load_model('Event')->get_one_by_ID($EVT_ID);
170 170
 
171
-                $filename = 'event-' . ($event instanceof EE_Event ? $event->slug() : esc_html__('unknown', 'event_espresso'));
171
+                $filename = 'event-'.($event instanceof EE_Event ? $event->slug() : esc_html__('unknown', 'event_espresso'));
172 172
             }
173 173
             $event_query_params[0]['EVT_ID'] = $value_to_equal;
174 174
             $related_models_query_params[0]['Event.EVT_ID'] = $value_to_equal;
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 
218 218
         $filename = $this->generate_filename($filename);
219 219
 
220
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
220
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
221 221
             EE_Error::add_error(
222 222
                 esc_html__(
223 223
                     "'An error occurred and the Event details could not be exported from the database.'",
@@ -244,16 +244,16 @@  discard block
 block discarded – undo
244 244
             foreach (EEM_Attendee::instance()->field_settings() as $field_name => $field_obj) {
245 245
                 if ($field_name == 'STA_ID') {
246 246
                     $state_name_field = EEM_State::instance()->field_settings_for('STA_name');
247
-                    $csv_row[ esc_html__('State', 'event_espresso') ] = $attendee_row[ $state_name_field->get_qualified_column(
248
-                    ) ];
247
+                    $csv_row[esc_html__('State', 'event_espresso')] = $attendee_row[$state_name_field->get_qualified_column(
248
+                    )];
249 249
                 } elseif ($field_name == 'CNT_ISO') {
250 250
                     $country_name_field = EEM_Country::instance()->field_settings_for('CNT_name');
251
-                    $csv_row[ esc_html__(
251
+                    $csv_row[esc_html__(
252 252
                         'Country',
253 253
                         'event_espresso'
254
-                    ) ] = $attendee_row[ $country_name_field->get_qualified_column() ];
254
+                    )] = $attendee_row[$country_name_field->get_qualified_column()];
255 255
                 } else {
256
-                    $csv_row[ $field_obj->get_nicename() ] = $attendee_row[ $field_obj->get_qualified_column() ];
256
+                    $csv_row[$field_obj->get_nicename()] = $attendee_row[$field_obj->get_qualified_column()];
257 257
                 }
258 258
             }
259 259
             $csv_data[] = $csv_row;
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
         $model_data = $this->_get_export_data_for_models($models_to_export);
293 293
         $filename = $this->generate_filename('all-attendees');
294 294
 
295
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
295
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $model_data)) {
296 296
             EE_Error::add_error(
297 297
                 esc_html__(
298 298
                     'An error occurred and the Attendee data could not be exported from the database.',
@@ -413,9 +413,9 @@  discard block
 block discarded – undo
413 413
         foreach ($registration_rows as $reg_row) {
414 414
             if (is_array($reg_row)) {
415 415
                 $reg_csv_array = array();
416
-                if (! $event_id) {
416
+                if ( ! $event_id) {
417 417
                     // get the event's name and Id
418
-                    $reg_csv_array[ esc_html__('Event', 'event_espresso') ] = sprintf(
418
+                    $reg_csv_array[esc_html__('Event', 'event_espresso')] = sprintf(
419 419
                         esc_html__('%1$s (%2$s)', 'event_espresso'),
420 420
                         $this->_prepare_value_from_db_for_display(
421 421
                             EEM_Event::instance(),
@@ -461,13 +461,13 @@  discard block
 block discarded – undo
461 461
                         $value = $this->_prepare_value_from_db_for_display(
462 462
                             $reg_model,
463 463
                             $field_name,
464
-                            $reg_row[ $field->get_qualified_column() ]
464
+                            $reg_row[$field->get_qualified_column()]
465 465
                         );
466 466
                     }
467
-                    $reg_csv_array[ $this->_get_column_name_for_field($field) ] = $value;
467
+                    $reg_csv_array[$this->_get_column_name_for_field($field)] = $value;
468 468
                     if ($field_name == 'REG_final_price') {
469 469
                         // add a column named Currency after the final price
470
-                        $reg_csv_array[ esc_html__("Currency", "event_espresso") ] = EE_Config::instance()->currency->code;
470
+                        $reg_csv_array[esc_html__("Currency", "event_espresso")] = EE_Config::instance()->currency->code;
471 471
                     }
472 472
                 }
473 473
                 // get pretty status
@@ -479,23 +479,23 @@  discard block
 block discarded – undo
479 479
                     false,
480 480
                     'sentence'
481 481
                 );
482
-                $reg_csv_array[ esc_html__(
482
+                $reg_csv_array[esc_html__(
483 483
                     "Registration Status",
484 484
                     'event_espresso'
485
-                ) ] = $stati[ $reg_row['Registration.STS_ID'] ];
485
+                )] = $stati[$reg_row['Registration.STS_ID']];
486 486
                 // get pretty trnasaction status
487
-                $reg_csv_array[ esc_html__(
487
+                $reg_csv_array[esc_html__(
488 488
                     "Transaction Status",
489 489
                     'event_espresso'
490
-                ) ] = $stati[ $reg_row['TransactionTable.STS_ID'] ];
491
-                $reg_csv_array[ esc_html__('Transaction Amount Due', 'event_espresso') ] = $is_primary_reg
490
+                )] = $stati[$reg_row['TransactionTable.STS_ID']];
491
+                $reg_csv_array[esc_html__('Transaction Amount Due', 'event_espresso')] = $is_primary_reg
492 492
                     ? $this->_prepare_value_from_db_for_display(
493 493
                         EEM_Transaction::instance(),
494 494
                         'TXN_total',
495 495
                         $reg_row['TransactionTable.TXN_total'],
496 496
                         'localized_float'
497 497
                     ) : '0.00';
498
-                $reg_csv_array[ esc_html__('Amount Paid', 'event_espresso') ] = $is_primary_reg
498
+                $reg_csv_array[esc_html__('Amount Paid', 'event_espresso')] = $is_primary_reg
499 499
                     ? $this->_prepare_value_from_db_for_display(
500 500
                         EEM_Transaction::instance(),
501 501
                         'TXN_paid',
@@ -519,15 +519,15 @@  discard block
 block discarded – undo
519 519
                     );
520 520
                     list($payment_methods, $gateway_txn_ids_etc, $payment_times) = PaymentsInfoCSV::extractPaymentInfo($payments_info);
521 521
                 }
522
-                $reg_csv_array[ esc_html__('Payment Date(s)', 'event_espresso') ] = implode(',', $payment_times);
523
-                $reg_csv_array[ esc_html__('Payment Method(s)', 'event_espresso') ] = implode(",", $payment_methods);
524
-                $reg_csv_array[ esc_html__('Gateway Transaction ID(s)', 'event_espresso') ] = implode(
522
+                $reg_csv_array[esc_html__('Payment Date(s)', 'event_espresso')] = implode(',', $payment_times);
523
+                $reg_csv_array[esc_html__('Payment Method(s)', 'event_espresso')] = implode(",", $payment_methods);
524
+                $reg_csv_array[esc_html__('Gateway Transaction ID(s)', 'event_espresso')] = implode(
525 525
                     ',',
526 526
                     $gateway_txn_ids_etc
527 527
                 );
528 528
 
529 529
                 // get whether or not the user has checked in
530
-                $reg_csv_array[ esc_html__("Check-Ins", "event_espresso") ] = $reg_model->count_related(
530
+                $reg_csv_array[esc_html__("Check-Ins", "event_espresso")] = $reg_model->count_related(
531 531
                     $reg_row['Registration.REG_ID'],
532 532
                     'Checkin'
533 533
                 );
@@ -559,8 +559,8 @@  discard block
 block discarded – undo
559 559
                     $ticket_name = esc_html__('Unknown', 'event_espresso');
560 560
                     $datetimes_strings = array(esc_html__('Unknown', 'event_espresso'));
561 561
                 }
562
-                $reg_csv_array[ $ticket_model->field_settings_for('TKT_name')->get_nicename() ] = $ticket_name;
563
-                $reg_csv_array[ esc_html__("Datetimes of Ticket", "event_espresso") ] = implode(", ", $datetimes_strings);
562
+                $reg_csv_array[$ticket_model->field_settings_for('TKT_name')->get_nicename()] = $ticket_name;
563
+                $reg_csv_array[esc_html__("Datetimes of Ticket", "event_espresso")] = implode(", ", $datetimes_strings);
564 564
                 // get datetime(s) of registration
565 565
 
566 566
                 // add attendee columns
@@ -581,20 +581,20 @@  discard block
 block discarded – undo
581 581
                             $value = $this->_prepare_value_from_db_for_display(
582 582
                                 EEM_Attendee::instance(),
583 583
                                 $att_field_name,
584
-                                $reg_row[ $field_obj->get_qualified_column() ]
584
+                                $reg_row[$field_obj->get_qualified_column()]
585 585
                             );
586 586
                         }
587 587
                     } else {
588 588
                         $value = '';
589 589
                     }
590 590
 
591
-                    $reg_csv_array[ $this->_get_column_name_for_field($field_obj) ] = $value;
591
+                    $reg_csv_array[$this->_get_column_name_for_field($field_obj)] = $value;
592 592
                 }
593 593
 
594 594
                 // make sure each registration has the same questions in the same order
595 595
                 foreach ($questions_for_these_regs_rows as $question_row) {
596
-                    if (! isset($reg_csv_array[ $question_row['Question.QST_admin_label'] ])) {
597
-                        $reg_csv_array[ $question_row['Question.QST_admin_label'] ] = null;
596
+                    if ( ! isset($reg_csv_array[$question_row['Question.QST_admin_label']])) {
597
+                        $reg_csv_array[$question_row['Question.QST_admin_label']] = null;
598 598
                     }
599 599
                 }
600 600
                 // now fill out the questions THEY answered
@@ -614,11 +614,11 @@  discard block
 block discarded – undo
614 614
                         $question_label = sprintf(esc_html__('Question $s', 'event_espresso'), $answer_row['Answer.QST_ID']);
615 615
                     }
616 616
                     if (isset($answer_row['Question.QST_type']) && $answer_row['Question.QST_type'] == EEM_Question::QST_type_state) {
617
-                        $reg_csv_array[ $question_label ] = EEM_State::instance()->get_state_name_by_ID(
617
+                        $reg_csv_array[$question_label] = EEM_State::instance()->get_state_name_by_ID(
618 618
                             (int) $answer_row['Answer.ANS_value']
619 619
                         );
620 620
                     } else {
621
-                        $reg_csv_array[ $question_label ] = $this->_prepare_value_from_db_for_display(
621
+                        $reg_csv_array[$question_label] = $this->_prepare_value_from_db_for_display(
622 622
                             EEM_Answer::instance(),
623 623
                             'ANS_value',
624 624
                             $answer_row['Answer.ANS_value']
@@ -644,16 +644,16 @@  discard block
 block discarded – undo
644 644
                 $model = EE_Registry::instance()->load_model($model_name);
645 645
                 foreach ($field_list as $field_name) {
646 646
                     $field = $model->field_settings_for($field_name);
647
-                    $reg_csv_array[ $this->_get_column_name_for_field(
647
+                    $reg_csv_array[$this->_get_column_name_for_field(
648 648
                         $field
649
-                    ) ] = null;// $registration->get($field->get_name());
649
+                    )] = null; // $registration->get($field->get_name());
650 650
                 }
651 651
             }
652 652
             $registrations_csv_ready_array [] = $reg_csv_array;
653 653
         }
654 654
         if ($event_id) {
655 655
             $event_slug = EEM_Event::instance()->get_var(array(array('EVT_ID' => $event_id)), 'EVT_slug');
656
-            if (! $event_slug) {
656
+            if ( ! $event_slug) {
657 657
                 $event_slug = esc_html__('unknown', 'event_espresso');
658 658
             }
659 659
         } else {
@@ -675,7 +675,7 @@  discard block
 block discarded – undo
675 675
      */
676 676
     protected function _get_column_name_for_field(EE_Model_Field_Base $field)
677 677
     {
678
-        return $field->get_nicename() . "[" . $field->get_name() . "]";
678
+        return $field->get_nicename()."[".$field->get_name()."]";
679 679
     }
680 680
 
681 681
 
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
             } else {
698 698
                 // generate regular where = clause
699 699
                 $EVT_CAT_ID = absint($this->_req_data['EVT_CAT_ID']);
700
-                $filename = 'event-category#' . $EVT_CAT_ID;
700
+                $filename = 'event-category#'.$EVT_CAT_ID;
701 701
                 $query_params[0]['term_taxonomy_id'] = $EVT_CAT_ID;
702 702
             }
703 703
         } else {
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
         $table_data = $this->_get_export_data_for_models($tables_to_export);
713 713
         $filename = $this->generate_filename($filename);
714 714
 
715
-        if (! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
715
+        if ( ! $this->EE_CSV->export_multiple_model_data_to_csv($filename, $table_data)) {
716 716
             EE_Error::add_error(
717 717
                 esc_html__(
718 718
                     'An error occurred and the Category details could not be exported from the database.',
@@ -734,8 +734,8 @@  discard block
 block discarded – undo
734 734
     private function generate_filename($export_name = '')
735 735
     {
736 736
         if ($export_name != '') {
737
-            $filename = get_bloginfo('name') . '-' . $export_name;
738
-            $filename = sanitize_key($filename) . '-' . $this->today;
737
+            $filename = get_bloginfo('name').'-'.$export_name;
738
+            $filename = sanitize_key($filename).'-'.$this->today;
739 739
             return $filename;
740 740
         } else {
741 741
             EE_Error::add_error(esc_html__("No filename was provided", "event_espresso"), __FILE__, __FUNCTION__, __LINE__);
@@ -765,25 +765,25 @@  discard block
 block discarded – undo
765 765
                 $model = EE_Registry::instance()->load_model($model_name);
766 766
                 $model_objects = $model->get_all($query_params);
767 767
 
768
-                $table_data[ $model_name ] = array();
768
+                $table_data[$model_name] = array();
769 769
                 foreach ($model_objects as $model_object) {
770 770
                     $model_data_array = array();
771 771
                     $fields = $model->field_settings();
772 772
                     foreach ($fields as $field) {
773
-                        $column_name = $field->get_nicename() . "[" . $field->get_name() . "]";
773
+                        $column_name = $field->get_nicename()."[".$field->get_name()."]";
774 774
                         if ($field instanceof EE_Datetime_Field) {
775 775
                             // $field->set_date_format('Y-m-d');
776 776
                             // $field->set_time_format('H:i:s');
777
-                            $model_data_array[ $column_name ] = $model_object->get_datetime(
777
+                            $model_data_array[$column_name] = $model_object->get_datetime(
778 778
                                 $field->get_name(),
779 779
                                 'Y-m-d',
780 780
                                 'H:i:s'
781 781
                             );
782 782
                         } else {
783
-                            $model_data_array[ $column_name ] = $model_object->get($field->get_name());
783
+                            $model_data_array[$column_name] = $model_object->get($field->get_name());
784 784
                         }
785 785
                     }
786
-                    $table_data[ $model_name ][] = $model_data_array;
786
+                    $table_data[$model_name][] = $model_data_array;
787 787
                 }
788 788
             }
789 789
         }
Please login to merge, or discard this patch.
core/db_classes/EE_Question_Option.class.php 1 patch
Indentation   +259 added lines, -259 removed lines patch added patch discarded remove patch
@@ -10,263 +10,263 @@
 block discarded – undo
10 10
  */
11 11
 class EE_Question_Option extends EE_Soft_Delete_Base_Class implements EEI_Duplicatable
12 12
 {
13
-    /**
14
-     * Question Option Opt Group Name
15
-     *
16
-     * @var string
17
-     */
18
-    protected string $_QSO_opt_group = '';
19
-
20
-
21
-    /**
22
-     * @param array  $props_n_values          incoming values
23
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
24
-     *                                        used.)
25
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
26
-     *                                        date_format and the second value is the time format
27
-     * @return EE_Question_Option
28
-     * @throws EE_Error
29
-     * @throws ReflectionException
30
-     */
31
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
32
-    {
33
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
34
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
35
-    }
36
-
37
-
38
-    /**
39
-     * @param array  $props_n_values  incoming values from the database
40
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
41
-     *                                the website will be used.
42
-     * @return EE_Question_Option
43
-     * @throws EE_Error
44
-     * @throws ReflectionException
45
-     */
46
-    public static function new_instance_from_db($props_n_values = [], $timezone = '')
47
-    {
48
-        return new self($props_n_values, true, $timezone);
49
-    }
50
-
51
-
52
-    /**
53
-     * Sets the option's key value
54
-     *
55
-     * @param string $value
56
-     * @throws EE_Error
57
-     * @throws ReflectionException
58
-     */
59
-    public function set_value(string $value)
60
-    {
61
-        $this->set('QSO_value', $value);
62
-    }
63
-
64
-
65
-    /**
66
-     * Sets the option's Display Text
67
-     *
68
-     * @param string $text
69
-     * @throws EE_Error
70
-     * @throws ReflectionException
71
-     */
72
-    public function set_desc(string $text)
73
-    {
74
-        $this->set('QSO_desc', $text);
75
-    }
76
-
77
-
78
-    /**
79
-     * Sets the order for this option
80
-     *
81
-     * @param int $order
82
-     * @throws EE_Error
83
-     * @throws ReflectionException
84
-     */
85
-    public function set_order(int $order)
86
-    {
87
-        $this->set('QSO_order', $order);
88
-    }
89
-
90
-
91
-    /**
92
-     * Sets the ID of the related question
93
-     *
94
-     * @param int $question_ID
95
-     * @throws EE_Error
96
-     * @throws ReflectionException
97
-     */
98
-    public function set_question_ID(int $question_ID)
99
-    {
100
-        $this->set('QST_ID', $question_ID);
101
-    }
102
-
103
-
104
-    /**
105
-     * Sets the option's opt_group
106
-     *
107
-     * @param string $text
108
-     */
109
-    public function set_opt_group(string $text)
110
-    {
111
-        $this->_QSO_opt_group = $text;
112
-    }
113
-
114
-
115
-    /**
116
-     * Gets the option's key value
117
-     *
118
-     * @return int|float|string|null
119
-     * @throws EE_Error
120
-     * @throws ReflectionException
121
-     */
122
-    public function value()
123
-    {
124
-        return $this->get('QSO_value');
125
-    }
126
-
127
-
128
-    /**
129
-     * Gets the option's display text
130
-     *
131
-     * @return string
132
-     * @throws EE_Error
133
-     * @throws ReflectionException
134
-     */
135
-    public function desc(): string
136
-    {
137
-        return (string) $this->get('QSO_desc');
138
-    }
139
-
140
-
141
-    /**
142
-     * Returns whether this option has been deleted or not
143
-     *
144
-     * @return boolean
145
-     * @throws EE_Error
146
-     * @throws ReflectionException
147
-     */
148
-    public function deleted(): bool
149
-    {
150
-        return (bool) $this->get('QSO_deleted');
151
-    }
152
-
153
-
154
-    /**
155
-     * Returns the order or the Question Option
156
-     *
157
-     * @return int
158
-     * @throws EE_Error
159
-     * @throws ReflectionException
160
-     */
161
-    public function order(): int
162
-    {
163
-        return (int) $this->get('QSO_option');
164
-    }
165
-
166
-
167
-    /**
168
-     * Gets the related question's ID
169
-     *
170
-     * @return int
171
-     * @throws EE_Error
172
-     * @throws ReflectionException
173
-     */
174
-    public function question_ID(): int
175
-    {
176
-        return (int) $this->get('QST_ID');
177
-    }
178
-
179
-
180
-    /**
181
-     * Returns the question related to this question option
182
-     *
183
-     * @return EE_Question
184
-     * @throws EE_Error
185
-     * @throws ReflectionException
186
-     */
187
-    public function question(): EE_Question
188
-    {
189
-        return $this->get_first_related('Question');
190
-    }
191
-
192
-
193
-    /**
194
-     * Gets the option's opt_group
195
-     *
196
-     * @return string
197
-     */
198
-    public function opt_group(): string
199
-    {
200
-        return $this->_QSO_opt_group;
201
-    }
202
-
203
-
204
-    /**
205
-     * Duplicates this question option. By default the new question option will be for the same question,
206
-     * but that can be overriden by setting the 'QST_ID' option
207
-     *
208
-     * @param array $options {
209
-     * @throws EE_Error
210
-     * @throws ReflectionException
211
-     */
212
-    public function duplicate($options = [])
213
-    {
214
-        $new_question_option = clone $this;
215
-        $new_question_option->set('QSO_ID', null);
216
-        if (
217
-            array_key_exists(
218
-                'QST_ID',
219
-                $options
220
-            )
221
-        ) {// use array_key_exists instead of isset because NULL might be a valid value
222
-            $new_question_option->set_question_ID($options['QST_ID']);
223
-        }
224
-        $new_question_option->save();
225
-    }
226
-
227
-
228
-    /**
229
-     * Gets the QSO_system value
230
-     *
231
-     * @return string
232
-     * @throws EE_Error
233
-     * @throws ReflectionException
234
-     */
235
-    public function system(): string
236
-    {
237
-        return (string) $this->get('QSO_system');
238
-    }
239
-
240
-
241
-    /**
242
-     * Sets QSO_system
243
-     *
244
-     * @param string $QSO_system
245
-     * @throws EE_Error
246
-     * @throws ReflectionException
247
-     */
248
-    public function set_system(string $QSO_system)
249
-    {
250
-        $this->set('QSO_system', $QSO_system);
251
-    }
252
-
253
-
254
-    /**
255
-     * @throws EE_Error
256
-     * @throws ReflectionException
257
-     */
258
-    public function isDefault(): bool
259
-    {
260
-        return (bool) $this->get('QSO_default');
261
-    }
262
-
263
-
264
-    /**
265
-     * @throws EE_Error
266
-     * @throws ReflectionException
267
-     */
268
-    public function setIsDefault(bool $is_default)
269
-    {
270
-        $this->set('QSO_default', $is_default);
271
-    }
13
+	/**
14
+	 * Question Option Opt Group Name
15
+	 *
16
+	 * @var string
17
+	 */
18
+	protected string $_QSO_opt_group = '';
19
+
20
+
21
+	/**
22
+	 * @param array  $props_n_values          incoming values
23
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
24
+	 *                                        used.)
25
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
26
+	 *                                        date_format and the second value is the time format
27
+	 * @return EE_Question_Option
28
+	 * @throws EE_Error
29
+	 * @throws ReflectionException
30
+	 */
31
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
32
+	{
33
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
34
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
35
+	}
36
+
37
+
38
+	/**
39
+	 * @param array  $props_n_values  incoming values from the database
40
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
41
+	 *                                the website will be used.
42
+	 * @return EE_Question_Option
43
+	 * @throws EE_Error
44
+	 * @throws ReflectionException
45
+	 */
46
+	public static function new_instance_from_db($props_n_values = [], $timezone = '')
47
+	{
48
+		return new self($props_n_values, true, $timezone);
49
+	}
50
+
51
+
52
+	/**
53
+	 * Sets the option's key value
54
+	 *
55
+	 * @param string $value
56
+	 * @throws EE_Error
57
+	 * @throws ReflectionException
58
+	 */
59
+	public function set_value(string $value)
60
+	{
61
+		$this->set('QSO_value', $value);
62
+	}
63
+
64
+
65
+	/**
66
+	 * Sets the option's Display Text
67
+	 *
68
+	 * @param string $text
69
+	 * @throws EE_Error
70
+	 * @throws ReflectionException
71
+	 */
72
+	public function set_desc(string $text)
73
+	{
74
+		$this->set('QSO_desc', $text);
75
+	}
76
+
77
+
78
+	/**
79
+	 * Sets the order for this option
80
+	 *
81
+	 * @param int $order
82
+	 * @throws EE_Error
83
+	 * @throws ReflectionException
84
+	 */
85
+	public function set_order(int $order)
86
+	{
87
+		$this->set('QSO_order', $order);
88
+	}
89
+
90
+
91
+	/**
92
+	 * Sets the ID of the related question
93
+	 *
94
+	 * @param int $question_ID
95
+	 * @throws EE_Error
96
+	 * @throws ReflectionException
97
+	 */
98
+	public function set_question_ID(int $question_ID)
99
+	{
100
+		$this->set('QST_ID', $question_ID);
101
+	}
102
+
103
+
104
+	/**
105
+	 * Sets the option's opt_group
106
+	 *
107
+	 * @param string $text
108
+	 */
109
+	public function set_opt_group(string $text)
110
+	{
111
+		$this->_QSO_opt_group = $text;
112
+	}
113
+
114
+
115
+	/**
116
+	 * Gets the option's key value
117
+	 *
118
+	 * @return int|float|string|null
119
+	 * @throws EE_Error
120
+	 * @throws ReflectionException
121
+	 */
122
+	public function value()
123
+	{
124
+		return $this->get('QSO_value');
125
+	}
126
+
127
+
128
+	/**
129
+	 * Gets the option's display text
130
+	 *
131
+	 * @return string
132
+	 * @throws EE_Error
133
+	 * @throws ReflectionException
134
+	 */
135
+	public function desc(): string
136
+	{
137
+		return (string) $this->get('QSO_desc');
138
+	}
139
+
140
+
141
+	/**
142
+	 * Returns whether this option has been deleted or not
143
+	 *
144
+	 * @return boolean
145
+	 * @throws EE_Error
146
+	 * @throws ReflectionException
147
+	 */
148
+	public function deleted(): bool
149
+	{
150
+		return (bool) $this->get('QSO_deleted');
151
+	}
152
+
153
+
154
+	/**
155
+	 * Returns the order or the Question Option
156
+	 *
157
+	 * @return int
158
+	 * @throws EE_Error
159
+	 * @throws ReflectionException
160
+	 */
161
+	public function order(): int
162
+	{
163
+		return (int) $this->get('QSO_option');
164
+	}
165
+
166
+
167
+	/**
168
+	 * Gets the related question's ID
169
+	 *
170
+	 * @return int
171
+	 * @throws EE_Error
172
+	 * @throws ReflectionException
173
+	 */
174
+	public function question_ID(): int
175
+	{
176
+		return (int) $this->get('QST_ID');
177
+	}
178
+
179
+
180
+	/**
181
+	 * Returns the question related to this question option
182
+	 *
183
+	 * @return EE_Question
184
+	 * @throws EE_Error
185
+	 * @throws ReflectionException
186
+	 */
187
+	public function question(): EE_Question
188
+	{
189
+		return $this->get_first_related('Question');
190
+	}
191
+
192
+
193
+	/**
194
+	 * Gets the option's opt_group
195
+	 *
196
+	 * @return string
197
+	 */
198
+	public function opt_group(): string
199
+	{
200
+		return $this->_QSO_opt_group;
201
+	}
202
+
203
+
204
+	/**
205
+	 * Duplicates this question option. By default the new question option will be for the same question,
206
+	 * but that can be overriden by setting the 'QST_ID' option
207
+	 *
208
+	 * @param array $options {
209
+	 * @throws EE_Error
210
+	 * @throws ReflectionException
211
+	 */
212
+	public function duplicate($options = [])
213
+	{
214
+		$new_question_option = clone $this;
215
+		$new_question_option->set('QSO_ID', null);
216
+		if (
217
+			array_key_exists(
218
+				'QST_ID',
219
+				$options
220
+			)
221
+		) {// use array_key_exists instead of isset because NULL might be a valid value
222
+			$new_question_option->set_question_ID($options['QST_ID']);
223
+		}
224
+		$new_question_option->save();
225
+	}
226
+
227
+
228
+	/**
229
+	 * Gets the QSO_system value
230
+	 *
231
+	 * @return string
232
+	 * @throws EE_Error
233
+	 * @throws ReflectionException
234
+	 */
235
+	public function system(): string
236
+	{
237
+		return (string) $this->get('QSO_system');
238
+	}
239
+
240
+
241
+	/**
242
+	 * Sets QSO_system
243
+	 *
244
+	 * @param string $QSO_system
245
+	 * @throws EE_Error
246
+	 * @throws ReflectionException
247
+	 */
248
+	public function set_system(string $QSO_system)
249
+	{
250
+		$this->set('QSO_system', $QSO_system);
251
+	}
252
+
253
+
254
+	/**
255
+	 * @throws EE_Error
256
+	 * @throws ReflectionException
257
+	 */
258
+	public function isDefault(): bool
259
+	{
260
+		return (bool) $this->get('QSO_default');
261
+	}
262
+
263
+
264
+	/**
265
+	 * @throws EE_Error
266
+	 * @throws ReflectionException
267
+	 */
268
+	public function setIsDefault(bool $is_default)
269
+	{
270
+		$this->set('QSO_default', $is_default);
271
+	}
272 272
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 2 patches
Indentation   +2597 added lines, -2597 removed lines patch added patch discarded remove patch
@@ -19,2601 +19,2601 @@
 block discarded – undo
19 19
  */
20 20
 class EE_Registration extends EE_Soft_Delete_Base_Class implements EEI_Registration, EEI_Admin_Links
21 21
 {
22
-    /**
23
-     * extra meta key for tracking reg status os trashed registrations
24
-     *
25
-     * @type string
26
-     */
27
-    public const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
28
-
29
-    /**
30
-     * extra meta key for tracking if registration has reserved ticket
31
-     *
32
-     * @type string
33
-     */
34
-    public const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
35
-
36
-    /**
37
-     * extra meta key for tracking registration cancellations
38
-     *
39
-     * @type string
40
-     */
41
-    public const META_KEY_REG_STATUS_CHANGE = 'registration_status_change';
42
-
43
-
44
-    /**
45
-     * @param array  $props_n_values          incoming values
46
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
47
-     *                                        used.)
48
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
49
-     *                                        date_format and the second value is the time format
50
-     * @return EE_Registration
51
-     * @throws EE_Error
52
-     * @throws InvalidArgumentException
53
-     * @throws InvalidDataTypeException
54
-     * @throws InvalidInterfaceException
55
-     * @throws ReflectionException
56
-     */
57
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
58
-    {
59
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
60
-        return $has_object
61
-            ?: new self($props_n_values, false, $timezone, $date_formats);
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_Registration
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 = [], $timezone = '')
77
-    {
78
-        return new self($props_n_values, true, $timezone);
79
-    }
80
-
81
-
82
-    /**
83
-     *        Set Event ID
84
-     *
85
-     * @param int $EVT_ID Event ID
86
-     * @throws DomainException
87
-     * @throws EE_Error
88
-     * @throws EntityNotFoundException
89
-     * @throws InvalidArgumentException
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     * @throws ReflectionException
93
-     * @throws RuntimeException
94
-     * @throws UnexpectedEntityException
95
-     */
96
-    public function set_event($EVT_ID = 0)
97
-    {
98
-        $this->set('EVT_ID', $EVT_ID);
99
-    }
100
-
101
-
102
-    /**
103
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
104
-     * be routed to internal methods
105
-     *
106
-     * @param string $field_name
107
-     * @param mixed  $field_value
108
-     * @param bool   $use_default
109
-     * @throws DomainException
110
-     * @throws EE_Error
111
-     * @throws EntityNotFoundException
112
-     * @throws InvalidArgumentException
113
-     * @throws InvalidDataTypeException
114
-     * @throws InvalidInterfaceException
115
-     * @throws ReflectionException
116
-     * @throws RuntimeException
117
-     * @throws UnexpectedEntityException
118
-     */
119
-    public function set($field_name, $field_value, $use_default = false)
120
-    {
121
-        switch ($field_name) {
122
-            case 'REG_code':
123
-                if (! empty($field_value) && ! $this->reg_code()) {
124
-                    $this->set_reg_code($field_value, $use_default);
125
-                }
126
-                break;
127
-            case 'STS_ID':
128
-                $this->set_status((string) $field_value, $use_default);
129
-                break;
130
-            default:
131
-                parent::set($field_name, $field_value, $use_default);
132
-        }
133
-    }
134
-
135
-
136
-    /**
137
-     * Set Status ID
138
-     * updates the registration status and ALSO...
139
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
140
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
141
-     *
142
-     * @param string                $new_STS_ID
143
-     * @param boolean               $use_default
144
-     * @param ContextInterface|null $context
145
-     * @return bool
146
-     * @throws DomainException
147
-     * @throws EE_Error
148
-     * @throws EntityNotFoundException
149
-     * @throws InvalidArgumentException
150
-     * @throws InvalidDataTypeException
151
-     * @throws InvalidInterfaceException
152
-     * @throws ReflectionException
153
-     * @throws RuntimeException
154
-     * @throws UnexpectedEntityException
155
-     */
156
-    public function set_status(
157
-        string $new_STS_ID = '',
158
-        bool $use_default = false,
159
-        ?ContextInterface $context = null
160
-    ): bool {
161
-        // get current REG_Status
162
-        $old_STS_ID = $this->status_ID();
163
-        $new_STS_ID = (string) apply_filters(
164
-            'AFEE__EE_Registration__set_status__new_STS_ID',
165
-            $new_STS_ID,
166
-            $context,
167
-            $this
168
-        );
169
-        // it's still good to allow the parent set method to have a say
170
-        parent::set('STS_ID', (! empty($new_STS_ID) ? $new_STS_ID : null), $use_default);
171
-        // if status has changed
172
-        if (
173
-            $old_STS_ID !== $new_STS_ID // and that status has actually changed
174
-            && ! empty($old_STS_ID) // and that old status is actually set
175
-            && ! empty($new_STS_ID) // as well as the new status
176
-            && $this->ID() // ensure registration is in the db
177
-        ) {
178
-            // THEN handle other changes that occur when reg status changes
179
-            // TO approved
180
-            if ($new_STS_ID === RegStatus::APPROVED) {
181
-                // reserve a space by incrementing ticket and datetime sold values
182
-                $this->reserveRegistrationSpace();
183
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
184
-                // OR FROM  approved
185
-            } elseif ($old_STS_ID === RegStatus::APPROVED) {
186
-                // release a space by decrementing ticket and datetime sold values
187
-                $this->releaseRegistrationSpace();
188
-                do_action(
189
-                    'AHEE__EE_Registration__set_status__from_approved',
190
-                    $this,
191
-                    $old_STS_ID,
192
-                    $new_STS_ID,
193
-                    $context
194
-                );
195
-            }
196
-            $this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
197
-            if ($this->statusChangeUpdatesTransaction($context)) {
198
-                $this->updateTransactionAfterStatusChange();
199
-            }
200
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
201
-        }
202
-        return ! empty($new_STS_ID);
203
-    }
204
-
205
-
206
-    /**
207
-     * update REGs and TXN when cancelled or declined registrations involved
208
-     *
209
-     * @param string                $new_STS_ID
210
-     * @param string                $old_STS_ID
211
-     * @param ContextInterface|null $context
212
-     * @throws EE_Error
213
-     * @throws InvalidArgumentException
214
-     * @throws InvalidDataTypeException
215
-     * @throws InvalidInterfaceException
216
-     * @throws ReflectionException
217
-     * @throws RuntimeException
218
-     */
219
-    private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ?ContextInterface $context = null)
220
-    {
221
-        // these reg statuses should not be considered in any calculations involving monies owing
222
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
223
-        // true if registration has been cancelled or declined
224
-        $this->updateIfCanceled(
225
-            $closed_reg_statuses,
226
-            $new_STS_ID,
227
-            $old_STS_ID,
228
-            $context
229
-        );
230
-        $this->updateIfReinstated(
231
-            $closed_reg_statuses,
232
-            $new_STS_ID,
233
-            $old_STS_ID,
234
-            $context
235
-        );
236
-    }
237
-
238
-
239
-    /**
240
-     * update REGs and TXN when cancelled or declined registrations involved
241
-     *
242
-     * @param array                 $closed_reg_statuses
243
-     * @param string                $new_STS_ID
244
-     * @param string                $old_STS_ID
245
-     * @param ContextInterface|null $context
246
-     * @throws EE_Error
247
-     * @throws InvalidArgumentException
248
-     * @throws InvalidDataTypeException
249
-     * @throws InvalidInterfaceException
250
-     * @throws ReflectionException
251
-     * @throws RuntimeException
252
-     */
253
-    private function updateIfCanceled(
254
-        array $closed_reg_statuses,
255
-        $new_STS_ID,
256
-        $old_STS_ID,
257
-        ?ContextInterface $context = null
258
-    ) {
259
-        // true if registration has been cancelled or declined
260
-        if (
261
-            in_array($new_STS_ID, $closed_reg_statuses, true)
262
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
263
-        ) {
264
-            /** @type EE_Registration_Processor $registration_processor */
265
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
266
-            /** @type EE_Transaction_Processor $transaction_processor */
267
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
268
-            // cancelled or declined registration
269
-            $registration_processor->update_registration_after_being_canceled_or_declined(
270
-                $this,
271
-                $closed_reg_statuses
272
-            );
273
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
274
-                $this,
275
-                $closed_reg_statuses,
276
-                false
277
-            );
278
-            do_action(
279
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
280
-                $this,
281
-                $old_STS_ID,
282
-                $new_STS_ID,
283
-                $context
284
-            );
285
-        }
286
-    }
287
-
288
-
289
-    /**
290
-     * update REGs and TXN when cancelled or declined registrations involved
291
-     *
292
-     * @param array                 $closed_reg_statuses
293
-     * @param string                $new_STS_ID
294
-     * @param string                $old_STS_ID
295
-     * @param ContextInterface|null $context
296
-     * @throws EE_Error
297
-     * @throws InvalidArgumentException
298
-     * @throws InvalidDataTypeException
299
-     * @throws InvalidInterfaceException
300
-     * @throws ReflectionException
301
-     * @throws RuntimeException
302
-     */
303
-    private function updateIfReinstated(
304
-        array $closed_reg_statuses,
305
-        $new_STS_ID,
306
-        $old_STS_ID,
307
-        ?ContextInterface $context = null
308
-    ) {
309
-        // true if reinstating cancelled or declined registration
310
-        if (
311
-            in_array($old_STS_ID, $closed_reg_statuses, true)
312
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
313
-        ) {
314
-            /** @type EE_Registration_Processor $registration_processor */
315
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
316
-            /** @type EE_Transaction_Processor $transaction_processor */
317
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
318
-            // reinstating cancelled or declined registration
319
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
320
-                $this,
321
-                $closed_reg_statuses
322
-            );
323
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
324
-                $this,
325
-                $closed_reg_statuses,
326
-                false
327
-            );
328
-            do_action(
329
-                'AHEE__EE_Registration__set_status__after_reinstated',
330
-                $this,
331
-                $old_STS_ID,
332
-                $new_STS_ID,
333
-                $context
334
-            );
335
-        }
336
-    }
337
-
338
-
339
-    /**
340
-     * @param ContextInterface|null $context
341
-     * @return bool
342
-     */
343
-    private function statusChangeUpdatesTransaction(?ContextInterface $context = null)
344
-    {
345
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
346
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
347
-            ['spco_reg_step_attendee_information_process_registrations'],
348
-            $context,
349
-            $this
350
-        );
351
-        return ! (
352
-            $context instanceof ContextInterface
353
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
354
-        );
355
-    }
356
-
357
-
358
-    /**
359
-     * @throws EE_Error
360
-     * @throws EntityNotFoundException
361
-     * @throws InvalidArgumentException
362
-     * @throws InvalidDataTypeException
363
-     * @throws InvalidInterfaceException
364
-     * @throws ReflectionException
365
-     * @throws RuntimeException
366
-     */
367
-    private function updateTransactionAfterStatusChange()
368
-    {
369
-        /** @type EE_Transaction_Payments $transaction_payments */
370
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
371
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
372
-        $this->transaction()->update_status_based_on_total_paid();
373
-    }
374
-
375
-
376
-    /**
377
-     * get Status ID
378
-     *
379
-     * @throws EE_Error
380
-     * @throws InvalidArgumentException
381
-     * @throws InvalidDataTypeException
382
-     * @throws InvalidInterfaceException
383
-     * @throws ReflectionException
384
-     */
385
-    public function status_ID()
386
-    {
387
-        return $this->get('STS_ID');
388
-    }
389
-
390
-
391
-    /**
392
-     * Gets the ticket this registration is for
393
-     *
394
-     * @param boolean $include_archived whether to include archived tickets or not.
395
-     * @return EE_Ticket|EE_Base_Class
396
-     * @throws EE_Error
397
-     * @throws InvalidArgumentException
398
-     * @throws InvalidDataTypeException
399
-     * @throws InvalidInterfaceException
400
-     * @throws ReflectionException
401
-     */
402
-    public function ticket($include_archived = true)
403
-    {
404
-        return EEM_Ticket::instance()->get_one_by_ID($this->ticket_ID());
405
-    }
406
-
407
-
408
-    /**
409
-     * Gets the event this registration is for
410
-     *
411
-     * @return EE_Event
412
-     * @throws EE_Error
413
-     * @throws EntityNotFoundException
414
-     * @throws InvalidArgumentException
415
-     * @throws InvalidDataTypeException
416
-     * @throws InvalidInterfaceException
417
-     * @throws ReflectionException
418
-     */
419
-    public function event(): EE_Event
420
-    {
421
-        $event = $this->event_obj();
422
-        if (! $event instanceof EE_Event) {
423
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
424
-        }
425
-        return $event;
426
-    }
427
-
428
-
429
-    /**
430
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
431
-     * with the author of the event this registration is for.
432
-     *
433
-     * @return int
434
-     * @throws EE_Error
435
-     * @throws EntityNotFoundException
436
-     * @throws InvalidArgumentException
437
-     * @throws InvalidDataTypeException
438
-     * @throws InvalidInterfaceException
439
-     * @throws ReflectionException
440
-     * @since 4.5.0
441
-     */
442
-    public function wp_user(): int
443
-    {
444
-        return $this->event()->wp_user();
445
-    }
446
-
447
-
448
-    /**
449
-     * increments this registration's related ticket sold and corresponding datetime sold values
450
-     *
451
-     * @return void
452
-     * @throws DomainException
453
-     * @throws EE_Error
454
-     * @throws EntityNotFoundException
455
-     * @throws InvalidArgumentException
456
-     * @throws InvalidDataTypeException
457
-     * @throws InvalidInterfaceException
458
-     * @throws ReflectionException
459
-     * @throws UnexpectedEntityException
460
-     */
461
-    private function reserveRegistrationSpace()
462
-    {
463
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
464
-        // so stop tracking that this reg has a ticket reserved
465
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
466
-        $ticket = $this->ticket();
467
-        $ticket->increaseSold();
468
-        // possibly set event status to sold out
469
-        $this->event()->perform_sold_out_status_check();
470
-    }
471
-
472
-
473
-    /**
474
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
475
-     *
476
-     * @return void
477
-     * @throws DomainException
478
-     * @throws EE_Error
479
-     * @throws EntityNotFoundException
480
-     * @throws InvalidArgumentException
481
-     * @throws InvalidDataTypeException
482
-     * @throws InvalidInterfaceException
483
-     * @throws ReflectionException
484
-     * @throws UnexpectedEntityException
485
-     */
486
-    private function releaseRegistrationSpace()
487
-    {
488
-        $ticket = $this->ticket();
489
-        $ticket->decreaseSold();
490
-        // possibly change event status from sold out back to previous status
491
-        $this->event()->perform_sold_out_status_check();
492
-    }
493
-
494
-
495
-    /**
496
-     * tracks this registration's ticket reservation in extra meta
497
-     * and can increment related ticket reserved and corresponding datetime reserved values
498
-     *
499
-     * @param bool   $update_ticket if true, will increment ticket and datetime reserved count
500
-     * @param string $source
501
-     * @return void
502
-     * @throws EE_Error
503
-     * @throws InvalidArgumentException
504
-     * @throws InvalidDataTypeException
505
-     * @throws InvalidInterfaceException
506
-     * @throws ReflectionException
507
-     */
508
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
509
-    {
510
-        // only reserve ticket if space is not currently reserved
511
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
512
-            $reserved = $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
513
-            if ($reserved && $update_ticket) {
514
-                $ticket = $this->ticket();
515
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
516
-                // comment out extra meta tracking
517
-                // $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
518
-                $ticket->save();
519
-            }
520
-        }
521
-    }
522
-
523
-
524
-    /**
525
-     * stops tracking this registration's ticket reservation in extra meta
526
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
527
-     *
528
-     * @param bool   $update_ticket if true, will decrement ticket and datetime reserved count
529
-     * @param string $source
530
-     * @return void
531
-     * @throws EE_Error
532
-     * @throws InvalidArgumentException
533
-     * @throws InvalidDataTypeException
534
-     * @throws InvalidInterfaceException
535
-     * @throws ReflectionException
536
-     */
537
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
538
-    {
539
-        // only release ticket if space is currently reserved
540
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
541
-            $released = $this->delete_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
542
-            if ($released && $update_ticket) {
543
-                $ticket = $this->ticket();
544
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
545
-                // comment out extra meta tracking
546
-                // $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
547
-            }
548
-        }
549
-    }
550
-
551
-
552
-    /**
553
-     * Set Attendee ID
554
-     *
555
-     * @param int $ATT_ID Attendee ID
556
-     * @throws DomainException
557
-     * @throws EE_Error
558
-     * @throws EntityNotFoundException
559
-     * @throws InvalidArgumentException
560
-     * @throws InvalidDataTypeException
561
-     * @throws InvalidInterfaceException
562
-     * @throws ReflectionException
563
-     * @throws RuntimeException
564
-     * @throws UnexpectedEntityException
565
-     */
566
-    public function set_attendee_id($ATT_ID = 0)
567
-    {
568
-        $this->set('ATT_ID', $ATT_ID);
569
-    }
570
-
571
-
572
-    /**
573
-     *        Set Transaction ID
574
-     *
575
-     * @param int $TXN_ID Transaction ID
576
-     * @throws DomainException
577
-     * @throws EE_Error
578
-     * @throws EntityNotFoundException
579
-     * @throws InvalidArgumentException
580
-     * @throws InvalidDataTypeException
581
-     * @throws InvalidInterfaceException
582
-     * @throws ReflectionException
583
-     * @throws RuntimeException
584
-     * @throws UnexpectedEntityException
585
-     */
586
-    public function set_transaction_id($TXN_ID = 0)
587
-    {
588
-        $this->set('TXN_ID', $TXN_ID);
589
-    }
590
-
591
-
592
-    /**
593
-     *        Set Session
594
-     *
595
-     * @param string $REG_session PHP Session ID
596
-     * @throws DomainException
597
-     * @throws EE_Error
598
-     * @throws EntityNotFoundException
599
-     * @throws InvalidArgumentException
600
-     * @throws InvalidDataTypeException
601
-     * @throws InvalidInterfaceException
602
-     * @throws ReflectionException
603
-     * @throws RuntimeException
604
-     * @throws UnexpectedEntityException
605
-     */
606
-    public function set_session($REG_session = '')
607
-    {
608
-        $this->set('REG_session', $REG_session);
609
-    }
610
-
611
-
612
-    /**
613
-     *        Set Registration URL Link
614
-     *
615
-     * @param string $REG_url_link Registration URL Link
616
-     * @throws DomainException
617
-     * @throws EE_Error
618
-     * @throws EntityNotFoundException
619
-     * @throws InvalidArgumentException
620
-     * @throws InvalidDataTypeException
621
-     * @throws InvalidInterfaceException
622
-     * @throws ReflectionException
623
-     * @throws RuntimeException
624
-     * @throws UnexpectedEntityException
625
-     */
626
-    public function set_reg_url_link($REG_url_link = '')
627
-    {
628
-        $this->set('REG_url_link', $REG_url_link);
629
-    }
630
-
631
-
632
-    /**
633
-     *        Set Attendee Counter
634
-     *
635
-     * @param int $REG_count Primary Attendee
636
-     * @throws DomainException
637
-     * @throws EE_Error
638
-     * @throws EntityNotFoundException
639
-     * @throws InvalidArgumentException
640
-     * @throws InvalidDataTypeException
641
-     * @throws InvalidInterfaceException
642
-     * @throws ReflectionException
643
-     * @throws RuntimeException
644
-     * @throws UnexpectedEntityException
645
-     */
646
-    public function set_count($REG_count = 1)
647
-    {
648
-        $this->set('REG_count', $REG_count);
649
-    }
650
-
651
-
652
-    /**
653
-     *        Set Group Size
654
-     *
655
-     * @param boolean $REG_group_size Group Registration
656
-     * @throws DomainException
657
-     * @throws EE_Error
658
-     * @throws EntityNotFoundException
659
-     * @throws InvalidArgumentException
660
-     * @throws InvalidDataTypeException
661
-     * @throws InvalidInterfaceException
662
-     * @throws ReflectionException
663
-     * @throws RuntimeException
664
-     * @throws UnexpectedEntityException
665
-     */
666
-    public function set_group_size($REG_group_size = false)
667
-    {
668
-        $this->set('REG_group_size', $REG_group_size);
669
-    }
670
-
671
-
672
-    /**
673
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
674
-     *    RegStatus::AWAITING_REVIEW
675
-     *
676
-     * @return        boolean
677
-     * @throws EE_Error
678
-     * @throws InvalidArgumentException
679
-     * @throws InvalidDataTypeException
680
-     * @throws InvalidInterfaceException
681
-     * @throws ReflectionException
682
-     */
683
-    public function is_not_approved()
684
-    {
685
-        return $this->status_ID() === RegStatus::AWAITING_REVIEW;
686
-    }
687
-
688
-
689
-    /**
690
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
691
-     *    RegStatus::PENDING_PAYMENT
692
-     *
693
-     * @return        boolean
694
-     * @throws EE_Error
695
-     * @throws InvalidArgumentException
696
-     * @throws InvalidDataTypeException
697
-     * @throws InvalidInterfaceException
698
-     * @throws ReflectionException
699
-     */
700
-    public function is_pending_payment()
701
-    {
702
-        return $this->status_ID() === RegStatus::PENDING_PAYMENT;
703
-    }
704
-
705
-
706
-    /**
707
-     *    is_approved -  convenience method that returns TRUE if REG status ID == RegStatus::APPROVED
708
-     *
709
-     * @return        boolean
710
-     * @throws EE_Error
711
-     * @throws InvalidArgumentException
712
-     * @throws InvalidDataTypeException
713
-     * @throws InvalidInterfaceException
714
-     * @throws ReflectionException
715
-     */
716
-    public function is_approved()
717
-    {
718
-        return $this->status_ID() === RegStatus::APPROVED;
719
-    }
720
-
721
-
722
-    /**
723
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == RegStatus::CANCELLED
724
-     *
725
-     * @return        boolean
726
-     * @throws EE_Error
727
-     * @throws InvalidArgumentException
728
-     * @throws InvalidDataTypeException
729
-     * @throws InvalidInterfaceException
730
-     * @throws ReflectionException
731
-     */
732
-    public function is_cancelled()
733
-    {
734
-        return $this->status_ID() === RegStatus::CANCELLED;
735
-    }
736
-
737
-
738
-    /**
739
-     *    is_declined -  convenience method that returns TRUE if REG status ID == RegStatus::DECLINED
740
-     *
741
-     * @return        boolean
742
-     * @throws EE_Error
743
-     * @throws InvalidArgumentException
744
-     * @throws InvalidDataTypeException
745
-     * @throws InvalidInterfaceException
746
-     * @throws ReflectionException
747
-     */
748
-    public function is_declined()
749
-    {
750
-        return $this->status_ID() === RegStatus::DECLINED;
751
-    }
752
-
753
-
754
-    /**
755
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
756
-     *    RegStatus::INCOMPLETE
757
-     *
758
-     * @return        boolean
759
-     * @throws EE_Error
760
-     * @throws InvalidArgumentException
761
-     * @throws InvalidDataTypeException
762
-     * @throws InvalidInterfaceException
763
-     * @throws ReflectionException
764
-     */
765
-    public function is_incomplete()
766
-    {
767
-        return $this->status_ID() === RegStatus::INCOMPLETE;
768
-    }
769
-
770
-
771
-    /**
772
-     *        Set Registration Date
773
-     *
774
-     * @param mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
775
-     *                                                 Date
776
-     * @throws DomainException
777
-     * @throws EE_Error
778
-     * @throws EntityNotFoundException
779
-     * @throws InvalidArgumentException
780
-     * @throws InvalidDataTypeException
781
-     * @throws InvalidInterfaceException
782
-     * @throws ReflectionException
783
-     * @throws RuntimeException
784
-     * @throws UnexpectedEntityException
785
-     */
786
-    public function set_reg_date($REG_date = false)
787
-    {
788
-        $this->set('REG_date', $REG_date);
789
-    }
790
-
791
-
792
-    /**
793
-     *    Set final price owing for this registration after all ticket/price modifications
794
-     *
795
-     * @param float $REG_final_price
796
-     * @throws DomainException
797
-     * @throws EE_Error
798
-     * @throws EntityNotFoundException
799
-     * @throws InvalidArgumentException
800
-     * @throws InvalidDataTypeException
801
-     * @throws InvalidInterfaceException
802
-     * @throws ReflectionException
803
-     * @throws RuntimeException
804
-     * @throws UnexpectedEntityException
805
-     */
806
-    public function set_final_price($REG_final_price = 0.00)
807
-    {
808
-        $this->set('REG_final_price', $REG_final_price);
809
-    }
810
-
811
-
812
-    /**
813
-     *    Set amount paid towards this registration's final price
814
-     *
815
-     * @param float|int|string $REG_paid
816
-     * @throws DomainException
817
-     * @throws EE_Error
818
-     * @throws EntityNotFoundException
819
-     * @throws InvalidArgumentException
820
-     * @throws InvalidDataTypeException
821
-     * @throws InvalidInterfaceException
822
-     * @throws ReflectionException
823
-     * @throws RuntimeException
824
-     * @throws UnexpectedEntityException
825
-     */
826
-    public function set_paid($REG_paid = 0.00)
827
-    {
828
-        $this->set('REG_paid', (float) $REG_paid);
829
-    }
830
-
831
-
832
-    /**
833
-     *        Attendee Is Going
834
-     *
835
-     * @param boolean $REG_att_is_going Attendee Is Going
836
-     * @throws DomainException
837
-     * @throws EE_Error
838
-     * @throws EntityNotFoundException
839
-     * @throws InvalidArgumentException
840
-     * @throws InvalidDataTypeException
841
-     * @throws InvalidInterfaceException
842
-     * @throws ReflectionException
843
-     * @throws RuntimeException
844
-     * @throws UnexpectedEntityException
845
-     */
846
-    public function set_att_is_going($REG_att_is_going = false)
847
-    {
848
-        $this->set('REG_att_is_going', $REG_att_is_going);
849
-    }
850
-
851
-
852
-    /**
853
-     * Gets the related attendee
854
-     *
855
-     * @return EE_Attendee|EE_Base_Class
856
-     * @throws EE_Error
857
-     * @throws InvalidArgumentException
858
-     * @throws InvalidDataTypeException
859
-     * @throws InvalidInterfaceException
860
-     * @throws ReflectionException
861
-     */
862
-    public function attendee()
863
-    {
864
-        return EEM_Attendee::instance()->get_one_by_ID($this->attendee_ID());
865
-    }
866
-
867
-
868
-    /**
869
-     * Gets the name of the attendee.
870
-     *
871
-     * @param bool $apply_html_entities set to true if you want to use HTML entities.
872
-     * @return string
873
-     * @throws EE_Error
874
-     * @throws InvalidArgumentException
875
-     * @throws InvalidDataTypeException
876
-     * @throws InvalidInterfaceException
877
-     * @throws ReflectionException
878
-     * @since 4.10.12.p
879
-     */
880
-    public function attendeeName($apply_html_entities = false)
881
-    {
882
-        $attendee = $this->attendee();
883
-        if ($attendee instanceof EE_Attendee) {
884
-            $attendee_name = $attendee->full_name($apply_html_entities);
885
-        } else {
886
-            $attendee_name = esc_html__('Unknown', 'event_espresso');
887
-        }
888
-        return $attendee_name;
889
-    }
890
-
891
-
892
-    /**
893
-     *        get Event ID
894
-     */
895
-    public function event_ID()
896
-    {
897
-        return $this->get('EVT_ID');
898
-    }
899
-
900
-
901
-    /**
902
-     *        get Event ID
903
-     */
904
-    public function event_name()
905
-    {
906
-        $event = $this->event_obj();
907
-        if ($event) {
908
-            return $event->name();
909
-        } else {
910
-            return null;
911
-        }
912
-    }
913
-
914
-
915
-    /**
916
-     * Fetches the event this registration is for
917
-     *
918
-     * @return EE_Base_Class|EE_Event
919
-     * @throws EE_Error
920
-     * @throws InvalidArgumentException
921
-     * @throws InvalidDataTypeException
922
-     * @throws InvalidInterfaceException
923
-     * @throws ReflectionException
924
-     */
925
-    public function event_obj()
926
-    {
927
-        return EEM_Event::instance()->get_one_by_ID($this->event_ID());
928
-    }
929
-
930
-
931
-    /**
932
-     *        get Attendee ID
933
-     */
934
-    public function attendee_ID()
935
-    {
936
-        return $this->get('ATT_ID');
937
-    }
938
-
939
-
940
-    /**
941
-     *        get PHP Session ID
942
-     */
943
-    public function session_ID()
944
-    {
945
-        return $this->get('REG_session');
946
-    }
947
-
948
-
949
-    /**
950
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
951
-     *
952
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
953
-     * @return string
954
-     * @throws DomainException
955
-     * @throws InvalidArgumentException
956
-     * @throws InvalidDataTypeException
957
-     * @throws InvalidInterfaceException
958
-     */
959
-    public function receipt_url($messenger = 'html')
960
-    {
961
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
962
-    }
963
-
964
-
965
-    /**
966
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
967
-     *
968
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
969
-     * @return string
970
-     * @throws DomainException
971
-     * @throws InvalidArgumentException
972
-     * @throws InvalidDataTypeException
973
-     * @throws InvalidInterfaceException
974
-     */
975
-    public function invoice_url($messenger = 'html')
976
-    {
977
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
978
-    }
979
-
980
-
981
-    /**
982
-     * get Registration URL Link
983
-     *
984
-     * @return string
985
-     * @throws EE_Error
986
-     * @throws InvalidArgumentException
987
-     * @throws InvalidDataTypeException
988
-     * @throws InvalidInterfaceException
989
-     * @throws ReflectionException
990
-     */
991
-    public function reg_url_link()
992
-    {
993
-        return (string) $this->get('REG_url_link');
994
-    }
995
-
996
-
997
-    /**
998
-     * Echoes out invoice_url()
999
-     *
1000
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
1001
-     * @return void
1002
-     * @throws DomainException
1003
-     * @throws EE_Error
1004
-     * @throws InvalidArgumentException
1005
-     * @throws InvalidDataTypeException
1006
-     * @throws InvalidInterfaceException
1007
-     * @throws ReflectionException
1008
-     */
1009
-    public function e_invoice_url($type = 'launch')
1010
-    {
1011
-        echo esc_url_raw($this->invoice_url($type));
1012
-    }
1013
-
1014
-
1015
-    /**
1016
-     * Echoes out payment_overview_url
1017
-     */
1018
-    public function e_payment_overview_url()
1019
-    {
1020
-        echo esc_url_raw($this->payment_overview_url());
1021
-    }
1022
-
1023
-
1024
-    /**
1025
-     * Gets the URL for the checkout payment options reg step
1026
-     * with this registration's REG_url_link added as a query parameter
1027
-     *
1028
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
1029
-     *                            payment overview url.
1030
-     * @return string
1031
-     * @throws EE_Error
1032
-     * @throws InvalidArgumentException
1033
-     * @throws InvalidDataTypeException
1034
-     * @throws InvalidInterfaceException
1035
-     * @throws ReflectionException
1036
-     */
1037
-    public function payment_overview_url($clear_session = false)
1038
-    {
1039
-        return add_query_arg(
1040
-            (array) apply_filters(
1041
-                'FHEE__EE_Registration__payment_overview_url__query_args',
1042
-                [
1043
-                    'e_reg_url_link' => $this->reg_url_link(),
1044
-                    'step'           => 'payment_options',
1045
-                    'revisit'        => true,
1046
-                    'clear_session'  => (bool) $clear_session,
1047
-                ],
1048
-                $this
1049
-            ),
1050
-            EE_Registry::instance()->CFG->core->reg_page_url()
1051
-        );
1052
-    }
1053
-
1054
-
1055
-    /**
1056
-     * Gets the URL for the checkout attendee information reg step
1057
-     * with this registration's REG_url_link added as a query parameter
1058
-     *
1059
-     * @return string
1060
-     * @throws EE_Error
1061
-     * @throws InvalidArgumentException
1062
-     * @throws InvalidDataTypeException
1063
-     * @throws InvalidInterfaceException
1064
-     * @throws ReflectionException
1065
-     */
1066
-    public function edit_attendee_information_url()
1067
-    {
1068
-        return add_query_arg(
1069
-            (array) apply_filters(
1070
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
1071
-                [
1072
-                    'e_reg_url_link' => $this->reg_url_link(),
1073
-                    'step'           => 'attendee_information',
1074
-                    'revisit'        => true,
1075
-                ],
1076
-                $this
1077
-            ),
1078
-            EE_Registry::instance()->CFG->core->reg_page_url()
1079
-        );
1080
-    }
1081
-
1082
-
1083
-    /**
1084
-     * Simply generates and returns the appropriate admin_url link to edit this registration
1085
-     *
1086
-     * @return string
1087
-     * @throws EE_Error
1088
-     * @throws InvalidArgumentException
1089
-     * @throws InvalidDataTypeException
1090
-     * @throws InvalidInterfaceException
1091
-     * @throws ReflectionException
1092
-     */
1093
-    public function get_admin_edit_url()
1094
-    {
1095
-        return EEH_URL::add_query_args_and_nonce(
1096
-            [
1097
-                'page'    => 'espresso_registrations',
1098
-                'action'  => 'view_registration',
1099
-                '_REG_ID' => $this->ID(),
1100
-            ],
1101
-            admin_url('admin.php')
1102
-        );
1103
-    }
1104
-
1105
-
1106
-    /**
1107
-     * is_primary_registrant?
1108
-     *
1109
-     * @throws EE_Error
1110
-     * @throws InvalidArgumentException
1111
-     * @throws InvalidDataTypeException
1112
-     * @throws InvalidInterfaceException
1113
-     * @throws ReflectionException
1114
-     */
1115
-    public function is_primary_registrant()
1116
-    {
1117
-        return (int) $this->get('REG_count') === 1;
1118
-    }
1119
-
1120
-
1121
-    /**
1122
-     * This returns the primary registration object for this registration group (which may be this object).
1123
-     *
1124
-     * @return EE_Registration
1125
-     * @throws EE_Error
1126
-     * @throws InvalidArgumentException
1127
-     * @throws InvalidDataTypeException
1128
-     * @throws InvalidInterfaceException
1129
-     * @throws ReflectionException
1130
-     */
1131
-    public function get_primary_registration()
1132
-    {
1133
-        if ($this->is_primary_registrant()) {
1134
-            return $this;
1135
-        }
1136
-
1137
-        // k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1138
-        /** @var EE_Registration $primary_registrant */
1139
-        $primary_registrant = EEM_Registration::instance()->get_one(
1140
-            [
1141
-                [
1142
-                    'TXN_ID'    => $this->transaction_ID(),
1143
-                    'REG_count' => 1,
1144
-                ],
1145
-            ]
1146
-        );
1147
-        return $primary_registrant;
1148
-    }
1149
-
1150
-
1151
-    /**
1152
-     * get  Attendee Number
1153
-     *
1154
-     * @throws EE_Error
1155
-     * @throws InvalidArgumentException
1156
-     * @throws InvalidDataTypeException
1157
-     * @throws InvalidInterfaceException
1158
-     * @throws ReflectionException
1159
-     */
1160
-    public function count()
1161
-    {
1162
-        return $this->get('REG_count');
1163
-    }
1164
-
1165
-
1166
-    /**
1167
-     * get Group Size
1168
-     *
1169
-     * @throws EE_Error
1170
-     * @throws InvalidArgumentException
1171
-     * @throws InvalidDataTypeException
1172
-     * @throws InvalidInterfaceException
1173
-     * @throws ReflectionException
1174
-     */
1175
-    public function group_size()
1176
-    {
1177
-        return $this->get('REG_group_size');
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * get Registration Date
1183
-     *
1184
-     * @throws EE_Error
1185
-     * @throws InvalidArgumentException
1186
-     * @throws InvalidDataTypeException
1187
-     * @throws InvalidInterfaceException
1188
-     * @throws ReflectionException
1189
-     */
1190
-    public function date()
1191
-    {
1192
-        return $this->get('REG_date');
1193
-    }
1194
-
1195
-
1196
-    /**
1197
-     * gets a pretty date
1198
-     *
1199
-     * @param string $date_format
1200
-     * @param string $time_format
1201
-     * @return string
1202
-     * @throws EE_Error
1203
-     * @throws InvalidArgumentException
1204
-     * @throws InvalidDataTypeException
1205
-     * @throws InvalidInterfaceException
1206
-     * @throws ReflectionException
1207
-     */
1208
-    public function pretty_date($date_format = null, $time_format = null)
1209
-    {
1210
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1211
-    }
1212
-
1213
-
1214
-    /**
1215
-     * final_price
1216
-     * the registration's share of the transaction total, so that the
1217
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1218
-     *
1219
-     * @return float
1220
-     * @throws EE_Error
1221
-     * @throws InvalidArgumentException
1222
-     * @throws InvalidDataTypeException
1223
-     * @throws InvalidInterfaceException
1224
-     * @throws ReflectionException
1225
-     */
1226
-    public function final_price(): float
1227
-    {
1228
-        return (float) $this->get('REG_final_price');
1229
-    }
1230
-
1231
-
1232
-    /**
1233
-     * pretty_final_price
1234
-     *  final price as formatted string, with correct decimal places and currency symbol
1235
-     *
1236
-     * @param string|null $schema
1237
-     *      Schemas:
1238
-     *      'localized_float': "3,023.00"
1239
-     *      'no_currency_code': "$3,023.00"
1240
-     *      null: "$3,023.00<span>USD</span>"
1241
-     * @return string
1242
-     * @throws EE_Error
1243
-     * @throws InvalidArgumentException
1244
-     * @throws InvalidDataTypeException
1245
-     * @throws InvalidInterfaceException
1246
-     * @throws ReflectionException
1247
-     */
1248
-    public function pretty_final_price(?string $schema = null)
1249
-    {
1250
-        return $this->get_pretty('REG_final_price', $schema);
1251
-    }
1252
-
1253
-
1254
-    /**
1255
-     * get paid (yeah)
1256
-     *
1257
-     * @return float
1258
-     * @throws EE_Error
1259
-     * @throws InvalidArgumentException
1260
-     * @throws InvalidDataTypeException
1261
-     * @throws InvalidInterfaceException
1262
-     * @throws ReflectionException
1263
-     */
1264
-    public function paid(): float
1265
-    {
1266
-        return (float) $this->get('REG_paid');
1267
-    }
1268
-
1269
-
1270
-    /**
1271
-     * pretty_paid
1272
-     *
1273
-     * @param string|null $schema
1274
-     *      Schemas:
1275
-     *      'localized_float': "3,023.00"
1276
-     *      'no_currency_code': "$3,023.00"
1277
-     *      null: "$3,023.00<span>USD</span>"
1278
-     * @return float
1279
-     * @throws EE_Error
1280
-     * @throws InvalidArgumentException
1281
-     * @throws InvalidDataTypeException
1282
-     * @throws InvalidInterfaceException
1283
-     * @throws ReflectionException
1284
-     */
1285
-    public function pretty_paid(?string $schema = null)
1286
-    {
1287
-        return $this->get_pretty('REG_paid', $schema);
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     * owes_monies_and_can_pay
1293
-     * whether this registration has monies owing and it's' status allows payment
1294
-     *
1295
-     * @param array $requires_payment list of registration statuses that allow a registrant to make a payment
1296
-     * @return bool
1297
-     * @throws EE_Error
1298
-     * @throws InvalidArgumentException
1299
-     * @throws InvalidDataTypeException
1300
-     * @throws InvalidInterfaceException
1301
-     * @throws ReflectionException
1302
-     */
1303
-    public function owes_monies_and_can_pay(array $requires_payment = []): bool
1304
-    {
1305
-        // these reg statuses require payment (if event is not free)
1306
-        $requires_payment = ! empty($requires_payment)
1307
-            ? $requires_payment
1308
-            : EEM_Registration::reg_statuses_that_allow_payment();
1309
-        if (
1310
-            $this->final_price() !== 0.0 &&
1311
-            $this->final_price() !== $this->paid() &&
1312
-            in_array($this->status_ID(), $requires_payment)
1313
-        ) {
1314
-            return true;
1315
-        }
1316
-        return false;
1317
-    }
1318
-
1319
-
1320
-    /**
1321
-     * Prints out the return value of $this->pretty_status()
1322
-     *
1323
-     * @param bool $show_icons
1324
-     * @return void
1325
-     * @throws EE_Error
1326
-     * @throws InvalidArgumentException
1327
-     * @throws InvalidDataTypeException
1328
-     * @throws InvalidInterfaceException
1329
-     * @throws ReflectionException
1330
-     */
1331
-    public function e_pretty_status($show_icons = false)
1332
-    {
1333
-        echo wp_kses($this->pretty_status($show_icons), AllowedTags::getAllowedTags());
1334
-    }
1335
-
1336
-
1337
-    /**
1338
-     * Returns a nice version of the status for displaying to customers
1339
-     *
1340
-     * @param bool $show_icons
1341
-     * @return string
1342
-     * @throws EE_Error
1343
-     * @throws InvalidArgumentException
1344
-     * @throws InvalidDataTypeException
1345
-     * @throws InvalidInterfaceException
1346
-     * @throws ReflectionException
1347
-     */
1348
-    public function pretty_status($show_icons = false)
1349
-    {
1350
-        $status = EEM_Status::instance()->localized_status(
1351
-            [$this->status_ID() => esc_html__('unknown', 'event_espresso')],
1352
-            false,
1353
-            'sentence'
1354
-        );
1355
-        $icon   = '';
1356
-        switch ($this->status_ID()) {
1357
-            case RegStatus::APPROVED:
1358
-                $icon = $show_icons
1359
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1360
-                    : '';
1361
-                break;
1362
-            case RegStatus::PENDING_PAYMENT:
1363
-                $icon = $show_icons
1364
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1365
-                    : '';
1366
-                break;
1367
-            case RegStatus::AWAITING_REVIEW:
1368
-                $icon = $show_icons
1369
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1370
-                    : '';
1371
-                break;
1372
-            case RegStatus::CANCELLED:
1373
-                $icon = $show_icons
1374
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1375
-                    : '';
1376
-                break;
1377
-            case RegStatus::INCOMPLETE:
1378
-                $icon = $show_icons
1379
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1380
-                    : '';
1381
-                break;
1382
-            case RegStatus::DECLINED:
1383
-                $icon = $show_icons
1384
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1385
-                    : '';
1386
-                break;
1387
-            case RegStatus::WAIT_LIST:
1388
-                $icon = $show_icons
1389
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1390
-                    : '';
1391
-                break;
1392
-        }
1393
-        return $icon . $status[ $this->status_ID() ];
1394
-    }
1395
-
1396
-
1397
-    /**
1398
-     *        get Attendee Is Going
1399
-     */
1400
-    public function att_is_going()
1401
-    {
1402
-        return $this->get('REG_att_is_going');
1403
-    }
1404
-
1405
-
1406
-    /**
1407
-     * Gets related answers
1408
-     *
1409
-     * @param array $query_params @see
1410
-     *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1411
-     * @return EE_Answer[]|EE_Base_Class[]
1412
-     * @throws EE_Error
1413
-     * @throws InvalidArgumentException
1414
-     * @throws InvalidDataTypeException
1415
-     * @throws InvalidInterfaceException
1416
-     * @throws ReflectionException
1417
-     */
1418
-    public function answers($query_params = [])
1419
-    {
1420
-        return $this->get_many_related('Answer', $query_params);
1421
-    }
1422
-
1423
-
1424
-    /**
1425
-     * Gets the registration's answer value to the specified question
1426
-     * (either the question's ID or a question object)
1427
-     *
1428
-     * @param EE_Question|int $question
1429
-     * @param bool            $pretty_value
1430
-     * @return array|string if pretty_value= true, the result will always be a string
1431
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1432
-     * will convert it into some kind of string)
1433
-     * @throws EE_Error
1434
-     * @throws InvalidArgumentException
1435
-     * @throws InvalidDataTypeException
1436
-     * @throws InvalidInterfaceException
1437
-     */
1438
-    public function answer_value_to_question($question, $pretty_value = true)
1439
-    {
1440
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1441
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1442
-    }
1443
-
1444
-
1445
-    /**
1446
-     * question_groups
1447
-     * returns an array of EE_Question_Group objects for this registration
1448
-     *
1449
-     * @return EE_Question_Group[]
1450
-     * @throws EE_Error
1451
-     * @throws InvalidArgumentException
1452
-     * @throws InvalidDataTypeException
1453
-     * @throws InvalidInterfaceException
1454
-     * @throws ReflectionException
1455
-     */
1456
-    public function question_groups()
1457
-    {
1458
-        return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1459
-    }
1460
-
1461
-
1462
-    /**
1463
-     * count_question_groups
1464
-     * returns a count of the number of EE_Question_Group objects for this registration
1465
-     *
1466
-     * @return int
1467
-     * @throws EE_Error
1468
-     * @throws EntityNotFoundException
1469
-     * @throws InvalidArgumentException
1470
-     * @throws InvalidDataTypeException
1471
-     * @throws InvalidInterfaceException
1472
-     * @throws ReflectionException
1473
-     */
1474
-    public function count_question_groups()
1475
-    {
1476
-        return EEM_Event::instance()->count_related(
1477
-            $this->event_ID(),
1478
-            'Question_Group',
1479
-            [
1480
-                [
1481
-                    'Event_Question_Group.'
1482
-                    . EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1483
-                ],
1484
-            ]
1485
-        );
1486
-    }
1487
-
1488
-
1489
-    /**
1490
-     * Returns the registration date in the 'standard' string format
1491
-     * (function may be improved in the future to allow for different formats and timezones)
1492
-     *
1493
-     * @return string
1494
-     * @throws EE_Error
1495
-     * @throws InvalidArgumentException
1496
-     * @throws InvalidDataTypeException
1497
-     * @throws InvalidInterfaceException
1498
-     * @throws ReflectionException
1499
-     */
1500
-    public function reg_date()
1501
-    {
1502
-        return $this->get_datetime('REG_date');
1503
-    }
1504
-
1505
-
1506
-    /**
1507
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1508
-     * the ticket this registration purchased, or the datetime they have registered
1509
-     * to attend)
1510
-     *
1511
-     * @return EE_Base_Class|EE_Datetime_Ticket
1512
-     * @throws EE_Error
1513
-     * @throws InvalidArgumentException
1514
-     * @throws InvalidDataTypeException
1515
-     * @throws InvalidInterfaceException
1516
-     * @throws ReflectionException
1517
-     */
1518
-    public function datetime_ticket()
1519
-    {
1520
-        return $this->get_first_related('Datetime_Ticket');
1521
-    }
1522
-
1523
-
1524
-    /**
1525
-     * Sets the registration's datetime_ticket.
1526
-     *
1527
-     * @param EE_Datetime_Ticket $datetime_ticket
1528
-     * @return EE_Base_Class|EE_Datetime_Ticket
1529
-     * @throws EE_Error
1530
-     * @throws InvalidArgumentException
1531
-     * @throws InvalidDataTypeException
1532
-     * @throws InvalidInterfaceException
1533
-     * @throws ReflectionException
1534
-     */
1535
-    public function set_datetime_ticket($datetime_ticket)
1536
-    {
1537
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1538
-    }
1539
-
1540
-
1541
-    /**
1542
-     * Gets deleted
1543
-     *
1544
-     * @return bool
1545
-     * @throws EE_Error
1546
-     * @throws InvalidArgumentException
1547
-     * @throws InvalidDataTypeException
1548
-     * @throws InvalidInterfaceException
1549
-     * @throws ReflectionException
1550
-     */
1551
-    public function deleted()
1552
-    {
1553
-        return $this->get('REG_deleted');
1554
-    }
1555
-
1556
-
1557
-    /**
1558
-     * Sets deleted
1559
-     *
1560
-     * @param boolean $deleted
1561
-     * @return void
1562
-     * @throws DomainException
1563
-     * @throws EE_Error
1564
-     * @throws EntityNotFoundException
1565
-     * @throws InvalidArgumentException
1566
-     * @throws InvalidDataTypeException
1567
-     * @throws InvalidInterfaceException
1568
-     * @throws ReflectionException
1569
-     * @throws RuntimeException
1570
-     * @throws UnexpectedEntityException
1571
-     */
1572
-    public function set_deleted($deleted)
1573
-    {
1574
-        if ($deleted) {
1575
-            $this->delete();
1576
-        } else {
1577
-            $this->restore();
1578
-        }
1579
-    }
1580
-
1581
-
1582
-    /**
1583
-     * Get the status object of this object
1584
-     *
1585
-     * @return EE_Base_Class|EE_Status
1586
-     * @throws EE_Error
1587
-     * @throws InvalidArgumentException
1588
-     * @throws InvalidDataTypeException
1589
-     * @throws InvalidInterfaceException
1590
-     * @throws ReflectionException
1591
-     */
1592
-    public function status_obj()
1593
-    {
1594
-        return $this->get_first_related('Status');
1595
-    }
1596
-
1597
-
1598
-    /**
1599
-     * Returns the number of times this registration has checked into any of the datetimes it's available for
1600
-     *
1601
-     * @return int
1602
-     * @throws EE_Error
1603
-     * @throws InvalidArgumentException
1604
-     * @throws InvalidDataTypeException
1605
-     * @throws InvalidInterfaceException
1606
-     * @throws ReflectionException
1607
-     */
1608
-    public function count_checkins()
1609
-    {
1610
-        return $this->get_model()->count_related($this, 'Checkin');
1611
-    }
1612
-
1613
-
1614
-    /**
1615
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1616
-     * registration is for.  Note, this is ONLY checked in (does not include checked out)
1617
-     *
1618
-     * @return int
1619
-     * @throws EE_Error
1620
-     * @throws InvalidArgumentException
1621
-     * @throws InvalidDataTypeException
1622
-     * @throws InvalidInterfaceException
1623
-     * @throws ReflectionException
1624
-     */
1625
-    public function count_checkins_not_checkedout()
1626
-    {
1627
-        return $this->get_model()->count_related($this, 'Checkin', [['CHK_in' => 1]]);
1628
-    }
1629
-
1630
-
1631
-    /**
1632
-     * The purpose of this method is simply to check whether this registration can check in to the given datetime.
1633
-     *
1634
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1635
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1636
-     *                                          consider registration status as well as datetime access.
1637
-     * @return bool
1638
-     * @throws EE_Error
1639
-     * @throws InvalidArgumentException
1640
-     * @throws InvalidDataTypeException
1641
-     * @throws InvalidInterfaceException
1642
-     * @throws ReflectionException
1643
-     */
1644
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1645
-    {
1646
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1647
-        // first check registration status
1648
-        if (! $DTT_ID || ($check_approved && ! $this->is_approved())) {
1649
-            return false;
1650
-        }
1651
-        // is there a datetime ticket that matches this dtt_ID?
1652
-        if (
1653
-            ! (EEM_Datetime_Ticket::instance()->exists(
1654
-                [
1655
-                    [
1656
-                        'TKT_ID' => $this->get('TKT_ID'),
1657
-                        'DTT_ID' => $DTT_ID,
1658
-                    ],
1659
-                ]
1660
-            ))
1661
-        ) {
1662
-            return false;
1663
-        }
1664
-
1665
-        // final check is against TKT_uses
1666
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1667
-    }
1668
-
1669
-
1670
-    /**
1671
-     * This method verifies whether the user can check in for the given datetime considering the max uses value set on
1672
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1673
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1674
-     * then return false.  Otherwise return true.
1675
-     *
1676
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1677
-     * @return bool true means can check in.  false means cannot check in.
1678
-     * @throws EE_Error
1679
-     * @throws InvalidArgumentException
1680
-     * @throws InvalidDataTypeException
1681
-     * @throws InvalidInterfaceException
1682
-     * @throws ReflectionException
1683
-     */
1684
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1685
-    {
1686
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1687
-
1688
-        if (! $DTT_ID) {
1689
-            return false;
1690
-        }
1691
-
1692
-        $max_uses = $this->ticket() instanceof EE_Ticket
1693
-            ? $this->ticket()->uses()
1694
-            : EE_INF;
1695
-
1696
-        // if max uses is not set or equals infinity then return true
1697
-        // because it's not a factor for whether user can check in or not.
1698
-        if (! $max_uses || $max_uses === EE_INF) {
1699
-            return true;
1700
-        }
1701
-
1702
-        // does this datetime have a check-in record?  If so, then the dtt count has already been verified so we can just
1703
-        // go ahead and toggle.
1704
-        if (EEM_Checkin::instance()->exists([['REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID]])) {
1705
-            return true;
1706
-        }
1707
-
1708
-        // made it here so the last check is whether the number of check-ins per unique datetime on this registration
1709
-        // disallows further check-ins.
1710
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1711
-            [
1712
-                [
1713
-                    'REG_ID' => $this->ID(),
1714
-                    'CHK_in' => true,
1715
-                ],
1716
-            ],
1717
-            'DTT_ID',
1718
-            true
1719
-        );
1720
-        // check-ins have already reached their max number of uses
1721
-        // so registrant can NOT check in
1722
-        if ($count_unique_dtt_checkins >= $max_uses) {
1723
-            EE_Error::add_error(
1724
-                esc_html__(
1725
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1726
-                    'event_espresso'
1727
-                ),
1728
-                __FILE__,
1729
-                __FUNCTION__,
1730
-                __LINE__
1731
-            );
1732
-            return false;
1733
-        }
1734
-        return true;
1735
-    }
1736
-
1737
-
1738
-    /**
1739
-     * toggle Check-in status for this registration
1740
-     * Check-ins are toggled in the following order:
1741
-     * never checked in -> checked in
1742
-     * checked in -> checked out
1743
-     * checked out -> checked in
1744
-     *
1745
-     * @param int  $DTT_ID  include specific datetime to toggle Check-in for.
1746
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1747
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1748
-     *                      can be checked in or not.  Otherwise this forces change in check-in status.
1749
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1750
-     * @throws EE_Error
1751
-     * @throws InvalidArgumentException
1752
-     * @throws InvalidDataTypeException
1753
-     * @throws InvalidInterfaceException
1754
-     * @throws ReflectionException
1755
-     */
1756
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1757
-    {
1758
-        if (empty($DTT_ID)) {
1759
-            $datetime = $this->get_latest_related_datetime();
1760
-            $DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1761
-            // verify the registration can check in for the given DTT_ID
1762
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1763
-            EE_Error::add_error(
1764
-                sprintf(
1765
-                    esc_html__(
1766
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1767
-                        'event_espresso'
1768
-                    ),
1769
-                    $this->ID(),
1770
-                    $DTT_ID
1771
-                ),
1772
-                __FILE__,
1773
-                __FUNCTION__,
1774
-                __LINE__
1775
-            );
1776
-            return false;
1777
-        }
1778
-        $status_paths = [
1779
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1780
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1781
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1782
-        ];
1783
-        // start by getting the current status so we know what status we'll be changing to.
1784
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1785
-        $status_to  = $status_paths[ $cur_status ];
1786
-        // database only records true for checked IN or false for checked OUT
1787
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1788
-        $new_status = $status_to === EE_Checkin::status_checked_in;
1789
-        // add relation - note Check-ins are always creating new rows
1790
-        // because we are keeping track of Check-ins over time.
1791
-        // Eventually we'll probably want to show a list table
1792
-        // for the individual Check-ins so that they can be managed.
1793
-        $checkin = EE_Checkin::new_instance(
1794
-            [
1795
-                'REG_ID' => $this->ID(),
1796
-                'DTT_ID' => $DTT_ID,
1797
-                'CHK_in' => $new_status,
1798
-            ]
1799
-        );
1800
-        // if the record could not be saved then return false
1801
-        if ($checkin->save() === 0) {
1802
-            if (WP_DEBUG) {
1803
-                global $wpdb;
1804
-                $error = sprintf(
1805
-                    esc_html__(
1806
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1807
-                        'event_espresso'
1808
-                    ),
1809
-                    '<br />',
1810
-                    $wpdb->last_error
1811
-                );
1812
-            } else {
1813
-                $error = esc_html__(
1814
-                    'Registration check in update failed because of an unknown database error',
1815
-                    'event_espresso'
1816
-                );
1817
-            }
1818
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1819
-            return false;
1820
-        }
1821
-        // Fire a checked_in and checkout_out action.
1822
-        $checked_status = $status_to === EE_Checkin::status_checked_in
1823
-            ? 'checked_in'
1824
-            : 'checked_out';
1825
-        do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1826
-        return $status_to;
1827
-    }
1828
-
1829
-
1830
-    /**
1831
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1832
-     * "Latest" is defined by the `DTT_EVT_start` column.
1833
-     *
1834
-     * @return EE_Datetime|null
1835
-     * @throws EE_Error
1836
-     * @throws InvalidArgumentException
1837
-     * @throws InvalidDataTypeException
1838
-     * @throws InvalidInterfaceException
1839
-     * @throws ReflectionException
1840
-     */
1841
-    public function get_latest_related_datetime(): ?EE_Datetime
1842
-    {
1843
-        return EEM_Datetime::instance()->get_one(
1844
-            [
1845
-                [
1846
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1847
-                ],
1848
-                'order_by' => ['DTT_EVT_start' => 'DESC'],
1849
-            ]
1850
-        );
1851
-    }
1852
-
1853
-
1854
-    /**
1855
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1856
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1857
-     *
1858
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1859
-     * @throws EE_Error
1860
-     * @throws InvalidArgumentException
1861
-     * @throws InvalidDataTypeException
1862
-     * @throws InvalidInterfaceException
1863
-     * @throws ReflectionException
1864
-     */
1865
-    public function get_earliest_related_datetime()
1866
-    {
1867
-        return EEM_Datetime::instance()->get_one(
1868
-            [
1869
-                [
1870
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1871
-                ],
1872
-                'order_by' => ['DTT_EVT_start' => 'ASC'],
1873
-            ]
1874
-        );
1875
-    }
1876
-
1877
-
1878
-    /**
1879
-     * This method simply returns the check-in status for this registration and the given datetime.
1880
-     * If neither the datetime nor the check-in values are provided as arguments,
1881
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1882
-     *
1883
-     * @param int|null        $DTT_ID  The ID of the datetime we're checking against
1884
-     *                                 (if empty we'll get the primary datetime for
1885
-     *                                 this registration (via event) and use its ID);
1886
-     * @param EE_Checkin|null $checkin If present, we use the given check-in object rather than the dtt_id.
1887
-     * @return int                     Integer representing Check-in status.
1888
-     * @throws EE_Error
1889
-     * @throws ReflectionException
1890
-     */
1891
-    public function check_in_status_for_datetime(?int $DTT_ID = 0, ?EE_Checkin $checkin = null): int
1892
-    {
1893
-        if ($checkin instanceof EE_Checkin) {
1894
-            return $checkin->status();
1895
-        }
1896
-
1897
-        if (! $DTT_ID) {
1898
-            return EE_Checkin::status_invalid;
1899
-        }
1900
-
1901
-        $checkin_query_params = [
1902
-            0          => ['DTT_ID' => $DTT_ID],
1903
-            'order_by' => ['CHK_timestamp' => 'DESC'],
1904
-        ];
1905
-
1906
-        $checkin = $this->get_first_related(
1907
-            'Checkin',
1908
-            $checkin_query_params
1909
-        );
1910
-        return $checkin instanceof EE_Checkin ? $checkin->status() : EE_Checkin::status_checked_never;
1911
-    }
1912
-
1913
-
1914
-    /**
1915
-     * This method returns a localized message for the toggled Check-in message.
1916
-     *
1917
-     * @param int|null $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1918
-     *                         then it is assumed Check-in for primary datetime was toggled.
1919
-     * @param bool     $error  This just flags that you want an error message returned. This is put in so that the error
1920
-     *                         message can be customized with the attendee name.
1921
-     * @return string internationalized message
1922
-     * @throws EE_Error
1923
-     * @throws ReflectionException
1924
-     */
1925
-    public function get_checkin_msg(?int $DTT_ID, bool $error = false): string
1926
-    {
1927
-        // let's get the attendee first so we can include the name of the attendee
1928
-        $attendee = $this->attendee();
1929
-        if ($attendee instanceof EE_Attendee) {
1930
-            if ($error) {
1931
-                return sprintf(
1932
-                    esc_html__("%s's check-in status was not changed.", "event_espresso"),
1933
-                    $attendee->full_name()
1934
-                );
1935
-            }
1936
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1937
-            // what is the status message going to be?
1938
-            switch ($cur_status) {
1939
-                case EE_Checkin::status_checked_never:
1940
-                    return sprintf(
1941
-                        esc_html__('%s has been removed from Check-in records', 'event_espresso'),
1942
-                        $attendee->full_name()
1943
-                    );
1944
-                case EE_Checkin::status_checked_in:
1945
-                    return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1946
-                case EE_Checkin::status_checked_out:
1947
-                    return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1948
-            }
1949
-        }
1950
-        return esc_html__('The check-in status could not be determined.', 'event_espresso');
1951
-    }
1952
-
1953
-
1954
-    /**
1955
-     * Returns the related EE_Transaction to this registration
1956
-     *
1957
-     * @return EE_Transaction
1958
-     * @throws EE_Error
1959
-     * @throws EntityNotFoundException
1960
-     * @throws ReflectionException
1961
-     */
1962
-    public function transaction(): EE_Transaction
1963
-    {
1964
-        $TXN_ID = $this->transaction_ID();
1965
-        $transaction = $TXN_ID
1966
-            ? EEM_Transaction::instance()->get_one_by_ID($TXN_ID)
1967
-            : $this->get_one_from_cache('Transaction');
1968
-        if (! $transaction instanceof \EE_Transaction) {
1969
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1970
-        }
1971
-        return $transaction;
1972
-    }
1973
-
1974
-
1975
-    /**
1976
-     * get Registration Code
1977
-     *
1978
-     * @return string
1979
-     * @throws EE_Error
1980
-     * @throws InvalidArgumentException
1981
-     * @throws InvalidDataTypeException
1982
-     * @throws InvalidInterfaceException
1983
-     * @throws ReflectionException
1984
-     */
1985
-    public function reg_code(): string
1986
-    {
1987
-        return $this->get('REG_code')
1988
-            ?: '';
1989
-    }
1990
-
1991
-
1992
-    /**
1993
-     * @return mixed
1994
-     * @throws EE_Error
1995
-     * @throws InvalidArgumentException
1996
-     * @throws InvalidDataTypeException
1997
-     * @throws InvalidInterfaceException
1998
-     * @throws ReflectionException
1999
-     */
2000
-    public function transaction_ID()
2001
-    {
2002
-        return $this->get('TXN_ID');
2003
-    }
2004
-
2005
-
2006
-    /**
2007
-     * @return int
2008
-     * @throws EE_Error
2009
-     * @throws InvalidArgumentException
2010
-     * @throws InvalidDataTypeException
2011
-     * @throws InvalidInterfaceException
2012
-     * @throws ReflectionException
2013
-     */
2014
-    public function ticket_ID()
2015
-    {
2016
-        return $this->get('TKT_ID');
2017
-    }
2018
-
2019
-
2020
-    /**
2021
-     * Set Registration Code
2022
-     *
2023
-     * @param RegCode|string $REG_code Registration Code
2024
-     * @param boolean        $use_default
2025
-     * @throws EE_Error
2026
-     * @throws InvalidArgumentException
2027
-     * @throws InvalidDataTypeException
2028
-     * @throws InvalidInterfaceException
2029
-     * @throws ReflectionException
2030
-     */
2031
-    public function set_reg_code($REG_code, bool $use_default = false)
2032
-    {
2033
-        if (! $this->reg_code()) {
2034
-            parent::set('REG_code', $REG_code, $use_default);
2035
-        } elseif (empty($REG_code)) {
2036
-            EE_Error::add_error(
2037
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
2038
-                __FILE__,
2039
-                __FUNCTION__,
2040
-                __LINE__
2041
-            );
2042
-        } else {
2043
-            EE_Error::doing_it_wrong(
2044
-                __CLASS__ . '::' . __FUNCTION__,
2045
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
2046
-                '4.6.0'
2047
-            );
2048
-        }
2049
-    }
2050
-
2051
-
2052
-    /**
2053
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
2054
-     * Note, if you want to just get all registrations in the same transaction (group), use:
2055
-     *    $registration->transaction()->registrations();
2056
-     *
2057
-     * @return EE_Registration[] or empty array if this isn't a group registration.
2058
-     * @throws EE_Error
2059
-     * @throws InvalidArgumentException
2060
-     * @throws InvalidDataTypeException
2061
-     * @throws InvalidInterfaceException
2062
-     * @throws ReflectionException
2063
-     * @since 4.5.0
2064
-     */
2065
-    public function get_all_other_registrations_in_group(bool $with_same_ticket = true): array
2066
-    {
2067
-        if ($this->group_size() < 2) {
2068
-            return [];
2069
-        }
2070
-
2071
-        $query[0] = [
2072
-            'TXN_ID' => $this->transaction_ID(),
2073
-            'REG_ID' => ['!=', $this->ID()],
2074
-        ];
2075
-
2076
-        if ($with_same_ticket) {
2077
-            $query[0]['TKT_ID'] = $this->ticket_ID();
2078
-        }
2079
-        /** @var EE_Registration[] $registrations */
2080
-        $registrations = $this->get_model()->get_all($query);
2081
-        return $registrations;
2082
-    }
2083
-
2084
-
2085
-    /**
2086
-     * Return the link to the admin details for the object.
2087
-     *
2088
-     * @return string
2089
-     * @throws EE_Error
2090
-     * @throws InvalidArgumentException
2091
-     * @throws InvalidDataTypeException
2092
-     * @throws InvalidInterfaceException
2093
-     * @throws ReflectionException
2094
-     */
2095
-    public function get_admin_details_link()
2096
-    {
2097
-        EE_Registry::instance()->load_helper('URL');
2098
-        return EEH_URL::add_query_args_and_nonce(
2099
-            [
2100
-                'page'    => 'espresso_registrations',
2101
-                'action'  => 'view_registration',
2102
-                '_REG_ID' => $this->ID(),
2103
-            ],
2104
-            admin_url('admin.php')
2105
-        );
2106
-    }
2107
-
2108
-
2109
-    /**
2110
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
2111
-     *
2112
-     * @return string
2113
-     * @throws EE_Error
2114
-     * @throws InvalidArgumentException
2115
-     * @throws InvalidDataTypeException
2116
-     * @throws InvalidInterfaceException
2117
-     * @throws ReflectionException
2118
-     */
2119
-    public function get_admin_edit_link()
2120
-    {
2121
-        return $this->get_admin_details_link();
2122
-    }
2123
-
2124
-
2125
-    /**
2126
-     * Returns the link to a settings page for the object.
2127
-     *
2128
-     * @return string
2129
-     * @throws EE_Error
2130
-     * @throws InvalidArgumentException
2131
-     * @throws InvalidDataTypeException
2132
-     * @throws InvalidInterfaceException
2133
-     * @throws ReflectionException
2134
-     */
2135
-    public function get_admin_settings_link()
2136
-    {
2137
-        return $this->get_admin_details_link();
2138
-    }
2139
-
2140
-
2141
-    /**
2142
-     * Returns the link to the "overview" for the object (typically the "list table" view).
2143
-     *
2144
-     * @return string
2145
-     * @throws EE_Error
2146
-     * @throws InvalidArgumentException
2147
-     * @throws InvalidDataTypeException
2148
-     * @throws InvalidInterfaceException
2149
-     * @throws ReflectionException
2150
-     */
2151
-    public function get_admin_overview_link()
2152
-    {
2153
-        EE_Registry::instance()->load_helper('URL');
2154
-        return EEH_URL::add_query_args_and_nonce(
2155
-            [
2156
-                'page' => 'espresso_registrations',
2157
-            ],
2158
-            admin_url('admin.php')
2159
-        );
2160
-    }
2161
-
2162
-
2163
-    /**
2164
-     * @param array $query_params
2165
-     * @return EE_Base_Class[]|EE_Registration[]
2166
-     * @throws EE_Error
2167
-     * @throws InvalidArgumentException
2168
-     * @throws InvalidDataTypeException
2169
-     * @throws InvalidInterfaceException
2170
-     * @throws ReflectionException
2171
-     */
2172
-    public function payments($query_params = [])
2173
-    {
2174
-        return $this->get_many_related('Payment', $query_params);
2175
-    }
2176
-
2177
-
2178
-    /**
2179
-     * @param array $query_params
2180
-     * @return EE_Base_Class[]|EE_Registration_Payment[]
2181
-     * @throws EE_Error
2182
-     * @throws InvalidArgumentException
2183
-     * @throws InvalidDataTypeException
2184
-     * @throws InvalidInterfaceException
2185
-     * @throws ReflectionException
2186
-     */
2187
-    public function registration_payments($query_params = [])
2188
-    {
2189
-        return $this->get_many_related('Registration_Payment', $query_params);
2190
-    }
2191
-
2192
-
2193
-    /**
2194
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
2195
-     * Note: if there are no payments on the registration there will be no payment method returned.
2196
-     *
2197
-     * @return EE_Payment|EE_Payment_Method|null
2198
-     * @throws EE_Error
2199
-     * @throws InvalidArgumentException
2200
-     * @throws InvalidDataTypeException
2201
-     * @throws InvalidInterfaceException
2202
-     */
2203
-    public function payment_method()
2204
-    {
2205
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
2206
-    }
2207
-
2208
-
2209
-    /**
2210
-     * @return \EE_Line_Item
2211
-     * @throws EE_Error
2212
-     * @throws EntityNotFoundException
2213
-     * @throws InvalidArgumentException
2214
-     * @throws InvalidDataTypeException
2215
-     * @throws InvalidInterfaceException
2216
-     * @throws ReflectionException
2217
-     */
2218
-    public function ticket_line_item()
2219
-    {
2220
-        $ticket            = $this->ticket();
2221
-        $transaction       = $this->transaction();
2222
-        $line_item         = null;
2223
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
2224
-            $transaction->total_line_item(),
2225
-            'Ticket',
2226
-            [$ticket->ID()]
2227
-        );
2228
-        foreach ($ticket_line_items as $ticket_line_item) {
2229
-            if (
2230
-                $ticket_line_item instanceof \EE_Line_Item
2231
-                && $ticket_line_item->OBJ_type() === 'Ticket'
2232
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
2233
-            ) {
2234
-                $line_item = $ticket_line_item;
2235
-                break;
2236
-            }
2237
-        }
2238
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
2239
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
2240
-        }
2241
-        return $line_item;
2242
-    }
2243
-
2244
-
2245
-    /**
2246
-     * Soft Deletes this model object.
2247
-     *
2248
-     * @return int
2249
-     * @throws DomainException
2250
-     * @throws EE_Error
2251
-     * @throws EntityNotFoundException
2252
-     * @throws InvalidArgumentException
2253
-     * @throws InvalidDataTypeException
2254
-     * @throws InvalidInterfaceException
2255
-     * @throws ReflectionException
2256
-     * @throws RuntimeException
2257
-     * @throws UnexpectedEntityException
2258
-     */
2259
-    public function delete()
2260
-    {
2261
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
2262
-            $this->set_status(
2263
-                RegStatus::CANCELLED,
2264
-                false,
2265
-                new Context(
2266
-                    __METHOD__,
2267
-                    esc_html__('Executed when a registration is trashed.', 'event_espresso')
2268
-                )
2269
-            );
2270
-        }
2271
-        return parent::delete();
2272
-    }
2273
-
2274
-
2275
-    /**
2276
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
2277
-     *
2278
-     * @return int
2279
-     * @throws DomainException
2280
-     * @throws EE_Error
2281
-     * @throws EntityNotFoundException
2282
-     * @throws InvalidArgumentException
2283
-     * @throws InvalidDataTypeException
2284
-     * @throws InvalidInterfaceException
2285
-     * @throws ReflectionException
2286
-     * @throws RuntimeException
2287
-     * @throws UnexpectedEntityException
2288
-     */
2289
-    public function restore(): int
2290
-    {
2291
-        $previous_status = $this->get_extra_meta(
2292
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
2293
-            true,
2294
-            RegStatus::CANCELLED
2295
-        );
2296
-        if ($previous_status) {
2297
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
2298
-            $this->set_status(
2299
-                $previous_status,
2300
-                false,
2301
-                new Context(
2302
-                    __METHOD__,
2303
-                    esc_html__('Executed when a trashed registration is restored.', 'event_espresso')
2304
-                )
2305
-            );
2306
-        }
2307
-        return parent::restore();
2308
-    }
2309
-
2310
-
2311
-    /**
2312
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
2313
-     *
2314
-     * @param boolean $trigger_set_status_logic  EE_Registration::set_status() can trigger additional logic
2315
-     *                                           depending on whether the reg status changes to or from "Approved"
2316
-     * @return boolean whether the Registration status was updated
2317
-     * @throws DomainException
2318
-     * @throws EE_Error
2319
-     * @throws EntityNotFoundException
2320
-     * @throws InvalidArgumentException
2321
-     * @throws InvalidDataTypeException
2322
-     * @throws InvalidInterfaceException
2323
-     * @throws ReflectionException
2324
-     * @throws RuntimeException
2325
-     * @throws UnexpectedEntityException
2326
-     */
2327
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2328
-    {
2329
-        $paid  = $this->paid();
2330
-        $price = $this->final_price();
2331
-        switch (true) {
2332
-            // overpaid or paid
2333
-            case EEH_Money::compare_floats($paid, $price, '>'):
2334
-            case EEH_Money::compare_floats($paid, $price):
2335
-                $new_status = RegStatus::APPROVED;
2336
-                break;
2337
-            //  underpaid
2338
-            case EEH_Money::compare_floats($paid, $price, '<'):
2339
-                $new_status = RegStatus::PENDING_PAYMENT;
2340
-                break;
2341
-            // uhhh Houston...
2342
-            default:
2343
-                throw new RuntimeException(
2344
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2345
-                );
2346
-        }
2347
-        if ($new_status !== $this->status_ID()) {
2348
-            if ($trigger_set_status_logic) {
2349
-                return $this->set_status(
2350
-                    $new_status,
2351
-                    false,
2352
-                    new Context(
2353
-                        __METHOD__,
2354
-                        esc_html__(
2355
-                            'Executed when the registration status is updated based on total paid.',
2356
-                            'event_espresso'
2357
-                        )
2358
-                    )
2359
-                );
2360
-            }
2361
-            parent::set('STS_ID', $new_status);
2362
-            return true;
2363
-        }
2364
-        return false;
2365
-    }
2366
-
2367
-
2368
-    /*************************** DEPRECATED ***************************/
2369
-
2370
-
2371
-    /**
2372
-     * @deprecated
2373
-     * @since     4.7.0
2374
-     */
2375
-    public function price_paid()
2376
-    {
2377
-        EE_Error::doing_it_wrong(
2378
-            'EE_Registration::price_paid()',
2379
-            esc_html__(
2380
-                'This method is deprecated, please use EE_Registration::final_price() instead.',
2381
-                'event_espresso'
2382
-            ),
2383
-            '4.7.0'
2384
-        );
2385
-        return $this->final_price();
2386
-    }
2387
-
2388
-
2389
-    /**
2390
-     * @param float $REG_final_price
2391
-     * @throws EE_Error
2392
-     * @throws EntityNotFoundException
2393
-     * @throws InvalidArgumentException
2394
-     * @throws InvalidDataTypeException
2395
-     * @throws InvalidInterfaceException
2396
-     * @throws ReflectionException
2397
-     * @throws RuntimeException
2398
-     * @throws DomainException
2399
-     * @deprecated
2400
-     * @since     4.7.0
2401
-     */
2402
-    public function set_price_paid($REG_final_price = 0.00)
2403
-    {
2404
-        EE_Error::doing_it_wrong(
2405
-            'EE_Registration::set_price_paid()',
2406
-            esc_html__(
2407
-                'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2408
-                'event_espresso'
2409
-            ),
2410
-            '4.7.0'
2411
-        );
2412
-        $this->set_final_price($REG_final_price);
2413
-    }
2414
-
2415
-
2416
-    /**
2417
-     * @return string
2418
-     * @throws EE_Error
2419
-     * @throws InvalidArgumentException
2420
-     * @throws InvalidDataTypeException
2421
-     * @throws InvalidInterfaceException
2422
-     * @throws ReflectionException
2423
-     * @deprecated
2424
-     * @since 4.7.0
2425
-     */
2426
-    public function pretty_price_paid()
2427
-    {
2428
-        EE_Error::doing_it_wrong(
2429
-            'EE_Registration::pretty_price_paid()',
2430
-            esc_html__(
2431
-                'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2432
-                'event_espresso'
2433
-            ),
2434
-            '4.7.0'
2435
-        );
2436
-        return $this->pretty_final_price();
2437
-    }
2438
-
2439
-
2440
-    /**
2441
-     * Gets the primary datetime related to this registration via the related Event to this registration
2442
-     *
2443
-     * @return EE_Datetime
2444
-     * @throws EE_Error
2445
-     * @throws EntityNotFoundException
2446
-     * @throws InvalidArgumentException
2447
-     * @throws InvalidDataTypeException
2448
-     * @throws InvalidInterfaceException
2449
-     * @throws ReflectionException
2450
-     * @deprecated 4.9.17
2451
-     */
2452
-    public function get_related_primary_datetime()
2453
-    {
2454
-        EE_Error::doing_it_wrong(
2455
-            __METHOD__,
2456
-            esc_html__(
2457
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2458
-                'event_espresso'
2459
-            ),
2460
-            '4.9.17',
2461
-            '5.0.0'
2462
-        );
2463
-        return $this->event()->primary_datetime();
2464
-    }
2465
-
2466
-
2467
-    /**
2468
-     * Returns the contact's name (or "Unknown" if there is no contact.)
2469
-     *
2470
-     * @return string
2471
-     * @throws EE_Error
2472
-     * @throws InvalidArgumentException
2473
-     * @throws InvalidDataTypeException
2474
-     * @throws InvalidInterfaceException
2475
-     * @throws ReflectionException
2476
-     * @since 4.10.12.p
2477
-     */
2478
-    public function name()
2479
-    {
2480
-        return $this->attendeeName();
2481
-    }
2482
-
2483
-
2484
-    /**
2485
-     * @return bool
2486
-     * @throws EE_Error
2487
-     * @throws ReflectionException
2488
-     */
2489
-    public function wasMoved(): bool
2490
-    {
2491
-        // only need to check 'registration-moved-to' because
2492
-        // the existence of a new REG ID means the registration was moved
2493
-        $reg_moved = $this->get_extra_meta('registration-moved-to', true, []);
2494
-        return isset($reg_moved['NEW_REG_ID']) && $reg_moved['NEW_REG_ID'];
2495
-    }
2496
-
2497
-
2498
-    /**
2499
-     * @param EE_Payment $payment
2500
-     * @param float|null $amount
2501
-     * @return float
2502
-     * @throws EE_Error
2503
-     * @throws ReflectionException
2504
-     * @since 5.0.8.p
2505
-     */
2506
-    public function applyPayment(EE_Payment $payment, ?float $amount = null): float
2507
-    {
2508
-        $payment_amount = $amount ?? $payment->amount();
2509
-        // ensure $payment_amount is NOT negative
2510
-        $payment_amount = (float) abs($payment_amount);
2511
-        $payment_amount = $payment->is_a_refund()
2512
-            ? $this->processRefund($payment_amount)
2513
-            : $this->processPayment($payment_amount);
2514
-        if ($payment_amount) {
2515
-            $reg_payment = EEM_Registration_Payment::instance()->get_one(
2516
-                [['REG_ID' => $this->ID(), 'PAY_ID' => $payment->ID()]]
2517
-            );
2518
-            // if existing registration payment exists
2519
-            if ($reg_payment instanceof EE_Registration_Payment) {
2520
-                // then update that record
2521
-                $reg_payment->set_amount($payment_amount);
2522
-            } else {
2523
-                // or add new relation between registration and payment and set amount
2524
-                $reg_payment = EE_Registration_Payment::new_instance(
2525
-                    [
2526
-                        'REG_ID'     => $this->ID(),
2527
-                        'PAY_ID'     => $payment->ID(),
2528
-                        'RPY_amount' => $payment_amount,
2529
-                    ]
2530
-                );
2531
-            }
2532
-            $reg_payment->save();
2533
-        }
2534
-        return $payment_amount;
2535
-    }
2536
-
2537
-
2538
-    /**
2539
-     * @throws EE_Error
2540
-     * @throws ReflectionException
2541
-     */
2542
-    private function processPayment(float $payment_amount): float
2543
-    {
2544
-        $paid  = $this->paid();
2545
-        $owing = $this->final_price() - $paid;
2546
-        if ($owing <= 0) {
2547
-            return 0.0;
2548
-        }
2549
-        // don't allow payment amount to exceed the incoming amount, OR the amount owing
2550
-        $payment_amount = min($payment_amount, $owing);
2551
-        $paid           = $paid + $payment_amount;
2552
-        // calculate and set new REG_paid
2553
-        $this->set_paid($paid);
2554
-        // make it stick
2555
-        $this->save();
2556
-        return (float) $payment_amount;
2557
-    }
2558
-
2559
-
2560
-    /**
2561
-     * @throws ReflectionException
2562
-     * @throws EE_Error
2563
-     */
2564
-    private function processRefund(float $payment_amount): float
2565
-    {
2566
-        $paid = $this->paid();
2567
-        if ($paid <= 0) {
2568
-            return 0.0;
2569
-        }
2570
-        // don't allow refund amount to exceed the incoming amount, OR the amount paid
2571
-        $payment_amount = min($payment_amount, $paid);
2572
-        // calculate and set new REG_paid
2573
-        $paid = $paid - $payment_amount;
2574
-        $this->set_paid($paid);
2575
-        // make it stick
2576
-        $this->save();
2577
-        // convert payment amount back to a negative value for storage in the db
2578
-        return (float) $payment_amount;
2579
-    }
2580
-
2581
-
2582
-    /**
2583
-     * @return string
2584
-     * @throws EE_Error
2585
-     * @throws ReflectionException
2586
-     * @since 5.0.20.p
2587
-     */
2588
-    public function defaultRegistrationStatus(): string
2589
-    {
2590
-        $default_event_reg_status = $this->event()->default_registration_status();
2591
-        $default_reg_status = (string) apply_filters(
2592
-            'AFEE__EE_Registration__defaultRegistrationStatus__default_reg_status',
2593
-            $default_event_reg_status,
2594
-            $this
2595
-        );
2596
-        return RegStatus::isValidStatus($default_reg_status, false)
2597
-            ? $default_reg_status
2598
-            : $default_event_reg_status;
2599
-    }
2600
-
2601
-
2602
-    /**
2603
-     * @return string
2604
-     * @throws EE_Error
2605
-     * @throws ReflectionException
2606
-     * @since 5.0.30.p
2607
-     */
2608
-    public function cancelRegistrationConfirmationCode(): string
2609
-    {
2610
-        // concatenate all the fields that make up the source string
2611
-        // ex: 944-1084-720-379-7-2024-10-11 18:21:00-626-379-7-2ff6
2612
-        $source_string = $this->ID() . $this->event_ID() . $this->attendee_ID() . $this->ticket_ID();
2613
-        $source_string .= $this->count() . $this->reg_date() . $this->reg_code();
2614
-        // create a hash of the source string, ex: a9c0d28f79b5602a428e386821015420
2615
-        $source_string = md5($source_string);
2616
-        // return the first 4 characters of the hash in uppercase, ex: A9C0
2617
-        return strtoupper(substr($source_string, 0, 4));
2618
-    }
22
+	/**
23
+	 * extra meta key for tracking reg status os trashed registrations
24
+	 *
25
+	 * @type string
26
+	 */
27
+	public const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
28
+
29
+	/**
30
+	 * extra meta key for tracking if registration has reserved ticket
31
+	 *
32
+	 * @type string
33
+	 */
34
+	public const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
35
+
36
+	/**
37
+	 * extra meta key for tracking registration cancellations
38
+	 *
39
+	 * @type string
40
+	 */
41
+	public const META_KEY_REG_STATUS_CHANGE = 'registration_status_change';
42
+
43
+
44
+	/**
45
+	 * @param array  $props_n_values          incoming values
46
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
47
+	 *                                        used.)
48
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
49
+	 *                                        date_format and the second value is the time format
50
+	 * @return EE_Registration
51
+	 * @throws EE_Error
52
+	 * @throws InvalidArgumentException
53
+	 * @throws InvalidDataTypeException
54
+	 * @throws InvalidInterfaceException
55
+	 * @throws ReflectionException
56
+	 */
57
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
58
+	{
59
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
60
+		return $has_object
61
+			?: new self($props_n_values, false, $timezone, $date_formats);
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_Registration
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 = [], $timezone = '')
77
+	{
78
+		return new self($props_n_values, true, $timezone);
79
+	}
80
+
81
+
82
+	/**
83
+	 *        Set Event ID
84
+	 *
85
+	 * @param int $EVT_ID Event ID
86
+	 * @throws DomainException
87
+	 * @throws EE_Error
88
+	 * @throws EntityNotFoundException
89
+	 * @throws InvalidArgumentException
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 * @throws ReflectionException
93
+	 * @throws RuntimeException
94
+	 * @throws UnexpectedEntityException
95
+	 */
96
+	public function set_event($EVT_ID = 0)
97
+	{
98
+		$this->set('EVT_ID', $EVT_ID);
99
+	}
100
+
101
+
102
+	/**
103
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
104
+	 * be routed to internal methods
105
+	 *
106
+	 * @param string $field_name
107
+	 * @param mixed  $field_value
108
+	 * @param bool   $use_default
109
+	 * @throws DomainException
110
+	 * @throws EE_Error
111
+	 * @throws EntityNotFoundException
112
+	 * @throws InvalidArgumentException
113
+	 * @throws InvalidDataTypeException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws ReflectionException
116
+	 * @throws RuntimeException
117
+	 * @throws UnexpectedEntityException
118
+	 */
119
+	public function set($field_name, $field_value, $use_default = false)
120
+	{
121
+		switch ($field_name) {
122
+			case 'REG_code':
123
+				if (! empty($field_value) && ! $this->reg_code()) {
124
+					$this->set_reg_code($field_value, $use_default);
125
+				}
126
+				break;
127
+			case 'STS_ID':
128
+				$this->set_status((string) $field_value, $use_default);
129
+				break;
130
+			default:
131
+				parent::set($field_name, $field_value, $use_default);
132
+		}
133
+	}
134
+
135
+
136
+	/**
137
+	 * Set Status ID
138
+	 * updates the registration status and ALSO...
139
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
140
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
141
+	 *
142
+	 * @param string                $new_STS_ID
143
+	 * @param boolean               $use_default
144
+	 * @param ContextInterface|null $context
145
+	 * @return bool
146
+	 * @throws DomainException
147
+	 * @throws EE_Error
148
+	 * @throws EntityNotFoundException
149
+	 * @throws InvalidArgumentException
150
+	 * @throws InvalidDataTypeException
151
+	 * @throws InvalidInterfaceException
152
+	 * @throws ReflectionException
153
+	 * @throws RuntimeException
154
+	 * @throws UnexpectedEntityException
155
+	 */
156
+	public function set_status(
157
+		string $new_STS_ID = '',
158
+		bool $use_default = false,
159
+		?ContextInterface $context = null
160
+	): bool {
161
+		// get current REG_Status
162
+		$old_STS_ID = $this->status_ID();
163
+		$new_STS_ID = (string) apply_filters(
164
+			'AFEE__EE_Registration__set_status__new_STS_ID',
165
+			$new_STS_ID,
166
+			$context,
167
+			$this
168
+		);
169
+		// it's still good to allow the parent set method to have a say
170
+		parent::set('STS_ID', (! empty($new_STS_ID) ? $new_STS_ID : null), $use_default);
171
+		// if status has changed
172
+		if (
173
+			$old_STS_ID !== $new_STS_ID // and that status has actually changed
174
+			&& ! empty($old_STS_ID) // and that old status is actually set
175
+			&& ! empty($new_STS_ID) // as well as the new status
176
+			&& $this->ID() // ensure registration is in the db
177
+		) {
178
+			// THEN handle other changes that occur when reg status changes
179
+			// TO approved
180
+			if ($new_STS_ID === RegStatus::APPROVED) {
181
+				// reserve a space by incrementing ticket and datetime sold values
182
+				$this->reserveRegistrationSpace();
183
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
184
+				// OR FROM  approved
185
+			} elseif ($old_STS_ID === RegStatus::APPROVED) {
186
+				// release a space by decrementing ticket and datetime sold values
187
+				$this->releaseRegistrationSpace();
188
+				do_action(
189
+					'AHEE__EE_Registration__set_status__from_approved',
190
+					$this,
191
+					$old_STS_ID,
192
+					$new_STS_ID,
193
+					$context
194
+				);
195
+			}
196
+			$this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
197
+			if ($this->statusChangeUpdatesTransaction($context)) {
198
+				$this->updateTransactionAfterStatusChange();
199
+			}
200
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
201
+		}
202
+		return ! empty($new_STS_ID);
203
+	}
204
+
205
+
206
+	/**
207
+	 * update REGs and TXN when cancelled or declined registrations involved
208
+	 *
209
+	 * @param string                $new_STS_ID
210
+	 * @param string                $old_STS_ID
211
+	 * @param ContextInterface|null $context
212
+	 * @throws EE_Error
213
+	 * @throws InvalidArgumentException
214
+	 * @throws InvalidDataTypeException
215
+	 * @throws InvalidInterfaceException
216
+	 * @throws ReflectionException
217
+	 * @throws RuntimeException
218
+	 */
219
+	private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ?ContextInterface $context = null)
220
+	{
221
+		// these reg statuses should not be considered in any calculations involving monies owing
222
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
223
+		// true if registration has been cancelled or declined
224
+		$this->updateIfCanceled(
225
+			$closed_reg_statuses,
226
+			$new_STS_ID,
227
+			$old_STS_ID,
228
+			$context
229
+		);
230
+		$this->updateIfReinstated(
231
+			$closed_reg_statuses,
232
+			$new_STS_ID,
233
+			$old_STS_ID,
234
+			$context
235
+		);
236
+	}
237
+
238
+
239
+	/**
240
+	 * update REGs and TXN when cancelled or declined registrations involved
241
+	 *
242
+	 * @param array                 $closed_reg_statuses
243
+	 * @param string                $new_STS_ID
244
+	 * @param string                $old_STS_ID
245
+	 * @param ContextInterface|null $context
246
+	 * @throws EE_Error
247
+	 * @throws InvalidArgumentException
248
+	 * @throws InvalidDataTypeException
249
+	 * @throws InvalidInterfaceException
250
+	 * @throws ReflectionException
251
+	 * @throws RuntimeException
252
+	 */
253
+	private function updateIfCanceled(
254
+		array $closed_reg_statuses,
255
+		$new_STS_ID,
256
+		$old_STS_ID,
257
+		?ContextInterface $context = null
258
+	) {
259
+		// true if registration has been cancelled or declined
260
+		if (
261
+			in_array($new_STS_ID, $closed_reg_statuses, true)
262
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
263
+		) {
264
+			/** @type EE_Registration_Processor $registration_processor */
265
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
266
+			/** @type EE_Transaction_Processor $transaction_processor */
267
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
268
+			// cancelled or declined registration
269
+			$registration_processor->update_registration_after_being_canceled_or_declined(
270
+				$this,
271
+				$closed_reg_statuses
272
+			);
273
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
274
+				$this,
275
+				$closed_reg_statuses,
276
+				false
277
+			);
278
+			do_action(
279
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
280
+				$this,
281
+				$old_STS_ID,
282
+				$new_STS_ID,
283
+				$context
284
+			);
285
+		}
286
+	}
287
+
288
+
289
+	/**
290
+	 * update REGs and TXN when cancelled or declined registrations involved
291
+	 *
292
+	 * @param array                 $closed_reg_statuses
293
+	 * @param string                $new_STS_ID
294
+	 * @param string                $old_STS_ID
295
+	 * @param ContextInterface|null $context
296
+	 * @throws EE_Error
297
+	 * @throws InvalidArgumentException
298
+	 * @throws InvalidDataTypeException
299
+	 * @throws InvalidInterfaceException
300
+	 * @throws ReflectionException
301
+	 * @throws RuntimeException
302
+	 */
303
+	private function updateIfReinstated(
304
+		array $closed_reg_statuses,
305
+		$new_STS_ID,
306
+		$old_STS_ID,
307
+		?ContextInterface $context = null
308
+	) {
309
+		// true if reinstating cancelled or declined registration
310
+		if (
311
+			in_array($old_STS_ID, $closed_reg_statuses, true)
312
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
313
+		) {
314
+			/** @type EE_Registration_Processor $registration_processor */
315
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
316
+			/** @type EE_Transaction_Processor $transaction_processor */
317
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
318
+			// reinstating cancelled or declined registration
319
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
320
+				$this,
321
+				$closed_reg_statuses
322
+			);
323
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
324
+				$this,
325
+				$closed_reg_statuses,
326
+				false
327
+			);
328
+			do_action(
329
+				'AHEE__EE_Registration__set_status__after_reinstated',
330
+				$this,
331
+				$old_STS_ID,
332
+				$new_STS_ID,
333
+				$context
334
+			);
335
+		}
336
+	}
337
+
338
+
339
+	/**
340
+	 * @param ContextInterface|null $context
341
+	 * @return bool
342
+	 */
343
+	private function statusChangeUpdatesTransaction(?ContextInterface $context = null)
344
+	{
345
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
346
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
347
+			['spco_reg_step_attendee_information_process_registrations'],
348
+			$context,
349
+			$this
350
+		);
351
+		return ! (
352
+			$context instanceof ContextInterface
353
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
354
+		);
355
+	}
356
+
357
+
358
+	/**
359
+	 * @throws EE_Error
360
+	 * @throws EntityNotFoundException
361
+	 * @throws InvalidArgumentException
362
+	 * @throws InvalidDataTypeException
363
+	 * @throws InvalidInterfaceException
364
+	 * @throws ReflectionException
365
+	 * @throws RuntimeException
366
+	 */
367
+	private function updateTransactionAfterStatusChange()
368
+	{
369
+		/** @type EE_Transaction_Payments $transaction_payments */
370
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
371
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
372
+		$this->transaction()->update_status_based_on_total_paid();
373
+	}
374
+
375
+
376
+	/**
377
+	 * get Status ID
378
+	 *
379
+	 * @throws EE_Error
380
+	 * @throws InvalidArgumentException
381
+	 * @throws InvalidDataTypeException
382
+	 * @throws InvalidInterfaceException
383
+	 * @throws ReflectionException
384
+	 */
385
+	public function status_ID()
386
+	{
387
+		return $this->get('STS_ID');
388
+	}
389
+
390
+
391
+	/**
392
+	 * Gets the ticket this registration is for
393
+	 *
394
+	 * @param boolean $include_archived whether to include archived tickets or not.
395
+	 * @return EE_Ticket|EE_Base_Class
396
+	 * @throws EE_Error
397
+	 * @throws InvalidArgumentException
398
+	 * @throws InvalidDataTypeException
399
+	 * @throws InvalidInterfaceException
400
+	 * @throws ReflectionException
401
+	 */
402
+	public function ticket($include_archived = true)
403
+	{
404
+		return EEM_Ticket::instance()->get_one_by_ID($this->ticket_ID());
405
+	}
406
+
407
+
408
+	/**
409
+	 * Gets the event this registration is for
410
+	 *
411
+	 * @return EE_Event
412
+	 * @throws EE_Error
413
+	 * @throws EntityNotFoundException
414
+	 * @throws InvalidArgumentException
415
+	 * @throws InvalidDataTypeException
416
+	 * @throws InvalidInterfaceException
417
+	 * @throws ReflectionException
418
+	 */
419
+	public function event(): EE_Event
420
+	{
421
+		$event = $this->event_obj();
422
+		if (! $event instanceof EE_Event) {
423
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
424
+		}
425
+		return $event;
426
+	}
427
+
428
+
429
+	/**
430
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
431
+	 * with the author of the event this registration is for.
432
+	 *
433
+	 * @return int
434
+	 * @throws EE_Error
435
+	 * @throws EntityNotFoundException
436
+	 * @throws InvalidArgumentException
437
+	 * @throws InvalidDataTypeException
438
+	 * @throws InvalidInterfaceException
439
+	 * @throws ReflectionException
440
+	 * @since 4.5.0
441
+	 */
442
+	public function wp_user(): int
443
+	{
444
+		return $this->event()->wp_user();
445
+	}
446
+
447
+
448
+	/**
449
+	 * increments this registration's related ticket sold and corresponding datetime sold values
450
+	 *
451
+	 * @return void
452
+	 * @throws DomainException
453
+	 * @throws EE_Error
454
+	 * @throws EntityNotFoundException
455
+	 * @throws InvalidArgumentException
456
+	 * @throws InvalidDataTypeException
457
+	 * @throws InvalidInterfaceException
458
+	 * @throws ReflectionException
459
+	 * @throws UnexpectedEntityException
460
+	 */
461
+	private function reserveRegistrationSpace()
462
+	{
463
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
464
+		// so stop tracking that this reg has a ticket reserved
465
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
466
+		$ticket = $this->ticket();
467
+		$ticket->increaseSold();
468
+		// possibly set event status to sold out
469
+		$this->event()->perform_sold_out_status_check();
470
+	}
471
+
472
+
473
+	/**
474
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
475
+	 *
476
+	 * @return void
477
+	 * @throws DomainException
478
+	 * @throws EE_Error
479
+	 * @throws EntityNotFoundException
480
+	 * @throws InvalidArgumentException
481
+	 * @throws InvalidDataTypeException
482
+	 * @throws InvalidInterfaceException
483
+	 * @throws ReflectionException
484
+	 * @throws UnexpectedEntityException
485
+	 */
486
+	private function releaseRegistrationSpace()
487
+	{
488
+		$ticket = $this->ticket();
489
+		$ticket->decreaseSold();
490
+		// possibly change event status from sold out back to previous status
491
+		$this->event()->perform_sold_out_status_check();
492
+	}
493
+
494
+
495
+	/**
496
+	 * tracks this registration's ticket reservation in extra meta
497
+	 * and can increment related ticket reserved and corresponding datetime reserved values
498
+	 *
499
+	 * @param bool   $update_ticket if true, will increment ticket and datetime reserved count
500
+	 * @param string $source
501
+	 * @return void
502
+	 * @throws EE_Error
503
+	 * @throws InvalidArgumentException
504
+	 * @throws InvalidDataTypeException
505
+	 * @throws InvalidInterfaceException
506
+	 * @throws ReflectionException
507
+	 */
508
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
509
+	{
510
+		// only reserve ticket if space is not currently reserved
511
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
512
+			$reserved = $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
513
+			if ($reserved && $update_ticket) {
514
+				$ticket = $this->ticket();
515
+				$ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
516
+				// comment out extra meta tracking
517
+				// $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
518
+				$ticket->save();
519
+			}
520
+		}
521
+	}
522
+
523
+
524
+	/**
525
+	 * stops tracking this registration's ticket reservation in extra meta
526
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
527
+	 *
528
+	 * @param bool   $update_ticket if true, will decrement ticket and datetime reserved count
529
+	 * @param string $source
530
+	 * @return void
531
+	 * @throws EE_Error
532
+	 * @throws InvalidArgumentException
533
+	 * @throws InvalidDataTypeException
534
+	 * @throws InvalidInterfaceException
535
+	 * @throws ReflectionException
536
+	 */
537
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
538
+	{
539
+		// only release ticket if space is currently reserved
540
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
541
+			$released = $this->delete_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
542
+			if ($released && $update_ticket) {
543
+				$ticket = $this->ticket();
544
+				$ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
545
+				// comment out extra meta tracking
546
+				// $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
547
+			}
548
+		}
549
+	}
550
+
551
+
552
+	/**
553
+	 * Set Attendee ID
554
+	 *
555
+	 * @param int $ATT_ID Attendee ID
556
+	 * @throws DomainException
557
+	 * @throws EE_Error
558
+	 * @throws EntityNotFoundException
559
+	 * @throws InvalidArgumentException
560
+	 * @throws InvalidDataTypeException
561
+	 * @throws InvalidInterfaceException
562
+	 * @throws ReflectionException
563
+	 * @throws RuntimeException
564
+	 * @throws UnexpectedEntityException
565
+	 */
566
+	public function set_attendee_id($ATT_ID = 0)
567
+	{
568
+		$this->set('ATT_ID', $ATT_ID);
569
+	}
570
+
571
+
572
+	/**
573
+	 *        Set Transaction ID
574
+	 *
575
+	 * @param int $TXN_ID Transaction ID
576
+	 * @throws DomainException
577
+	 * @throws EE_Error
578
+	 * @throws EntityNotFoundException
579
+	 * @throws InvalidArgumentException
580
+	 * @throws InvalidDataTypeException
581
+	 * @throws InvalidInterfaceException
582
+	 * @throws ReflectionException
583
+	 * @throws RuntimeException
584
+	 * @throws UnexpectedEntityException
585
+	 */
586
+	public function set_transaction_id($TXN_ID = 0)
587
+	{
588
+		$this->set('TXN_ID', $TXN_ID);
589
+	}
590
+
591
+
592
+	/**
593
+	 *        Set Session
594
+	 *
595
+	 * @param string $REG_session PHP Session ID
596
+	 * @throws DomainException
597
+	 * @throws EE_Error
598
+	 * @throws EntityNotFoundException
599
+	 * @throws InvalidArgumentException
600
+	 * @throws InvalidDataTypeException
601
+	 * @throws InvalidInterfaceException
602
+	 * @throws ReflectionException
603
+	 * @throws RuntimeException
604
+	 * @throws UnexpectedEntityException
605
+	 */
606
+	public function set_session($REG_session = '')
607
+	{
608
+		$this->set('REG_session', $REG_session);
609
+	}
610
+
611
+
612
+	/**
613
+	 *        Set Registration URL Link
614
+	 *
615
+	 * @param string $REG_url_link Registration URL Link
616
+	 * @throws DomainException
617
+	 * @throws EE_Error
618
+	 * @throws EntityNotFoundException
619
+	 * @throws InvalidArgumentException
620
+	 * @throws InvalidDataTypeException
621
+	 * @throws InvalidInterfaceException
622
+	 * @throws ReflectionException
623
+	 * @throws RuntimeException
624
+	 * @throws UnexpectedEntityException
625
+	 */
626
+	public function set_reg_url_link($REG_url_link = '')
627
+	{
628
+		$this->set('REG_url_link', $REG_url_link);
629
+	}
630
+
631
+
632
+	/**
633
+	 *        Set Attendee Counter
634
+	 *
635
+	 * @param int $REG_count Primary Attendee
636
+	 * @throws DomainException
637
+	 * @throws EE_Error
638
+	 * @throws EntityNotFoundException
639
+	 * @throws InvalidArgumentException
640
+	 * @throws InvalidDataTypeException
641
+	 * @throws InvalidInterfaceException
642
+	 * @throws ReflectionException
643
+	 * @throws RuntimeException
644
+	 * @throws UnexpectedEntityException
645
+	 */
646
+	public function set_count($REG_count = 1)
647
+	{
648
+		$this->set('REG_count', $REG_count);
649
+	}
650
+
651
+
652
+	/**
653
+	 *        Set Group Size
654
+	 *
655
+	 * @param boolean $REG_group_size Group Registration
656
+	 * @throws DomainException
657
+	 * @throws EE_Error
658
+	 * @throws EntityNotFoundException
659
+	 * @throws InvalidArgumentException
660
+	 * @throws InvalidDataTypeException
661
+	 * @throws InvalidInterfaceException
662
+	 * @throws ReflectionException
663
+	 * @throws RuntimeException
664
+	 * @throws UnexpectedEntityException
665
+	 */
666
+	public function set_group_size($REG_group_size = false)
667
+	{
668
+		$this->set('REG_group_size', $REG_group_size);
669
+	}
670
+
671
+
672
+	/**
673
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
674
+	 *    RegStatus::AWAITING_REVIEW
675
+	 *
676
+	 * @return        boolean
677
+	 * @throws EE_Error
678
+	 * @throws InvalidArgumentException
679
+	 * @throws InvalidDataTypeException
680
+	 * @throws InvalidInterfaceException
681
+	 * @throws ReflectionException
682
+	 */
683
+	public function is_not_approved()
684
+	{
685
+		return $this->status_ID() === RegStatus::AWAITING_REVIEW;
686
+	}
687
+
688
+
689
+	/**
690
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
691
+	 *    RegStatus::PENDING_PAYMENT
692
+	 *
693
+	 * @return        boolean
694
+	 * @throws EE_Error
695
+	 * @throws InvalidArgumentException
696
+	 * @throws InvalidDataTypeException
697
+	 * @throws InvalidInterfaceException
698
+	 * @throws ReflectionException
699
+	 */
700
+	public function is_pending_payment()
701
+	{
702
+		return $this->status_ID() === RegStatus::PENDING_PAYMENT;
703
+	}
704
+
705
+
706
+	/**
707
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == RegStatus::APPROVED
708
+	 *
709
+	 * @return        boolean
710
+	 * @throws EE_Error
711
+	 * @throws InvalidArgumentException
712
+	 * @throws InvalidDataTypeException
713
+	 * @throws InvalidInterfaceException
714
+	 * @throws ReflectionException
715
+	 */
716
+	public function is_approved()
717
+	{
718
+		return $this->status_ID() === RegStatus::APPROVED;
719
+	}
720
+
721
+
722
+	/**
723
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == RegStatus::CANCELLED
724
+	 *
725
+	 * @return        boolean
726
+	 * @throws EE_Error
727
+	 * @throws InvalidArgumentException
728
+	 * @throws InvalidDataTypeException
729
+	 * @throws InvalidInterfaceException
730
+	 * @throws ReflectionException
731
+	 */
732
+	public function is_cancelled()
733
+	{
734
+		return $this->status_ID() === RegStatus::CANCELLED;
735
+	}
736
+
737
+
738
+	/**
739
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == RegStatus::DECLINED
740
+	 *
741
+	 * @return        boolean
742
+	 * @throws EE_Error
743
+	 * @throws InvalidArgumentException
744
+	 * @throws InvalidDataTypeException
745
+	 * @throws InvalidInterfaceException
746
+	 * @throws ReflectionException
747
+	 */
748
+	public function is_declined()
749
+	{
750
+		return $this->status_ID() === RegStatus::DECLINED;
751
+	}
752
+
753
+
754
+	/**
755
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
756
+	 *    RegStatus::INCOMPLETE
757
+	 *
758
+	 * @return        boolean
759
+	 * @throws EE_Error
760
+	 * @throws InvalidArgumentException
761
+	 * @throws InvalidDataTypeException
762
+	 * @throws InvalidInterfaceException
763
+	 * @throws ReflectionException
764
+	 */
765
+	public function is_incomplete()
766
+	{
767
+		return $this->status_ID() === RegStatus::INCOMPLETE;
768
+	}
769
+
770
+
771
+	/**
772
+	 *        Set Registration Date
773
+	 *
774
+	 * @param mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
775
+	 *                                                 Date
776
+	 * @throws DomainException
777
+	 * @throws EE_Error
778
+	 * @throws EntityNotFoundException
779
+	 * @throws InvalidArgumentException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws InvalidInterfaceException
782
+	 * @throws ReflectionException
783
+	 * @throws RuntimeException
784
+	 * @throws UnexpectedEntityException
785
+	 */
786
+	public function set_reg_date($REG_date = false)
787
+	{
788
+		$this->set('REG_date', $REG_date);
789
+	}
790
+
791
+
792
+	/**
793
+	 *    Set final price owing for this registration after all ticket/price modifications
794
+	 *
795
+	 * @param float $REG_final_price
796
+	 * @throws DomainException
797
+	 * @throws EE_Error
798
+	 * @throws EntityNotFoundException
799
+	 * @throws InvalidArgumentException
800
+	 * @throws InvalidDataTypeException
801
+	 * @throws InvalidInterfaceException
802
+	 * @throws ReflectionException
803
+	 * @throws RuntimeException
804
+	 * @throws UnexpectedEntityException
805
+	 */
806
+	public function set_final_price($REG_final_price = 0.00)
807
+	{
808
+		$this->set('REG_final_price', $REG_final_price);
809
+	}
810
+
811
+
812
+	/**
813
+	 *    Set amount paid towards this registration's final price
814
+	 *
815
+	 * @param float|int|string $REG_paid
816
+	 * @throws DomainException
817
+	 * @throws EE_Error
818
+	 * @throws EntityNotFoundException
819
+	 * @throws InvalidArgumentException
820
+	 * @throws InvalidDataTypeException
821
+	 * @throws InvalidInterfaceException
822
+	 * @throws ReflectionException
823
+	 * @throws RuntimeException
824
+	 * @throws UnexpectedEntityException
825
+	 */
826
+	public function set_paid($REG_paid = 0.00)
827
+	{
828
+		$this->set('REG_paid', (float) $REG_paid);
829
+	}
830
+
831
+
832
+	/**
833
+	 *        Attendee Is Going
834
+	 *
835
+	 * @param boolean $REG_att_is_going Attendee Is Going
836
+	 * @throws DomainException
837
+	 * @throws EE_Error
838
+	 * @throws EntityNotFoundException
839
+	 * @throws InvalidArgumentException
840
+	 * @throws InvalidDataTypeException
841
+	 * @throws InvalidInterfaceException
842
+	 * @throws ReflectionException
843
+	 * @throws RuntimeException
844
+	 * @throws UnexpectedEntityException
845
+	 */
846
+	public function set_att_is_going($REG_att_is_going = false)
847
+	{
848
+		$this->set('REG_att_is_going', $REG_att_is_going);
849
+	}
850
+
851
+
852
+	/**
853
+	 * Gets the related attendee
854
+	 *
855
+	 * @return EE_Attendee|EE_Base_Class
856
+	 * @throws EE_Error
857
+	 * @throws InvalidArgumentException
858
+	 * @throws InvalidDataTypeException
859
+	 * @throws InvalidInterfaceException
860
+	 * @throws ReflectionException
861
+	 */
862
+	public function attendee()
863
+	{
864
+		return EEM_Attendee::instance()->get_one_by_ID($this->attendee_ID());
865
+	}
866
+
867
+
868
+	/**
869
+	 * Gets the name of the attendee.
870
+	 *
871
+	 * @param bool $apply_html_entities set to true if you want to use HTML entities.
872
+	 * @return string
873
+	 * @throws EE_Error
874
+	 * @throws InvalidArgumentException
875
+	 * @throws InvalidDataTypeException
876
+	 * @throws InvalidInterfaceException
877
+	 * @throws ReflectionException
878
+	 * @since 4.10.12.p
879
+	 */
880
+	public function attendeeName($apply_html_entities = false)
881
+	{
882
+		$attendee = $this->attendee();
883
+		if ($attendee instanceof EE_Attendee) {
884
+			$attendee_name = $attendee->full_name($apply_html_entities);
885
+		} else {
886
+			$attendee_name = esc_html__('Unknown', 'event_espresso');
887
+		}
888
+		return $attendee_name;
889
+	}
890
+
891
+
892
+	/**
893
+	 *        get Event ID
894
+	 */
895
+	public function event_ID()
896
+	{
897
+		return $this->get('EVT_ID');
898
+	}
899
+
900
+
901
+	/**
902
+	 *        get Event ID
903
+	 */
904
+	public function event_name()
905
+	{
906
+		$event = $this->event_obj();
907
+		if ($event) {
908
+			return $event->name();
909
+		} else {
910
+			return null;
911
+		}
912
+	}
913
+
914
+
915
+	/**
916
+	 * Fetches the event this registration is for
917
+	 *
918
+	 * @return EE_Base_Class|EE_Event
919
+	 * @throws EE_Error
920
+	 * @throws InvalidArgumentException
921
+	 * @throws InvalidDataTypeException
922
+	 * @throws InvalidInterfaceException
923
+	 * @throws ReflectionException
924
+	 */
925
+	public function event_obj()
926
+	{
927
+		return EEM_Event::instance()->get_one_by_ID($this->event_ID());
928
+	}
929
+
930
+
931
+	/**
932
+	 *        get Attendee ID
933
+	 */
934
+	public function attendee_ID()
935
+	{
936
+		return $this->get('ATT_ID');
937
+	}
938
+
939
+
940
+	/**
941
+	 *        get PHP Session ID
942
+	 */
943
+	public function session_ID()
944
+	{
945
+		return $this->get('REG_session');
946
+	}
947
+
948
+
949
+	/**
950
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
951
+	 *
952
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
953
+	 * @return string
954
+	 * @throws DomainException
955
+	 * @throws InvalidArgumentException
956
+	 * @throws InvalidDataTypeException
957
+	 * @throws InvalidInterfaceException
958
+	 */
959
+	public function receipt_url($messenger = 'html')
960
+	{
961
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
962
+	}
963
+
964
+
965
+	/**
966
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
967
+	 *
968
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
969
+	 * @return string
970
+	 * @throws DomainException
971
+	 * @throws InvalidArgumentException
972
+	 * @throws InvalidDataTypeException
973
+	 * @throws InvalidInterfaceException
974
+	 */
975
+	public function invoice_url($messenger = 'html')
976
+	{
977
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
978
+	}
979
+
980
+
981
+	/**
982
+	 * get Registration URL Link
983
+	 *
984
+	 * @return string
985
+	 * @throws EE_Error
986
+	 * @throws InvalidArgumentException
987
+	 * @throws InvalidDataTypeException
988
+	 * @throws InvalidInterfaceException
989
+	 * @throws ReflectionException
990
+	 */
991
+	public function reg_url_link()
992
+	{
993
+		return (string) $this->get('REG_url_link');
994
+	}
995
+
996
+
997
+	/**
998
+	 * Echoes out invoice_url()
999
+	 *
1000
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
1001
+	 * @return void
1002
+	 * @throws DomainException
1003
+	 * @throws EE_Error
1004
+	 * @throws InvalidArgumentException
1005
+	 * @throws InvalidDataTypeException
1006
+	 * @throws InvalidInterfaceException
1007
+	 * @throws ReflectionException
1008
+	 */
1009
+	public function e_invoice_url($type = 'launch')
1010
+	{
1011
+		echo esc_url_raw($this->invoice_url($type));
1012
+	}
1013
+
1014
+
1015
+	/**
1016
+	 * Echoes out payment_overview_url
1017
+	 */
1018
+	public function e_payment_overview_url()
1019
+	{
1020
+		echo esc_url_raw($this->payment_overview_url());
1021
+	}
1022
+
1023
+
1024
+	/**
1025
+	 * Gets the URL for the checkout payment options reg step
1026
+	 * with this registration's REG_url_link added as a query parameter
1027
+	 *
1028
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
1029
+	 *                            payment overview url.
1030
+	 * @return string
1031
+	 * @throws EE_Error
1032
+	 * @throws InvalidArgumentException
1033
+	 * @throws InvalidDataTypeException
1034
+	 * @throws InvalidInterfaceException
1035
+	 * @throws ReflectionException
1036
+	 */
1037
+	public function payment_overview_url($clear_session = false)
1038
+	{
1039
+		return add_query_arg(
1040
+			(array) apply_filters(
1041
+				'FHEE__EE_Registration__payment_overview_url__query_args',
1042
+				[
1043
+					'e_reg_url_link' => $this->reg_url_link(),
1044
+					'step'           => 'payment_options',
1045
+					'revisit'        => true,
1046
+					'clear_session'  => (bool) $clear_session,
1047
+				],
1048
+				$this
1049
+			),
1050
+			EE_Registry::instance()->CFG->core->reg_page_url()
1051
+		);
1052
+	}
1053
+
1054
+
1055
+	/**
1056
+	 * Gets the URL for the checkout attendee information reg step
1057
+	 * with this registration's REG_url_link added as a query parameter
1058
+	 *
1059
+	 * @return string
1060
+	 * @throws EE_Error
1061
+	 * @throws InvalidArgumentException
1062
+	 * @throws InvalidDataTypeException
1063
+	 * @throws InvalidInterfaceException
1064
+	 * @throws ReflectionException
1065
+	 */
1066
+	public function edit_attendee_information_url()
1067
+	{
1068
+		return add_query_arg(
1069
+			(array) apply_filters(
1070
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
1071
+				[
1072
+					'e_reg_url_link' => $this->reg_url_link(),
1073
+					'step'           => 'attendee_information',
1074
+					'revisit'        => true,
1075
+				],
1076
+				$this
1077
+			),
1078
+			EE_Registry::instance()->CFG->core->reg_page_url()
1079
+		);
1080
+	}
1081
+
1082
+
1083
+	/**
1084
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
1085
+	 *
1086
+	 * @return string
1087
+	 * @throws EE_Error
1088
+	 * @throws InvalidArgumentException
1089
+	 * @throws InvalidDataTypeException
1090
+	 * @throws InvalidInterfaceException
1091
+	 * @throws ReflectionException
1092
+	 */
1093
+	public function get_admin_edit_url()
1094
+	{
1095
+		return EEH_URL::add_query_args_and_nonce(
1096
+			[
1097
+				'page'    => 'espresso_registrations',
1098
+				'action'  => 'view_registration',
1099
+				'_REG_ID' => $this->ID(),
1100
+			],
1101
+			admin_url('admin.php')
1102
+		);
1103
+	}
1104
+
1105
+
1106
+	/**
1107
+	 * is_primary_registrant?
1108
+	 *
1109
+	 * @throws EE_Error
1110
+	 * @throws InvalidArgumentException
1111
+	 * @throws InvalidDataTypeException
1112
+	 * @throws InvalidInterfaceException
1113
+	 * @throws ReflectionException
1114
+	 */
1115
+	public function is_primary_registrant()
1116
+	{
1117
+		return (int) $this->get('REG_count') === 1;
1118
+	}
1119
+
1120
+
1121
+	/**
1122
+	 * This returns the primary registration object for this registration group (which may be this object).
1123
+	 *
1124
+	 * @return EE_Registration
1125
+	 * @throws EE_Error
1126
+	 * @throws InvalidArgumentException
1127
+	 * @throws InvalidDataTypeException
1128
+	 * @throws InvalidInterfaceException
1129
+	 * @throws ReflectionException
1130
+	 */
1131
+	public function get_primary_registration()
1132
+	{
1133
+		if ($this->is_primary_registrant()) {
1134
+			return $this;
1135
+		}
1136
+
1137
+		// k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1138
+		/** @var EE_Registration $primary_registrant */
1139
+		$primary_registrant = EEM_Registration::instance()->get_one(
1140
+			[
1141
+				[
1142
+					'TXN_ID'    => $this->transaction_ID(),
1143
+					'REG_count' => 1,
1144
+				],
1145
+			]
1146
+		);
1147
+		return $primary_registrant;
1148
+	}
1149
+
1150
+
1151
+	/**
1152
+	 * get  Attendee Number
1153
+	 *
1154
+	 * @throws EE_Error
1155
+	 * @throws InvalidArgumentException
1156
+	 * @throws InvalidDataTypeException
1157
+	 * @throws InvalidInterfaceException
1158
+	 * @throws ReflectionException
1159
+	 */
1160
+	public function count()
1161
+	{
1162
+		return $this->get('REG_count');
1163
+	}
1164
+
1165
+
1166
+	/**
1167
+	 * get Group Size
1168
+	 *
1169
+	 * @throws EE_Error
1170
+	 * @throws InvalidArgumentException
1171
+	 * @throws InvalidDataTypeException
1172
+	 * @throws InvalidInterfaceException
1173
+	 * @throws ReflectionException
1174
+	 */
1175
+	public function group_size()
1176
+	{
1177
+		return $this->get('REG_group_size');
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * get Registration Date
1183
+	 *
1184
+	 * @throws EE_Error
1185
+	 * @throws InvalidArgumentException
1186
+	 * @throws InvalidDataTypeException
1187
+	 * @throws InvalidInterfaceException
1188
+	 * @throws ReflectionException
1189
+	 */
1190
+	public function date()
1191
+	{
1192
+		return $this->get('REG_date');
1193
+	}
1194
+
1195
+
1196
+	/**
1197
+	 * gets a pretty date
1198
+	 *
1199
+	 * @param string $date_format
1200
+	 * @param string $time_format
1201
+	 * @return string
1202
+	 * @throws EE_Error
1203
+	 * @throws InvalidArgumentException
1204
+	 * @throws InvalidDataTypeException
1205
+	 * @throws InvalidInterfaceException
1206
+	 * @throws ReflectionException
1207
+	 */
1208
+	public function pretty_date($date_format = null, $time_format = null)
1209
+	{
1210
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1211
+	}
1212
+
1213
+
1214
+	/**
1215
+	 * final_price
1216
+	 * the registration's share of the transaction total, so that the
1217
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1218
+	 *
1219
+	 * @return float
1220
+	 * @throws EE_Error
1221
+	 * @throws InvalidArgumentException
1222
+	 * @throws InvalidDataTypeException
1223
+	 * @throws InvalidInterfaceException
1224
+	 * @throws ReflectionException
1225
+	 */
1226
+	public function final_price(): float
1227
+	{
1228
+		return (float) $this->get('REG_final_price');
1229
+	}
1230
+
1231
+
1232
+	/**
1233
+	 * pretty_final_price
1234
+	 *  final price as formatted string, with correct decimal places and currency symbol
1235
+	 *
1236
+	 * @param string|null $schema
1237
+	 *      Schemas:
1238
+	 *      'localized_float': "3,023.00"
1239
+	 *      'no_currency_code': "$3,023.00"
1240
+	 *      null: "$3,023.00<span>USD</span>"
1241
+	 * @return string
1242
+	 * @throws EE_Error
1243
+	 * @throws InvalidArgumentException
1244
+	 * @throws InvalidDataTypeException
1245
+	 * @throws InvalidInterfaceException
1246
+	 * @throws ReflectionException
1247
+	 */
1248
+	public function pretty_final_price(?string $schema = null)
1249
+	{
1250
+		return $this->get_pretty('REG_final_price', $schema);
1251
+	}
1252
+
1253
+
1254
+	/**
1255
+	 * get paid (yeah)
1256
+	 *
1257
+	 * @return float
1258
+	 * @throws EE_Error
1259
+	 * @throws InvalidArgumentException
1260
+	 * @throws InvalidDataTypeException
1261
+	 * @throws InvalidInterfaceException
1262
+	 * @throws ReflectionException
1263
+	 */
1264
+	public function paid(): float
1265
+	{
1266
+		return (float) $this->get('REG_paid');
1267
+	}
1268
+
1269
+
1270
+	/**
1271
+	 * pretty_paid
1272
+	 *
1273
+	 * @param string|null $schema
1274
+	 *      Schemas:
1275
+	 *      'localized_float': "3,023.00"
1276
+	 *      'no_currency_code': "$3,023.00"
1277
+	 *      null: "$3,023.00<span>USD</span>"
1278
+	 * @return float
1279
+	 * @throws EE_Error
1280
+	 * @throws InvalidArgumentException
1281
+	 * @throws InvalidDataTypeException
1282
+	 * @throws InvalidInterfaceException
1283
+	 * @throws ReflectionException
1284
+	 */
1285
+	public function pretty_paid(?string $schema = null)
1286
+	{
1287
+		return $this->get_pretty('REG_paid', $schema);
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 * owes_monies_and_can_pay
1293
+	 * whether this registration has monies owing and it's' status allows payment
1294
+	 *
1295
+	 * @param array $requires_payment list of registration statuses that allow a registrant to make a payment
1296
+	 * @return bool
1297
+	 * @throws EE_Error
1298
+	 * @throws InvalidArgumentException
1299
+	 * @throws InvalidDataTypeException
1300
+	 * @throws InvalidInterfaceException
1301
+	 * @throws ReflectionException
1302
+	 */
1303
+	public function owes_monies_and_can_pay(array $requires_payment = []): bool
1304
+	{
1305
+		// these reg statuses require payment (if event is not free)
1306
+		$requires_payment = ! empty($requires_payment)
1307
+			? $requires_payment
1308
+			: EEM_Registration::reg_statuses_that_allow_payment();
1309
+		if (
1310
+			$this->final_price() !== 0.0 &&
1311
+			$this->final_price() !== $this->paid() &&
1312
+			in_array($this->status_ID(), $requires_payment)
1313
+		) {
1314
+			return true;
1315
+		}
1316
+		return false;
1317
+	}
1318
+
1319
+
1320
+	/**
1321
+	 * Prints out the return value of $this->pretty_status()
1322
+	 *
1323
+	 * @param bool $show_icons
1324
+	 * @return void
1325
+	 * @throws EE_Error
1326
+	 * @throws InvalidArgumentException
1327
+	 * @throws InvalidDataTypeException
1328
+	 * @throws InvalidInterfaceException
1329
+	 * @throws ReflectionException
1330
+	 */
1331
+	public function e_pretty_status($show_icons = false)
1332
+	{
1333
+		echo wp_kses($this->pretty_status($show_icons), AllowedTags::getAllowedTags());
1334
+	}
1335
+
1336
+
1337
+	/**
1338
+	 * Returns a nice version of the status for displaying to customers
1339
+	 *
1340
+	 * @param bool $show_icons
1341
+	 * @return string
1342
+	 * @throws EE_Error
1343
+	 * @throws InvalidArgumentException
1344
+	 * @throws InvalidDataTypeException
1345
+	 * @throws InvalidInterfaceException
1346
+	 * @throws ReflectionException
1347
+	 */
1348
+	public function pretty_status($show_icons = false)
1349
+	{
1350
+		$status = EEM_Status::instance()->localized_status(
1351
+			[$this->status_ID() => esc_html__('unknown', 'event_espresso')],
1352
+			false,
1353
+			'sentence'
1354
+		);
1355
+		$icon   = '';
1356
+		switch ($this->status_ID()) {
1357
+			case RegStatus::APPROVED:
1358
+				$icon = $show_icons
1359
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1360
+					: '';
1361
+				break;
1362
+			case RegStatus::PENDING_PAYMENT:
1363
+				$icon = $show_icons
1364
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1365
+					: '';
1366
+				break;
1367
+			case RegStatus::AWAITING_REVIEW:
1368
+				$icon = $show_icons
1369
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1370
+					: '';
1371
+				break;
1372
+			case RegStatus::CANCELLED:
1373
+				$icon = $show_icons
1374
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1375
+					: '';
1376
+				break;
1377
+			case RegStatus::INCOMPLETE:
1378
+				$icon = $show_icons
1379
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1380
+					: '';
1381
+				break;
1382
+			case RegStatus::DECLINED:
1383
+				$icon = $show_icons
1384
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1385
+					: '';
1386
+				break;
1387
+			case RegStatus::WAIT_LIST:
1388
+				$icon = $show_icons
1389
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1390
+					: '';
1391
+				break;
1392
+		}
1393
+		return $icon . $status[ $this->status_ID() ];
1394
+	}
1395
+
1396
+
1397
+	/**
1398
+	 *        get Attendee Is Going
1399
+	 */
1400
+	public function att_is_going()
1401
+	{
1402
+		return $this->get('REG_att_is_going');
1403
+	}
1404
+
1405
+
1406
+	/**
1407
+	 * Gets related answers
1408
+	 *
1409
+	 * @param array $query_params @see
1410
+	 *                            https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1411
+	 * @return EE_Answer[]|EE_Base_Class[]
1412
+	 * @throws EE_Error
1413
+	 * @throws InvalidArgumentException
1414
+	 * @throws InvalidDataTypeException
1415
+	 * @throws InvalidInterfaceException
1416
+	 * @throws ReflectionException
1417
+	 */
1418
+	public function answers($query_params = [])
1419
+	{
1420
+		return $this->get_many_related('Answer', $query_params);
1421
+	}
1422
+
1423
+
1424
+	/**
1425
+	 * Gets the registration's answer value to the specified question
1426
+	 * (either the question's ID or a question object)
1427
+	 *
1428
+	 * @param EE_Question|int $question
1429
+	 * @param bool            $pretty_value
1430
+	 * @return array|string if pretty_value= true, the result will always be a string
1431
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1432
+	 * will convert it into some kind of string)
1433
+	 * @throws EE_Error
1434
+	 * @throws InvalidArgumentException
1435
+	 * @throws InvalidDataTypeException
1436
+	 * @throws InvalidInterfaceException
1437
+	 */
1438
+	public function answer_value_to_question($question, $pretty_value = true)
1439
+	{
1440
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1441
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1442
+	}
1443
+
1444
+
1445
+	/**
1446
+	 * question_groups
1447
+	 * returns an array of EE_Question_Group objects for this registration
1448
+	 *
1449
+	 * @return EE_Question_Group[]
1450
+	 * @throws EE_Error
1451
+	 * @throws InvalidArgumentException
1452
+	 * @throws InvalidDataTypeException
1453
+	 * @throws InvalidInterfaceException
1454
+	 * @throws ReflectionException
1455
+	 */
1456
+	public function question_groups()
1457
+	{
1458
+		return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1459
+	}
1460
+
1461
+
1462
+	/**
1463
+	 * count_question_groups
1464
+	 * returns a count of the number of EE_Question_Group objects for this registration
1465
+	 *
1466
+	 * @return int
1467
+	 * @throws EE_Error
1468
+	 * @throws EntityNotFoundException
1469
+	 * @throws InvalidArgumentException
1470
+	 * @throws InvalidDataTypeException
1471
+	 * @throws InvalidInterfaceException
1472
+	 * @throws ReflectionException
1473
+	 */
1474
+	public function count_question_groups()
1475
+	{
1476
+		return EEM_Event::instance()->count_related(
1477
+			$this->event_ID(),
1478
+			'Question_Group',
1479
+			[
1480
+				[
1481
+					'Event_Question_Group.'
1482
+					. EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1483
+				],
1484
+			]
1485
+		);
1486
+	}
1487
+
1488
+
1489
+	/**
1490
+	 * Returns the registration date in the 'standard' string format
1491
+	 * (function may be improved in the future to allow for different formats and timezones)
1492
+	 *
1493
+	 * @return string
1494
+	 * @throws EE_Error
1495
+	 * @throws InvalidArgumentException
1496
+	 * @throws InvalidDataTypeException
1497
+	 * @throws InvalidInterfaceException
1498
+	 * @throws ReflectionException
1499
+	 */
1500
+	public function reg_date()
1501
+	{
1502
+		return $this->get_datetime('REG_date');
1503
+	}
1504
+
1505
+
1506
+	/**
1507
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1508
+	 * the ticket this registration purchased, or the datetime they have registered
1509
+	 * to attend)
1510
+	 *
1511
+	 * @return EE_Base_Class|EE_Datetime_Ticket
1512
+	 * @throws EE_Error
1513
+	 * @throws InvalidArgumentException
1514
+	 * @throws InvalidDataTypeException
1515
+	 * @throws InvalidInterfaceException
1516
+	 * @throws ReflectionException
1517
+	 */
1518
+	public function datetime_ticket()
1519
+	{
1520
+		return $this->get_first_related('Datetime_Ticket');
1521
+	}
1522
+
1523
+
1524
+	/**
1525
+	 * Sets the registration's datetime_ticket.
1526
+	 *
1527
+	 * @param EE_Datetime_Ticket $datetime_ticket
1528
+	 * @return EE_Base_Class|EE_Datetime_Ticket
1529
+	 * @throws EE_Error
1530
+	 * @throws InvalidArgumentException
1531
+	 * @throws InvalidDataTypeException
1532
+	 * @throws InvalidInterfaceException
1533
+	 * @throws ReflectionException
1534
+	 */
1535
+	public function set_datetime_ticket($datetime_ticket)
1536
+	{
1537
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1538
+	}
1539
+
1540
+
1541
+	/**
1542
+	 * Gets deleted
1543
+	 *
1544
+	 * @return bool
1545
+	 * @throws EE_Error
1546
+	 * @throws InvalidArgumentException
1547
+	 * @throws InvalidDataTypeException
1548
+	 * @throws InvalidInterfaceException
1549
+	 * @throws ReflectionException
1550
+	 */
1551
+	public function deleted()
1552
+	{
1553
+		return $this->get('REG_deleted');
1554
+	}
1555
+
1556
+
1557
+	/**
1558
+	 * Sets deleted
1559
+	 *
1560
+	 * @param boolean $deleted
1561
+	 * @return void
1562
+	 * @throws DomainException
1563
+	 * @throws EE_Error
1564
+	 * @throws EntityNotFoundException
1565
+	 * @throws InvalidArgumentException
1566
+	 * @throws InvalidDataTypeException
1567
+	 * @throws InvalidInterfaceException
1568
+	 * @throws ReflectionException
1569
+	 * @throws RuntimeException
1570
+	 * @throws UnexpectedEntityException
1571
+	 */
1572
+	public function set_deleted($deleted)
1573
+	{
1574
+		if ($deleted) {
1575
+			$this->delete();
1576
+		} else {
1577
+			$this->restore();
1578
+		}
1579
+	}
1580
+
1581
+
1582
+	/**
1583
+	 * Get the status object of this object
1584
+	 *
1585
+	 * @return EE_Base_Class|EE_Status
1586
+	 * @throws EE_Error
1587
+	 * @throws InvalidArgumentException
1588
+	 * @throws InvalidDataTypeException
1589
+	 * @throws InvalidInterfaceException
1590
+	 * @throws ReflectionException
1591
+	 */
1592
+	public function status_obj()
1593
+	{
1594
+		return $this->get_first_related('Status');
1595
+	}
1596
+
1597
+
1598
+	/**
1599
+	 * Returns the number of times this registration has checked into any of the datetimes it's available for
1600
+	 *
1601
+	 * @return int
1602
+	 * @throws EE_Error
1603
+	 * @throws InvalidArgumentException
1604
+	 * @throws InvalidDataTypeException
1605
+	 * @throws InvalidInterfaceException
1606
+	 * @throws ReflectionException
1607
+	 */
1608
+	public function count_checkins()
1609
+	{
1610
+		return $this->get_model()->count_related($this, 'Checkin');
1611
+	}
1612
+
1613
+
1614
+	/**
1615
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1616
+	 * registration is for.  Note, this is ONLY checked in (does not include checked out)
1617
+	 *
1618
+	 * @return int
1619
+	 * @throws EE_Error
1620
+	 * @throws InvalidArgumentException
1621
+	 * @throws InvalidDataTypeException
1622
+	 * @throws InvalidInterfaceException
1623
+	 * @throws ReflectionException
1624
+	 */
1625
+	public function count_checkins_not_checkedout()
1626
+	{
1627
+		return $this->get_model()->count_related($this, 'Checkin', [['CHK_in' => 1]]);
1628
+	}
1629
+
1630
+
1631
+	/**
1632
+	 * The purpose of this method is simply to check whether this registration can check in to the given datetime.
1633
+	 *
1634
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1635
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1636
+	 *                                          consider registration status as well as datetime access.
1637
+	 * @return bool
1638
+	 * @throws EE_Error
1639
+	 * @throws InvalidArgumentException
1640
+	 * @throws InvalidDataTypeException
1641
+	 * @throws InvalidInterfaceException
1642
+	 * @throws ReflectionException
1643
+	 */
1644
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1645
+	{
1646
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1647
+		// first check registration status
1648
+		if (! $DTT_ID || ($check_approved && ! $this->is_approved())) {
1649
+			return false;
1650
+		}
1651
+		// is there a datetime ticket that matches this dtt_ID?
1652
+		if (
1653
+			! (EEM_Datetime_Ticket::instance()->exists(
1654
+				[
1655
+					[
1656
+						'TKT_ID' => $this->get('TKT_ID'),
1657
+						'DTT_ID' => $DTT_ID,
1658
+					],
1659
+				]
1660
+			))
1661
+		) {
1662
+			return false;
1663
+		}
1664
+
1665
+		// final check is against TKT_uses
1666
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1667
+	}
1668
+
1669
+
1670
+	/**
1671
+	 * This method verifies whether the user can check in for the given datetime considering the max uses value set on
1672
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1673
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1674
+	 * then return false.  Otherwise return true.
1675
+	 *
1676
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1677
+	 * @return bool true means can check in.  false means cannot check in.
1678
+	 * @throws EE_Error
1679
+	 * @throws InvalidArgumentException
1680
+	 * @throws InvalidDataTypeException
1681
+	 * @throws InvalidInterfaceException
1682
+	 * @throws ReflectionException
1683
+	 */
1684
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1685
+	{
1686
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1687
+
1688
+		if (! $DTT_ID) {
1689
+			return false;
1690
+		}
1691
+
1692
+		$max_uses = $this->ticket() instanceof EE_Ticket
1693
+			? $this->ticket()->uses()
1694
+			: EE_INF;
1695
+
1696
+		// if max uses is not set or equals infinity then return true
1697
+		// because it's not a factor for whether user can check in or not.
1698
+		if (! $max_uses || $max_uses === EE_INF) {
1699
+			return true;
1700
+		}
1701
+
1702
+		// does this datetime have a check-in record?  If so, then the dtt count has already been verified so we can just
1703
+		// go ahead and toggle.
1704
+		if (EEM_Checkin::instance()->exists([['REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID]])) {
1705
+			return true;
1706
+		}
1707
+
1708
+		// made it here so the last check is whether the number of check-ins per unique datetime on this registration
1709
+		// disallows further check-ins.
1710
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1711
+			[
1712
+				[
1713
+					'REG_ID' => $this->ID(),
1714
+					'CHK_in' => true,
1715
+				],
1716
+			],
1717
+			'DTT_ID',
1718
+			true
1719
+		);
1720
+		// check-ins have already reached their max number of uses
1721
+		// so registrant can NOT check in
1722
+		if ($count_unique_dtt_checkins >= $max_uses) {
1723
+			EE_Error::add_error(
1724
+				esc_html__(
1725
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1726
+					'event_espresso'
1727
+				),
1728
+				__FILE__,
1729
+				__FUNCTION__,
1730
+				__LINE__
1731
+			);
1732
+			return false;
1733
+		}
1734
+		return true;
1735
+	}
1736
+
1737
+
1738
+	/**
1739
+	 * toggle Check-in status for this registration
1740
+	 * Check-ins are toggled in the following order:
1741
+	 * never checked in -> checked in
1742
+	 * checked in -> checked out
1743
+	 * checked out -> checked in
1744
+	 *
1745
+	 * @param int  $DTT_ID  include specific datetime to toggle Check-in for.
1746
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1747
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1748
+	 *                      can be checked in or not.  Otherwise this forces change in check-in status.
1749
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1750
+	 * @throws EE_Error
1751
+	 * @throws InvalidArgumentException
1752
+	 * @throws InvalidDataTypeException
1753
+	 * @throws InvalidInterfaceException
1754
+	 * @throws ReflectionException
1755
+	 */
1756
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1757
+	{
1758
+		if (empty($DTT_ID)) {
1759
+			$datetime = $this->get_latest_related_datetime();
1760
+			$DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1761
+			// verify the registration can check in for the given DTT_ID
1762
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1763
+			EE_Error::add_error(
1764
+				sprintf(
1765
+					esc_html__(
1766
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1767
+						'event_espresso'
1768
+					),
1769
+					$this->ID(),
1770
+					$DTT_ID
1771
+				),
1772
+				__FILE__,
1773
+				__FUNCTION__,
1774
+				__LINE__
1775
+			);
1776
+			return false;
1777
+		}
1778
+		$status_paths = [
1779
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1780
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1781
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1782
+		];
1783
+		// start by getting the current status so we know what status we'll be changing to.
1784
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1785
+		$status_to  = $status_paths[ $cur_status ];
1786
+		// database only records true for checked IN or false for checked OUT
1787
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1788
+		$new_status = $status_to === EE_Checkin::status_checked_in;
1789
+		// add relation - note Check-ins are always creating new rows
1790
+		// because we are keeping track of Check-ins over time.
1791
+		// Eventually we'll probably want to show a list table
1792
+		// for the individual Check-ins so that they can be managed.
1793
+		$checkin = EE_Checkin::new_instance(
1794
+			[
1795
+				'REG_ID' => $this->ID(),
1796
+				'DTT_ID' => $DTT_ID,
1797
+				'CHK_in' => $new_status,
1798
+			]
1799
+		);
1800
+		// if the record could not be saved then return false
1801
+		if ($checkin->save() === 0) {
1802
+			if (WP_DEBUG) {
1803
+				global $wpdb;
1804
+				$error = sprintf(
1805
+					esc_html__(
1806
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1807
+						'event_espresso'
1808
+					),
1809
+					'<br />',
1810
+					$wpdb->last_error
1811
+				);
1812
+			} else {
1813
+				$error = esc_html__(
1814
+					'Registration check in update failed because of an unknown database error',
1815
+					'event_espresso'
1816
+				);
1817
+			}
1818
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1819
+			return false;
1820
+		}
1821
+		// Fire a checked_in and checkout_out action.
1822
+		$checked_status = $status_to === EE_Checkin::status_checked_in
1823
+			? 'checked_in'
1824
+			: 'checked_out';
1825
+		do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1826
+		return $status_to;
1827
+	}
1828
+
1829
+
1830
+	/**
1831
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1832
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1833
+	 *
1834
+	 * @return EE_Datetime|null
1835
+	 * @throws EE_Error
1836
+	 * @throws InvalidArgumentException
1837
+	 * @throws InvalidDataTypeException
1838
+	 * @throws InvalidInterfaceException
1839
+	 * @throws ReflectionException
1840
+	 */
1841
+	public function get_latest_related_datetime(): ?EE_Datetime
1842
+	{
1843
+		return EEM_Datetime::instance()->get_one(
1844
+			[
1845
+				[
1846
+					'Ticket.Registration.REG_ID' => $this->ID(),
1847
+				],
1848
+				'order_by' => ['DTT_EVT_start' => 'DESC'],
1849
+			]
1850
+		);
1851
+	}
1852
+
1853
+
1854
+	/**
1855
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1856
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1857
+	 *
1858
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1859
+	 * @throws EE_Error
1860
+	 * @throws InvalidArgumentException
1861
+	 * @throws InvalidDataTypeException
1862
+	 * @throws InvalidInterfaceException
1863
+	 * @throws ReflectionException
1864
+	 */
1865
+	public function get_earliest_related_datetime()
1866
+	{
1867
+		return EEM_Datetime::instance()->get_one(
1868
+			[
1869
+				[
1870
+					'Ticket.Registration.REG_ID' => $this->ID(),
1871
+				],
1872
+				'order_by' => ['DTT_EVT_start' => 'ASC'],
1873
+			]
1874
+		);
1875
+	}
1876
+
1877
+
1878
+	/**
1879
+	 * This method simply returns the check-in status for this registration and the given datetime.
1880
+	 * If neither the datetime nor the check-in values are provided as arguments,
1881
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1882
+	 *
1883
+	 * @param int|null        $DTT_ID  The ID of the datetime we're checking against
1884
+	 *                                 (if empty we'll get the primary datetime for
1885
+	 *                                 this registration (via event) and use its ID);
1886
+	 * @param EE_Checkin|null $checkin If present, we use the given check-in object rather than the dtt_id.
1887
+	 * @return int                     Integer representing Check-in status.
1888
+	 * @throws EE_Error
1889
+	 * @throws ReflectionException
1890
+	 */
1891
+	public function check_in_status_for_datetime(?int $DTT_ID = 0, ?EE_Checkin $checkin = null): int
1892
+	{
1893
+		if ($checkin instanceof EE_Checkin) {
1894
+			return $checkin->status();
1895
+		}
1896
+
1897
+		if (! $DTT_ID) {
1898
+			return EE_Checkin::status_invalid;
1899
+		}
1900
+
1901
+		$checkin_query_params = [
1902
+			0          => ['DTT_ID' => $DTT_ID],
1903
+			'order_by' => ['CHK_timestamp' => 'DESC'],
1904
+		];
1905
+
1906
+		$checkin = $this->get_first_related(
1907
+			'Checkin',
1908
+			$checkin_query_params
1909
+		);
1910
+		return $checkin instanceof EE_Checkin ? $checkin->status() : EE_Checkin::status_checked_never;
1911
+	}
1912
+
1913
+
1914
+	/**
1915
+	 * This method returns a localized message for the toggled Check-in message.
1916
+	 *
1917
+	 * @param int|null $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1918
+	 *                         then it is assumed Check-in for primary datetime was toggled.
1919
+	 * @param bool     $error  This just flags that you want an error message returned. This is put in so that the error
1920
+	 *                         message can be customized with the attendee name.
1921
+	 * @return string internationalized message
1922
+	 * @throws EE_Error
1923
+	 * @throws ReflectionException
1924
+	 */
1925
+	public function get_checkin_msg(?int $DTT_ID, bool $error = false): string
1926
+	{
1927
+		// let's get the attendee first so we can include the name of the attendee
1928
+		$attendee = $this->attendee();
1929
+		if ($attendee instanceof EE_Attendee) {
1930
+			if ($error) {
1931
+				return sprintf(
1932
+					esc_html__("%s's check-in status was not changed.", "event_espresso"),
1933
+					$attendee->full_name()
1934
+				);
1935
+			}
1936
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1937
+			// what is the status message going to be?
1938
+			switch ($cur_status) {
1939
+				case EE_Checkin::status_checked_never:
1940
+					return sprintf(
1941
+						esc_html__('%s has been removed from Check-in records', 'event_espresso'),
1942
+						$attendee->full_name()
1943
+					);
1944
+				case EE_Checkin::status_checked_in:
1945
+					return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1946
+				case EE_Checkin::status_checked_out:
1947
+					return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1948
+			}
1949
+		}
1950
+		return esc_html__('The check-in status could not be determined.', 'event_espresso');
1951
+	}
1952
+
1953
+
1954
+	/**
1955
+	 * Returns the related EE_Transaction to this registration
1956
+	 *
1957
+	 * @return EE_Transaction
1958
+	 * @throws EE_Error
1959
+	 * @throws EntityNotFoundException
1960
+	 * @throws ReflectionException
1961
+	 */
1962
+	public function transaction(): EE_Transaction
1963
+	{
1964
+		$TXN_ID = $this->transaction_ID();
1965
+		$transaction = $TXN_ID
1966
+			? EEM_Transaction::instance()->get_one_by_ID($TXN_ID)
1967
+			: $this->get_one_from_cache('Transaction');
1968
+		if (! $transaction instanceof \EE_Transaction) {
1969
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1970
+		}
1971
+		return $transaction;
1972
+	}
1973
+
1974
+
1975
+	/**
1976
+	 * get Registration Code
1977
+	 *
1978
+	 * @return string
1979
+	 * @throws EE_Error
1980
+	 * @throws InvalidArgumentException
1981
+	 * @throws InvalidDataTypeException
1982
+	 * @throws InvalidInterfaceException
1983
+	 * @throws ReflectionException
1984
+	 */
1985
+	public function reg_code(): string
1986
+	{
1987
+		return $this->get('REG_code')
1988
+			?: '';
1989
+	}
1990
+
1991
+
1992
+	/**
1993
+	 * @return mixed
1994
+	 * @throws EE_Error
1995
+	 * @throws InvalidArgumentException
1996
+	 * @throws InvalidDataTypeException
1997
+	 * @throws InvalidInterfaceException
1998
+	 * @throws ReflectionException
1999
+	 */
2000
+	public function transaction_ID()
2001
+	{
2002
+		return $this->get('TXN_ID');
2003
+	}
2004
+
2005
+
2006
+	/**
2007
+	 * @return int
2008
+	 * @throws EE_Error
2009
+	 * @throws InvalidArgumentException
2010
+	 * @throws InvalidDataTypeException
2011
+	 * @throws InvalidInterfaceException
2012
+	 * @throws ReflectionException
2013
+	 */
2014
+	public function ticket_ID()
2015
+	{
2016
+		return $this->get('TKT_ID');
2017
+	}
2018
+
2019
+
2020
+	/**
2021
+	 * Set Registration Code
2022
+	 *
2023
+	 * @param RegCode|string $REG_code Registration Code
2024
+	 * @param boolean        $use_default
2025
+	 * @throws EE_Error
2026
+	 * @throws InvalidArgumentException
2027
+	 * @throws InvalidDataTypeException
2028
+	 * @throws InvalidInterfaceException
2029
+	 * @throws ReflectionException
2030
+	 */
2031
+	public function set_reg_code($REG_code, bool $use_default = false)
2032
+	{
2033
+		if (! $this->reg_code()) {
2034
+			parent::set('REG_code', $REG_code, $use_default);
2035
+		} elseif (empty($REG_code)) {
2036
+			EE_Error::add_error(
2037
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
2038
+				__FILE__,
2039
+				__FUNCTION__,
2040
+				__LINE__
2041
+			);
2042
+		} else {
2043
+			EE_Error::doing_it_wrong(
2044
+				__CLASS__ . '::' . __FUNCTION__,
2045
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
2046
+				'4.6.0'
2047
+			);
2048
+		}
2049
+	}
2050
+
2051
+
2052
+	/**
2053
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
2054
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
2055
+	 *    $registration->transaction()->registrations();
2056
+	 *
2057
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
2058
+	 * @throws EE_Error
2059
+	 * @throws InvalidArgumentException
2060
+	 * @throws InvalidDataTypeException
2061
+	 * @throws InvalidInterfaceException
2062
+	 * @throws ReflectionException
2063
+	 * @since 4.5.0
2064
+	 */
2065
+	public function get_all_other_registrations_in_group(bool $with_same_ticket = true): array
2066
+	{
2067
+		if ($this->group_size() < 2) {
2068
+			return [];
2069
+		}
2070
+
2071
+		$query[0] = [
2072
+			'TXN_ID' => $this->transaction_ID(),
2073
+			'REG_ID' => ['!=', $this->ID()],
2074
+		];
2075
+
2076
+		if ($with_same_ticket) {
2077
+			$query[0]['TKT_ID'] = $this->ticket_ID();
2078
+		}
2079
+		/** @var EE_Registration[] $registrations */
2080
+		$registrations = $this->get_model()->get_all($query);
2081
+		return $registrations;
2082
+	}
2083
+
2084
+
2085
+	/**
2086
+	 * Return the link to the admin details for the object.
2087
+	 *
2088
+	 * @return string
2089
+	 * @throws EE_Error
2090
+	 * @throws InvalidArgumentException
2091
+	 * @throws InvalidDataTypeException
2092
+	 * @throws InvalidInterfaceException
2093
+	 * @throws ReflectionException
2094
+	 */
2095
+	public function get_admin_details_link()
2096
+	{
2097
+		EE_Registry::instance()->load_helper('URL');
2098
+		return EEH_URL::add_query_args_and_nonce(
2099
+			[
2100
+				'page'    => 'espresso_registrations',
2101
+				'action'  => 'view_registration',
2102
+				'_REG_ID' => $this->ID(),
2103
+			],
2104
+			admin_url('admin.php')
2105
+		);
2106
+	}
2107
+
2108
+
2109
+	/**
2110
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
2111
+	 *
2112
+	 * @return string
2113
+	 * @throws EE_Error
2114
+	 * @throws InvalidArgumentException
2115
+	 * @throws InvalidDataTypeException
2116
+	 * @throws InvalidInterfaceException
2117
+	 * @throws ReflectionException
2118
+	 */
2119
+	public function get_admin_edit_link()
2120
+	{
2121
+		return $this->get_admin_details_link();
2122
+	}
2123
+
2124
+
2125
+	/**
2126
+	 * Returns the link to a settings page for the object.
2127
+	 *
2128
+	 * @return string
2129
+	 * @throws EE_Error
2130
+	 * @throws InvalidArgumentException
2131
+	 * @throws InvalidDataTypeException
2132
+	 * @throws InvalidInterfaceException
2133
+	 * @throws ReflectionException
2134
+	 */
2135
+	public function get_admin_settings_link()
2136
+	{
2137
+		return $this->get_admin_details_link();
2138
+	}
2139
+
2140
+
2141
+	/**
2142
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
2143
+	 *
2144
+	 * @return string
2145
+	 * @throws EE_Error
2146
+	 * @throws InvalidArgumentException
2147
+	 * @throws InvalidDataTypeException
2148
+	 * @throws InvalidInterfaceException
2149
+	 * @throws ReflectionException
2150
+	 */
2151
+	public function get_admin_overview_link()
2152
+	{
2153
+		EE_Registry::instance()->load_helper('URL');
2154
+		return EEH_URL::add_query_args_and_nonce(
2155
+			[
2156
+				'page' => 'espresso_registrations',
2157
+			],
2158
+			admin_url('admin.php')
2159
+		);
2160
+	}
2161
+
2162
+
2163
+	/**
2164
+	 * @param array $query_params
2165
+	 * @return EE_Base_Class[]|EE_Registration[]
2166
+	 * @throws EE_Error
2167
+	 * @throws InvalidArgumentException
2168
+	 * @throws InvalidDataTypeException
2169
+	 * @throws InvalidInterfaceException
2170
+	 * @throws ReflectionException
2171
+	 */
2172
+	public function payments($query_params = [])
2173
+	{
2174
+		return $this->get_many_related('Payment', $query_params);
2175
+	}
2176
+
2177
+
2178
+	/**
2179
+	 * @param array $query_params
2180
+	 * @return EE_Base_Class[]|EE_Registration_Payment[]
2181
+	 * @throws EE_Error
2182
+	 * @throws InvalidArgumentException
2183
+	 * @throws InvalidDataTypeException
2184
+	 * @throws InvalidInterfaceException
2185
+	 * @throws ReflectionException
2186
+	 */
2187
+	public function registration_payments($query_params = [])
2188
+	{
2189
+		return $this->get_many_related('Registration_Payment', $query_params);
2190
+	}
2191
+
2192
+
2193
+	/**
2194
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
2195
+	 * Note: if there are no payments on the registration there will be no payment method returned.
2196
+	 *
2197
+	 * @return EE_Payment|EE_Payment_Method|null
2198
+	 * @throws EE_Error
2199
+	 * @throws InvalidArgumentException
2200
+	 * @throws InvalidDataTypeException
2201
+	 * @throws InvalidInterfaceException
2202
+	 */
2203
+	public function payment_method()
2204
+	{
2205
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
2206
+	}
2207
+
2208
+
2209
+	/**
2210
+	 * @return \EE_Line_Item
2211
+	 * @throws EE_Error
2212
+	 * @throws EntityNotFoundException
2213
+	 * @throws InvalidArgumentException
2214
+	 * @throws InvalidDataTypeException
2215
+	 * @throws InvalidInterfaceException
2216
+	 * @throws ReflectionException
2217
+	 */
2218
+	public function ticket_line_item()
2219
+	{
2220
+		$ticket            = $this->ticket();
2221
+		$transaction       = $this->transaction();
2222
+		$line_item         = null;
2223
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
2224
+			$transaction->total_line_item(),
2225
+			'Ticket',
2226
+			[$ticket->ID()]
2227
+		);
2228
+		foreach ($ticket_line_items as $ticket_line_item) {
2229
+			if (
2230
+				$ticket_line_item instanceof \EE_Line_Item
2231
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
2232
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
2233
+			) {
2234
+				$line_item = $ticket_line_item;
2235
+				break;
2236
+			}
2237
+		}
2238
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
2239
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
2240
+		}
2241
+		return $line_item;
2242
+	}
2243
+
2244
+
2245
+	/**
2246
+	 * Soft Deletes this model object.
2247
+	 *
2248
+	 * @return int
2249
+	 * @throws DomainException
2250
+	 * @throws EE_Error
2251
+	 * @throws EntityNotFoundException
2252
+	 * @throws InvalidArgumentException
2253
+	 * @throws InvalidDataTypeException
2254
+	 * @throws InvalidInterfaceException
2255
+	 * @throws ReflectionException
2256
+	 * @throws RuntimeException
2257
+	 * @throws UnexpectedEntityException
2258
+	 */
2259
+	public function delete()
2260
+	{
2261
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
2262
+			$this->set_status(
2263
+				RegStatus::CANCELLED,
2264
+				false,
2265
+				new Context(
2266
+					__METHOD__,
2267
+					esc_html__('Executed when a registration is trashed.', 'event_espresso')
2268
+				)
2269
+			);
2270
+		}
2271
+		return parent::delete();
2272
+	}
2273
+
2274
+
2275
+	/**
2276
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
2277
+	 *
2278
+	 * @return int
2279
+	 * @throws DomainException
2280
+	 * @throws EE_Error
2281
+	 * @throws EntityNotFoundException
2282
+	 * @throws InvalidArgumentException
2283
+	 * @throws InvalidDataTypeException
2284
+	 * @throws InvalidInterfaceException
2285
+	 * @throws ReflectionException
2286
+	 * @throws RuntimeException
2287
+	 * @throws UnexpectedEntityException
2288
+	 */
2289
+	public function restore(): int
2290
+	{
2291
+		$previous_status = $this->get_extra_meta(
2292
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
2293
+			true,
2294
+			RegStatus::CANCELLED
2295
+		);
2296
+		if ($previous_status) {
2297
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
2298
+			$this->set_status(
2299
+				$previous_status,
2300
+				false,
2301
+				new Context(
2302
+					__METHOD__,
2303
+					esc_html__('Executed when a trashed registration is restored.', 'event_espresso')
2304
+				)
2305
+			);
2306
+		}
2307
+		return parent::restore();
2308
+	}
2309
+
2310
+
2311
+	/**
2312
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
2313
+	 *
2314
+	 * @param boolean $trigger_set_status_logic  EE_Registration::set_status() can trigger additional logic
2315
+	 *                                           depending on whether the reg status changes to or from "Approved"
2316
+	 * @return boolean whether the Registration status was updated
2317
+	 * @throws DomainException
2318
+	 * @throws EE_Error
2319
+	 * @throws EntityNotFoundException
2320
+	 * @throws InvalidArgumentException
2321
+	 * @throws InvalidDataTypeException
2322
+	 * @throws InvalidInterfaceException
2323
+	 * @throws ReflectionException
2324
+	 * @throws RuntimeException
2325
+	 * @throws UnexpectedEntityException
2326
+	 */
2327
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2328
+	{
2329
+		$paid  = $this->paid();
2330
+		$price = $this->final_price();
2331
+		switch (true) {
2332
+			// overpaid or paid
2333
+			case EEH_Money::compare_floats($paid, $price, '>'):
2334
+			case EEH_Money::compare_floats($paid, $price):
2335
+				$new_status = RegStatus::APPROVED;
2336
+				break;
2337
+			//  underpaid
2338
+			case EEH_Money::compare_floats($paid, $price, '<'):
2339
+				$new_status = RegStatus::PENDING_PAYMENT;
2340
+				break;
2341
+			// uhhh Houston...
2342
+			default:
2343
+				throw new RuntimeException(
2344
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2345
+				);
2346
+		}
2347
+		if ($new_status !== $this->status_ID()) {
2348
+			if ($trigger_set_status_logic) {
2349
+				return $this->set_status(
2350
+					$new_status,
2351
+					false,
2352
+					new Context(
2353
+						__METHOD__,
2354
+						esc_html__(
2355
+							'Executed when the registration status is updated based on total paid.',
2356
+							'event_espresso'
2357
+						)
2358
+					)
2359
+				);
2360
+			}
2361
+			parent::set('STS_ID', $new_status);
2362
+			return true;
2363
+		}
2364
+		return false;
2365
+	}
2366
+
2367
+
2368
+	/*************************** DEPRECATED ***************************/
2369
+
2370
+
2371
+	/**
2372
+	 * @deprecated
2373
+	 * @since     4.7.0
2374
+	 */
2375
+	public function price_paid()
2376
+	{
2377
+		EE_Error::doing_it_wrong(
2378
+			'EE_Registration::price_paid()',
2379
+			esc_html__(
2380
+				'This method is deprecated, please use EE_Registration::final_price() instead.',
2381
+				'event_espresso'
2382
+			),
2383
+			'4.7.0'
2384
+		);
2385
+		return $this->final_price();
2386
+	}
2387
+
2388
+
2389
+	/**
2390
+	 * @param float $REG_final_price
2391
+	 * @throws EE_Error
2392
+	 * @throws EntityNotFoundException
2393
+	 * @throws InvalidArgumentException
2394
+	 * @throws InvalidDataTypeException
2395
+	 * @throws InvalidInterfaceException
2396
+	 * @throws ReflectionException
2397
+	 * @throws RuntimeException
2398
+	 * @throws DomainException
2399
+	 * @deprecated
2400
+	 * @since     4.7.0
2401
+	 */
2402
+	public function set_price_paid($REG_final_price = 0.00)
2403
+	{
2404
+		EE_Error::doing_it_wrong(
2405
+			'EE_Registration::set_price_paid()',
2406
+			esc_html__(
2407
+				'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2408
+				'event_espresso'
2409
+			),
2410
+			'4.7.0'
2411
+		);
2412
+		$this->set_final_price($REG_final_price);
2413
+	}
2414
+
2415
+
2416
+	/**
2417
+	 * @return string
2418
+	 * @throws EE_Error
2419
+	 * @throws InvalidArgumentException
2420
+	 * @throws InvalidDataTypeException
2421
+	 * @throws InvalidInterfaceException
2422
+	 * @throws ReflectionException
2423
+	 * @deprecated
2424
+	 * @since 4.7.0
2425
+	 */
2426
+	public function pretty_price_paid()
2427
+	{
2428
+		EE_Error::doing_it_wrong(
2429
+			'EE_Registration::pretty_price_paid()',
2430
+			esc_html__(
2431
+				'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2432
+				'event_espresso'
2433
+			),
2434
+			'4.7.0'
2435
+		);
2436
+		return $this->pretty_final_price();
2437
+	}
2438
+
2439
+
2440
+	/**
2441
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2442
+	 *
2443
+	 * @return EE_Datetime
2444
+	 * @throws EE_Error
2445
+	 * @throws EntityNotFoundException
2446
+	 * @throws InvalidArgumentException
2447
+	 * @throws InvalidDataTypeException
2448
+	 * @throws InvalidInterfaceException
2449
+	 * @throws ReflectionException
2450
+	 * @deprecated 4.9.17
2451
+	 */
2452
+	public function get_related_primary_datetime()
2453
+	{
2454
+		EE_Error::doing_it_wrong(
2455
+			__METHOD__,
2456
+			esc_html__(
2457
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2458
+				'event_espresso'
2459
+			),
2460
+			'4.9.17',
2461
+			'5.0.0'
2462
+		);
2463
+		return $this->event()->primary_datetime();
2464
+	}
2465
+
2466
+
2467
+	/**
2468
+	 * Returns the contact's name (or "Unknown" if there is no contact.)
2469
+	 *
2470
+	 * @return string
2471
+	 * @throws EE_Error
2472
+	 * @throws InvalidArgumentException
2473
+	 * @throws InvalidDataTypeException
2474
+	 * @throws InvalidInterfaceException
2475
+	 * @throws ReflectionException
2476
+	 * @since 4.10.12.p
2477
+	 */
2478
+	public function name()
2479
+	{
2480
+		return $this->attendeeName();
2481
+	}
2482
+
2483
+
2484
+	/**
2485
+	 * @return bool
2486
+	 * @throws EE_Error
2487
+	 * @throws ReflectionException
2488
+	 */
2489
+	public function wasMoved(): bool
2490
+	{
2491
+		// only need to check 'registration-moved-to' because
2492
+		// the existence of a new REG ID means the registration was moved
2493
+		$reg_moved = $this->get_extra_meta('registration-moved-to', true, []);
2494
+		return isset($reg_moved['NEW_REG_ID']) && $reg_moved['NEW_REG_ID'];
2495
+	}
2496
+
2497
+
2498
+	/**
2499
+	 * @param EE_Payment $payment
2500
+	 * @param float|null $amount
2501
+	 * @return float
2502
+	 * @throws EE_Error
2503
+	 * @throws ReflectionException
2504
+	 * @since 5.0.8.p
2505
+	 */
2506
+	public function applyPayment(EE_Payment $payment, ?float $amount = null): float
2507
+	{
2508
+		$payment_amount = $amount ?? $payment->amount();
2509
+		// ensure $payment_amount is NOT negative
2510
+		$payment_amount = (float) abs($payment_amount);
2511
+		$payment_amount = $payment->is_a_refund()
2512
+			? $this->processRefund($payment_amount)
2513
+			: $this->processPayment($payment_amount);
2514
+		if ($payment_amount) {
2515
+			$reg_payment = EEM_Registration_Payment::instance()->get_one(
2516
+				[['REG_ID' => $this->ID(), 'PAY_ID' => $payment->ID()]]
2517
+			);
2518
+			// if existing registration payment exists
2519
+			if ($reg_payment instanceof EE_Registration_Payment) {
2520
+				// then update that record
2521
+				$reg_payment->set_amount($payment_amount);
2522
+			} else {
2523
+				// or add new relation between registration and payment and set amount
2524
+				$reg_payment = EE_Registration_Payment::new_instance(
2525
+					[
2526
+						'REG_ID'     => $this->ID(),
2527
+						'PAY_ID'     => $payment->ID(),
2528
+						'RPY_amount' => $payment_amount,
2529
+					]
2530
+				);
2531
+			}
2532
+			$reg_payment->save();
2533
+		}
2534
+		return $payment_amount;
2535
+	}
2536
+
2537
+
2538
+	/**
2539
+	 * @throws EE_Error
2540
+	 * @throws ReflectionException
2541
+	 */
2542
+	private function processPayment(float $payment_amount): float
2543
+	{
2544
+		$paid  = $this->paid();
2545
+		$owing = $this->final_price() - $paid;
2546
+		if ($owing <= 0) {
2547
+			return 0.0;
2548
+		}
2549
+		// don't allow payment amount to exceed the incoming amount, OR the amount owing
2550
+		$payment_amount = min($payment_amount, $owing);
2551
+		$paid           = $paid + $payment_amount;
2552
+		// calculate and set new REG_paid
2553
+		$this->set_paid($paid);
2554
+		// make it stick
2555
+		$this->save();
2556
+		return (float) $payment_amount;
2557
+	}
2558
+
2559
+
2560
+	/**
2561
+	 * @throws ReflectionException
2562
+	 * @throws EE_Error
2563
+	 */
2564
+	private function processRefund(float $payment_amount): float
2565
+	{
2566
+		$paid = $this->paid();
2567
+		if ($paid <= 0) {
2568
+			return 0.0;
2569
+		}
2570
+		// don't allow refund amount to exceed the incoming amount, OR the amount paid
2571
+		$payment_amount = min($payment_amount, $paid);
2572
+		// calculate and set new REG_paid
2573
+		$paid = $paid - $payment_amount;
2574
+		$this->set_paid($paid);
2575
+		// make it stick
2576
+		$this->save();
2577
+		// convert payment amount back to a negative value for storage in the db
2578
+		return (float) $payment_amount;
2579
+	}
2580
+
2581
+
2582
+	/**
2583
+	 * @return string
2584
+	 * @throws EE_Error
2585
+	 * @throws ReflectionException
2586
+	 * @since 5.0.20.p
2587
+	 */
2588
+	public function defaultRegistrationStatus(): string
2589
+	{
2590
+		$default_event_reg_status = $this->event()->default_registration_status();
2591
+		$default_reg_status = (string) apply_filters(
2592
+			'AFEE__EE_Registration__defaultRegistrationStatus__default_reg_status',
2593
+			$default_event_reg_status,
2594
+			$this
2595
+		);
2596
+		return RegStatus::isValidStatus($default_reg_status, false)
2597
+			? $default_reg_status
2598
+			: $default_event_reg_status;
2599
+	}
2600
+
2601
+
2602
+	/**
2603
+	 * @return string
2604
+	 * @throws EE_Error
2605
+	 * @throws ReflectionException
2606
+	 * @since 5.0.30.p
2607
+	 */
2608
+	public function cancelRegistrationConfirmationCode(): string
2609
+	{
2610
+		// concatenate all the fields that make up the source string
2611
+		// ex: 944-1084-720-379-7-2024-10-11 18:21:00-626-379-7-2ff6
2612
+		$source_string = $this->ID() . $this->event_ID() . $this->attendee_ID() . $this->ticket_ID();
2613
+		$source_string .= $this->count() . $this->reg_date() . $this->reg_code();
2614
+		// create a hash of the source string, ex: a9c0d28f79b5602a428e386821015420
2615
+		$source_string = md5($source_string);
2616
+		// return the first 4 characters of the hash in uppercase, ex: A9C0
2617
+		return strtoupper(substr($source_string, 0, 4));
2618
+	}
2619 2619
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
     {
121 121
         switch ($field_name) {
122 122
             case 'REG_code':
123
-                if (! empty($field_value) && ! $this->reg_code()) {
123
+                if ( ! empty($field_value) && ! $this->reg_code()) {
124 124
                     $this->set_reg_code($field_value, $use_default);
125 125
                 }
126 126
                 break;
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
             $this
168 168
         );
169 169
         // it's still good to allow the parent set method to have a say
170
-        parent::set('STS_ID', (! empty($new_STS_ID) ? $new_STS_ID : null), $use_default);
170
+        parent::set('STS_ID', ( ! empty($new_STS_ID) ? $new_STS_ID : null), $use_default);
171 171
         // if status has changed
172 172
         if (
173 173
             $old_STS_ID !== $new_STS_ID // and that status has actually changed
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
     public function event(): EE_Event
420 420
     {
421 421
         $event = $this->event_obj();
422
-        if (! $event instanceof EE_Event) {
422
+        if ( ! $event instanceof EE_Event) {
423 423
             throw new EntityNotFoundException('Event ID', $this->event_ID());
424 424
         }
425 425
         return $event;
@@ -462,7 +462,7 @@  discard block
 block discarded – undo
462 462
     {
463 463
         // reserved ticket and datetime counts will be decremented as sold counts are incremented
464 464
         // so stop tracking that this reg has a ticket reserved
465
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
465
+        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:".__LINE__.')');
466 466
         $ticket = $this->ticket();
467 467
         $ticket->increaseSold();
468 468
         // possibly set event status to sold out
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
             $reserved = $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
513 513
             if ($reserved && $update_ticket) {
514 514
                 $ticket = $this->ticket();
515
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
515
+                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:".__LINE__.')');
516 516
                 // comment out extra meta tracking
517 517
                 // $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
518 518
                 $ticket->save();
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
             $released = $this->delete_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true);
542 542
             if ($released && $update_ticket) {
543 543
                 $ticket = $this->ticket();
544
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
544
+                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:".__LINE__.')');
545 545
                 // comment out extra meta tracking
546 546
                 // $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
547 547
             }
@@ -1352,7 +1352,7 @@  discard block
 block discarded – undo
1352 1352
             false,
1353 1353
             'sentence'
1354 1354
         );
1355
-        $icon   = '';
1355
+        $icon = '';
1356 1356
         switch ($this->status_ID()) {
1357 1357
             case RegStatus::APPROVED:
1358 1358
                 $icon = $show_icons
@@ -1390,7 +1390,7 @@  discard block
 block discarded – undo
1390 1390
                     : '';
1391 1391
                 break;
1392 1392
         }
1393
-        return $icon . $status[ $this->status_ID() ];
1393
+        return $icon.$status[$this->status_ID()];
1394 1394
     }
1395 1395
 
1396 1396
 
@@ -1645,7 +1645,7 @@  discard block
 block discarded – undo
1645 1645
     {
1646 1646
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1647 1647
         // first check registration status
1648
-        if (! $DTT_ID || ($check_approved && ! $this->is_approved())) {
1648
+        if ( ! $DTT_ID || ($check_approved && ! $this->is_approved())) {
1649 1649
             return false;
1650 1650
         }
1651 1651
         // is there a datetime ticket that matches this dtt_ID?
@@ -1685,7 +1685,7 @@  discard block
 block discarded – undo
1685 1685
     {
1686 1686
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1687 1687
 
1688
-        if (! $DTT_ID) {
1688
+        if ( ! $DTT_ID) {
1689 1689
             return false;
1690 1690
         }
1691 1691
 
@@ -1695,7 +1695,7 @@  discard block
 block discarded – undo
1695 1695
 
1696 1696
         // if max uses is not set or equals infinity then return true
1697 1697
         // because it's not a factor for whether user can check in or not.
1698
-        if (! $max_uses || $max_uses === EE_INF) {
1698
+        if ( ! $max_uses || $max_uses === EE_INF) {
1699 1699
             return true;
1700 1700
         }
1701 1701
 
@@ -1759,7 +1759,7 @@  discard block
 block discarded – undo
1759 1759
             $datetime = $this->get_latest_related_datetime();
1760 1760
             $DTT_ID   = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1761 1761
             // verify the registration can check in for the given DTT_ID
1762
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1762
+        } elseif ( ! $this->can_checkin($DTT_ID, $verify)) {
1763 1763
             EE_Error::add_error(
1764 1764
                 sprintf(
1765 1765
                     esc_html__(
@@ -1782,7 +1782,7 @@  discard block
 block discarded – undo
1782 1782
         ];
1783 1783
         // start by getting the current status so we know what status we'll be changing to.
1784 1784
         $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1785
-        $status_to  = $status_paths[ $cur_status ];
1785
+        $status_to  = $status_paths[$cur_status];
1786 1786
         // database only records true for checked IN or false for checked OUT
1787 1787
         // no record ( null ) means checked in NEVER, but we obviously don't save that
1788 1788
         $new_status = $status_to === EE_Checkin::status_checked_in;
@@ -1894,7 +1894,7 @@  discard block
 block discarded – undo
1894 1894
             return $checkin->status();
1895 1895
         }
1896 1896
 
1897
-        if (! $DTT_ID) {
1897
+        if ( ! $DTT_ID) {
1898 1898
             return EE_Checkin::status_invalid;
1899 1899
         }
1900 1900
 
@@ -1965,7 +1965,7 @@  discard block
 block discarded – undo
1965 1965
         $transaction = $TXN_ID
1966 1966
             ? EEM_Transaction::instance()->get_one_by_ID($TXN_ID)
1967 1967
             : $this->get_one_from_cache('Transaction');
1968
-        if (! $transaction instanceof \EE_Transaction) {
1968
+        if ( ! $transaction instanceof \EE_Transaction) {
1969 1969
             throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1970 1970
         }
1971 1971
         return $transaction;
@@ -2030,7 +2030,7 @@  discard block
 block discarded – undo
2030 2030
      */
2031 2031
     public function set_reg_code($REG_code, bool $use_default = false)
2032 2032
     {
2033
-        if (! $this->reg_code()) {
2033
+        if ( ! $this->reg_code()) {
2034 2034
             parent::set('REG_code', $REG_code, $use_default);
2035 2035
         } elseif (empty($REG_code)) {
2036 2036
             EE_Error::add_error(
@@ -2041,7 +2041,7 @@  discard block
 block discarded – undo
2041 2041
             );
2042 2042
         } else {
2043 2043
             EE_Error::doing_it_wrong(
2044
-                __CLASS__ . '::' . __FUNCTION__,
2044
+                __CLASS__.'::'.__FUNCTION__,
2045 2045
                 esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
2046 2046
                 '4.6.0'
2047 2047
             );
@@ -2235,7 +2235,7 @@  discard block
 block discarded – undo
2235 2235
                 break;
2236 2236
             }
2237 2237
         }
2238
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
2238
+        if ( ! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
2239 2239
             throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
2240 2240
         }
2241 2241
         return $line_item;
@@ -2609,8 +2609,8 @@  discard block
 block discarded – undo
2609 2609
     {
2610 2610
         // concatenate all the fields that make up the source string
2611 2611
         // ex: 944-1084-720-379-7-2024-10-11 18:21:00-626-379-7-2ff6
2612
-        $source_string = $this->ID() . $this->event_ID() . $this->attendee_ID() . $this->ticket_ID();
2613
-        $source_string .= $this->count() . $this->reg_date() . $this->reg_code();
2612
+        $source_string = $this->ID().$this->event_ID().$this->attendee_ID().$this->ticket_ID();
2613
+        $source_string .= $this->count().$this->reg_date().$this->reg_code();
2614 2614
         // create a hash of the source string, ex: a9c0d28f79b5602a428e386821015420
2615 2615
         $source_string = md5($source_string);
2616 2616
         // return the first 4 characters of the hash in uppercase, ex: A9C0
Please login to merge, or discard this patch.
core/db_classes/EE_Question.class.php 2 patches
Indentation   +746 added lines, -746 removed lines patch added patch discarded remove patch
@@ -13,750 +13,750 @@
 block discarded – undo
13 13
  */
14 14
 class EE_Question extends EE_Soft_Delete_Base_Class implements EEI_Duplicatable
15 15
 {
16
-    private ?string $type = null;
17
-
18
-
19
-    /**
20
-     * @param array  $props_n_values          incoming values
21
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
22
-     *                                        used.)
23
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
24
-     *                                        date_format and the second value is the time format
25
-     * @return EE_Question
26
-     * @throws EE_Error
27
-     * @throws ReflectionException
28
-     */
29
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = []): EE_Question
30
-    {
31
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
32
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
33
-    }
34
-
35
-
36
-    /**
37
-     * @param array  $props_n_values  incoming values from the database
38
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
39
-     *                                the website will be used.
40
-     * @return EE_Question
41
-     * @throws EE_Error
42
-     * @throws ReflectionException
43
-     */
44
-    public static function new_instance_from_db($props_n_values = [], $timezone = ''): EE_Question
45
-    {
46
-        return new self($props_n_values, true, $timezone);
47
-    }
48
-
49
-
50
-    /**
51
-     * @return EEM_Question
52
-     * @throws EE_Error
53
-     * @throws ReflectionException
54
-     * @since 5.0.30.p
55
-     */
56
-    private function getModel(): EEM_Question
57
-    {
58
-        return $this->get_model();
59
-    }
60
-
61
-
62
-    /**
63
-     * @param string $QST_display_text
64
-     * @throws EE_Error
65
-     * @throws ReflectionException
66
-     */
67
-    public function set_display_text(string $QST_display_text = '')
68
-    {
69
-        $this->set('QST_display_text', $QST_display_text);
70
-    }
71
-
72
-
73
-    /**
74
-     * @param string $QST_admin_label
75
-     * @throws EE_Error
76
-     * @throws ReflectionException
77
-     */
78
-    public function set_admin_label(string $QST_admin_label = '')
79
-    {
80
-        $this->set('QST_admin_label', $QST_admin_label);
81
-    }
82
-
83
-
84
-    /**
85
-     * @param mixed $QST_system
86
-     * @throws EE_Error
87
-     * @throws ReflectionException
88
-     */
89
-    public function set_system_ID(string $QST_system = '')
90
-    {
91
-        $this->set('QST_system', $QST_system);
92
-    }
93
-
94
-
95
-    /**
96
-     * @param string $QST_type
97
-     * @throws EE_Error
98
-     * @throws ReflectionException
99
-     */
100
-    public function set_question_type(string $QST_type = '')
101
-    {
102
-        $this->set('QST_type', $QST_type);
103
-    }
104
-
105
-
106
-    /**
107
-     * Sets whether this question must be answered when presented in a form
108
-     *
109
-     * @param bool $QST_required
110
-     * @throws EE_Error
111
-     * @throws ReflectionException
112
-     */
113
-    public function set_required(bool $QST_required = false)
114
-    {
115
-        $this->set('QST_required', $QST_required);
116
-    }
117
-
118
-
119
-    /**
120
-     * @param string $QST_required_text
121
-     * @throws EE_Error
122
-     * @throws ReflectionException
123
-     */
124
-    public function set_required_text(string $QST_required_text = '')
125
-    {
126
-        $this->set('QST_required_text', $QST_required_text);
127
-    }
128
-
129
-
130
-    /**
131
-     * Sets the order of this question when placed in a sequence of questions
132
-     *
133
-     * @param int $QST_order
134
-     * @throws EE_Error
135
-     * @throws ReflectionException
136
-     */
137
-    public function set_order(int $QST_order = 0)
138
-    {
139
-        $this->set('QST_order', $QST_order);
140
-    }
141
-
142
-
143
-    /**
144
-     * @param bool $QST_admin_only
145
-     * @throws EE_Error
146
-     * @throws ReflectionException
147
-     */
148
-    public function set_admin_only(bool $QST_admin_only = false)
149
-    {
150
-        $this->set('QST_admin_only', $QST_admin_only);
151
-    }
152
-
153
-
154
-    /**
155
-     * Sets the WordPress user ID on the question
156
-     *
157
-     * @param int $QST_wp_user
158
-     * @throws EE_Error
159
-     * @throws ReflectionException
160
-     */
161
-    public function set_wp_user(int $QST_wp_user = 1)
162
-    {
163
-        $this->set('QST_wp_user', $QST_wp_user);
164
-    }
165
-
166
-
167
-    /**
168
-     * Sets whether the question has been deleted
169
-     * we use this boolean instead of actually deleting it
170
-     * because when users delete this question they really want to remove the question from future forms,
171
-     * BUT keep their old answers which depend on this record actually existing.
172
-     *
173
-     * @param bool $QST_deleted
174
-     * @throws EE_Error
175
-     * @throws ReflectionException
176
-     */
177
-    public function set_deleted(bool $QST_deleted = false)
178
-    {
179
-        $this->set('QST_deleted', $QST_deleted);
180
-    }
181
-
182
-
183
-    /**
184
-     *  used for the input label text displayed to users on the frontend
185
-     *
186
-     * @return string
187
-     * @throws EE_Error
188
-     * @throws ReflectionException
189
-     */
190
-    public function display_text(): string
191
-    {
192
-        return (string) $this->get('QST_display_text');
193
-    }
194
-
195
-
196
-    /**
197
-     * input label used in the admin
198
-     *
199
-     * @return string
200
-     * @throws EE_Error
201
-     * @throws ReflectionException
202
-     */
203
-    public function admin_label(): string
204
-    {
205
-        return (string) $this->get('QST_admin_label');
206
-    }
207
-
208
-
209
-    /**
210
-     * returns the attendee column name for this question
211
-     *
212
-     * @return string
213
-     * @throws EE_Error
214
-     * @throws ReflectionException
215
-     */
216
-    public function system_ID(): string
217
-    {
218
-        return (string) $this->get('QST_system');
219
-    }
220
-
221
-
222
-    /**
223
-     * if question is required or not (boolean)
224
-     *
225
-     * @return bool
226
-     * @throws EE_Error
227
-     * @throws ReflectionException
228
-     */
229
-    public function required(): bool
230
-    {
231
-        return (bool) $this->get('QST_required');
232
-    }
233
-
234
-
235
-    /**
236
-     * returns the text which should be displayed when a user
237
-     * doesn't answer this question in a form
238
-     *
239
-     * @return string
240
-     * @throws EE_Error
241
-     * @throws ReflectionException
242
-     */
243
-    public function required_text(): string
244
-    {
245
-        return (string) $this->get('QST_required_text');
246
-    }
247
-
248
-
249
-    /**
250
-     * returns the type of this question: one of the QST_type_* constants on the EEM_Question model
251
-     *
252
-     * @return string
253
-     * @throws EE_Error
254
-     * @throws ReflectionException
255
-     */
256
-    public function type(): string
257
-    {
258
-        if ($this->type === null) {
259
-            $this->type = (string) $this->get('QST_type');
260
-        }
261
-        return $this->type;
262
-    }
263
-
264
-
265
-    /**
266
-     * returns an integer showing where this question should be placed in a sequence of questions
267
-     *
268
-     * @return int
269
-     * @throws EE_Error
270
-     * @throws ReflectionException
271
-     */
272
-    public function order(): int
273
-    {
274
-        return (int) $this->get('QST_order');
275
-    }
276
-
277
-
278
-    /**
279
-     * returns whether this question should only appear to admins, or to everyone
280
-     *
281
-     * @return bool
282
-     * @throws EE_Error
283
-     * @throws ReflectionException
284
-     */
285
-    public function admin_only(): bool
286
-    {
287
-        return (bool) $this->get('QST_admin_only');
288
-    }
289
-
290
-
291
-    /**
292
-     * returns the id the WordPress user who created this question
293
-     *
294
-     * @return int
295
-     * @throws EE_Error
296
-     * @throws ReflectionException
297
-     */
298
-    public function wp_user(): int
299
-    {
300
-        return (int) $this->get('QST_wp_user');
301
-    }
302
-
303
-
304
-    /**
305
-     * returns whether this question has been marked as 'deleted'
306
-     *
307
-     * @return bool
308
-     * @throws EE_Error
309
-     * @throws ReflectionException
310
-     */
311
-    public function deleted(): bool
312
-    {
313
-        return (bool) $this->get('QST_deleted');
314
-    }
315
-
316
-
317
-    /**
318
-     * Gets an array of related EE_Answer  to this EE_Question
319
-     *
320
-     * @return EE_Answer[]
321
-     * @throws EE_Error
322
-     * @throws ReflectionException
323
-     */
324
-    public function answers(): array
325
-    {
326
-        return $this->get_many_related('Answer');
327
-    }
328
-
329
-
330
-    /**
331
-     * Boolean check for if there are answers on this question in th db
332
-     *
333
-     * @return bool true = has answers, false = no answers.
334
-     * @throws EE_Error
335
-     * @throws ReflectionException
336
-     */
337
-    public function has_answers(): bool
338
-    {
339
-        return (bool) $this->count_related('Answer') > 0;
340
-    }
341
-
342
-
343
-    /**
344
-     * gets an array of EE_Question_Group which relate to this question
345
-     *
346
-     * @return EE_Question_Group[]
347
-     * @throws EE_Error
348
-     * @throws ReflectionException
349
-     */
350
-    public function question_groups(): array
351
-    {
352
-        return $this->get_many_related('Question_Group');
353
-    }
354
-
355
-
356
-    /**
357
-     * Returns all the options for this question. By default, it returns only the not-yet-deleted ones.
358
-     *
359
-     * @param bool $notDeletedOptionsOnly                         whether to return ALL options,
360
-     *                                                            or only the ones which have not yet been deleted
361
-     * @param string|array|null $selected_value_to_always_include when retrieving options to an ANSWERED question,
362
-     *                                                            we want to usually only show non-deleted options
363
-     *                                                            AND the value that was selected for the answer,
364
-     *                                                            whether it was trashed or not.
365
-     * @return EE_Question_Option[]
366
-     * @throws EE_Error
367
-     * @throws ReflectionException
368
-     */
369
-    public function options(bool $notDeletedOptionsOnly = true, $selected_value_to_always_include = null): array
370
-    {
371
-        if (! $this->ID()) {
372
-            return [];
373
-        }
374
-        $query_params = [];
375
-        if ($selected_value_to_always_include) {
376
-            if (is_array($selected_value_to_always_include)) {
377
-                $query_params[0]['OR*options-query']['QSO_value'] = ['IN', $selected_value_to_always_include];
378
-            } else {
379
-                $query_params[0]['OR*options-query']['QSO_value'] = $selected_value_to_always_include;
380
-            }
381
-        }
382
-        if ($notDeletedOptionsOnly) {
383
-            $query_params[0]['OR*options-query']['QSO_deleted'] = false;
384
-        }
385
-        // order by QSO_order
386
-        $query_params['order_by'] = ['QSO_order' => 'ASC'];
387
-        return $this->get_many_related('Question_Option', $query_params);
388
-    }
389
-
390
-
391
-    /**
392
-     * returns an array of EE_Question_Options which relate to this question
393
-     *
394
-     * @return EE_Question_Option[]
395
-     */
396
-    public function temp_options(): array
397
-    {
398
-        return $this->_model_relations['Question_Option'];
399
-    }
400
-
401
-
402
-    /**
403
-     * Adds an option for this question. Note: if the option were previously associated with a different
404
-     * Question, that relationship will be overwritten.
405
-     *
406
-     * @param EE_Question_Option $option
407
-     * @return EE_Base_Class
408
-     * @throws EE_Error
409
-     * @throws ReflectionException
410
-     */
411
-    public function add_option(EE_Question_Option $option): EE_Base_Class
412
-    {
413
-        return $this->_add_relation_to($option, 'Question_Option');
414
-    }
415
-
416
-
417
-    /**
418
-     * Adds an option directly to this question without saving to the db
419
-     *
420
-     * @param EE_Question_Option $option
421
-     * @return bool success
422
-     */
423
-    public function add_temp_option(EE_Question_Option $option): bool
424
-    {
425
-        $this->_model_relations['Question_Option'][] = $option;
426
-        return true;
427
-    }
428
-
429
-
430
-    /**
431
-     * Marks the option as deleted.
432
-     *
433
-     * @param EE_Question_Option $option
434
-     * @return bool success
435
-     * @throws EE_Error
436
-     * @throws ReflectionException
437
-     */
438
-    public function remove_option(EE_Question_Option $option): bool
439
-    {
440
-        return (bool) $this->_remove_relation_to($option, 'Question_Option');
441
-    }
442
-
443
-
444
-    /**
445
-     * @return bool
446
-     * @throws EE_Error
447
-     * @throws ReflectionException
448
-     */
449
-    public function is_system_question(): bool
450
-    {
451
-        $system_ID = $this->get('QST_system');
452
-        return ! empty($system_ID);
453
-    }
454
-
455
-
456
-    /**
457
-     * The purpose of this method is set the question order this question order to be the max out of all questions
458
-     *
459
-     * @return void
460
-     * @throws EE_Error
461
-     * @throws ReflectionException
462
-     */
463
-    public function set_order_to_latest()
464
-    {
465
-        $latest_order = $this->getModel()->get_latest_question_order();
466
-        $latest_order++;
467
-        $this->set('QST_order', $latest_order);
468
-    }
469
-
470
-
471
-    /**
472
-     * Retrieves the list of allowed question types from the model.
473
-     *
474
-     * @return string[]
475
-     * @throws EE_Error
476
-     * @throws ReflectionException
477
-     */
478
-    private function _allowed_question_types(): array
479
-    {
480
-        return $this->getModel()->allowed_question_types();
481
-    }
482
-
483
-
484
-    /**
485
-     * Duplicates this question and its question options
486
-     *
487
-     * @param array $options
488
-     * @return EE_Question|null
489
-     * @throws EE_Error
490
-     * @throws ReflectionException
491
-     */
492
-    public function duplicate($options = []): ?EE_Question
493
-    {
494
-        $new_question = clone $this;
495
-        $new_question->set('QST_ID', 0);
496
-        $new_question->set_display_text(
497
-            sprintf(esc_html__('%s **Duplicate**', 'event_espresso'), $this->display_text())
498
-        );
499
-        $new_question->set_admin_label(sprintf(esc_html__('%s **Duplicate**', 'event_espresso'), $this->admin_label()));
500
-        $new_question->set_system_ID('');
501
-        $new_question->set_wp_user(get_current_user_id());
502
-        // if we're duplicating a trashed question, assume we don't want the new one to be trashed
503
-        $new_question->set_deleted();
504
-        $success = $new_question->save();
505
-        if ($success) {
506
-            // we don't totally want to duplicate the question options, because we want them to be for the NEW question
507
-            foreach ($this->options() as $question_option) {
508
-                $question_option->duplicate(['QST_ID' => $new_question->ID()]);
509
-            }
510
-            return $new_question;
511
-        }
512
-        return null;
513
-    }
514
-
515
-
516
-    /**
517
-     * Returns the question's maximum allowed response size
518
-     *
519
-     * @return int|float
520
-     * @throws EE_Error
521
-     * @throws ReflectionException
522
-     */
523
-    public function max()
524
-    {
525
-        return $this->get('QST_max');
526
-    }
527
-
528
-
529
-    /**
530
-     * Sets the question's maximum allowed response size
531
-     *
532
-     * @param int|float $new_max
533
-     * @return void
534
-     * @throws EE_Error
535
-     * @throws ReflectionException
536
-     */
537
-    public function set_max($new_max)
538
-    {
539
-        $this->set('QST_max', $new_max);
540
-    }
541
-
542
-
543
-    /**
544
-     * Creates a form input from this question which can be used in HTML forms
545
-     *
546
-     * @param EE_Registration|null $registration
547
-     * @param EE_Answer|null       $answer
548
-     * @param array                $input_constructor_args
549
-     * @return EE_Form_Input_Base
550
-     * @throws EE_Error
551
-     * @throws ReflectionException
552
-     */
553
-    public function generate_form_input(
554
-        ?EE_Registration $registration = null,
555
-        ?EE_Answer $answer = null,
556
-        array $input_constructor_args = []
557
-    ): EE_Form_Input_Base {
558
-        $input_constructor_args = array_merge(
559
-            [
560
-                'required'                          => $this->required(),
561
-                'html_label_text'                   => $this->display_text(),
562
-                'required_validation_error_message' => $this->required_text(),
563
-            ],
564
-            $input_constructor_args
565
-        );
566
-        if (! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
567
-            $answer = EEM_Answer::instance()->get_registration_question_answer_object($registration, $this->ID());
568
-        }
569
-        $enum_options = $this->isEnumType() ? $this->options() : [];
570
-        // has this question been answered ?
571
-        if (
572
-            $answer instanceof EE_Answer
573
-            && $answer->value() !== ''
574
-        ) {
575
-            // answer gets htmlspecialchars called on it, undo that please
576
-            // because the form input's display strategy may call esc_attr too
577
-            // which also does html special characters
578
-            $values_with_html_special_chars = $answer->value();
579
-            if (is_array($values_with_html_special_chars)) {
580
-                $default_value = array_map('htmlspecialchars_decode', $values_with_html_special_chars);
581
-            } else {
582
-                $default_value = htmlspecialchars_decode($values_with_html_special_chars);
583
-            }
584
-            $input_constructor_args['default'] = $default_value;
585
-        } else {
586
-            foreach ($enum_options as $enum_option) {
587
-                if (! $enum_option instanceof EE_Question_Option) {
588
-                    continue;
589
-                }
590
-                if ($enum_option->isDefault()) {
591
-                    $input_constructor_args['default'] = $enum_option->value();
592
-                    break;
593
-                }
594
-            }
595
-        }
596
-        $max_max_for_question = EEM_Question::instance()->absolute_max_for_system_question($this->system_ID());
597
-        if (
598
-            in_array(
599
-                $this->type(),
600
-                EEM_Question::instance()->questionTypesWithMaxLength(),
601
-                true
602
-            )
603
-        ) {
604
-            $input_constructor_args['validation_strategies'][] = new EE_Max_Length_Validation_Strategy(
605
-                null,
606
-                min($max_max_for_question, $this->max())
607
-            );
608
-        }
609
-        $input_constructor_args = apply_filters(
610
-            'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__input_constructor_args',
611
-            $input_constructor_args,
612
-            $registration,
613
-            $this,
614
-            $answer
615
-        );
616
-
617
-        switch ($this->type()) {
618
-            // Text
619
-            case EEM_Question::QST_type_text:
620
-                $result = new EE_Text_Input($input_constructor_args);
621
-                break;
622
-            // Textarea
623
-            case EEM_Question::QST_type_textarea:
624
-                $result = new EE_Text_Area_Input($input_constructor_args);
625
-                break;
626
-            // Radio Buttons
627
-            case EEM_Question::QST_type_radio:
628
-                $result = new EE_Radio_Button_Input($enum_options, $input_constructor_args);
629
-                break;
630
-            // Dropdown
631
-            case EEM_Question::QST_type_dropdown:
632
-                $result = new EE_Select_Input($enum_options, $input_constructor_args);
633
-                break;
634
-            // State Dropdown
635
-            case EEM_Question::QST_type_state:
636
-                $state_options = apply_filters(
637
-                    'FHEE__EE_Question__generate_form_input__state_options',
638
-                    null,
639
-                    $this,
640
-                    $registration,
641
-                    $answer
642
-                );
643
-                $result        = new EE_State_Select_Input($state_options, $input_constructor_args);
644
-                break;
645
-            // Country Dropdown
646
-            case EEM_Question::QST_type_country:
647
-                $country_options = apply_filters(
648
-                    'FHEE__EE_Question__generate_form_input__country_options',
649
-                    null,
650
-                    $this,
651
-                    $registration,
652
-                    $answer
653
-                );
654
-                $result          = new EE_Country_Select_Input($country_options, $input_constructor_args);
655
-                break;
656
-            // Checkboxes
657
-            case EEM_Question::QST_type_checkbox:
658
-                $result = new EE_Checkbox_Multi_Input($enum_options, $input_constructor_args);
659
-                break;
660
-            // Date
661
-            case EEM_Question::QST_type_date:
662
-                $result = new EE_Datepicker_Input($input_constructor_args);
663
-                break;
664
-            case EEM_Question::QST_type_html_textarea:
665
-                $input_constructor_args['validation_strategies'][] = new EE_Simple_HTML_Validation_Strategy();
666
-                $result                                            = new EE_Text_Area_Input($input_constructor_args);
667
-                $result->remove_validation_strategy('EE_Plaintext_Validation_Strategy');
668
-                break;
669
-            case EEM_Question::QST_type_email:
670
-                $result = new EE_Email_Input($input_constructor_args);
671
-                break;
672
-            // Email confirm
673
-            case EEM_Question::QST_type_email_confirm:
674
-                $result = new EE_Email_Confirm_Input($input_constructor_args);
675
-                break;
676
-            case EEM_Question::QST_type_us_phone:
677
-                $result = new EE_Phone_Input($input_constructor_args);
678
-                break;
679
-            case EEM_Question::QST_type_int:
680
-                $result = new EE_Integer_Input($input_constructor_args);
681
-                break;
682
-            case EEM_Question::QST_type_decimal:
683
-                $result = new EE_Float_Input($input_constructor_args);
684
-                break;
685
-            case EEM_Question::QST_type_url:
686
-                $result = new EE_URL_Input($input_constructor_args);
687
-                break;
688
-            case EEM_Question::QST_type_year:
689
-                $result = new EE_Year_Input(
690
-                    $input_constructor_args,
691
-                    apply_filters(
692
-                        'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__four_digit',
693
-                        true,
694
-                        $this
695
-                    ),
696
-                    apply_filters(
697
-                        'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__early_range',
698
-                        100,
699
-                        $this
700
-                    ),
701
-                    apply_filters(
702
-                        'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__end_range',
703
-                        100,
704
-                        $this
705
-                    )
706
-                );
707
-                break;
708
-            case EEM_Question::QST_type_multi_select:
709
-                $result = new EE_Select_Multiple_Input($enum_options, $input_constructor_args);
710
-                break;
711
-            // fallback
712
-            default:
713
-                $default_input = apply_filters(
714
-                    'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__default',
715
-                    null,
716
-                    $this->type(),
717
-                    $this,
718
-                    $input_constructor_args
719
-                );
720
-                if (! $default_input) {
721
-                    $default_input = new EE_Text_Input($input_constructor_args);
722
-                }
723
-                $result = $default_input;
724
-        }
725
-        return apply_filters('FHEE__EE_Question__generate_form_input__return', $result, $registration, $this, $answer);
726
-    }
727
-
728
-
729
-    /**
730
-     * Returns whether this question type should have question option entries
731
-     *
732
-     * @return bool
733
-     * @throws EE_Error
734
-     * @throws ReflectionException
735
-     */
736
-    public function should_have_question_options(): bool
737
-    {
738
-        return in_array(
739
-            $this->type(),
740
-            $this->getModel()->question_types_with_options(),
741
-            true
742
-        );
743
-    }
744
-
745
-
746
-    /**
747
-     * @return bool
748
-     * @throws EE_Error
749
-     * @throws ReflectionException
750
-     * @since 5.0.30.p
751
-     */
752
-    public function isEnumType(): bool
753
-    {
754
-        return $this->type() === EEM_Question::QST_type_checkbox
755
-            || $this->type() === EEM_Question::QST_type_dropdown
756
-            || $this->type() === EEM_Question::QST_type_multi_select
757
-            || $this->type() === EEM_Question::QST_type_radio
758
-            || $this->type() === EEM_Question::QST_type_country
759
-            || $this->type() === EEM_Question::QST_type_state
760
-            || $this->type() === EEM_Question::QST_type_year;
761
-    }
16
+	private ?string $type = null;
17
+
18
+
19
+	/**
20
+	 * @param array  $props_n_values          incoming values
21
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
22
+	 *                                        used.)
23
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
24
+	 *                                        date_format and the second value is the time format
25
+	 * @return EE_Question
26
+	 * @throws EE_Error
27
+	 * @throws ReflectionException
28
+	 */
29
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = []): EE_Question
30
+	{
31
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
32
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
33
+	}
34
+
35
+
36
+	/**
37
+	 * @param array  $props_n_values  incoming values from the database
38
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
39
+	 *                                the website will be used.
40
+	 * @return EE_Question
41
+	 * @throws EE_Error
42
+	 * @throws ReflectionException
43
+	 */
44
+	public static function new_instance_from_db($props_n_values = [], $timezone = ''): EE_Question
45
+	{
46
+		return new self($props_n_values, true, $timezone);
47
+	}
48
+
49
+
50
+	/**
51
+	 * @return EEM_Question
52
+	 * @throws EE_Error
53
+	 * @throws ReflectionException
54
+	 * @since 5.0.30.p
55
+	 */
56
+	private function getModel(): EEM_Question
57
+	{
58
+		return $this->get_model();
59
+	}
60
+
61
+
62
+	/**
63
+	 * @param string $QST_display_text
64
+	 * @throws EE_Error
65
+	 * @throws ReflectionException
66
+	 */
67
+	public function set_display_text(string $QST_display_text = '')
68
+	{
69
+		$this->set('QST_display_text', $QST_display_text);
70
+	}
71
+
72
+
73
+	/**
74
+	 * @param string $QST_admin_label
75
+	 * @throws EE_Error
76
+	 * @throws ReflectionException
77
+	 */
78
+	public function set_admin_label(string $QST_admin_label = '')
79
+	{
80
+		$this->set('QST_admin_label', $QST_admin_label);
81
+	}
82
+
83
+
84
+	/**
85
+	 * @param mixed $QST_system
86
+	 * @throws EE_Error
87
+	 * @throws ReflectionException
88
+	 */
89
+	public function set_system_ID(string $QST_system = '')
90
+	{
91
+		$this->set('QST_system', $QST_system);
92
+	}
93
+
94
+
95
+	/**
96
+	 * @param string $QST_type
97
+	 * @throws EE_Error
98
+	 * @throws ReflectionException
99
+	 */
100
+	public function set_question_type(string $QST_type = '')
101
+	{
102
+		$this->set('QST_type', $QST_type);
103
+	}
104
+
105
+
106
+	/**
107
+	 * Sets whether this question must be answered when presented in a form
108
+	 *
109
+	 * @param bool $QST_required
110
+	 * @throws EE_Error
111
+	 * @throws ReflectionException
112
+	 */
113
+	public function set_required(bool $QST_required = false)
114
+	{
115
+		$this->set('QST_required', $QST_required);
116
+	}
117
+
118
+
119
+	/**
120
+	 * @param string $QST_required_text
121
+	 * @throws EE_Error
122
+	 * @throws ReflectionException
123
+	 */
124
+	public function set_required_text(string $QST_required_text = '')
125
+	{
126
+		$this->set('QST_required_text', $QST_required_text);
127
+	}
128
+
129
+
130
+	/**
131
+	 * Sets the order of this question when placed in a sequence of questions
132
+	 *
133
+	 * @param int $QST_order
134
+	 * @throws EE_Error
135
+	 * @throws ReflectionException
136
+	 */
137
+	public function set_order(int $QST_order = 0)
138
+	{
139
+		$this->set('QST_order', $QST_order);
140
+	}
141
+
142
+
143
+	/**
144
+	 * @param bool $QST_admin_only
145
+	 * @throws EE_Error
146
+	 * @throws ReflectionException
147
+	 */
148
+	public function set_admin_only(bool $QST_admin_only = false)
149
+	{
150
+		$this->set('QST_admin_only', $QST_admin_only);
151
+	}
152
+
153
+
154
+	/**
155
+	 * Sets the WordPress user ID on the question
156
+	 *
157
+	 * @param int $QST_wp_user
158
+	 * @throws EE_Error
159
+	 * @throws ReflectionException
160
+	 */
161
+	public function set_wp_user(int $QST_wp_user = 1)
162
+	{
163
+		$this->set('QST_wp_user', $QST_wp_user);
164
+	}
165
+
166
+
167
+	/**
168
+	 * Sets whether the question has been deleted
169
+	 * we use this boolean instead of actually deleting it
170
+	 * because when users delete this question they really want to remove the question from future forms,
171
+	 * BUT keep their old answers which depend on this record actually existing.
172
+	 *
173
+	 * @param bool $QST_deleted
174
+	 * @throws EE_Error
175
+	 * @throws ReflectionException
176
+	 */
177
+	public function set_deleted(bool $QST_deleted = false)
178
+	{
179
+		$this->set('QST_deleted', $QST_deleted);
180
+	}
181
+
182
+
183
+	/**
184
+	 *  used for the input label text displayed to users on the frontend
185
+	 *
186
+	 * @return string
187
+	 * @throws EE_Error
188
+	 * @throws ReflectionException
189
+	 */
190
+	public function display_text(): string
191
+	{
192
+		return (string) $this->get('QST_display_text');
193
+	}
194
+
195
+
196
+	/**
197
+	 * input label used in the admin
198
+	 *
199
+	 * @return string
200
+	 * @throws EE_Error
201
+	 * @throws ReflectionException
202
+	 */
203
+	public function admin_label(): string
204
+	{
205
+		return (string) $this->get('QST_admin_label');
206
+	}
207
+
208
+
209
+	/**
210
+	 * returns the attendee column name for this question
211
+	 *
212
+	 * @return string
213
+	 * @throws EE_Error
214
+	 * @throws ReflectionException
215
+	 */
216
+	public function system_ID(): string
217
+	{
218
+		return (string) $this->get('QST_system');
219
+	}
220
+
221
+
222
+	/**
223
+	 * if question is required or not (boolean)
224
+	 *
225
+	 * @return bool
226
+	 * @throws EE_Error
227
+	 * @throws ReflectionException
228
+	 */
229
+	public function required(): bool
230
+	{
231
+		return (bool) $this->get('QST_required');
232
+	}
233
+
234
+
235
+	/**
236
+	 * returns the text which should be displayed when a user
237
+	 * doesn't answer this question in a form
238
+	 *
239
+	 * @return string
240
+	 * @throws EE_Error
241
+	 * @throws ReflectionException
242
+	 */
243
+	public function required_text(): string
244
+	{
245
+		return (string) $this->get('QST_required_text');
246
+	}
247
+
248
+
249
+	/**
250
+	 * returns the type of this question: one of the QST_type_* constants on the EEM_Question model
251
+	 *
252
+	 * @return string
253
+	 * @throws EE_Error
254
+	 * @throws ReflectionException
255
+	 */
256
+	public function type(): string
257
+	{
258
+		if ($this->type === null) {
259
+			$this->type = (string) $this->get('QST_type');
260
+		}
261
+		return $this->type;
262
+	}
263
+
264
+
265
+	/**
266
+	 * returns an integer showing where this question should be placed in a sequence of questions
267
+	 *
268
+	 * @return int
269
+	 * @throws EE_Error
270
+	 * @throws ReflectionException
271
+	 */
272
+	public function order(): int
273
+	{
274
+		return (int) $this->get('QST_order');
275
+	}
276
+
277
+
278
+	/**
279
+	 * returns whether this question should only appear to admins, or to everyone
280
+	 *
281
+	 * @return bool
282
+	 * @throws EE_Error
283
+	 * @throws ReflectionException
284
+	 */
285
+	public function admin_only(): bool
286
+	{
287
+		return (bool) $this->get('QST_admin_only');
288
+	}
289
+
290
+
291
+	/**
292
+	 * returns the id the WordPress user who created this question
293
+	 *
294
+	 * @return int
295
+	 * @throws EE_Error
296
+	 * @throws ReflectionException
297
+	 */
298
+	public function wp_user(): int
299
+	{
300
+		return (int) $this->get('QST_wp_user');
301
+	}
302
+
303
+
304
+	/**
305
+	 * returns whether this question has been marked as 'deleted'
306
+	 *
307
+	 * @return bool
308
+	 * @throws EE_Error
309
+	 * @throws ReflectionException
310
+	 */
311
+	public function deleted(): bool
312
+	{
313
+		return (bool) $this->get('QST_deleted');
314
+	}
315
+
316
+
317
+	/**
318
+	 * Gets an array of related EE_Answer  to this EE_Question
319
+	 *
320
+	 * @return EE_Answer[]
321
+	 * @throws EE_Error
322
+	 * @throws ReflectionException
323
+	 */
324
+	public function answers(): array
325
+	{
326
+		return $this->get_many_related('Answer');
327
+	}
328
+
329
+
330
+	/**
331
+	 * Boolean check for if there are answers on this question in th db
332
+	 *
333
+	 * @return bool true = has answers, false = no answers.
334
+	 * @throws EE_Error
335
+	 * @throws ReflectionException
336
+	 */
337
+	public function has_answers(): bool
338
+	{
339
+		return (bool) $this->count_related('Answer') > 0;
340
+	}
341
+
342
+
343
+	/**
344
+	 * gets an array of EE_Question_Group which relate to this question
345
+	 *
346
+	 * @return EE_Question_Group[]
347
+	 * @throws EE_Error
348
+	 * @throws ReflectionException
349
+	 */
350
+	public function question_groups(): array
351
+	{
352
+		return $this->get_many_related('Question_Group');
353
+	}
354
+
355
+
356
+	/**
357
+	 * Returns all the options for this question. By default, it returns only the not-yet-deleted ones.
358
+	 *
359
+	 * @param bool $notDeletedOptionsOnly                         whether to return ALL options,
360
+	 *                                                            or only the ones which have not yet been deleted
361
+	 * @param string|array|null $selected_value_to_always_include when retrieving options to an ANSWERED question,
362
+	 *                                                            we want to usually only show non-deleted options
363
+	 *                                                            AND the value that was selected for the answer,
364
+	 *                                                            whether it was trashed or not.
365
+	 * @return EE_Question_Option[]
366
+	 * @throws EE_Error
367
+	 * @throws ReflectionException
368
+	 */
369
+	public function options(bool $notDeletedOptionsOnly = true, $selected_value_to_always_include = null): array
370
+	{
371
+		if (! $this->ID()) {
372
+			return [];
373
+		}
374
+		$query_params = [];
375
+		if ($selected_value_to_always_include) {
376
+			if (is_array($selected_value_to_always_include)) {
377
+				$query_params[0]['OR*options-query']['QSO_value'] = ['IN', $selected_value_to_always_include];
378
+			} else {
379
+				$query_params[0]['OR*options-query']['QSO_value'] = $selected_value_to_always_include;
380
+			}
381
+		}
382
+		if ($notDeletedOptionsOnly) {
383
+			$query_params[0]['OR*options-query']['QSO_deleted'] = false;
384
+		}
385
+		// order by QSO_order
386
+		$query_params['order_by'] = ['QSO_order' => 'ASC'];
387
+		return $this->get_many_related('Question_Option', $query_params);
388
+	}
389
+
390
+
391
+	/**
392
+	 * returns an array of EE_Question_Options which relate to this question
393
+	 *
394
+	 * @return EE_Question_Option[]
395
+	 */
396
+	public function temp_options(): array
397
+	{
398
+		return $this->_model_relations['Question_Option'];
399
+	}
400
+
401
+
402
+	/**
403
+	 * Adds an option for this question. Note: if the option were previously associated with a different
404
+	 * Question, that relationship will be overwritten.
405
+	 *
406
+	 * @param EE_Question_Option $option
407
+	 * @return EE_Base_Class
408
+	 * @throws EE_Error
409
+	 * @throws ReflectionException
410
+	 */
411
+	public function add_option(EE_Question_Option $option): EE_Base_Class
412
+	{
413
+		return $this->_add_relation_to($option, 'Question_Option');
414
+	}
415
+
416
+
417
+	/**
418
+	 * Adds an option directly to this question without saving to the db
419
+	 *
420
+	 * @param EE_Question_Option $option
421
+	 * @return bool success
422
+	 */
423
+	public function add_temp_option(EE_Question_Option $option): bool
424
+	{
425
+		$this->_model_relations['Question_Option'][] = $option;
426
+		return true;
427
+	}
428
+
429
+
430
+	/**
431
+	 * Marks the option as deleted.
432
+	 *
433
+	 * @param EE_Question_Option $option
434
+	 * @return bool success
435
+	 * @throws EE_Error
436
+	 * @throws ReflectionException
437
+	 */
438
+	public function remove_option(EE_Question_Option $option): bool
439
+	{
440
+		return (bool) $this->_remove_relation_to($option, 'Question_Option');
441
+	}
442
+
443
+
444
+	/**
445
+	 * @return bool
446
+	 * @throws EE_Error
447
+	 * @throws ReflectionException
448
+	 */
449
+	public function is_system_question(): bool
450
+	{
451
+		$system_ID = $this->get('QST_system');
452
+		return ! empty($system_ID);
453
+	}
454
+
455
+
456
+	/**
457
+	 * The purpose of this method is set the question order this question order to be the max out of all questions
458
+	 *
459
+	 * @return void
460
+	 * @throws EE_Error
461
+	 * @throws ReflectionException
462
+	 */
463
+	public function set_order_to_latest()
464
+	{
465
+		$latest_order = $this->getModel()->get_latest_question_order();
466
+		$latest_order++;
467
+		$this->set('QST_order', $latest_order);
468
+	}
469
+
470
+
471
+	/**
472
+	 * Retrieves the list of allowed question types from the model.
473
+	 *
474
+	 * @return string[]
475
+	 * @throws EE_Error
476
+	 * @throws ReflectionException
477
+	 */
478
+	private function _allowed_question_types(): array
479
+	{
480
+		return $this->getModel()->allowed_question_types();
481
+	}
482
+
483
+
484
+	/**
485
+	 * Duplicates this question and its question options
486
+	 *
487
+	 * @param array $options
488
+	 * @return EE_Question|null
489
+	 * @throws EE_Error
490
+	 * @throws ReflectionException
491
+	 */
492
+	public function duplicate($options = []): ?EE_Question
493
+	{
494
+		$new_question = clone $this;
495
+		$new_question->set('QST_ID', 0);
496
+		$new_question->set_display_text(
497
+			sprintf(esc_html__('%s **Duplicate**', 'event_espresso'), $this->display_text())
498
+		);
499
+		$new_question->set_admin_label(sprintf(esc_html__('%s **Duplicate**', 'event_espresso'), $this->admin_label()));
500
+		$new_question->set_system_ID('');
501
+		$new_question->set_wp_user(get_current_user_id());
502
+		// if we're duplicating a trashed question, assume we don't want the new one to be trashed
503
+		$new_question->set_deleted();
504
+		$success = $new_question->save();
505
+		if ($success) {
506
+			// we don't totally want to duplicate the question options, because we want them to be for the NEW question
507
+			foreach ($this->options() as $question_option) {
508
+				$question_option->duplicate(['QST_ID' => $new_question->ID()]);
509
+			}
510
+			return $new_question;
511
+		}
512
+		return null;
513
+	}
514
+
515
+
516
+	/**
517
+	 * Returns the question's maximum allowed response size
518
+	 *
519
+	 * @return int|float
520
+	 * @throws EE_Error
521
+	 * @throws ReflectionException
522
+	 */
523
+	public function max()
524
+	{
525
+		return $this->get('QST_max');
526
+	}
527
+
528
+
529
+	/**
530
+	 * Sets the question's maximum allowed response size
531
+	 *
532
+	 * @param int|float $new_max
533
+	 * @return void
534
+	 * @throws EE_Error
535
+	 * @throws ReflectionException
536
+	 */
537
+	public function set_max($new_max)
538
+	{
539
+		$this->set('QST_max', $new_max);
540
+	}
541
+
542
+
543
+	/**
544
+	 * Creates a form input from this question which can be used in HTML forms
545
+	 *
546
+	 * @param EE_Registration|null $registration
547
+	 * @param EE_Answer|null       $answer
548
+	 * @param array                $input_constructor_args
549
+	 * @return EE_Form_Input_Base
550
+	 * @throws EE_Error
551
+	 * @throws ReflectionException
552
+	 */
553
+	public function generate_form_input(
554
+		?EE_Registration $registration = null,
555
+		?EE_Answer $answer = null,
556
+		array $input_constructor_args = []
557
+	): EE_Form_Input_Base {
558
+		$input_constructor_args = array_merge(
559
+			[
560
+				'required'                          => $this->required(),
561
+				'html_label_text'                   => $this->display_text(),
562
+				'required_validation_error_message' => $this->required_text(),
563
+			],
564
+			$input_constructor_args
565
+		);
566
+		if (! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
567
+			$answer = EEM_Answer::instance()->get_registration_question_answer_object($registration, $this->ID());
568
+		}
569
+		$enum_options = $this->isEnumType() ? $this->options() : [];
570
+		// has this question been answered ?
571
+		if (
572
+			$answer instanceof EE_Answer
573
+			&& $answer->value() !== ''
574
+		) {
575
+			// answer gets htmlspecialchars called on it, undo that please
576
+			// because the form input's display strategy may call esc_attr too
577
+			// which also does html special characters
578
+			$values_with_html_special_chars = $answer->value();
579
+			if (is_array($values_with_html_special_chars)) {
580
+				$default_value = array_map('htmlspecialchars_decode', $values_with_html_special_chars);
581
+			} else {
582
+				$default_value = htmlspecialchars_decode($values_with_html_special_chars);
583
+			}
584
+			$input_constructor_args['default'] = $default_value;
585
+		} else {
586
+			foreach ($enum_options as $enum_option) {
587
+				if (! $enum_option instanceof EE_Question_Option) {
588
+					continue;
589
+				}
590
+				if ($enum_option->isDefault()) {
591
+					$input_constructor_args['default'] = $enum_option->value();
592
+					break;
593
+				}
594
+			}
595
+		}
596
+		$max_max_for_question = EEM_Question::instance()->absolute_max_for_system_question($this->system_ID());
597
+		if (
598
+			in_array(
599
+				$this->type(),
600
+				EEM_Question::instance()->questionTypesWithMaxLength(),
601
+				true
602
+			)
603
+		) {
604
+			$input_constructor_args['validation_strategies'][] = new EE_Max_Length_Validation_Strategy(
605
+				null,
606
+				min($max_max_for_question, $this->max())
607
+			);
608
+		}
609
+		$input_constructor_args = apply_filters(
610
+			'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__input_constructor_args',
611
+			$input_constructor_args,
612
+			$registration,
613
+			$this,
614
+			$answer
615
+		);
616
+
617
+		switch ($this->type()) {
618
+			// Text
619
+			case EEM_Question::QST_type_text:
620
+				$result = new EE_Text_Input($input_constructor_args);
621
+				break;
622
+			// Textarea
623
+			case EEM_Question::QST_type_textarea:
624
+				$result = new EE_Text_Area_Input($input_constructor_args);
625
+				break;
626
+			// Radio Buttons
627
+			case EEM_Question::QST_type_radio:
628
+				$result = new EE_Radio_Button_Input($enum_options, $input_constructor_args);
629
+				break;
630
+			// Dropdown
631
+			case EEM_Question::QST_type_dropdown:
632
+				$result = new EE_Select_Input($enum_options, $input_constructor_args);
633
+				break;
634
+			// State Dropdown
635
+			case EEM_Question::QST_type_state:
636
+				$state_options = apply_filters(
637
+					'FHEE__EE_Question__generate_form_input__state_options',
638
+					null,
639
+					$this,
640
+					$registration,
641
+					$answer
642
+				);
643
+				$result        = new EE_State_Select_Input($state_options, $input_constructor_args);
644
+				break;
645
+			// Country Dropdown
646
+			case EEM_Question::QST_type_country:
647
+				$country_options = apply_filters(
648
+					'FHEE__EE_Question__generate_form_input__country_options',
649
+					null,
650
+					$this,
651
+					$registration,
652
+					$answer
653
+				);
654
+				$result          = new EE_Country_Select_Input($country_options, $input_constructor_args);
655
+				break;
656
+			// Checkboxes
657
+			case EEM_Question::QST_type_checkbox:
658
+				$result = new EE_Checkbox_Multi_Input($enum_options, $input_constructor_args);
659
+				break;
660
+			// Date
661
+			case EEM_Question::QST_type_date:
662
+				$result = new EE_Datepicker_Input($input_constructor_args);
663
+				break;
664
+			case EEM_Question::QST_type_html_textarea:
665
+				$input_constructor_args['validation_strategies'][] = new EE_Simple_HTML_Validation_Strategy();
666
+				$result                                            = new EE_Text_Area_Input($input_constructor_args);
667
+				$result->remove_validation_strategy('EE_Plaintext_Validation_Strategy');
668
+				break;
669
+			case EEM_Question::QST_type_email:
670
+				$result = new EE_Email_Input($input_constructor_args);
671
+				break;
672
+			// Email confirm
673
+			case EEM_Question::QST_type_email_confirm:
674
+				$result = new EE_Email_Confirm_Input($input_constructor_args);
675
+				break;
676
+			case EEM_Question::QST_type_us_phone:
677
+				$result = new EE_Phone_Input($input_constructor_args);
678
+				break;
679
+			case EEM_Question::QST_type_int:
680
+				$result = new EE_Integer_Input($input_constructor_args);
681
+				break;
682
+			case EEM_Question::QST_type_decimal:
683
+				$result = new EE_Float_Input($input_constructor_args);
684
+				break;
685
+			case EEM_Question::QST_type_url:
686
+				$result = new EE_URL_Input($input_constructor_args);
687
+				break;
688
+			case EEM_Question::QST_type_year:
689
+				$result = new EE_Year_Input(
690
+					$input_constructor_args,
691
+					apply_filters(
692
+						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__four_digit',
693
+						true,
694
+						$this
695
+					),
696
+					apply_filters(
697
+						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__early_range',
698
+						100,
699
+						$this
700
+					),
701
+					apply_filters(
702
+						'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__year_question__end_range',
703
+						100,
704
+						$this
705
+					)
706
+				);
707
+				break;
708
+			case EEM_Question::QST_type_multi_select:
709
+				$result = new EE_Select_Multiple_Input($enum_options, $input_constructor_args);
710
+				break;
711
+			// fallback
712
+			default:
713
+				$default_input = apply_filters(
714
+					'FHEE__EE_SPCO_Reg_Step_Attendee_Information___generate_question_input__default',
715
+					null,
716
+					$this->type(),
717
+					$this,
718
+					$input_constructor_args
719
+				);
720
+				if (! $default_input) {
721
+					$default_input = new EE_Text_Input($input_constructor_args);
722
+				}
723
+				$result = $default_input;
724
+		}
725
+		return apply_filters('FHEE__EE_Question__generate_form_input__return', $result, $registration, $this, $answer);
726
+	}
727
+
728
+
729
+	/**
730
+	 * Returns whether this question type should have question option entries
731
+	 *
732
+	 * @return bool
733
+	 * @throws EE_Error
734
+	 * @throws ReflectionException
735
+	 */
736
+	public function should_have_question_options(): bool
737
+	{
738
+		return in_array(
739
+			$this->type(),
740
+			$this->getModel()->question_types_with_options(),
741
+			true
742
+		);
743
+	}
744
+
745
+
746
+	/**
747
+	 * @return bool
748
+	 * @throws EE_Error
749
+	 * @throws ReflectionException
750
+	 * @since 5.0.30.p
751
+	 */
752
+	public function isEnumType(): bool
753
+	{
754
+		return $this->type() === EEM_Question::QST_type_checkbox
755
+			|| $this->type() === EEM_Question::QST_type_dropdown
756
+			|| $this->type() === EEM_Question::QST_type_multi_select
757
+			|| $this->type() === EEM_Question::QST_type_radio
758
+			|| $this->type() === EEM_Question::QST_type_country
759
+			|| $this->type() === EEM_Question::QST_type_state
760
+			|| $this->type() === EEM_Question::QST_type_year;
761
+	}
762 762
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
      */
369 369
     public function options(bool $notDeletedOptionsOnly = true, $selected_value_to_always_include = null): array
370 370
     {
371
-        if (! $this->ID()) {
371
+        if ( ! $this->ID()) {
372 372
             return [];
373 373
         }
374 374
         $query_params = [];
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
             ],
564 564
             $input_constructor_args
565 565
         );
566
-        if (! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
566
+        if ( ! $answer instanceof EE_Answer && $registration instanceof EE_Registration) {
567 567
             $answer = EEM_Answer::instance()->get_registration_question_answer_object($registration, $this->ID());
568 568
         }
569 569
         $enum_options = $this->isEnumType() ? $this->options() : [];
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
             $input_constructor_args['default'] = $default_value;
585 585
         } else {
586 586
             foreach ($enum_options as $enum_option) {
587
-                if (! $enum_option instanceof EE_Question_Option) {
587
+                if ( ! $enum_option instanceof EE_Question_Option) {
588 588
                     continue;
589 589
                 }
590 590
                 if ($enum_option->isDefault()) {
@@ -640,7 +640,7 @@  discard block
 block discarded – undo
640 640
                     $registration,
641 641
                     $answer
642 642
                 );
643
-                $result        = new EE_State_Select_Input($state_options, $input_constructor_args);
643
+                $result = new EE_State_Select_Input($state_options, $input_constructor_args);
644 644
                 break;
645 645
             // Country Dropdown
646 646
             case EEM_Question::QST_type_country:
@@ -651,7 +651,7 @@  discard block
 block discarded – undo
651 651
                     $registration,
652 652
                     $answer
653 653
                 );
654
-                $result          = new EE_Country_Select_Input($country_options, $input_constructor_args);
654
+                $result = new EE_Country_Select_Input($country_options, $input_constructor_args);
655 655
                 break;
656 656
             // Checkboxes
657 657
             case EEM_Question::QST_type_checkbox:
@@ -717,7 +717,7 @@  discard block
 block discarded – undo
717 717
                     $this,
718 718
                     $input_constructor_args
719 719
                 );
720
-                if (! $default_input) {
720
+                if ( ! $default_input) {
721 721
                     $default_input = new EE_Text_Input($input_constructor_args);
722 722
                 }
723 723
                 $result = $default_input;
Please login to merge, or discard this patch.
core/db_classes/EE_Ticket.class.php 2 patches
Indentation   +2148 added lines, -2148 removed lines patch added patch discarded remove patch
@@ -15,2156 +15,2156 @@
 block discarded – undo
15 15
  */
16 16
 class EE_Ticket extends EE_Soft_Delete_Base_Class implements EEI_Line_Item_Object, EEI_Event_Relation, EEI_Has_Icon
17 17
 {
18
-    /**
19
-     * TicKet Archived:
20
-     * constant used by ticket_status() to indicate that a ticket is archived
21
-     * and no longer available for purchase
22
-     */
23
-    const archived = 'TKA';
24
-
25
-    /**
26
-     * TicKet Expired:
27
-     * constant used by ticket_status() to indicate that a ticket is expired
28
-     * and no longer available for purchase
29
-     */
30
-    const expired = 'TKE';
31
-
32
-    /**
33
-     * TicKet On sale:
34
-     * constant used by ticket_status() to indicate that a ticket is On Sale
35
-     * and IS available for purchase
36
-     */
37
-    const onsale = 'TKO';
38
-
39
-    /**
40
-     * TicKet Pending:
41
-     * constant used by ticket_status() to indicate that a ticket is pending
42
-     * and is NOT YET available for purchase
43
-     */
44
-    const pending = 'TKP';
45
-
46
-    /**
47
-     * TicKet Sold out:
48
-     * constant used by ticket_status() to indicate that a ticket is sold out
49
-     * and no longer available for purchases
50
-     */
51
-    const sold_out = 'TKS';
52
-
53
-    /**
54
-     * extra meta key for tracking ticket reservations
55
-     *
56
-     * @type string
57
-     */
58
-    const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
59
-
60
-    /**
61
-     * override of parent property
62
-     *
63
-     * @var EEM_Ticket
64
-     */
65
-    protected $_model;
66
-
67
-    /**
68
-     * cached result from method of the same name
69
-     *
70
-     * @var float $_ticket_total_with_taxes
71
-     */
72
-    private $_ticket_total_with_taxes;
73
-
74
-    /**
75
-     * @var TicketPriceModifiers
76
-     */
77
-    protected $ticket_price_modifiers;
78
-
79
-
80
-    /**
81
-     * @param array  $props_n_values          incoming values
82
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
83
-     *                                        used.)
84
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
85
-     *                                        date_format and the second value is the time format
86
-     * @return EE_Ticket
87
-     * @throws EE_Error
88
-     * @throws ReflectionException
89
-     */
90
-    public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
91
-    {
92
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
93
-        return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
94
-    }
95
-
96
-
97
-    /**
98
-     * @param array  $props_n_values  incoming values from the database
99
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
100
-     *                                the website will be used.
101
-     * @return EE_Ticket
102
-     * @throws EE_Error
103
-     * @throws ReflectionException
104
-     */
105
-    public static function new_instance_from_db($props_n_values = [], $timezone = '')
106
-    {
107
-        return new self($props_n_values, true, $timezone);
108
-    }
109
-
110
-
111
-    /**
112
-     * @param array  $fieldValues
113
-     * @param false  $bydb
114
-     * @param string $timezone
115
-     * @param array  $date_formats
116
-     * @throws EE_Error
117
-     * @throws ReflectionException
118
-     */
119
-    public function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
120
-    {
121
-        parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
122
-        $this->ticket_price_modifiers = new TicketPriceModifiers($this);
123
-    }
124
-
125
-
126
-    /**
127
-     * @return bool
128
-     * @throws EE_Error
129
-     * @throws ReflectionException
130
-     */
131
-    public function parent()
132
-    {
133
-        return $this->get('TKT_parent');
134
-    }
135
-
136
-
137
-    /**
138
-     * return if a ticket has quantities available for purchase
139
-     *
140
-     * @param int $DTT_ID the primary key for a particular datetime
141
-     * @return boolean
142
-     * @throws EE_Error
143
-     * @throws ReflectionException
144
-     */
145
-    public function available($DTT_ID = 0)
146
-    {
147
-        // are we checking availability for a particular datetime ?
148
-        if ($DTT_ID) {
149
-            // get that datetime object
150
-            $datetime = $this->get_first_related('Datetime', [['DTT_ID' => $DTT_ID]]);
151
-            // if  ticket sales for this datetime have exceeded the reg limit...
152
-            if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
153
-                return false;
154
-            }
155
-        }
156
-        // datetime is still open for registration, but is this ticket sold out ?
157
-        return $this->qty() < 1 || $this->qty() > $this->sold();
158
-    }
159
-
160
-
161
-    /**
162
-     * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
163
-     *
164
-     * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
165
-     *                               relevant status const
166
-     * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
167
-     *                               further processing
168
-     * @return mixed status int if the display string isn't requested
169
-     * @throws EE_Error
170
-     * @throws ReflectionException
171
-     */
172
-    public function ticket_status($display = false, $remaining = null)
173
-    {
174
-        $remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
175
-        if (! $remaining) {
176
-            return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
177
-        }
178
-        if ($this->get('TKT_deleted')) {
179
-            return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
180
-        }
181
-        if ($this->is_expired()) {
182
-            return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
183
-        }
184
-        if ($this->is_pending()) {
185
-            return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
186
-        }
187
-        if ($this->is_on_sale()) {
188
-            return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
189
-        }
190
-        return '';
191
-    }
192
-
193
-
194
-    /**
195
-     * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
196
-     * considering ALL the factors used for figuring that out.
197
-     *
198
-     * @param int $DTT_ID if an int above 0 is included here then we get a specific dtt.
199
-     * @return boolean         true = tickets remaining, false not.
200
-     * @throws EE_Error
201
-     * @throws ReflectionException
202
-     */
203
-    public function is_remaining($DTT_ID = 0)
204
-    {
205
-        $num_remaining = $this->remaining($DTT_ID);
206
-        if ($num_remaining === 0) {
207
-            return false;
208
-        }
209
-        if ($num_remaining > 0 && $num_remaining < $this->min()) {
210
-            return false;
211
-        }
212
-        return true;
213
-    }
214
-
215
-
216
-    /**
217
-     * return the total number of tickets available for purchase
218
-     *
219
-     * @param int $DTT_ID  the primary key for a particular datetime.
220
-     *                     set to 0 for all related datetimes
221
-     * @return int
222
-     * @throws EE_Error
223
-     * @throws ReflectionException
224
-     */
225
-    public function remaining($DTT_ID = 0)
226
-    {
227
-        return $this->real_quantity_on_ticket('saleable', $DTT_ID);
228
-    }
229
-
230
-
231
-    /**
232
-     * Gets min
233
-     *
234
-     * @return int
235
-     * @throws EE_Error
236
-     * @throws ReflectionException
237
-     */
238
-    public function min()
239
-    {
240
-        return $this->get('TKT_min');
241
-    }
242
-
243
-
244
-    /**
245
-     * return if a ticket is no longer available cause its available dates have expired.
246
-     *
247
-     * @return boolean
248
-     * @throws EE_Error
249
-     * @throws ReflectionException
250
-     */
251
-    public function is_expired()
252
-    {
253
-        return ($this->get_raw('TKT_end_date') < time());
254
-    }
255
-
256
-
257
-    /**
258
-     * Return if a ticket is yet to go on sale or not
259
-     *
260
-     * @return boolean
261
-     * @throws EE_Error
262
-     * @throws ReflectionException
263
-     */
264
-    public function is_pending()
265
-    {
266
-        return ($this->get_raw('TKT_start_date') >= time());
267
-    }
268
-
269
-
270
-    /**
271
-     * Return if a ticket is on sale or not
272
-     *
273
-     * @return boolean
274
-     * @throws EE_Error
275
-     * @throws ReflectionException
276
-     */
277
-    public function is_on_sale()
278
-    {
279
-        return ($this->get_raw('TKT_start_date') <= time() && $this->get_raw('TKT_end_date') >= time());
280
-    }
281
-
282
-
283
-    /**
284
-     * This returns the chronologically last datetime that this ticket is associated with
285
-     *
286
-     * @param string $date_format
287
-     * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
288
-     *                            the end date ie: Jan 01 "to" Dec 31
289
-     * @return string
290
-     * @throws EE_Error
291
-     * @throws ReflectionException
292
-     */
293
-    public function date_range($date_format = '', $conjunction = ' - ')
294
-    {
295
-        $date_format = ! empty($date_format) ? $date_format : $this->_dt_frmt;
296
-        $first_date  = $this->first_datetime() instanceof EE_Datetime
297
-            ? $this->first_datetime()->get_i18n_datetime('DTT_EVT_start', $date_format)
298
-            : '';
299
-        $last_date   = $this->last_datetime() instanceof EE_Datetime
300
-            ? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $date_format)
301
-            : '';
302
-
303
-        return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
304
-    }
305
-
306
-
307
-    /**
308
-     * This returns the chronologically first datetime that this ticket is associated with
309
-     *
310
-     * @return EE_Datetime
311
-     * @throws EE_Error
312
-     * @throws ReflectionException
313
-     */
314
-    public function first_datetime()
315
-    {
316
-        $datetimes = $this->datetimes(['limit' => 1]);
317
-        return reset($datetimes);
318
-    }
319
-
320
-
321
-    /**
322
-     * Gets all the datetimes this ticket can be used for attending.
323
-     * Unless otherwise specified, orders datetimes by start date.
324
-     *
325
-     * @param array $query_params
326
-     * @return EE_Datetime[]|EE_Base_Class[]
327
-     * @throws EE_Error
328
-     * @throws ReflectionException
329
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
330
-     */
331
-    public function datetimes($query_params = [])
332
-    {
333
-        if (! isset($query_params['order_by'])) {
334
-            $query_params['order_by']['DTT_order'] = 'ASC';
335
-        }
336
-        return $this->get_many_related('Datetime', $query_params);
337
-    }
338
-
339
-
340
-    /**
341
-     * This returns the chronologically last datetime that this ticket is associated with
342
-     *
343
-     * @return EE_Datetime
344
-     * @throws EE_Error
345
-     * @throws ReflectionException
346
-     */
347
-    public function last_datetime()
348
-    {
349
-        $datetimes = $this->datetimes(['limit' => 1, 'order_by' => ['DTT_EVT_start' => 'DESC']]);
350
-        return end($datetimes);
351
-    }
352
-
353
-
354
-    /**
355
-     * This returns the total tickets sold depending on the given parameters.
356
-     *
357
-     * @param string $what    Can be one of two options: 'ticket', 'datetime'.
358
-     *                        'ticket' = total ticket sales for all datetimes this ticket is related to
359
-     *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
360
-     *                        'datetime' = total ticket sales in the datetime_ticket table.
361
-     *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
362
-     *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
363
-     * @param int    $dtt_id  [optional] include the dtt_id with $what = 'datetime'.
364
-     * @return mixed (array|int)          how many tickets have sold
365
-     * @throws EE_Error
366
-     * @throws ReflectionException
367
-     */
368
-    public function tickets_sold($what = 'ticket', $dtt_id = null)
369
-    {
370
-        $total        = 0;
371
-        $tickets_sold = $this->_all_tickets_sold();
372
-        switch ($what) {
373
-            case 'ticket':
374
-                return $tickets_sold['ticket'];
375
-
376
-            case 'datetime':
377
-                if (empty($tickets_sold['datetime'])) {
378
-                    return $total;
379
-                }
380
-                if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
381
-                    EE_Error::add_error(
382
-                        esc_html__(
383
-                            '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?',
384
-                            'event_espresso'
385
-                        ),
386
-                        __FILE__,
387
-                        __FUNCTION__,
388
-                        __LINE__
389
-                    );
390
-                    return $total;
391
-                }
392
-                return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
393
-
394
-            default:
395
-                return $total;
396
-        }
397
-    }
398
-
399
-
400
-    /**
401
-     * This returns an array indexed by datetime_id for tickets sold with this ticket.
402
-     *
403
-     * @return EE_Ticket[]
404
-     * @throws EE_Error
405
-     * @throws ReflectionException
406
-     */
407
-    protected function _all_tickets_sold()
408
-    {
409
-        $datetimes    = $this->get_many_related('Datetime');
410
-        $tickets_sold = [];
411
-        if (! empty($datetimes)) {
412
-            foreach ($datetimes as $datetime) {
413
-                $tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
414
-            }
415
-        }
416
-        // Tickets sold
417
-        $tickets_sold['ticket'] = $this->sold();
418
-        return $tickets_sold;
419
-    }
420
-
421
-
422
-    /**
423
-     * This returns the base price object for the ticket.
424
-     *
425
-     * @param bool $return_array whether to return as an array indexed by price id or just the object.
426
-     * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
427
-     * @throws EE_Error
428
-     * @throws ReflectionException
429
-     */
430
-    public function base_price(bool $return_array = false)
431
-    {
432
-        $base_price = $this->ticket_price_modifiers->getBasePrice();
433
-        if (! empty($base_price)) {
434
-            return $return_array ? $base_price : reset($base_price);
435
-        }
436
-        $_where = ['Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price];
437
-        return $return_array
438
-            ? $this->get_many_related('Price', [$_where])
439
-            : $this->get_first_related('Price', [$_where]);
440
-    }
441
-
442
-
443
-    /**
444
-     * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
445
-     *
446
-     * @return EE_Price[]
447
-     * @throws EE_Error
448
-     * @throws ReflectionException
449
-     */
450
-    public function price_modifiers(): array
451
-    {
452
-        $price_modifiers = $this->usesGlobalTaxes()
453
-            ? $this->ticket_price_modifiers->getAllDiscountAndSurchargeModifiersForTicket()
454
-            : $this->ticket_price_modifiers->getAllModifiersForTicket();
455
-        if (! empty($price_modifiers)) {
456
-            return $price_modifiers;
457
-        }
458
-        return $this->prices(
459
-            [
460
-                [
461
-                    'Price_Type.PBT_ID' => [
462
-                        'NOT IN',
463
-                        [EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax],
464
-                    ],
465
-                ],
466
-            ]
467
-        );
468
-    }
469
-
470
-
471
-    /**
472
-     * This returns ONLY the TAX price modifiers for the ticket
473
-     *
474
-     * @return EE_Price[]
475
-     * @throws EE_Error
476
-     * @throws ReflectionException
477
-     */
478
-    public function tax_price_modifiers(): array
479
-    {
480
-        $tax_price_modifiers = $this->ticket_price_modifiers->getAllTaxesForTicket();
481
-        if (! empty($tax_price_modifiers)) {
482
-            return $tax_price_modifiers;
483
-        }
484
-        return $this->prices([['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax]]);
485
-    }
486
-
487
-
488
-    /**
489
-     * Gets all the prices that combine to form the final price of this ticket
490
-     *
491
-     * @param array $query_params
492
-     * @return EE_Price[]|EE_Base_Class[]
493
-     * @throws EE_Error
494
-     * @throws ReflectionException
495
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
496
-     */
497
-    public function prices(array $query_params = []): array
498
-    {
499
-        if (! isset($query_params['order_by'])) {
500
-            $query_params['order_by']['PRC_order'] = 'ASC';
501
-        }
502
-        return $this->get_many_related('Price', $query_params);
503
-    }
504
-
505
-
506
-    /**
507
-     * Gets all the ticket datetimes (ie, relations between datetimes and tickets)
508
-     *
509
-     * @param array $query_params
510
-     * @return EE_Datetime_Ticket|EE_Base_Class[]
511
-     * @throws EE_Error
512
-     * @throws ReflectionException
513
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
514
-     */
515
-    public function datetime_tickets($query_params = [])
516
-    {
517
-        return $this->get_many_related('Datetime_Ticket', $query_params);
518
-    }
519
-
520
-
521
-    /**
522
-     * Gets all the datetimes from the db ordered by DTT_order
523
-     *
524
-     * @param boolean $show_expired
525
-     * @param boolean $show_deleted
526
-     * @return EE_Datetime[]
527
-     * @throws EE_Error
528
-     * @throws ReflectionException
529
-     */
530
-    public function datetimes_ordered($show_expired = true, $show_deleted = false)
531
-    {
532
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
533
-            $this->ID(),
534
-            $show_expired,
535
-            $show_deleted
536
-        );
537
-    }
538
-
539
-
540
-    /**
541
-     * Gets ID
542
-     *
543
-     * @return int
544
-     * @throws EE_Error
545
-     * @throws ReflectionException
546
-     */
547
-    public function ID()
548
-    {
549
-        return (int) $this->get('TKT_ID');
550
-    }
551
-
552
-
553
-    /**
554
-     * get the author of the ticket.
555
-     *
556
-     * @return int
557
-     * @throws EE_Error
558
-     * @throws ReflectionException
559
-     * @since 4.5.0
560
-     */
561
-    public function wp_user()
562
-    {
563
-        return $this->get('TKT_wp_user');
564
-    }
565
-
566
-
567
-    /**
568
-     * Gets the template for the ticket
569
-     *
570
-     * @return EE_Ticket_Template|EE_Base_Class
571
-     * @throws EE_Error
572
-     * @throws ReflectionException
573
-     */
574
-    public function template()
575
-    {
576
-        return $this->get_first_related('Ticket_Template');
577
-    }
578
-
579
-
580
-    /**
581
-     * Simply returns an array of EE_Price objects that are taxes.
582
-     *
583
-     * @return EE_Price[]
584
-     * @throws EE_Error
585
-     * @throws ReflectionException
586
-     */
587
-    public function get_ticket_taxes_for_admin(): array
588
-    {
589
-        return $this->usesGlobalTaxes() ? EE_Taxes::get_taxes_for_admin() : $this->tax_price_modifiers();
590
-    }
591
-
592
-
593
-    /**
594
-     * alias of taxable() to better indicate that ticket uses the legacy method of applying default "global" taxes
595
-     * as opposed to having tax price modifiers added directly to each ticket
596
-     *
597
-     * @return bool
598
-     * @throws EE_Error
599
-     * @throws ReflectionException
600
-     * @since   5.0.0.p
601
-     */
602
-    public function usesGlobalTaxes(): bool
603
-    {
604
-        return $this->taxable();
605
-    }
606
-
607
-
608
-    /**
609
-     * @return float
610
-     * @throws EE_Error
611
-     * @throws ReflectionException
612
-     */
613
-    public function ticket_price()
614
-    {
615
-        return $this->get('TKT_price');
616
-    }
617
-
618
-
619
-    /**
620
-     * @return mixed
621
-     * @throws EE_Error
622
-     * @throws ReflectionException
623
-     */
624
-    public function pretty_price()
625
-    {
626
-        return $this->get_pretty('TKT_price');
627
-    }
628
-
629
-
630
-    /**
631
-     * @return bool
632
-     * @throws EE_Error
633
-     * @throws ReflectionException
634
-     */
635
-    public function is_free()
636
-    {
637
-        return $this->get_ticket_total_with_taxes() === (float) 0;
638
-    }
639
-
640
-
641
-    /**
642
-     * get_ticket_total_with_taxes
643
-     *
644
-     * @param bool $no_cache
645
-     * @return float
646
-     * @throws EE_Error
647
-     * @throws ReflectionException
648
-     */
649
-    public function get_ticket_total_with_taxes(bool $no_cache = false): float
650
-    {
651
-        if ($this->_ticket_total_with_taxes === null || $no_cache) {
652
-            $this->_ticket_total_with_taxes = $this->get_ticket_subtotal();
653
-            // add taxes
654
-            if ($this->usesGlobalTaxes()) {
655
-                $this->_ticket_total_with_taxes += $this->get_ticket_taxes_total_for_admin();
656
-            } else {
657
-                $subtotal = $this->_ticket_total_with_taxes;
658
-                foreach ($this->tax_price_modifiers() as $tax) {
659
-                    $this->_ticket_total_with_taxes += $subtotal * $tax->amount() / 100;
660
-                }
661
-            }
662
-        }
663
-        return (float) $this->_ticket_total_with_taxes;
664
-    }
665
-
666
-
667
-    /**
668
-     * @throws EE_Error
669
-     * @throws ReflectionException
670
-     */
671
-    public function ensure_TKT_Price_correct()
672
-    {
673
-        $this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
674
-        $this->save();
675
-    }
676
-
677
-
678
-    /**
679
-     * @return float
680
-     * @throws EE_Error
681
-     * @throws ReflectionException
682
-     */
683
-    public function get_ticket_subtotal()
684
-    {
685
-        return EE_Taxes::get_subtotal_for_admin($this);
686
-    }
687
-
688
-
689
-    /**
690
-     * Returns the total taxes applied to this ticket
691
-     *
692
-     * @return float
693
-     * @throws EE_Error
694
-     * @throws ReflectionException
695
-     */
696
-    public function get_ticket_taxes_total_for_admin()
697
-    {
698
-        return EE_Taxes::get_total_taxes_for_admin($this);
699
-    }
700
-
701
-
702
-    /**
703
-     * Sets name
704
-     *
705
-     * @param string $name
706
-     * @throws EE_Error
707
-     * @throws ReflectionException
708
-     */
709
-    public function set_name($name)
710
-    {
711
-        $this->set('TKT_name', $name);
712
-    }
713
-
714
-
715
-    /**
716
-     * Gets description
717
-     *
718
-     * @return string
719
-     * @throws EE_Error
720
-     * @throws ReflectionException
721
-     */
722
-    public function description()
723
-    {
724
-        return $this->get('TKT_description');
725
-    }
726
-
727
-
728
-    /**
729
-     * Sets description
730
-     *
731
-     * @param string $description
732
-     * @throws EE_Error
733
-     * @throws ReflectionException
734
-     */
735
-    public function set_description($description)
736
-    {
737
-        $this->set('TKT_description', $description);
738
-    }
739
-
740
-
741
-    /**
742
-     * Gets start_date
743
-     *
744
-     * @param string|null $date_format
745
-     * @param string|null $time_format
746
-     * @return string
747
-     * @throws EE_Error
748
-     * @throws ReflectionException
749
-     */
750
-    public function start_date(?string $date_format = '', ?string $time_format = ''): string
751
-    {
752
-        return $this->_get_datetime('TKT_start_date', $date_format, $time_format);
753
-    }
754
-
755
-
756
-    /**
757
-     * Sets start_date
758
-     *
759
-     * @param string $start_date
760
-     * @return void
761
-     * @throws EE_Error
762
-     * @throws ReflectionException
763
-     */
764
-    public function set_start_date($start_date)
765
-    {
766
-        $this->_set_date_time('B', $start_date, 'TKT_start_date');
767
-    }
768
-
769
-
770
-    /**
771
-     * Gets end_date
772
-     *
773
-     * @param string|null $date_format
774
-     * @param string|null $time_format
775
-     * @return string
776
-     * @throws EE_Error
777
-     * @throws ReflectionException
778
-     */
779
-    public function end_date(?string $date_format = '', ?string $time_format = ''): string
780
-    {
781
-        return $this->_get_datetime('TKT_end_date', $date_format, $time_format);
782
-    }
783
-
784
-
785
-    /**
786
-     * Sets end_date
787
-     *
788
-     * @param string $end_date
789
-     * @return void
790
-     * @throws EE_Error
791
-     * @throws ReflectionException
792
-     */
793
-    public function set_end_date($end_date)
794
-    {
795
-        $this->_set_date_time('B', $end_date, 'TKT_end_date');
796
-    }
797
-
798
-
799
-    /**
800
-     * Sets sell until time
801
-     *
802
-     * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
803
-     * @throws EE_Error
804
-     * @throws ReflectionException
805
-     * @since 4.5.0
806
-     */
807
-    public function set_end_time($time)
808
-    {
809
-        $this->_set_time_for($time, 'TKT_end_date');
810
-    }
811
-
812
-
813
-    /**
814
-     * Sets min
815
-     *
816
-     * @param int $min
817
-     * @return void
818
-     * @throws EE_Error
819
-     * @throws ReflectionException
820
-     */
821
-    public function set_min($min)
822
-    {
823
-        $this->set('TKT_min', $min);
824
-    }
825
-
826
-
827
-    /**
828
-     * Gets max
829
-     *
830
-     * @return int
831
-     * @throws EE_Error
832
-     * @throws ReflectionException
833
-     */
834
-    public function max()
835
-    {
836
-        return $this->get('TKT_max');
837
-    }
838
-
839
-
840
-    /**
841
-     * Sets max
842
-     *
843
-     * @param int $max
844
-     * @return void
845
-     * @throws EE_Error
846
-     * @throws ReflectionException
847
-     */
848
-    public function set_max($max)
849
-    {
850
-        $this->set('TKT_max', $max);
851
-    }
852
-
853
-
854
-    /**
855
-     * Sets price
856
-     *
857
-     * @param float $price
858
-     * @return void
859
-     * @throws EE_Error
860
-     * @throws ReflectionException
861
-     */
862
-    public function set_price($price)
863
-    {
864
-        $this->set('TKT_price', $price);
865
-    }
866
-
867
-
868
-    /**
869
-     * Gets sold
870
-     *
871
-     * @return int
872
-     * @throws EE_Error
873
-     * @throws ReflectionException
874
-     */
875
-    public function sold(): int
876
-    {
877
-        return (int) $this->get_raw('TKT_sold');
878
-    }
879
-
880
-
881
-    /**
882
-     * Sets sold
883
-     *
884
-     * @param int $sold
885
-     * @return void
886
-     * @throws EE_Error
887
-     * @throws ReflectionException
888
-     */
889
-    public function set_sold($sold)
890
-    {
891
-        // sold can not go below zero
892
-        $sold = max(0, $sold);
893
-        $this->set('TKT_sold', $sold);
894
-    }
895
-
896
-
897
-    /**
898
-     * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
899
-     * associated datetimes.
900
-     *
901
-     * @param int $qty
902
-     * @return boolean
903
-     * @throws EE_Error
904
-     * @throws InvalidArgumentException
905
-     * @throws InvalidDataTypeException
906
-     * @throws InvalidInterfaceException
907
-     * @throws ReflectionException
908
-     * @since 4.9.80.p
909
-     */
910
-    public function increaseSold($qty = 1)
911
-    {
912
-        $qty = absint($qty);
913
-        // increment sold and decrement reserved datetime quantities simultaneously
914
-        // don't worry about failures, because they must have already had a spot reserved
915
-        $this->increaseSoldForDatetimes($qty);
916
-        // Increment and decrement ticket quantities simultaneously
917
-        $success = $this->adjustNumericFieldsInDb(
918
-            [
919
-                'TKT_reserved' => $qty * -1,
920
-                'TKT_sold'     => $qty,
921
-            ]
922
-        );
923
-        do_action(
924
-            'AHEE__EE_Ticket__increase_sold',
925
-            $this,
926
-            $qty,
927
-            $this->sold(),
928
-            $success
929
-        );
930
-        return $success;
931
-    }
932
-
933
-
934
-    /**
935
-     * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
936
-     *
937
-     * @param int           $qty positive or negative. Positive means to increase sold counts (and decrease reserved
938
-     *                           counts), Negative means to decreases old counts (and increase reserved counts).
939
-     * @param EE_Datetime[] $datetimes
940
-     * @throws EE_Error
941
-     * @throws InvalidArgumentException
942
-     * @throws InvalidDataTypeException
943
-     * @throws InvalidInterfaceException
944
-     * @throws ReflectionException
945
-     * @since 4.9.80.p
946
-     */
947
-    protected function increaseSoldForDatetimes($qty, array $datetimes = [])
948
-    {
949
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
950
-        foreach ($datetimes as $datetime) {
951
-            $datetime->increaseSold($qty);
952
-        }
953
-    }
954
-
955
-
956
-    /**
957
-     * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
958
-     * DB and then updates the model objects.
959
-     * Does not affect the reserved counts.
960
-     *
961
-     * @param int $qty
962
-     * @return boolean
963
-     * @throws EE_Error
964
-     * @throws InvalidArgumentException
965
-     * @throws InvalidDataTypeException
966
-     * @throws InvalidInterfaceException
967
-     * @throws ReflectionException
968
-     * @since 4.9.80.p
969
-     */
970
-    public function decreaseSold($qty = 1)
971
-    {
972
-        $qty = absint($qty);
973
-        $this->decreaseSoldForDatetimes($qty);
974
-        $success = $this->adjustNumericFieldsInDb(
975
-            [
976
-                'TKT_sold' => $qty * -1,
977
-            ]
978
-        );
979
-        do_action(
980
-            'AHEE__EE_Ticket__decrease_sold',
981
-            $this,
982
-            $qty,
983
-            $this->sold(),
984
-            $success
985
-        );
986
-        return $success;
987
-    }
988
-
989
-
990
-    /**
991
-     * Decreases sold on related datetimes
992
-     *
993
-     * @param int           $qty
994
-     * @param EE_Datetime[] $datetimes
995
-     * @return void
996
-     * @throws EE_Error
997
-     * @throws InvalidArgumentException
998
-     * @throws InvalidDataTypeException
999
-     * @throws InvalidInterfaceException
1000
-     * @throws ReflectionException
1001
-     * @since 4.9.80.p
1002
-     */
1003
-    protected function decreaseSoldForDatetimes($qty = 1, array $datetimes = [])
1004
-    {
1005
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1006
-        if (is_array($datetimes)) {
1007
-            foreach ($datetimes as $datetime) {
1008
-                if ($datetime instanceof EE_Datetime) {
1009
-                    $datetime->decreaseSold($qty);
1010
-                }
1011
-            }
1012
-        }
1013
-    }
1014
-
1015
-
1016
-    /**
1017
-     * Gets qty of reserved tickets
1018
-     *
1019
-     * @return int
1020
-     * @throws EE_Error
1021
-     * @throws ReflectionException
1022
-     */
1023
-    public function reserved(): int
1024
-    {
1025
-        return (int) $this->get_raw('TKT_reserved');
1026
-    }
1027
-
1028
-
1029
-    /**
1030
-     * Sets reserved
1031
-     *
1032
-     * @param int $reserved
1033
-     * @return void
1034
-     * @throws EE_Error
1035
-     * @throws ReflectionException
1036
-     */
1037
-    public function set_reserved($reserved)
1038
-    {
1039
-        // reserved can not go below zero
1040
-        $reserved = max(0, (int) $reserved);
1041
-        $this->set('TKT_reserved', $reserved);
1042
-    }
1043
-
1044
-
1045
-    /**
1046
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1047
-     *
1048
-     * @param int    $qty
1049
-     * @param string $source
1050
-     * @return bool whether we successfully reserved the ticket or not.
1051
-     * @throws EE_Error
1052
-     * @throws InvalidArgumentException
1053
-     * @throws ReflectionException
1054
-     * @throws InvalidDataTypeException
1055
-     * @throws InvalidInterfaceException
1056
-     * @since 4.9.80.p
1057
-     */
1058
-    public function increaseReserved($qty = 1, $source = 'unknown')
1059
-    {
1060
-        $qty = absint($qty);
1061
-        do_action(
1062
-            'AHEE__EE_Ticket__increase_reserved__begin',
1063
-            $this,
1064
-            $qty,
1065
-            $source
1066
-        );
1067
-        // comment out extra meta tracking
1068
-        // $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "{$qty} from {$source}");
1069
-        $success                         = false;
1070
-        $datetimes_adjusted_successfully = $this->increaseReservedForDatetimes($qty);
1071
-        if ($datetimes_adjusted_successfully) {
1072
-            $success = $this->incrementFieldConditionallyInDb(
1073
-                'TKT_reserved',
1074
-                'TKT_sold',
1075
-                'TKT_qty',
1076
-                $qty
1077
-            );
1078
-            if (! $success) {
1079
-                // The datetimes were successfully bumped, but not the
1080
-                // ticket. So we need to manually roll back the datetimes.
1081
-                $this->decreaseReservedForDatetimes($qty);
1082
-            }
1083
-        }
1084
-        do_action(
1085
-            'AHEE__EE_Ticket__increase_reserved',
1086
-            $this,
1087
-            $qty,
1088
-            $this->reserved(),
1089
-            $success
1090
-        );
1091
-        return $success;
1092
-    }
1093
-
1094
-
1095
-    /**
1096
-     * Increases reserved counts on related datetimes
1097
-     *
1098
-     * @param int           $qty
1099
-     * @param EE_Datetime[] $datetimes
1100
-     * @return boolean indicating success
1101
-     * @throws EE_Error
1102
-     * @throws InvalidArgumentException
1103
-     * @throws InvalidDataTypeException
1104
-     * @throws InvalidInterfaceException
1105
-     * @throws ReflectionException
1106
-     * @since 4.9.80.p
1107
-     */
1108
-    protected function increaseReservedForDatetimes($qty = 1, array $datetimes = [])
1109
-    {
1110
-        $datetimes         = ! empty($datetimes) ? $datetimes : $this->datetimes();
1111
-        $datetimes_updated = [];
1112
-        $limit_exceeded    = false;
1113
-        if (is_array($datetimes)) {
1114
-            foreach ($datetimes as $datetime) {
1115
-                if ($datetime instanceof EE_Datetime) {
1116
-                    if ($datetime->increaseReserved($qty)) {
1117
-                        $datetimes_updated[] = $datetime;
1118
-                    } else {
1119
-                        $limit_exceeded = true;
1120
-                        break;
1121
-                    }
1122
-                }
1123
-            }
1124
-            // If somewhere along the way we detected a datetime whose
1125
-            // limit was exceeded, do a manual rollback.
1126
-            if ($limit_exceeded) {
1127
-                $this->decreaseReservedForDatetimes($qty, $datetimes_updated);
1128
-                return false;
1129
-            }
1130
-        }
1131
-        return true;
1132
-    }
1133
-
1134
-
1135
-    /**
1136
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1137
-     *
1138
-     * @param int    $qty
1139
-     * @param bool   $adjust_datetimes
1140
-     * @param string $source
1141
-     * @return boolean
1142
-     * @throws EE_Error
1143
-     * @throws InvalidArgumentException
1144
-     * @throws ReflectionException
1145
-     * @throws InvalidDataTypeException
1146
-     * @throws InvalidInterfaceException
1147
-     * @since 4.9.80.p
1148
-     */
1149
-    public function decreaseReserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1150
-    {
1151
-        $qty = absint($qty);
1152
-        // comment out extra meta tracking
1153
-        // $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "-{$qty} from {$source}");
1154
-        if ($adjust_datetimes) {
1155
-            $this->decreaseReservedForDatetimes($qty);
1156
-        }
1157
-        $success = $this->adjustNumericFieldsInDb(
1158
-            [
1159
-                'TKT_reserved' => $qty * -1,
1160
-            ]
1161
-        );
1162
-        do_action(
1163
-            'AHEE__EE_Ticket__decrease_reserved',
1164
-            $this,
1165
-            $qty,
1166
-            $this->reserved(),
1167
-            $success
1168
-        );
1169
-        return $success;
1170
-    }
1171
-
1172
-
1173
-    /**
1174
-     * Decreases the reserved count on the specified datetimes.
1175
-     *
1176
-     * @param int           $qty
1177
-     * @param EE_Datetime[] $datetimes
1178
-     * @throws EE_Error
1179
-     * @throws InvalidArgumentException
1180
-     * @throws ReflectionException
1181
-     * @throws InvalidDataTypeException
1182
-     * @throws InvalidInterfaceException
1183
-     * @since 4.9.80.p
1184
-     */
1185
-    protected function decreaseReservedForDatetimes($qty = 1, array $datetimes = [])
1186
-    {
1187
-        $datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1188
-        foreach ($datetimes as $datetime) {
1189
-            if ($datetime instanceof EE_Datetime) {
1190
-                $datetime->decreaseReserved($qty);
1191
-            }
1192
-        }
1193
-    }
1194
-
1195
-
1196
-    /**
1197
-     * Gets ticket quantity
1198
-     *
1199
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1200
-     *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
1201
-     *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
1202
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1203
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1204
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1205
-     * @return int
1206
-     * @throws EE_Error
1207
-     * @throws ReflectionException
1208
-     */
1209
-    public function qty($context = '')
1210
-    {
1211
-        switch ($context) {
1212
-            case 'reg_limit':
1213
-                return $this->real_quantity_on_ticket();
1214
-            case 'saleable':
1215
-                return $this->real_quantity_on_ticket('saleable');
1216
-            default:
1217
-                return $this->get_raw('TKT_qty');
1218
-        }
1219
-    }
1220
-
1221
-
1222
-    /**
1223
-     * Gets ticket quantity
1224
-     *
1225
-     * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1226
-     *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1227
-     *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1228
-     *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1229
-     *                            is therefore the truest measure of tickets that can be purchased at the moment
1230
-     * @param int    $DTT_ID      the primary key for a particular datetime.
1231
-     *                            set to 0 for all related datetimes
1232
-     * @return int|float          int for finite quantity or float for INF
1233
-     * @throws EE_Error
1234
-     * @throws ReflectionException
1235
-     */
1236
-    public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1237
-    {
1238
-        $raw = $this->get_raw('TKT_qty');
1239
-        // return immediately if it's zero
1240
-        if ($raw === 0) {
1241
-            return $raw;
1242
-        }
1243
-        // echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1244
-        // ensure qty doesn't exceed raw value for THIS ticket
1245
-        $qty = min(EE_INF, $raw);
1246
-        // echo "\n . qty: " . $qty . '<br />';
1247
-        // calculate this ticket's total sales and reservations
1248
-        $sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1249
-        // echo "\n . sold: " . $this->sold() . '<br />';
1250
-        // echo "\n . reserved: " . $this->reserved() . '<br />';
1251
-        // echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1252
-        // first we need to calculate the maximum number of tickets available for the datetime
1253
-        // do we want data for one datetime or all of them ?
1254
-        $query_params = $DTT_ID ? [['DTT_ID' => $DTT_ID]] : [];
1255
-        $datetimes    = $this->get_many_related('Datetime', $query_params);
1256
-        if (is_array($datetimes) && ! empty($datetimes)) {
1257
-            foreach ($datetimes as $datetime) {
1258
-                if ($datetime instanceof EE_Datetime) {
1259
-                    // $datetime->refresh_from_db();
1260
-                    // echo "\n . . datetime name: " . $datetime->name() . '<br />';
1261
-                    // echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1262
-                    // initialize with no restrictions for each datetime
1263
-                    // but adjust datetime qty based on datetime reg limit
1264
-                    $datetime_qty = min(EE_INF, $datetime->reg_limit());
1265
-                    // echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1266
-                    // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1267
-                    // if we want the actual saleable amount, then we need to consider OTHER ticket sales
1268
-                    // and reservations for this datetime, that do NOT include sales and reservations
1269
-                    // for this ticket (so we add $this->sold() and $this->reserved() back in)
1270
-                    if ($context === 'saleable') {
1271
-                        $datetime_qty = max(
1272
-                            $datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1273
-                            0
1274
-                        );
1275
-                        // echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1276
-                        // echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1277
-                        // echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1278
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1279
-                        $datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1280
-                        // echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1281
-                    }
1282
-                    $qty = min($datetime_qty, $qty);
1283
-                    // echo "\n . . qty: " . $qty . '<br />';
1284
-                }
1285
-            }
1286
-        }
1287
-        // NOW that we know the  maximum number of tickets available for the datetime
1288
-        // we can finally factor in the details for this specific ticket
1289
-        if ($qty > 0 && $context === 'saleable') {
1290
-            // and subtract the sales for THIS ticket
1291
-            $qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1292
-            // echo "\n . qty: " . $qty . '<br />';
1293
-        }
1294
-        // echo "\nFINAL QTY: " . $qty . "<br /><br />";
1295
-        return $qty;
1296
-    }
1297
-
1298
-
1299
-    /**
1300
-     * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1301
-     *
1302
-     * @param int $qty
1303
-     * @return void
1304
-     * @throws EE_Error
1305
-     * @throws ReflectionException
1306
-     */
1307
-    public function set_qty($qty)
1308
-    {
1309
-        $datetimes = $this->datetimes();
1310
-        foreach ($datetimes as $datetime) {
1311
-            if ($datetime instanceof EE_Datetime) {
1312
-                $qty = min($qty, $datetime->reg_limit());
1313
-            }
1314
-        }
1315
-        $this->set('TKT_qty', $qty);
1316
-    }
1317
-
1318
-
1319
-    /**
1320
-     * Gets uses
1321
-     *
1322
-     * @return int
1323
-     * @throws EE_Error
1324
-     * @throws ReflectionException
1325
-     */
1326
-    public function uses()
1327
-    {
1328
-        return $this->get('TKT_uses');
1329
-    }
1330
-
1331
-
1332
-    /**
1333
-     * Sets uses
1334
-     *
1335
-     * @param int $uses
1336
-     * @return void
1337
-     * @throws EE_Error
1338
-     * @throws ReflectionException
1339
-     */
1340
-    public function set_uses($uses)
1341
-    {
1342
-        $this->set('TKT_uses', $uses);
1343
-    }
1344
-
1345
-
1346
-    /**
1347
-     * returns whether ticket is required or not.
1348
-     *
1349
-     * @return boolean
1350
-     * @throws EE_Error
1351
-     * @throws ReflectionException
1352
-     */
1353
-    public function required()
1354
-    {
1355
-        return $this->get('TKT_required');
1356
-    }
1357
-
1358
-
1359
-    /**
1360
-     * sets the TKT_required property
1361
-     *
1362
-     * @param boolean $required
1363
-     * @return void
1364
-     * @throws EE_Error
1365
-     * @throws ReflectionException
1366
-     */
1367
-    public function set_required($required)
1368
-    {
1369
-        $this->set('TKT_required', $required);
1370
-    }
1371
-
1372
-
1373
-    /**
1374
-     * Gets taxable
1375
-     *
1376
-     * @return boolean
1377
-     * @throws EE_Error
1378
-     * @throws ReflectionException
1379
-     */
1380
-    public function taxable()
1381
-    {
1382
-        return $this->get('TKT_taxable');
1383
-    }
1384
-
1385
-
1386
-    /**
1387
-     * Sets taxable
1388
-     *
1389
-     * @param boolean $taxable
1390
-     * @return void
1391
-     * @throws EE_Error
1392
-     * @throws ReflectionException
1393
-     */
1394
-    public function set_taxable($taxable)
1395
-    {
1396
-        $this->set('TKT_taxable', $taxable);
1397
-    }
1398
-
1399
-
1400
-    /**
1401
-     * Gets is_default
1402
-     *
1403
-     * @return boolean
1404
-     * @throws EE_Error
1405
-     * @throws ReflectionException
1406
-     */
1407
-    public function is_default()
1408
-    {
1409
-        return $this->get('TKT_is_default');
1410
-    }
1411
-
1412
-
1413
-    /**
1414
-     * Sets is_default
1415
-     *
1416
-     * @param boolean $is_default
1417
-     * @return void
1418
-     * @throws EE_Error
1419
-     * @throws ReflectionException
1420
-     */
1421
-    public function set_is_default($is_default)
1422
-    {
1423
-        $this->set('TKT_is_default', $is_default);
1424
-    }
1425
-
1426
-
1427
-    /**
1428
-     * Gets order
1429
-     *
1430
-     * @return int
1431
-     * @throws EE_Error
1432
-     * @throws ReflectionException
1433
-     */
1434
-    public function order()
1435
-    {
1436
-        return $this->get('TKT_order');
1437
-    }
1438
-
1439
-
1440
-    /**
1441
-     * Sets order
1442
-     *
1443
-     * @param int $order
1444
-     * @return void
1445
-     * @throws EE_Error
1446
-     * @throws ReflectionException
1447
-     */
1448
-    public function set_order($order)
1449
-    {
1450
-        $this->set('TKT_order', $order);
1451
-    }
1452
-
1453
-
1454
-    /**
1455
-     * Gets row
1456
-     *
1457
-     * @return int
1458
-     * @throws EE_Error
1459
-     * @throws ReflectionException
1460
-     */
1461
-    public function row()
1462
-    {
1463
-        return $this->get('TKT_row');
1464
-    }
1465
-
1466
-
1467
-    /**
1468
-     * Sets row
1469
-     *
1470
-     * @param int $row
1471
-     * @return void
1472
-     * @throws EE_Error
1473
-     * @throws ReflectionException
1474
-     */
1475
-    public function set_row($row)
1476
-    {
1477
-        $this->set('TKT_row', $row);
1478
-    }
1479
-
1480
-
1481
-    /**
1482
-     * Gets deleted
1483
-     *
1484
-     * @return boolean
1485
-     * @throws EE_Error
1486
-     * @throws ReflectionException
1487
-     */
1488
-    public function deleted()
1489
-    {
1490
-        return $this->get('TKT_deleted');
1491
-    }
1492
-
1493
-
1494
-    /**
1495
-     * Sets deleted
1496
-     *
1497
-     * @param boolean $deleted
1498
-     * @return void
1499
-     * @throws EE_Error
1500
-     * @throws ReflectionException
1501
-     */
1502
-    public function set_deleted($deleted)
1503
-    {
1504
-        $this->set('TKT_deleted', $deleted);
1505
-    }
1506
-
1507
-
1508
-    /**
1509
-     * Gets parent
1510
-     *
1511
-     * @return int
1512
-     * @throws EE_Error
1513
-     * @throws ReflectionException
1514
-     */
1515
-    public function parent_ID()
1516
-    {
1517
-        return $this->get('TKT_parent');
1518
-    }
1519
-
1520
-
1521
-    /**
1522
-     * Sets parent
1523
-     *
1524
-     * @param int $parent
1525
-     * @return void
1526
-     * @throws EE_Error
1527
-     * @throws ReflectionException
1528
-     */
1529
-    public function set_parent_ID($parent)
1530
-    {
1531
-        $this->set('TKT_parent', $parent);
1532
-    }
1533
-
1534
-
1535
-    /**
1536
-     * @return boolean
1537
-     * @throws EE_Error
1538
-     * @throws InvalidArgumentException
1539
-     * @throws InvalidDataTypeException
1540
-     * @throws InvalidInterfaceException
1541
-     * @throws ReflectionException
1542
-     */
1543
-    public function reverse_calculate()
1544
-    {
1545
-        return $this->get('TKT_reverse_calculate');
1546
-    }
1547
-
1548
-
1549
-    /**
1550
-     * @param boolean $reverse_calculate
1551
-     * @throws EE_Error
1552
-     * @throws InvalidArgumentException
1553
-     * @throws InvalidDataTypeException
1554
-     * @throws InvalidInterfaceException
1555
-     * @throws ReflectionException
1556
-     */
1557
-    public function set_reverse_calculate($reverse_calculate)
1558
-    {
1559
-        $this->set('TKT_reverse_calculate', $reverse_calculate);
1560
-    }
1561
-
1562
-
1563
-    /**
1564
-     * Gets a string which is handy for showing in gateways etc that describes the ticket.
1565
-     *
1566
-     * @return string
1567
-     * @throws EE_Error
1568
-     * @throws ReflectionException
1569
-     */
1570
-    public function name_and_info()
1571
-    {
1572
-        $times = [];
1573
-        foreach ($this->datetimes() as $datetime) {
1574
-            $times[] = $datetime->start_date_and_time();
1575
-        }
1576
-        /* translators: %1$s ticket name, %2$s start datetimes separated by comma, %3$s ticket price */
1577
-        return sprintf(
1578
-            esc_html__('%1$s @ %2$s for %3$s', 'event_espresso'),
1579
-            $this->name(),
1580
-            implode(', ', $times),
1581
-            $this->pretty_price()
1582
-        );
1583
-    }
1584
-
1585
-
1586
-    /**
1587
-     * Gets name
1588
-     *
1589
-     * @return string
1590
-     * @throws EE_Error
1591
-     * @throws ReflectionException
1592
-     */
1593
-    public function name()
1594
-    {
1595
-        return $this->get('TKT_name');
1596
-    }
1597
-
1598
-
1599
-    /**
1600
-     * Gets price
1601
-     *
1602
-     * @return float
1603
-     * @throws EE_Error
1604
-     * @throws ReflectionException
1605
-     */
1606
-    public function price()
1607
-    {
1608
-        return $this->get('TKT_price');
1609
-    }
1610
-
1611
-
1612
-    /**
1613
-     * Gets all the registrations for this ticket
1614
-     *
1615
-     * @param array $query_params
1616
-     * @return EE_Registration[]|EE_Base_Class[]
1617
-     * @throws EE_Error
1618
-     * @throws ReflectionException
1619
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1620
-     */
1621
-    public function registrations($query_params = [])
1622
-    {
1623
-        return $this->get_many_related('Registration', $query_params);
1624
-    }
1625
-
1626
-
1627
-    /**
1628
-     * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1629
-     *
1630
-     * @return int
1631
-     * @throws EE_Error
1632
-     * @throws ReflectionException
1633
-     */
1634
-    public function update_tickets_sold()
1635
-    {
1636
-        $count_regs_for_this_ticket = $this->count_registrations(
1637
-            [
1638
-                [
1639
-                    'STS_ID'      => RegStatus::APPROVED,
1640
-                    'REG_deleted' => 0,
1641
-                ],
1642
-            ]
1643
-        );
1644
-        $this->set_sold($count_regs_for_this_ticket);
1645
-        $this->save();
1646
-        return $count_regs_for_this_ticket;
1647
-    }
1648
-
1649
-
1650
-    /**
1651
-     * Counts the registrations for this ticket
1652
-     *
1653
-     * @param array $query_params
1654
-     * @return int
1655
-     * @throws EE_Error
1656
-     * @throws ReflectionException
1657
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1658
-     */
1659
-    public function count_registrations($query_params = [])
1660
-    {
1661
-        return $this->count_related('Registration', $query_params);
1662
-    }
1663
-
1664
-
1665
-    /**
1666
-     * Implementation for EEI_Has_Icon interface method.
1667
-     *
1668
-     * @return string
1669
-     * @see EEI_Visual_Representation for comments
1670
-     */
1671
-    public function get_icon()
1672
-    {
1673
-        return '<span class="dashicons dashicons-tickets-alt"></span>';
1674
-    }
1675
-
1676
-
1677
-    /**
1678
-     * Implementation of the EEI_Event_Relation interface method
1679
-     *
1680
-     * @return EE_Event
1681
-     * @throws EE_Error
1682
-     * @throws UnexpectedEntityException
1683
-     * @throws ReflectionException
1684
-     * @see EEI_Event_Relation for comments
1685
-     */
1686
-    public function get_related_event()
1687
-    {
1688
-        // get one datetime to use for getting the event
1689
-        $datetime = $this->first_datetime();
1690
-        if (! $datetime instanceof EE_Datetime) {
1691
-            throw new UnexpectedEntityException(
1692
-                $datetime,
1693
-                'EE_Datetime',
1694
-                sprintf(
1695
-                    esc_html__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1696
-                    $this->name()
1697
-                )
1698
-            );
1699
-        }
1700
-        $event = $datetime->event();
1701
-        if (! $event instanceof EE_Event) {
1702
-            throw new UnexpectedEntityException(
1703
-                $event,
1704
-                'EE_Event',
1705
-                sprintf(
1706
-                    esc_html__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1707
-                    $this->name()
1708
-                )
1709
-            );
1710
-        }
1711
-        return $event;
1712
-    }
1713
-
1714
-
1715
-    /**
1716
-     * Implementation of the EEI_Event_Relation interface method
1717
-     *
1718
-     * @return string
1719
-     * @throws UnexpectedEntityException
1720
-     * @throws EE_Error
1721
-     * @throws ReflectionException
1722
-     * @see EEI_Event_Relation for comments
1723
-     */
1724
-    public function get_event_name()
1725
-    {
1726
-        $event = $this->get_related_event();
1727
-        return $event instanceof EE_Event ? $event->name() : '';
1728
-    }
1729
-
1730
-
1731
-    /**
1732
-     * Implementation of the EEI_Event_Relation interface method
1733
-     *
1734
-     * @return int
1735
-     * @throws UnexpectedEntityException
1736
-     * @throws EE_Error
1737
-     * @throws ReflectionException
1738
-     * @see EEI_Event_Relation for comments
1739
-     */
1740
-    public function get_event_ID()
1741
-    {
1742
-        $event = $this->get_related_event();
1743
-        return $event instanceof EE_Event ? $event->ID() : 0;
1744
-    }
1745
-
1746
-
1747
-    /**
1748
-     * This simply returns whether a ticket can be permanently deleted or not.
1749
-     * The criteria for determining this is whether the ticket has any related registrations.
1750
-     * If there are none then it can be permanently deleted.
1751
-     *
1752
-     * @return bool
1753
-     * @throws EE_Error
1754
-     * @throws ReflectionException
1755
-     */
1756
-    public function is_permanently_deleteable()
1757
-    {
1758
-        return $this->count_registrations() === 0;
1759
-    }
1760
-
1761
-
1762
-    /**
1763
-     * @return int
1764
-     * @throws EE_Error
1765
-     * @throws ReflectionException
1766
-     * @since   5.0.0.p
1767
-     */
1768
-    public function visibility(): int
1769
-    {
1770
-        return $this->get('TKT_visibility');
1771
-    }
1772
-
1773
-
1774
-    /**
1775
-     * @return bool
1776
-     * @throws EE_Error
1777
-     * @throws ReflectionException
1778
-     * @since   5.0.0.p
1779
-     */
1780
-    public function isHidden(): bool
1781
-    {
1782
-        return $this->visibility() === EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1783
-    }
1784
-
1785
-
1786
-    /**
1787
-     * @return bool
1788
-     * @throws EE_Error
1789
-     * @throws ReflectionException
1790
-     * @since   5.0.0.p
1791
-     */
1792
-    public function isNotHidden(): bool
1793
-    {
1794
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1795
-    }
1796
-
1797
-
1798
-    /**
1799
-     * @return bool
1800
-     * @throws EE_Error
1801
-     * @throws ReflectionException
1802
-     * @since   5.0.0.p
1803
-     */
1804
-    public function isPublicOnly(): bool
1805
-    {
1806
-        return $this->isNotHidden() && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE;
1807
-    }
1808
-
1809
-
1810
-    /**
1811
-     * @return bool
1812
-     * @throws EE_Error
1813
-     * @throws ReflectionException
1814
-     * @since   5.0.0.p
1815
-     */
1816
-    public function isMembersOnly(): bool
1817
-    {
1818
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE
1819
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE;
1820
-    }
1821
-
1822
-
1823
-    /**
1824
-     * @return bool
1825
-     * @throws EE_Error
1826
-     * @throws ReflectionException
1827
-     * @since   5.0.0.p
1828
-     */
1829
-    public function isAdminsOnly(): bool
1830
-    {
1831
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE
1832
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE;
1833
-    }
1834
-
1835
-
1836
-    /**
1837
-     * @return bool
1838
-     * @throws EE_Error
1839
-     * @throws ReflectionException
1840
-     * @since   5.0.0.p
1841
-     */
1842
-    public function isAdminUiOnly(): bool
1843
-    {
1844
-        return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE
1845
-               && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE;
1846
-    }
1847
-
1848
-
1849
-    /**
1850
-     * @param int $visibility
1851
-     * @throws EE_Error
1852
-     * @throws ReflectionException
1853
-     * @since   5.0.0.p
1854
-     */
1855
-    public function set_visibility(int $visibility)
1856
-    {
1857
-        $ticket_visibility_options = $this->_model->ticketVisibilityOptions();
1858
-        $ticket_visibility         = -1;
1859
-        foreach ($ticket_visibility_options as $ticket_visibility_option) {
1860
-            if ($visibility === $ticket_visibility_option) {
1861
-                $ticket_visibility = $visibility;
1862
-            }
1863
-        }
1864
-        if ($ticket_visibility === -1) {
1865
-            throw new DomainException(
1866
-                sprintf(
1867
-                    esc_html__(
1868
-                        '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 ',
1869
-                        'event_espresso'
1870
-                    ),
1871
-                    $visibility,
1872
-                    '<br />',
1873
-                    var_export($ticket_visibility_options, true)
1874
-                )
1875
-            );
1876
-        }
1877
-        $this->set('TKT_visibility', $ticket_visibility);
1878
-    }
1879
-
1880
-
1881
-    /**
1882
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1883
-     * @param string                   $relationName
1884
-     * @param array                    $extra_join_model_fields_n_values
1885
-     * @param string|null              $cache_id
1886
-     * @return EE_Base_Class
1887
-     * @throws EE_Error
1888
-     * @throws ReflectionException
1889
-     * @since   5.0.0.p
1890
-     */
1891
-    public function _add_relation_to(
1892
-        $otherObjectModelObjectOrID,
1893
-        $relationName,
1894
-        $extra_join_model_fields_n_values = [],
1895
-        $cache_id = null
1896
-    ) {
1897
-        if ($relationName === 'Datetime' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1898
-            /** @var EE_Datetime $datetime */
1899
-            $datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1900
-            $datetime->increaseSold($this->sold(), false);
1901
-            $datetime->increaseReserved($this->reserved());
1902
-            $datetime->save();
1903
-            $otherObjectModelObjectOrID = $datetime;
1904
-        }
1905
-        return parent::_add_relation_to(
1906
-            $otherObjectModelObjectOrID,
1907
-            $relationName,
1908
-            $extra_join_model_fields_n_values,
1909
-            $cache_id
1910
-        );
1911
-    }
1912
-
1913
-
1914
-    /**
1915
-     * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1916
-     * @param string                   $relationName
1917
-     * @param array                    $where_query
1918
-     * @return bool|EE_Base_Class|null
1919
-     * @throws EE_Error
1920
-     * @throws ReflectionException
1921
-     * @since   5.0.0.p
1922
-     */
1923
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1924
-    {
1925
-        // if we're adding a new relation to a datetime
1926
-        if ($relationName === 'Datetime' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1927
-            /** @var EE_Datetime $datetime */
1928
-            $datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1929
-            $datetime->decreaseSold($this->sold());
1930
-            $datetime->decreaseReserved($this->reserved());
1931
-            $datetime->save();
1932
-            $otherObjectModelObjectOrID = $datetime;
1933
-        }
1934
-        return parent::_remove_relation_to(
1935
-            $otherObjectModelObjectOrID,
1936
-            $relationName,
1937
-            $where_query
1938
-        );
1939
-    }
1940
-
1941
-
1942
-    /**
1943
-     * Removes ALL the related things for the $relationName.
1944
-     *
1945
-     * @param string $relationName
1946
-     * @param array  $where_query_params
1947
-     * @return EE_Base_Class
1948
-     * @throws ReflectionException
1949
-     * @throws InvalidArgumentException
1950
-     * @throws InvalidInterfaceException
1951
-     * @throws InvalidDataTypeException
1952
-     * @throws EE_Error
1953
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1954
-     */
1955
-    public function _remove_relations($relationName, $where_query_params = [])
1956
-    {
1957
-        if ($relationName === 'Datetime') {
1958
-            $datetimes = $this->datetimes();
1959
-            foreach ($datetimes as $datetime) {
1960
-                $datetime->decreaseSold($this->sold());
1961
-                $datetime->decreaseReserved($this->reserved());
1962
-                $datetime->save();
1963
-            }
1964
-        }
1965
-        return parent::_remove_relations($relationName, $where_query_params);
1966
-    }
1967
-
1968
-
1969
-    /*******************************************************************
18
+	/**
19
+	 * TicKet Archived:
20
+	 * constant used by ticket_status() to indicate that a ticket is archived
21
+	 * and no longer available for purchase
22
+	 */
23
+	const archived = 'TKA';
24
+
25
+	/**
26
+	 * TicKet Expired:
27
+	 * constant used by ticket_status() to indicate that a ticket is expired
28
+	 * and no longer available for purchase
29
+	 */
30
+	const expired = 'TKE';
31
+
32
+	/**
33
+	 * TicKet On sale:
34
+	 * constant used by ticket_status() to indicate that a ticket is On Sale
35
+	 * and IS available for purchase
36
+	 */
37
+	const onsale = 'TKO';
38
+
39
+	/**
40
+	 * TicKet Pending:
41
+	 * constant used by ticket_status() to indicate that a ticket is pending
42
+	 * and is NOT YET available for purchase
43
+	 */
44
+	const pending = 'TKP';
45
+
46
+	/**
47
+	 * TicKet Sold out:
48
+	 * constant used by ticket_status() to indicate that a ticket is sold out
49
+	 * and no longer available for purchases
50
+	 */
51
+	const sold_out = 'TKS';
52
+
53
+	/**
54
+	 * extra meta key for tracking ticket reservations
55
+	 *
56
+	 * @type string
57
+	 */
58
+	const META_KEY_TICKET_RESERVATIONS = 'ticket_reservations';
59
+
60
+	/**
61
+	 * override of parent property
62
+	 *
63
+	 * @var EEM_Ticket
64
+	 */
65
+	protected $_model;
66
+
67
+	/**
68
+	 * cached result from method of the same name
69
+	 *
70
+	 * @var float $_ticket_total_with_taxes
71
+	 */
72
+	private $_ticket_total_with_taxes;
73
+
74
+	/**
75
+	 * @var TicketPriceModifiers
76
+	 */
77
+	protected $ticket_price_modifiers;
78
+
79
+
80
+	/**
81
+	 * @param array  $props_n_values          incoming values
82
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
83
+	 *                                        used.)
84
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
85
+	 *                                        date_format and the second value is the time format
86
+	 * @return EE_Ticket
87
+	 * @throws EE_Error
88
+	 * @throws ReflectionException
89
+	 */
90
+	public static function new_instance($props_n_values = [], $timezone = '', $date_formats = [])
91
+	{
92
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
93
+		return $has_object ?: new self($props_n_values, false, $timezone, $date_formats);
94
+	}
95
+
96
+
97
+	/**
98
+	 * @param array  $props_n_values  incoming values from the database
99
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
100
+	 *                                the website will be used.
101
+	 * @return EE_Ticket
102
+	 * @throws EE_Error
103
+	 * @throws ReflectionException
104
+	 */
105
+	public static function new_instance_from_db($props_n_values = [], $timezone = '')
106
+	{
107
+		return new self($props_n_values, true, $timezone);
108
+	}
109
+
110
+
111
+	/**
112
+	 * @param array  $fieldValues
113
+	 * @param false  $bydb
114
+	 * @param string $timezone
115
+	 * @param array  $date_formats
116
+	 * @throws EE_Error
117
+	 * @throws ReflectionException
118
+	 */
119
+	public function __construct($fieldValues = [], $bydb = false, $timezone = '', $date_formats = [])
120
+	{
121
+		parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
122
+		$this->ticket_price_modifiers = new TicketPriceModifiers($this);
123
+	}
124
+
125
+
126
+	/**
127
+	 * @return bool
128
+	 * @throws EE_Error
129
+	 * @throws ReflectionException
130
+	 */
131
+	public function parent()
132
+	{
133
+		return $this->get('TKT_parent');
134
+	}
135
+
136
+
137
+	/**
138
+	 * return if a ticket has quantities available for purchase
139
+	 *
140
+	 * @param int $DTT_ID the primary key for a particular datetime
141
+	 * @return boolean
142
+	 * @throws EE_Error
143
+	 * @throws ReflectionException
144
+	 */
145
+	public function available($DTT_ID = 0)
146
+	{
147
+		// are we checking availability for a particular datetime ?
148
+		if ($DTT_ID) {
149
+			// get that datetime object
150
+			$datetime = $this->get_first_related('Datetime', [['DTT_ID' => $DTT_ID]]);
151
+			// if  ticket sales for this datetime have exceeded the reg limit...
152
+			if ($datetime instanceof EE_Datetime && $datetime->sold_out()) {
153
+				return false;
154
+			}
155
+		}
156
+		// datetime is still open for registration, but is this ticket sold out ?
157
+		return $this->qty() < 1 || $this->qty() > $this->sold();
158
+	}
159
+
160
+
161
+	/**
162
+	 * Using the start date and end date this method calculates whether the ticket is On Sale, Pending, or Expired
163
+	 *
164
+	 * @param bool        $display   true = we'll return a localized string, otherwise we just return the value of the
165
+	 *                               relevant status const
166
+	 * @param bool | null $remaining if it is already known that tickets are available, then simply pass a bool to save
167
+	 *                               further processing
168
+	 * @return mixed status int if the display string isn't requested
169
+	 * @throws EE_Error
170
+	 * @throws ReflectionException
171
+	 */
172
+	public function ticket_status($display = false, $remaining = null)
173
+	{
174
+		$remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
175
+		if (! $remaining) {
176
+			return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
177
+		}
178
+		if ($this->get('TKT_deleted')) {
179
+			return $display ? EEH_Template::pretty_status(EE_Ticket::archived, false, 'sentence') : EE_Ticket::archived;
180
+		}
181
+		if ($this->is_expired()) {
182
+			return $display ? EEH_Template::pretty_status(EE_Ticket::expired, false, 'sentence') : EE_Ticket::expired;
183
+		}
184
+		if ($this->is_pending()) {
185
+			return $display ? EEH_Template::pretty_status(EE_Ticket::pending, false, 'sentence') : EE_Ticket::pending;
186
+		}
187
+		if ($this->is_on_sale()) {
188
+			return $display ? EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence') : EE_Ticket::onsale;
189
+		}
190
+		return '';
191
+	}
192
+
193
+
194
+	/**
195
+	 * The purpose of this method is to simply return a boolean for whether there are any tickets remaining for sale
196
+	 * considering ALL the factors used for figuring that out.
197
+	 *
198
+	 * @param int $DTT_ID if an int above 0 is included here then we get a specific dtt.
199
+	 * @return boolean         true = tickets remaining, false not.
200
+	 * @throws EE_Error
201
+	 * @throws ReflectionException
202
+	 */
203
+	public function is_remaining($DTT_ID = 0)
204
+	{
205
+		$num_remaining = $this->remaining($DTT_ID);
206
+		if ($num_remaining === 0) {
207
+			return false;
208
+		}
209
+		if ($num_remaining > 0 && $num_remaining < $this->min()) {
210
+			return false;
211
+		}
212
+		return true;
213
+	}
214
+
215
+
216
+	/**
217
+	 * return the total number of tickets available for purchase
218
+	 *
219
+	 * @param int $DTT_ID  the primary key for a particular datetime.
220
+	 *                     set to 0 for all related datetimes
221
+	 * @return int
222
+	 * @throws EE_Error
223
+	 * @throws ReflectionException
224
+	 */
225
+	public function remaining($DTT_ID = 0)
226
+	{
227
+		return $this->real_quantity_on_ticket('saleable', $DTT_ID);
228
+	}
229
+
230
+
231
+	/**
232
+	 * Gets min
233
+	 *
234
+	 * @return int
235
+	 * @throws EE_Error
236
+	 * @throws ReflectionException
237
+	 */
238
+	public function min()
239
+	{
240
+		return $this->get('TKT_min');
241
+	}
242
+
243
+
244
+	/**
245
+	 * return if a ticket is no longer available cause its available dates have expired.
246
+	 *
247
+	 * @return boolean
248
+	 * @throws EE_Error
249
+	 * @throws ReflectionException
250
+	 */
251
+	public function is_expired()
252
+	{
253
+		return ($this->get_raw('TKT_end_date') < time());
254
+	}
255
+
256
+
257
+	/**
258
+	 * Return if a ticket is yet to go on sale or not
259
+	 *
260
+	 * @return boolean
261
+	 * @throws EE_Error
262
+	 * @throws ReflectionException
263
+	 */
264
+	public function is_pending()
265
+	{
266
+		return ($this->get_raw('TKT_start_date') >= time());
267
+	}
268
+
269
+
270
+	/**
271
+	 * Return if a ticket is on sale or not
272
+	 *
273
+	 * @return boolean
274
+	 * @throws EE_Error
275
+	 * @throws ReflectionException
276
+	 */
277
+	public function is_on_sale()
278
+	{
279
+		return ($this->get_raw('TKT_start_date') <= time() && $this->get_raw('TKT_end_date') >= time());
280
+	}
281
+
282
+
283
+	/**
284
+	 * This returns the chronologically last datetime that this ticket is associated with
285
+	 *
286
+	 * @param string $date_format
287
+	 * @param string $conjunction - conjunction junction what's your function ? this string joins the start date with
288
+	 *                            the end date ie: Jan 01 "to" Dec 31
289
+	 * @return string
290
+	 * @throws EE_Error
291
+	 * @throws ReflectionException
292
+	 */
293
+	public function date_range($date_format = '', $conjunction = ' - ')
294
+	{
295
+		$date_format = ! empty($date_format) ? $date_format : $this->_dt_frmt;
296
+		$first_date  = $this->first_datetime() instanceof EE_Datetime
297
+			? $this->first_datetime()->get_i18n_datetime('DTT_EVT_start', $date_format)
298
+			: '';
299
+		$last_date   = $this->last_datetime() instanceof EE_Datetime
300
+			? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $date_format)
301
+			: '';
302
+
303
+		return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
304
+	}
305
+
306
+
307
+	/**
308
+	 * This returns the chronologically first datetime that this ticket is associated with
309
+	 *
310
+	 * @return EE_Datetime
311
+	 * @throws EE_Error
312
+	 * @throws ReflectionException
313
+	 */
314
+	public function first_datetime()
315
+	{
316
+		$datetimes = $this->datetimes(['limit' => 1]);
317
+		return reset($datetimes);
318
+	}
319
+
320
+
321
+	/**
322
+	 * Gets all the datetimes this ticket can be used for attending.
323
+	 * Unless otherwise specified, orders datetimes by start date.
324
+	 *
325
+	 * @param array $query_params
326
+	 * @return EE_Datetime[]|EE_Base_Class[]
327
+	 * @throws EE_Error
328
+	 * @throws ReflectionException
329
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
330
+	 */
331
+	public function datetimes($query_params = [])
332
+	{
333
+		if (! isset($query_params['order_by'])) {
334
+			$query_params['order_by']['DTT_order'] = 'ASC';
335
+		}
336
+		return $this->get_many_related('Datetime', $query_params);
337
+	}
338
+
339
+
340
+	/**
341
+	 * This returns the chronologically last datetime that this ticket is associated with
342
+	 *
343
+	 * @return EE_Datetime
344
+	 * @throws EE_Error
345
+	 * @throws ReflectionException
346
+	 */
347
+	public function last_datetime()
348
+	{
349
+		$datetimes = $this->datetimes(['limit' => 1, 'order_by' => ['DTT_EVT_start' => 'DESC']]);
350
+		return end($datetimes);
351
+	}
352
+
353
+
354
+	/**
355
+	 * This returns the total tickets sold depending on the given parameters.
356
+	 *
357
+	 * @param string $what    Can be one of two options: 'ticket', 'datetime'.
358
+	 *                        'ticket' = total ticket sales for all datetimes this ticket is related to
359
+	 *                        'datetime' = total ticket sales for a specified datetime (required $dtt_id)
360
+	 *                        'datetime' = total ticket sales in the datetime_ticket table.
361
+	 *                        If $dtt_id is not given then we return an array of sales indexed by datetime.
362
+	 *                        If $dtt_id IS given then we return the tickets sold for that given datetime.
363
+	 * @param int    $dtt_id  [optional] include the dtt_id with $what = 'datetime'.
364
+	 * @return mixed (array|int)          how many tickets have sold
365
+	 * @throws EE_Error
366
+	 * @throws ReflectionException
367
+	 */
368
+	public function tickets_sold($what = 'ticket', $dtt_id = null)
369
+	{
370
+		$total        = 0;
371
+		$tickets_sold = $this->_all_tickets_sold();
372
+		switch ($what) {
373
+			case 'ticket':
374
+				return $tickets_sold['ticket'];
375
+
376
+			case 'datetime':
377
+				if (empty($tickets_sold['datetime'])) {
378
+					return $total;
379
+				}
380
+				if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
381
+					EE_Error::add_error(
382
+						esc_html__(
383
+							'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?',
384
+							'event_espresso'
385
+						),
386
+						__FILE__,
387
+						__FUNCTION__,
388
+						__LINE__
389
+					);
390
+					return $total;
391
+				}
392
+				return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
393
+
394
+			default:
395
+				return $total;
396
+		}
397
+	}
398
+
399
+
400
+	/**
401
+	 * This returns an array indexed by datetime_id for tickets sold with this ticket.
402
+	 *
403
+	 * @return EE_Ticket[]
404
+	 * @throws EE_Error
405
+	 * @throws ReflectionException
406
+	 */
407
+	protected function _all_tickets_sold()
408
+	{
409
+		$datetimes    = $this->get_many_related('Datetime');
410
+		$tickets_sold = [];
411
+		if (! empty($datetimes)) {
412
+			foreach ($datetimes as $datetime) {
413
+				$tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
414
+			}
415
+		}
416
+		// Tickets sold
417
+		$tickets_sold['ticket'] = $this->sold();
418
+		return $tickets_sold;
419
+	}
420
+
421
+
422
+	/**
423
+	 * This returns the base price object for the ticket.
424
+	 *
425
+	 * @param bool $return_array whether to return as an array indexed by price id or just the object.
426
+	 * @return EE_Price|EE_Base_Class|EE_Price[]|EE_Base_Class[]
427
+	 * @throws EE_Error
428
+	 * @throws ReflectionException
429
+	 */
430
+	public function base_price(bool $return_array = false)
431
+	{
432
+		$base_price = $this->ticket_price_modifiers->getBasePrice();
433
+		if (! empty($base_price)) {
434
+			return $return_array ? $base_price : reset($base_price);
435
+		}
436
+		$_where = ['Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price];
437
+		return $return_array
438
+			? $this->get_many_related('Price', [$_where])
439
+			: $this->get_first_related('Price', [$_where]);
440
+	}
441
+
442
+
443
+	/**
444
+	 * This returns ONLY the price modifiers for the ticket (i.e. no taxes or base price)
445
+	 *
446
+	 * @return EE_Price[]
447
+	 * @throws EE_Error
448
+	 * @throws ReflectionException
449
+	 */
450
+	public function price_modifiers(): array
451
+	{
452
+		$price_modifiers = $this->usesGlobalTaxes()
453
+			? $this->ticket_price_modifiers->getAllDiscountAndSurchargeModifiersForTicket()
454
+			: $this->ticket_price_modifiers->getAllModifiersForTicket();
455
+		if (! empty($price_modifiers)) {
456
+			return $price_modifiers;
457
+		}
458
+		return $this->prices(
459
+			[
460
+				[
461
+					'Price_Type.PBT_ID' => [
462
+						'NOT IN',
463
+						[EEM_Price_Type::base_type_base_price, EEM_Price_Type::base_type_tax],
464
+					],
465
+				],
466
+			]
467
+		);
468
+	}
469
+
470
+
471
+	/**
472
+	 * This returns ONLY the TAX price modifiers for the ticket
473
+	 *
474
+	 * @return EE_Price[]
475
+	 * @throws EE_Error
476
+	 * @throws ReflectionException
477
+	 */
478
+	public function tax_price_modifiers(): array
479
+	{
480
+		$tax_price_modifiers = $this->ticket_price_modifiers->getAllTaxesForTicket();
481
+		if (! empty($tax_price_modifiers)) {
482
+			return $tax_price_modifiers;
483
+		}
484
+		return $this->prices([['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax]]);
485
+	}
486
+
487
+
488
+	/**
489
+	 * Gets all the prices that combine to form the final price of this ticket
490
+	 *
491
+	 * @param array $query_params
492
+	 * @return EE_Price[]|EE_Base_Class[]
493
+	 * @throws EE_Error
494
+	 * @throws ReflectionException
495
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
496
+	 */
497
+	public function prices(array $query_params = []): array
498
+	{
499
+		if (! isset($query_params['order_by'])) {
500
+			$query_params['order_by']['PRC_order'] = 'ASC';
501
+		}
502
+		return $this->get_many_related('Price', $query_params);
503
+	}
504
+
505
+
506
+	/**
507
+	 * Gets all the ticket datetimes (ie, relations between datetimes and tickets)
508
+	 *
509
+	 * @param array $query_params
510
+	 * @return EE_Datetime_Ticket|EE_Base_Class[]
511
+	 * @throws EE_Error
512
+	 * @throws ReflectionException
513
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
514
+	 */
515
+	public function datetime_tickets($query_params = [])
516
+	{
517
+		return $this->get_many_related('Datetime_Ticket', $query_params);
518
+	}
519
+
520
+
521
+	/**
522
+	 * Gets all the datetimes from the db ordered by DTT_order
523
+	 *
524
+	 * @param boolean $show_expired
525
+	 * @param boolean $show_deleted
526
+	 * @return EE_Datetime[]
527
+	 * @throws EE_Error
528
+	 * @throws ReflectionException
529
+	 */
530
+	public function datetimes_ordered($show_expired = true, $show_deleted = false)
531
+	{
532
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_ticket_ordered_by_DTT_order(
533
+			$this->ID(),
534
+			$show_expired,
535
+			$show_deleted
536
+		);
537
+	}
538
+
539
+
540
+	/**
541
+	 * Gets ID
542
+	 *
543
+	 * @return int
544
+	 * @throws EE_Error
545
+	 * @throws ReflectionException
546
+	 */
547
+	public function ID()
548
+	{
549
+		return (int) $this->get('TKT_ID');
550
+	}
551
+
552
+
553
+	/**
554
+	 * get the author of the ticket.
555
+	 *
556
+	 * @return int
557
+	 * @throws EE_Error
558
+	 * @throws ReflectionException
559
+	 * @since 4.5.0
560
+	 */
561
+	public function wp_user()
562
+	{
563
+		return $this->get('TKT_wp_user');
564
+	}
565
+
566
+
567
+	/**
568
+	 * Gets the template for the ticket
569
+	 *
570
+	 * @return EE_Ticket_Template|EE_Base_Class
571
+	 * @throws EE_Error
572
+	 * @throws ReflectionException
573
+	 */
574
+	public function template()
575
+	{
576
+		return $this->get_first_related('Ticket_Template');
577
+	}
578
+
579
+
580
+	/**
581
+	 * Simply returns an array of EE_Price objects that are taxes.
582
+	 *
583
+	 * @return EE_Price[]
584
+	 * @throws EE_Error
585
+	 * @throws ReflectionException
586
+	 */
587
+	public function get_ticket_taxes_for_admin(): array
588
+	{
589
+		return $this->usesGlobalTaxes() ? EE_Taxes::get_taxes_for_admin() : $this->tax_price_modifiers();
590
+	}
591
+
592
+
593
+	/**
594
+	 * alias of taxable() to better indicate that ticket uses the legacy method of applying default "global" taxes
595
+	 * as opposed to having tax price modifiers added directly to each ticket
596
+	 *
597
+	 * @return bool
598
+	 * @throws EE_Error
599
+	 * @throws ReflectionException
600
+	 * @since   5.0.0.p
601
+	 */
602
+	public function usesGlobalTaxes(): bool
603
+	{
604
+		return $this->taxable();
605
+	}
606
+
607
+
608
+	/**
609
+	 * @return float
610
+	 * @throws EE_Error
611
+	 * @throws ReflectionException
612
+	 */
613
+	public function ticket_price()
614
+	{
615
+		return $this->get('TKT_price');
616
+	}
617
+
618
+
619
+	/**
620
+	 * @return mixed
621
+	 * @throws EE_Error
622
+	 * @throws ReflectionException
623
+	 */
624
+	public function pretty_price()
625
+	{
626
+		return $this->get_pretty('TKT_price');
627
+	}
628
+
629
+
630
+	/**
631
+	 * @return bool
632
+	 * @throws EE_Error
633
+	 * @throws ReflectionException
634
+	 */
635
+	public function is_free()
636
+	{
637
+		return $this->get_ticket_total_with_taxes() === (float) 0;
638
+	}
639
+
640
+
641
+	/**
642
+	 * get_ticket_total_with_taxes
643
+	 *
644
+	 * @param bool $no_cache
645
+	 * @return float
646
+	 * @throws EE_Error
647
+	 * @throws ReflectionException
648
+	 */
649
+	public function get_ticket_total_with_taxes(bool $no_cache = false): float
650
+	{
651
+		if ($this->_ticket_total_with_taxes === null || $no_cache) {
652
+			$this->_ticket_total_with_taxes = $this->get_ticket_subtotal();
653
+			// add taxes
654
+			if ($this->usesGlobalTaxes()) {
655
+				$this->_ticket_total_with_taxes += $this->get_ticket_taxes_total_for_admin();
656
+			} else {
657
+				$subtotal = $this->_ticket_total_with_taxes;
658
+				foreach ($this->tax_price_modifiers() as $tax) {
659
+					$this->_ticket_total_with_taxes += $subtotal * $tax->amount() / 100;
660
+				}
661
+			}
662
+		}
663
+		return (float) $this->_ticket_total_with_taxes;
664
+	}
665
+
666
+
667
+	/**
668
+	 * @throws EE_Error
669
+	 * @throws ReflectionException
670
+	 */
671
+	public function ensure_TKT_Price_correct()
672
+	{
673
+		$this->set('TKT_price', EE_Taxes::get_subtotal_for_admin($this));
674
+		$this->save();
675
+	}
676
+
677
+
678
+	/**
679
+	 * @return float
680
+	 * @throws EE_Error
681
+	 * @throws ReflectionException
682
+	 */
683
+	public function get_ticket_subtotal()
684
+	{
685
+		return EE_Taxes::get_subtotal_for_admin($this);
686
+	}
687
+
688
+
689
+	/**
690
+	 * Returns the total taxes applied to this ticket
691
+	 *
692
+	 * @return float
693
+	 * @throws EE_Error
694
+	 * @throws ReflectionException
695
+	 */
696
+	public function get_ticket_taxes_total_for_admin()
697
+	{
698
+		return EE_Taxes::get_total_taxes_for_admin($this);
699
+	}
700
+
701
+
702
+	/**
703
+	 * Sets name
704
+	 *
705
+	 * @param string $name
706
+	 * @throws EE_Error
707
+	 * @throws ReflectionException
708
+	 */
709
+	public function set_name($name)
710
+	{
711
+		$this->set('TKT_name', $name);
712
+	}
713
+
714
+
715
+	/**
716
+	 * Gets description
717
+	 *
718
+	 * @return string
719
+	 * @throws EE_Error
720
+	 * @throws ReflectionException
721
+	 */
722
+	public function description()
723
+	{
724
+		return $this->get('TKT_description');
725
+	}
726
+
727
+
728
+	/**
729
+	 * Sets description
730
+	 *
731
+	 * @param string $description
732
+	 * @throws EE_Error
733
+	 * @throws ReflectionException
734
+	 */
735
+	public function set_description($description)
736
+	{
737
+		$this->set('TKT_description', $description);
738
+	}
739
+
740
+
741
+	/**
742
+	 * Gets start_date
743
+	 *
744
+	 * @param string|null $date_format
745
+	 * @param string|null $time_format
746
+	 * @return string
747
+	 * @throws EE_Error
748
+	 * @throws ReflectionException
749
+	 */
750
+	public function start_date(?string $date_format = '', ?string $time_format = ''): string
751
+	{
752
+		return $this->_get_datetime('TKT_start_date', $date_format, $time_format);
753
+	}
754
+
755
+
756
+	/**
757
+	 * Sets start_date
758
+	 *
759
+	 * @param string $start_date
760
+	 * @return void
761
+	 * @throws EE_Error
762
+	 * @throws ReflectionException
763
+	 */
764
+	public function set_start_date($start_date)
765
+	{
766
+		$this->_set_date_time('B', $start_date, 'TKT_start_date');
767
+	}
768
+
769
+
770
+	/**
771
+	 * Gets end_date
772
+	 *
773
+	 * @param string|null $date_format
774
+	 * @param string|null $time_format
775
+	 * @return string
776
+	 * @throws EE_Error
777
+	 * @throws ReflectionException
778
+	 */
779
+	public function end_date(?string $date_format = '', ?string $time_format = ''): string
780
+	{
781
+		return $this->_get_datetime('TKT_end_date', $date_format, $time_format);
782
+	}
783
+
784
+
785
+	/**
786
+	 * Sets end_date
787
+	 *
788
+	 * @param string $end_date
789
+	 * @return void
790
+	 * @throws EE_Error
791
+	 * @throws ReflectionException
792
+	 */
793
+	public function set_end_date($end_date)
794
+	{
795
+		$this->_set_date_time('B', $end_date, 'TKT_end_date');
796
+	}
797
+
798
+
799
+	/**
800
+	 * Sets sell until time
801
+	 *
802
+	 * @param string $time a string representation of the sell until time (ex 9am or 7:30pm)
803
+	 * @throws EE_Error
804
+	 * @throws ReflectionException
805
+	 * @since 4.5.0
806
+	 */
807
+	public function set_end_time($time)
808
+	{
809
+		$this->_set_time_for($time, 'TKT_end_date');
810
+	}
811
+
812
+
813
+	/**
814
+	 * Sets min
815
+	 *
816
+	 * @param int $min
817
+	 * @return void
818
+	 * @throws EE_Error
819
+	 * @throws ReflectionException
820
+	 */
821
+	public function set_min($min)
822
+	{
823
+		$this->set('TKT_min', $min);
824
+	}
825
+
826
+
827
+	/**
828
+	 * Gets max
829
+	 *
830
+	 * @return int
831
+	 * @throws EE_Error
832
+	 * @throws ReflectionException
833
+	 */
834
+	public function max()
835
+	{
836
+		return $this->get('TKT_max');
837
+	}
838
+
839
+
840
+	/**
841
+	 * Sets max
842
+	 *
843
+	 * @param int $max
844
+	 * @return void
845
+	 * @throws EE_Error
846
+	 * @throws ReflectionException
847
+	 */
848
+	public function set_max($max)
849
+	{
850
+		$this->set('TKT_max', $max);
851
+	}
852
+
853
+
854
+	/**
855
+	 * Sets price
856
+	 *
857
+	 * @param float $price
858
+	 * @return void
859
+	 * @throws EE_Error
860
+	 * @throws ReflectionException
861
+	 */
862
+	public function set_price($price)
863
+	{
864
+		$this->set('TKT_price', $price);
865
+	}
866
+
867
+
868
+	/**
869
+	 * Gets sold
870
+	 *
871
+	 * @return int
872
+	 * @throws EE_Error
873
+	 * @throws ReflectionException
874
+	 */
875
+	public function sold(): int
876
+	{
877
+		return (int) $this->get_raw('TKT_sold');
878
+	}
879
+
880
+
881
+	/**
882
+	 * Sets sold
883
+	 *
884
+	 * @param int $sold
885
+	 * @return void
886
+	 * @throws EE_Error
887
+	 * @throws ReflectionException
888
+	 */
889
+	public function set_sold($sold)
890
+	{
891
+		// sold can not go below zero
892
+		$sold = max(0, $sold);
893
+		$this->set('TKT_sold', $sold);
894
+	}
895
+
896
+
897
+	/**
898
+	 * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
899
+	 * associated datetimes.
900
+	 *
901
+	 * @param int $qty
902
+	 * @return boolean
903
+	 * @throws EE_Error
904
+	 * @throws InvalidArgumentException
905
+	 * @throws InvalidDataTypeException
906
+	 * @throws InvalidInterfaceException
907
+	 * @throws ReflectionException
908
+	 * @since 4.9.80.p
909
+	 */
910
+	public function increaseSold($qty = 1)
911
+	{
912
+		$qty = absint($qty);
913
+		// increment sold and decrement reserved datetime quantities simultaneously
914
+		// don't worry about failures, because they must have already had a spot reserved
915
+		$this->increaseSoldForDatetimes($qty);
916
+		// Increment and decrement ticket quantities simultaneously
917
+		$success = $this->adjustNumericFieldsInDb(
918
+			[
919
+				'TKT_reserved' => $qty * -1,
920
+				'TKT_sold'     => $qty,
921
+			]
922
+		);
923
+		do_action(
924
+			'AHEE__EE_Ticket__increase_sold',
925
+			$this,
926
+			$qty,
927
+			$this->sold(),
928
+			$success
929
+		);
930
+		return $success;
931
+	}
932
+
933
+
934
+	/**
935
+	 * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
936
+	 *
937
+	 * @param int           $qty positive or negative. Positive means to increase sold counts (and decrease reserved
938
+	 *                           counts), Negative means to decreases old counts (and increase reserved counts).
939
+	 * @param EE_Datetime[] $datetimes
940
+	 * @throws EE_Error
941
+	 * @throws InvalidArgumentException
942
+	 * @throws InvalidDataTypeException
943
+	 * @throws InvalidInterfaceException
944
+	 * @throws ReflectionException
945
+	 * @since 4.9.80.p
946
+	 */
947
+	protected function increaseSoldForDatetimes($qty, array $datetimes = [])
948
+	{
949
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
950
+		foreach ($datetimes as $datetime) {
951
+			$datetime->increaseSold($qty);
952
+		}
953
+	}
954
+
955
+
956
+	/**
957
+	 * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
958
+	 * DB and then updates the model objects.
959
+	 * Does not affect the reserved counts.
960
+	 *
961
+	 * @param int $qty
962
+	 * @return boolean
963
+	 * @throws EE_Error
964
+	 * @throws InvalidArgumentException
965
+	 * @throws InvalidDataTypeException
966
+	 * @throws InvalidInterfaceException
967
+	 * @throws ReflectionException
968
+	 * @since 4.9.80.p
969
+	 */
970
+	public function decreaseSold($qty = 1)
971
+	{
972
+		$qty = absint($qty);
973
+		$this->decreaseSoldForDatetimes($qty);
974
+		$success = $this->adjustNumericFieldsInDb(
975
+			[
976
+				'TKT_sold' => $qty * -1,
977
+			]
978
+		);
979
+		do_action(
980
+			'AHEE__EE_Ticket__decrease_sold',
981
+			$this,
982
+			$qty,
983
+			$this->sold(),
984
+			$success
985
+		);
986
+		return $success;
987
+	}
988
+
989
+
990
+	/**
991
+	 * Decreases sold on related datetimes
992
+	 *
993
+	 * @param int           $qty
994
+	 * @param EE_Datetime[] $datetimes
995
+	 * @return void
996
+	 * @throws EE_Error
997
+	 * @throws InvalidArgumentException
998
+	 * @throws InvalidDataTypeException
999
+	 * @throws InvalidInterfaceException
1000
+	 * @throws ReflectionException
1001
+	 * @since 4.9.80.p
1002
+	 */
1003
+	protected function decreaseSoldForDatetimes($qty = 1, array $datetimes = [])
1004
+	{
1005
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1006
+		if (is_array($datetimes)) {
1007
+			foreach ($datetimes as $datetime) {
1008
+				if ($datetime instanceof EE_Datetime) {
1009
+					$datetime->decreaseSold($qty);
1010
+				}
1011
+			}
1012
+		}
1013
+	}
1014
+
1015
+
1016
+	/**
1017
+	 * Gets qty of reserved tickets
1018
+	 *
1019
+	 * @return int
1020
+	 * @throws EE_Error
1021
+	 * @throws ReflectionException
1022
+	 */
1023
+	public function reserved(): int
1024
+	{
1025
+		return (int) $this->get_raw('TKT_reserved');
1026
+	}
1027
+
1028
+
1029
+	/**
1030
+	 * Sets reserved
1031
+	 *
1032
+	 * @param int $reserved
1033
+	 * @return void
1034
+	 * @throws EE_Error
1035
+	 * @throws ReflectionException
1036
+	 */
1037
+	public function set_reserved($reserved)
1038
+	{
1039
+		// reserved can not go below zero
1040
+		$reserved = max(0, (int) $reserved);
1041
+		$this->set('TKT_reserved', $reserved);
1042
+	}
1043
+
1044
+
1045
+	/**
1046
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1047
+	 *
1048
+	 * @param int    $qty
1049
+	 * @param string $source
1050
+	 * @return bool whether we successfully reserved the ticket or not.
1051
+	 * @throws EE_Error
1052
+	 * @throws InvalidArgumentException
1053
+	 * @throws ReflectionException
1054
+	 * @throws InvalidDataTypeException
1055
+	 * @throws InvalidInterfaceException
1056
+	 * @since 4.9.80.p
1057
+	 */
1058
+	public function increaseReserved($qty = 1, $source = 'unknown')
1059
+	{
1060
+		$qty = absint($qty);
1061
+		do_action(
1062
+			'AHEE__EE_Ticket__increase_reserved__begin',
1063
+			$this,
1064
+			$qty,
1065
+			$source
1066
+		);
1067
+		// comment out extra meta tracking
1068
+		// $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "{$qty} from {$source}");
1069
+		$success                         = false;
1070
+		$datetimes_adjusted_successfully = $this->increaseReservedForDatetimes($qty);
1071
+		if ($datetimes_adjusted_successfully) {
1072
+			$success = $this->incrementFieldConditionallyInDb(
1073
+				'TKT_reserved',
1074
+				'TKT_sold',
1075
+				'TKT_qty',
1076
+				$qty
1077
+			);
1078
+			if (! $success) {
1079
+				// The datetimes were successfully bumped, but not the
1080
+				// ticket. So we need to manually roll back the datetimes.
1081
+				$this->decreaseReservedForDatetimes($qty);
1082
+			}
1083
+		}
1084
+		do_action(
1085
+			'AHEE__EE_Ticket__increase_reserved',
1086
+			$this,
1087
+			$qty,
1088
+			$this->reserved(),
1089
+			$success
1090
+		);
1091
+		return $success;
1092
+	}
1093
+
1094
+
1095
+	/**
1096
+	 * Increases reserved counts on related datetimes
1097
+	 *
1098
+	 * @param int           $qty
1099
+	 * @param EE_Datetime[] $datetimes
1100
+	 * @return boolean indicating success
1101
+	 * @throws EE_Error
1102
+	 * @throws InvalidArgumentException
1103
+	 * @throws InvalidDataTypeException
1104
+	 * @throws InvalidInterfaceException
1105
+	 * @throws ReflectionException
1106
+	 * @since 4.9.80.p
1107
+	 */
1108
+	protected function increaseReservedForDatetimes($qty = 1, array $datetimes = [])
1109
+	{
1110
+		$datetimes         = ! empty($datetimes) ? $datetimes : $this->datetimes();
1111
+		$datetimes_updated = [];
1112
+		$limit_exceeded    = false;
1113
+		if (is_array($datetimes)) {
1114
+			foreach ($datetimes as $datetime) {
1115
+				if ($datetime instanceof EE_Datetime) {
1116
+					if ($datetime->increaseReserved($qty)) {
1117
+						$datetimes_updated[] = $datetime;
1118
+					} else {
1119
+						$limit_exceeded = true;
1120
+						break;
1121
+					}
1122
+				}
1123
+			}
1124
+			// If somewhere along the way we detected a datetime whose
1125
+			// limit was exceeded, do a manual rollback.
1126
+			if ($limit_exceeded) {
1127
+				$this->decreaseReservedForDatetimes($qty, $datetimes_updated);
1128
+				return false;
1129
+			}
1130
+		}
1131
+		return true;
1132
+	}
1133
+
1134
+
1135
+	/**
1136
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1137
+	 *
1138
+	 * @param int    $qty
1139
+	 * @param bool   $adjust_datetimes
1140
+	 * @param string $source
1141
+	 * @return boolean
1142
+	 * @throws EE_Error
1143
+	 * @throws InvalidArgumentException
1144
+	 * @throws ReflectionException
1145
+	 * @throws InvalidDataTypeException
1146
+	 * @throws InvalidInterfaceException
1147
+	 * @since 4.9.80.p
1148
+	 */
1149
+	public function decreaseReserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
1150
+	{
1151
+		$qty = absint($qty);
1152
+		// comment out extra meta tracking
1153
+		// $this->add_extra_meta(EE_Ticket::META_KEY_TICKET_RESERVATIONS, "-{$qty} from {$source}");
1154
+		if ($adjust_datetimes) {
1155
+			$this->decreaseReservedForDatetimes($qty);
1156
+		}
1157
+		$success = $this->adjustNumericFieldsInDb(
1158
+			[
1159
+				'TKT_reserved' => $qty * -1,
1160
+			]
1161
+		);
1162
+		do_action(
1163
+			'AHEE__EE_Ticket__decrease_reserved',
1164
+			$this,
1165
+			$qty,
1166
+			$this->reserved(),
1167
+			$success
1168
+		);
1169
+		return $success;
1170
+	}
1171
+
1172
+
1173
+	/**
1174
+	 * Decreases the reserved count on the specified datetimes.
1175
+	 *
1176
+	 * @param int           $qty
1177
+	 * @param EE_Datetime[] $datetimes
1178
+	 * @throws EE_Error
1179
+	 * @throws InvalidArgumentException
1180
+	 * @throws ReflectionException
1181
+	 * @throws InvalidDataTypeException
1182
+	 * @throws InvalidInterfaceException
1183
+	 * @since 4.9.80.p
1184
+	 */
1185
+	protected function decreaseReservedForDatetimes($qty = 1, array $datetimes = [])
1186
+	{
1187
+		$datetimes = ! empty($datetimes) ? $datetimes : $this->datetimes();
1188
+		foreach ($datetimes as $datetime) {
1189
+			if ($datetime instanceof EE_Datetime) {
1190
+				$datetime->decreaseReserved($qty);
1191
+			}
1192
+		}
1193
+	}
1194
+
1195
+
1196
+	/**
1197
+	 * Gets ticket quantity
1198
+	 *
1199
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1200
+	 *                            therefore $context can be one of three values: '', 'reg_limit', or 'saleable'
1201
+	 *                            '' (default) quantity is the actual db value for TKT_qty, unaffected by other objects
1202
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1203
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1204
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1205
+	 * @return int
1206
+	 * @throws EE_Error
1207
+	 * @throws ReflectionException
1208
+	 */
1209
+	public function qty($context = '')
1210
+	{
1211
+		switch ($context) {
1212
+			case 'reg_limit':
1213
+				return $this->real_quantity_on_ticket();
1214
+			case 'saleable':
1215
+				return $this->real_quantity_on_ticket('saleable');
1216
+			default:
1217
+				return $this->get_raw('TKT_qty');
1218
+		}
1219
+	}
1220
+
1221
+
1222
+	/**
1223
+	 * Gets ticket quantity
1224
+	 *
1225
+	 * @param string $context     ticket quantity is somewhat subjective depending on the exact information sought
1226
+	 *                            therefore $context can be one of two values: 'reg_limit', or 'saleable'
1227
+	 *                            REG LIMIT: caps qty based on DTT_reg_limit for ALL related datetimes
1228
+	 *                            SALEABLE: also considers datetime sold and returns zero if ANY DTT is sold out, and
1229
+	 *                            is therefore the truest measure of tickets that can be purchased at the moment
1230
+	 * @param int    $DTT_ID      the primary key for a particular datetime.
1231
+	 *                            set to 0 for all related datetimes
1232
+	 * @return int|float          int for finite quantity or float for INF
1233
+	 * @throws EE_Error
1234
+	 * @throws ReflectionException
1235
+	 */
1236
+	public function real_quantity_on_ticket($context = 'reg_limit', $DTT_ID = 0)
1237
+	{
1238
+		$raw = $this->get_raw('TKT_qty');
1239
+		// return immediately if it's zero
1240
+		if ($raw === 0) {
1241
+			return $raw;
1242
+		}
1243
+		// echo "\n\n<br />Ticket: " . $this->name() . '<br />';
1244
+		// ensure qty doesn't exceed raw value for THIS ticket
1245
+		$qty = min(EE_INF, $raw);
1246
+		// echo "\n . qty: " . $qty . '<br />';
1247
+		// calculate this ticket's total sales and reservations
1248
+		$sold_and_reserved_for_this_ticket = $this->sold() + $this->reserved();
1249
+		// echo "\n . sold: " . $this->sold() . '<br />';
1250
+		// echo "\n . reserved: " . $this->reserved() . '<br />';
1251
+		// echo "\n . sold_and_reserved_for_this_ticket: " . $sold_and_reserved_for_this_ticket . '<br />';
1252
+		// first we need to calculate the maximum number of tickets available for the datetime
1253
+		// do we want data for one datetime or all of them ?
1254
+		$query_params = $DTT_ID ? [['DTT_ID' => $DTT_ID]] : [];
1255
+		$datetimes    = $this->get_many_related('Datetime', $query_params);
1256
+		if (is_array($datetimes) && ! empty($datetimes)) {
1257
+			foreach ($datetimes as $datetime) {
1258
+				if ($datetime instanceof EE_Datetime) {
1259
+					// $datetime->refresh_from_db();
1260
+					// echo "\n . . datetime name: " . $datetime->name() . '<br />';
1261
+					// echo "\n . . datetime ID: " . $datetime->ID() . '<br />';
1262
+					// initialize with no restrictions for each datetime
1263
+					// but adjust datetime qty based on datetime reg limit
1264
+					$datetime_qty = min(EE_INF, $datetime->reg_limit());
1265
+					// echo "\n . . . datetime reg_limit: " . $datetime->reg_limit() . '<br />';
1266
+					// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1267
+					// if we want the actual saleable amount, then we need to consider OTHER ticket sales
1268
+					// and reservations for this datetime, that do NOT include sales and reservations
1269
+					// for this ticket (so we add $this->sold() and $this->reserved() back in)
1270
+					if ($context === 'saleable') {
1271
+						$datetime_qty = max(
1272
+							$datetime_qty - $datetime->sold_and_reserved() + $sold_and_reserved_for_this_ticket,
1273
+							0
1274
+						);
1275
+						// echo "\n . . . datetime sold: " . $datetime->sold() . '<br />';
1276
+						// echo "\n . . . datetime reserved: " . $datetime->reserved() . '<br />';
1277
+						// echo "\n . . . datetime sold_and_reserved: " . $datetime->sold_and_reserved() . '<br />';
1278
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1279
+						$datetime_qty = ! $datetime->sold_out() ? $datetime_qty : 0;
1280
+						// echo "\n . . . datetime_qty: " . $datetime_qty . '<br />';
1281
+					}
1282
+					$qty = min($datetime_qty, $qty);
1283
+					// echo "\n . . qty: " . $qty . '<br />';
1284
+				}
1285
+			}
1286
+		}
1287
+		// NOW that we know the  maximum number of tickets available for the datetime
1288
+		// we can finally factor in the details for this specific ticket
1289
+		if ($qty > 0 && $context === 'saleable') {
1290
+			// and subtract the sales for THIS ticket
1291
+			$qty = max($qty - $sold_and_reserved_for_this_ticket, 0);
1292
+			// echo "\n . qty: " . $qty . '<br />';
1293
+		}
1294
+		// echo "\nFINAL QTY: " . $qty . "<br /><br />";
1295
+		return $qty;
1296
+	}
1297
+
1298
+
1299
+	/**
1300
+	 * Sets qty - IMPORTANT!!! Does NOT allow QTY to be set higher than the lowest reg limit of any related datetimes
1301
+	 *
1302
+	 * @param int $qty
1303
+	 * @return void
1304
+	 * @throws EE_Error
1305
+	 * @throws ReflectionException
1306
+	 */
1307
+	public function set_qty($qty)
1308
+	{
1309
+		$datetimes = $this->datetimes();
1310
+		foreach ($datetimes as $datetime) {
1311
+			if ($datetime instanceof EE_Datetime) {
1312
+				$qty = min($qty, $datetime->reg_limit());
1313
+			}
1314
+		}
1315
+		$this->set('TKT_qty', $qty);
1316
+	}
1317
+
1318
+
1319
+	/**
1320
+	 * Gets uses
1321
+	 *
1322
+	 * @return int
1323
+	 * @throws EE_Error
1324
+	 * @throws ReflectionException
1325
+	 */
1326
+	public function uses()
1327
+	{
1328
+		return $this->get('TKT_uses');
1329
+	}
1330
+
1331
+
1332
+	/**
1333
+	 * Sets uses
1334
+	 *
1335
+	 * @param int $uses
1336
+	 * @return void
1337
+	 * @throws EE_Error
1338
+	 * @throws ReflectionException
1339
+	 */
1340
+	public function set_uses($uses)
1341
+	{
1342
+		$this->set('TKT_uses', $uses);
1343
+	}
1344
+
1345
+
1346
+	/**
1347
+	 * returns whether ticket is required or not.
1348
+	 *
1349
+	 * @return boolean
1350
+	 * @throws EE_Error
1351
+	 * @throws ReflectionException
1352
+	 */
1353
+	public function required()
1354
+	{
1355
+		return $this->get('TKT_required');
1356
+	}
1357
+
1358
+
1359
+	/**
1360
+	 * sets the TKT_required property
1361
+	 *
1362
+	 * @param boolean $required
1363
+	 * @return void
1364
+	 * @throws EE_Error
1365
+	 * @throws ReflectionException
1366
+	 */
1367
+	public function set_required($required)
1368
+	{
1369
+		$this->set('TKT_required', $required);
1370
+	}
1371
+
1372
+
1373
+	/**
1374
+	 * Gets taxable
1375
+	 *
1376
+	 * @return boolean
1377
+	 * @throws EE_Error
1378
+	 * @throws ReflectionException
1379
+	 */
1380
+	public function taxable()
1381
+	{
1382
+		return $this->get('TKT_taxable');
1383
+	}
1384
+
1385
+
1386
+	/**
1387
+	 * Sets taxable
1388
+	 *
1389
+	 * @param boolean $taxable
1390
+	 * @return void
1391
+	 * @throws EE_Error
1392
+	 * @throws ReflectionException
1393
+	 */
1394
+	public function set_taxable($taxable)
1395
+	{
1396
+		$this->set('TKT_taxable', $taxable);
1397
+	}
1398
+
1399
+
1400
+	/**
1401
+	 * Gets is_default
1402
+	 *
1403
+	 * @return boolean
1404
+	 * @throws EE_Error
1405
+	 * @throws ReflectionException
1406
+	 */
1407
+	public function is_default()
1408
+	{
1409
+		return $this->get('TKT_is_default');
1410
+	}
1411
+
1412
+
1413
+	/**
1414
+	 * Sets is_default
1415
+	 *
1416
+	 * @param boolean $is_default
1417
+	 * @return void
1418
+	 * @throws EE_Error
1419
+	 * @throws ReflectionException
1420
+	 */
1421
+	public function set_is_default($is_default)
1422
+	{
1423
+		$this->set('TKT_is_default', $is_default);
1424
+	}
1425
+
1426
+
1427
+	/**
1428
+	 * Gets order
1429
+	 *
1430
+	 * @return int
1431
+	 * @throws EE_Error
1432
+	 * @throws ReflectionException
1433
+	 */
1434
+	public function order()
1435
+	{
1436
+		return $this->get('TKT_order');
1437
+	}
1438
+
1439
+
1440
+	/**
1441
+	 * Sets order
1442
+	 *
1443
+	 * @param int $order
1444
+	 * @return void
1445
+	 * @throws EE_Error
1446
+	 * @throws ReflectionException
1447
+	 */
1448
+	public function set_order($order)
1449
+	{
1450
+		$this->set('TKT_order', $order);
1451
+	}
1452
+
1453
+
1454
+	/**
1455
+	 * Gets row
1456
+	 *
1457
+	 * @return int
1458
+	 * @throws EE_Error
1459
+	 * @throws ReflectionException
1460
+	 */
1461
+	public function row()
1462
+	{
1463
+		return $this->get('TKT_row');
1464
+	}
1465
+
1466
+
1467
+	/**
1468
+	 * Sets row
1469
+	 *
1470
+	 * @param int $row
1471
+	 * @return void
1472
+	 * @throws EE_Error
1473
+	 * @throws ReflectionException
1474
+	 */
1475
+	public function set_row($row)
1476
+	{
1477
+		$this->set('TKT_row', $row);
1478
+	}
1479
+
1480
+
1481
+	/**
1482
+	 * Gets deleted
1483
+	 *
1484
+	 * @return boolean
1485
+	 * @throws EE_Error
1486
+	 * @throws ReflectionException
1487
+	 */
1488
+	public function deleted()
1489
+	{
1490
+		return $this->get('TKT_deleted');
1491
+	}
1492
+
1493
+
1494
+	/**
1495
+	 * Sets deleted
1496
+	 *
1497
+	 * @param boolean $deleted
1498
+	 * @return void
1499
+	 * @throws EE_Error
1500
+	 * @throws ReflectionException
1501
+	 */
1502
+	public function set_deleted($deleted)
1503
+	{
1504
+		$this->set('TKT_deleted', $deleted);
1505
+	}
1506
+
1507
+
1508
+	/**
1509
+	 * Gets parent
1510
+	 *
1511
+	 * @return int
1512
+	 * @throws EE_Error
1513
+	 * @throws ReflectionException
1514
+	 */
1515
+	public function parent_ID()
1516
+	{
1517
+		return $this->get('TKT_parent');
1518
+	}
1519
+
1520
+
1521
+	/**
1522
+	 * Sets parent
1523
+	 *
1524
+	 * @param int $parent
1525
+	 * @return void
1526
+	 * @throws EE_Error
1527
+	 * @throws ReflectionException
1528
+	 */
1529
+	public function set_parent_ID($parent)
1530
+	{
1531
+		$this->set('TKT_parent', $parent);
1532
+	}
1533
+
1534
+
1535
+	/**
1536
+	 * @return boolean
1537
+	 * @throws EE_Error
1538
+	 * @throws InvalidArgumentException
1539
+	 * @throws InvalidDataTypeException
1540
+	 * @throws InvalidInterfaceException
1541
+	 * @throws ReflectionException
1542
+	 */
1543
+	public function reverse_calculate()
1544
+	{
1545
+		return $this->get('TKT_reverse_calculate');
1546
+	}
1547
+
1548
+
1549
+	/**
1550
+	 * @param boolean $reverse_calculate
1551
+	 * @throws EE_Error
1552
+	 * @throws InvalidArgumentException
1553
+	 * @throws InvalidDataTypeException
1554
+	 * @throws InvalidInterfaceException
1555
+	 * @throws ReflectionException
1556
+	 */
1557
+	public function set_reverse_calculate($reverse_calculate)
1558
+	{
1559
+		$this->set('TKT_reverse_calculate', $reverse_calculate);
1560
+	}
1561
+
1562
+
1563
+	/**
1564
+	 * Gets a string which is handy for showing in gateways etc that describes the ticket.
1565
+	 *
1566
+	 * @return string
1567
+	 * @throws EE_Error
1568
+	 * @throws ReflectionException
1569
+	 */
1570
+	public function name_and_info()
1571
+	{
1572
+		$times = [];
1573
+		foreach ($this->datetimes() as $datetime) {
1574
+			$times[] = $datetime->start_date_and_time();
1575
+		}
1576
+		/* translators: %1$s ticket name, %2$s start datetimes separated by comma, %3$s ticket price */
1577
+		return sprintf(
1578
+			esc_html__('%1$s @ %2$s for %3$s', 'event_espresso'),
1579
+			$this->name(),
1580
+			implode(', ', $times),
1581
+			$this->pretty_price()
1582
+		);
1583
+	}
1584
+
1585
+
1586
+	/**
1587
+	 * Gets name
1588
+	 *
1589
+	 * @return string
1590
+	 * @throws EE_Error
1591
+	 * @throws ReflectionException
1592
+	 */
1593
+	public function name()
1594
+	{
1595
+		return $this->get('TKT_name');
1596
+	}
1597
+
1598
+
1599
+	/**
1600
+	 * Gets price
1601
+	 *
1602
+	 * @return float
1603
+	 * @throws EE_Error
1604
+	 * @throws ReflectionException
1605
+	 */
1606
+	public function price()
1607
+	{
1608
+		return $this->get('TKT_price');
1609
+	}
1610
+
1611
+
1612
+	/**
1613
+	 * Gets all the registrations for this ticket
1614
+	 *
1615
+	 * @param array $query_params
1616
+	 * @return EE_Registration[]|EE_Base_Class[]
1617
+	 * @throws EE_Error
1618
+	 * @throws ReflectionException
1619
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1620
+	 */
1621
+	public function registrations($query_params = [])
1622
+	{
1623
+		return $this->get_many_related('Registration', $query_params);
1624
+	}
1625
+
1626
+
1627
+	/**
1628
+	 * Updates the TKT_sold attribute (and saves) based on the number of APPROVED registrations for this ticket.
1629
+	 *
1630
+	 * @return int
1631
+	 * @throws EE_Error
1632
+	 * @throws ReflectionException
1633
+	 */
1634
+	public function update_tickets_sold()
1635
+	{
1636
+		$count_regs_for_this_ticket = $this->count_registrations(
1637
+			[
1638
+				[
1639
+					'STS_ID'      => RegStatus::APPROVED,
1640
+					'REG_deleted' => 0,
1641
+				],
1642
+			]
1643
+		);
1644
+		$this->set_sold($count_regs_for_this_ticket);
1645
+		$this->save();
1646
+		return $count_regs_for_this_ticket;
1647
+	}
1648
+
1649
+
1650
+	/**
1651
+	 * Counts the registrations for this ticket
1652
+	 *
1653
+	 * @param array $query_params
1654
+	 * @return int
1655
+	 * @throws EE_Error
1656
+	 * @throws ReflectionException
1657
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1658
+	 */
1659
+	public function count_registrations($query_params = [])
1660
+	{
1661
+		return $this->count_related('Registration', $query_params);
1662
+	}
1663
+
1664
+
1665
+	/**
1666
+	 * Implementation for EEI_Has_Icon interface method.
1667
+	 *
1668
+	 * @return string
1669
+	 * @see EEI_Visual_Representation for comments
1670
+	 */
1671
+	public function get_icon()
1672
+	{
1673
+		return '<span class="dashicons dashicons-tickets-alt"></span>';
1674
+	}
1675
+
1676
+
1677
+	/**
1678
+	 * Implementation of the EEI_Event_Relation interface method
1679
+	 *
1680
+	 * @return EE_Event
1681
+	 * @throws EE_Error
1682
+	 * @throws UnexpectedEntityException
1683
+	 * @throws ReflectionException
1684
+	 * @see EEI_Event_Relation for comments
1685
+	 */
1686
+	public function get_related_event()
1687
+	{
1688
+		// get one datetime to use for getting the event
1689
+		$datetime = $this->first_datetime();
1690
+		if (! $datetime instanceof EE_Datetime) {
1691
+			throw new UnexpectedEntityException(
1692
+				$datetime,
1693
+				'EE_Datetime',
1694
+				sprintf(
1695
+					esc_html__('The ticket (%s) is not associated with any valid datetimes.', 'event_espresso'),
1696
+					$this->name()
1697
+				)
1698
+			);
1699
+		}
1700
+		$event = $datetime->event();
1701
+		if (! $event instanceof EE_Event) {
1702
+			throw new UnexpectedEntityException(
1703
+				$event,
1704
+				'EE_Event',
1705
+				sprintf(
1706
+					esc_html__('The ticket (%s) is not associated with a valid event.', 'event_espresso'),
1707
+					$this->name()
1708
+				)
1709
+			);
1710
+		}
1711
+		return $event;
1712
+	}
1713
+
1714
+
1715
+	/**
1716
+	 * Implementation of the EEI_Event_Relation interface method
1717
+	 *
1718
+	 * @return string
1719
+	 * @throws UnexpectedEntityException
1720
+	 * @throws EE_Error
1721
+	 * @throws ReflectionException
1722
+	 * @see EEI_Event_Relation for comments
1723
+	 */
1724
+	public function get_event_name()
1725
+	{
1726
+		$event = $this->get_related_event();
1727
+		return $event instanceof EE_Event ? $event->name() : '';
1728
+	}
1729
+
1730
+
1731
+	/**
1732
+	 * Implementation of the EEI_Event_Relation interface method
1733
+	 *
1734
+	 * @return int
1735
+	 * @throws UnexpectedEntityException
1736
+	 * @throws EE_Error
1737
+	 * @throws ReflectionException
1738
+	 * @see EEI_Event_Relation for comments
1739
+	 */
1740
+	public function get_event_ID()
1741
+	{
1742
+		$event = $this->get_related_event();
1743
+		return $event instanceof EE_Event ? $event->ID() : 0;
1744
+	}
1745
+
1746
+
1747
+	/**
1748
+	 * This simply returns whether a ticket can be permanently deleted or not.
1749
+	 * The criteria for determining this is whether the ticket has any related registrations.
1750
+	 * If there are none then it can be permanently deleted.
1751
+	 *
1752
+	 * @return bool
1753
+	 * @throws EE_Error
1754
+	 * @throws ReflectionException
1755
+	 */
1756
+	public function is_permanently_deleteable()
1757
+	{
1758
+		return $this->count_registrations() === 0;
1759
+	}
1760
+
1761
+
1762
+	/**
1763
+	 * @return int
1764
+	 * @throws EE_Error
1765
+	 * @throws ReflectionException
1766
+	 * @since   5.0.0.p
1767
+	 */
1768
+	public function visibility(): int
1769
+	{
1770
+		return $this->get('TKT_visibility');
1771
+	}
1772
+
1773
+
1774
+	/**
1775
+	 * @return bool
1776
+	 * @throws EE_Error
1777
+	 * @throws ReflectionException
1778
+	 * @since   5.0.0.p
1779
+	 */
1780
+	public function isHidden(): bool
1781
+	{
1782
+		return $this->visibility() === EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1783
+	}
1784
+
1785
+
1786
+	/**
1787
+	 * @return bool
1788
+	 * @throws EE_Error
1789
+	 * @throws ReflectionException
1790
+	 * @since   5.0.0.p
1791
+	 */
1792
+	public function isNotHidden(): bool
1793
+	{
1794
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_NONE_VALUE;
1795
+	}
1796
+
1797
+
1798
+	/**
1799
+	 * @return bool
1800
+	 * @throws EE_Error
1801
+	 * @throws ReflectionException
1802
+	 * @since   5.0.0.p
1803
+	 */
1804
+	public function isPublicOnly(): bool
1805
+	{
1806
+		return $this->isNotHidden() && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE;
1807
+	}
1808
+
1809
+
1810
+	/**
1811
+	 * @return bool
1812
+	 * @throws EE_Error
1813
+	 * @throws ReflectionException
1814
+	 * @since   5.0.0.p
1815
+	 */
1816
+	public function isMembersOnly(): bool
1817
+	{
1818
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_PUBLIC_VALUE
1819
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE;
1820
+	}
1821
+
1822
+
1823
+	/**
1824
+	 * @return bool
1825
+	 * @throws EE_Error
1826
+	 * @throws ReflectionException
1827
+	 * @since   5.0.0.p
1828
+	 */
1829
+	public function isAdminsOnly(): bool
1830
+	{
1831
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_MEMBERS_ONLY_VALUE
1832
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE;
1833
+	}
1834
+
1835
+
1836
+	/**
1837
+	 * @return bool
1838
+	 * @throws EE_Error
1839
+	 * @throws ReflectionException
1840
+	 * @since   5.0.0.p
1841
+	 */
1842
+	public function isAdminUiOnly(): bool
1843
+	{
1844
+		return $this->visibility() > EEM_Ticket::TICKET_VISIBILITY_ADMINS_ONLY_VALUE
1845
+			   && $this->visibility() <= EEM_Ticket::TICKET_VISIBILITY_ADMIN_UI_ONLY_VALUE;
1846
+	}
1847
+
1848
+
1849
+	/**
1850
+	 * @param int $visibility
1851
+	 * @throws EE_Error
1852
+	 * @throws ReflectionException
1853
+	 * @since   5.0.0.p
1854
+	 */
1855
+	public function set_visibility(int $visibility)
1856
+	{
1857
+		$ticket_visibility_options = $this->_model->ticketVisibilityOptions();
1858
+		$ticket_visibility         = -1;
1859
+		foreach ($ticket_visibility_options as $ticket_visibility_option) {
1860
+			if ($visibility === $ticket_visibility_option) {
1861
+				$ticket_visibility = $visibility;
1862
+			}
1863
+		}
1864
+		if ($ticket_visibility === -1) {
1865
+			throw new DomainException(
1866
+				sprintf(
1867
+					esc_html__(
1868
+						'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 ',
1869
+						'event_espresso'
1870
+					),
1871
+					$visibility,
1872
+					'<br />',
1873
+					var_export($ticket_visibility_options, true)
1874
+				)
1875
+			);
1876
+		}
1877
+		$this->set('TKT_visibility', $ticket_visibility);
1878
+	}
1879
+
1880
+
1881
+	/**
1882
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1883
+	 * @param string                   $relationName
1884
+	 * @param array                    $extra_join_model_fields_n_values
1885
+	 * @param string|null              $cache_id
1886
+	 * @return EE_Base_Class
1887
+	 * @throws EE_Error
1888
+	 * @throws ReflectionException
1889
+	 * @since   5.0.0.p
1890
+	 */
1891
+	public function _add_relation_to(
1892
+		$otherObjectModelObjectOrID,
1893
+		$relationName,
1894
+		$extra_join_model_fields_n_values = [],
1895
+		$cache_id = null
1896
+	) {
1897
+		if ($relationName === 'Datetime' && ! $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1898
+			/** @var EE_Datetime $datetime */
1899
+			$datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1900
+			$datetime->increaseSold($this->sold(), false);
1901
+			$datetime->increaseReserved($this->reserved());
1902
+			$datetime->save();
1903
+			$otherObjectModelObjectOrID = $datetime;
1904
+		}
1905
+		return parent::_add_relation_to(
1906
+			$otherObjectModelObjectOrID,
1907
+			$relationName,
1908
+			$extra_join_model_fields_n_values,
1909
+			$cache_id
1910
+		);
1911
+	}
1912
+
1913
+
1914
+	/**
1915
+	 * @param EE_Base_Class|int|string $otherObjectModelObjectOrID
1916
+	 * @param string                   $relationName
1917
+	 * @param array                    $where_query
1918
+	 * @return bool|EE_Base_Class|null
1919
+	 * @throws EE_Error
1920
+	 * @throws ReflectionException
1921
+	 * @since   5.0.0.p
1922
+	 */
1923
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = [])
1924
+	{
1925
+		// if we're adding a new relation to a datetime
1926
+		if ($relationName === 'Datetime' && $this->hasRelation($otherObjectModelObjectOrID, $relationName)) {
1927
+			/** @var EE_Datetime $datetime */
1928
+			$datetime = EEM_Datetime::instance()->ensure_is_obj($otherObjectModelObjectOrID);
1929
+			$datetime->decreaseSold($this->sold());
1930
+			$datetime->decreaseReserved($this->reserved());
1931
+			$datetime->save();
1932
+			$otherObjectModelObjectOrID = $datetime;
1933
+		}
1934
+		return parent::_remove_relation_to(
1935
+			$otherObjectModelObjectOrID,
1936
+			$relationName,
1937
+			$where_query
1938
+		);
1939
+	}
1940
+
1941
+
1942
+	/**
1943
+	 * Removes ALL the related things for the $relationName.
1944
+	 *
1945
+	 * @param string $relationName
1946
+	 * @param array  $where_query_params
1947
+	 * @return EE_Base_Class
1948
+	 * @throws ReflectionException
1949
+	 * @throws InvalidArgumentException
1950
+	 * @throws InvalidInterfaceException
1951
+	 * @throws InvalidDataTypeException
1952
+	 * @throws EE_Error
1953
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1954
+	 */
1955
+	public function _remove_relations($relationName, $where_query_params = [])
1956
+	{
1957
+		if ($relationName === 'Datetime') {
1958
+			$datetimes = $this->datetimes();
1959
+			foreach ($datetimes as $datetime) {
1960
+				$datetime->decreaseSold($this->sold());
1961
+				$datetime->decreaseReserved($this->reserved());
1962
+				$datetime->save();
1963
+			}
1964
+		}
1965
+		return parent::_remove_relations($relationName, $where_query_params);
1966
+	}
1967
+
1968
+
1969
+	/*******************************************************************
1970 1970
      ***********************  DEPRECATED METHODS  **********************
1971 1971
      *******************************************************************/
1972 1972
 
1973 1973
 
1974
-    /**
1975
-     * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
1976
-     * associated datetimes.
1977
-     *
1978
-     * @param int $qty
1979
-     * @return void
1980
-     * @throws EE_Error
1981
-     * @throws InvalidArgumentException
1982
-     * @throws InvalidDataTypeException
1983
-     * @throws InvalidInterfaceException
1984
-     * @throws ReflectionException
1985
-     * @deprecated 4.9.80.p
1986
-     */
1987
-    public function increase_sold($qty = 1)
1988
-    {
1989
-        EE_Error::doing_it_wrong(
1990
-            __FUNCTION__,
1991
-            esc_html__('Please use EE_Ticket::increaseSold() instead', 'event_espresso'),
1992
-            '4.9.80.p',
1993
-            '5.0.0.p'
1994
-        );
1995
-        $this->increaseSold($qty);
1996
-    }
1997
-
1998
-
1999
-    /**
2000
-     * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
2001
-     *
2002
-     * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
2003
-     *                 Negative means to decreases old counts (and increase reserved counts).
2004
-     * @throws EE_Error
2005
-     * @throws InvalidArgumentException
2006
-     * @throws InvalidDataTypeException
2007
-     * @throws InvalidInterfaceException
2008
-     * @throws ReflectionException
2009
-     * @deprecated 4.9.80.p
2010
-     */
2011
-    protected function _increase_sold_for_datetimes($qty)
2012
-    {
2013
-        EE_Error::doing_it_wrong(
2014
-            __FUNCTION__,
2015
-            esc_html__('Please use EE_Ticket::increaseSoldForDatetimes() instead', 'event_espresso'),
2016
-            '4.9.80.p',
2017
-            '5.0.0.p'
2018
-        );
2019
-        $this->increaseSoldForDatetimes($qty);
2020
-    }
2021
-
2022
-
2023
-    /**
2024
-     * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
2025
-     * DB and then updates the model objects.
2026
-     * Does not affect the reserved counts.
2027
-     *
2028
-     * @param int $qty
2029
-     * @return void
2030
-     * @throws EE_Error
2031
-     * @throws InvalidArgumentException
2032
-     * @throws InvalidDataTypeException
2033
-     * @throws InvalidInterfaceException
2034
-     * @throws ReflectionException
2035
-     * @deprecated 4.9.80.p
2036
-     */
2037
-    public function decrease_sold($qty = 1)
2038
-    {
2039
-        EE_Error::doing_it_wrong(
2040
-            __FUNCTION__,
2041
-            esc_html__('Please use EE_Ticket::decreaseSold() instead', 'event_espresso'),
2042
-            '4.9.80.p',
2043
-            '5.0.0.p'
2044
-        );
2045
-        $this->decreaseSold($qty);
2046
-    }
2047
-
2048
-
2049
-    /**
2050
-     * Decreases sold on related datetimes
2051
-     *
2052
-     * @param int $qty
2053
-     * @return void
2054
-     * @throws EE_Error
2055
-     * @throws InvalidArgumentException
2056
-     * @throws InvalidDataTypeException
2057
-     * @throws InvalidInterfaceException
2058
-     * @throws ReflectionException
2059
-     * @deprecated 4.9.80.p
2060
-     */
2061
-    protected function _decrease_sold_for_datetimes($qty = 1)
2062
-    {
2063
-        EE_Error::doing_it_wrong(
2064
-            __FUNCTION__,
2065
-            esc_html__('Please use EE_Ticket::decreaseSoldForDatetimes() instead', 'event_espresso'),
2066
-            '4.9.80.p',
2067
-            '5.0.0.p'
2068
-        );
2069
-        $this->decreaseSoldForDatetimes($qty);
2070
-    }
2071
-
2072
-
2073
-    /**
2074
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
2075
-     *
2076
-     * @param int    $qty
2077
-     * @param string $source
2078
-     * @return bool whether we successfully reserved the ticket or not.
2079
-     * @throws EE_Error
2080
-     * @throws InvalidArgumentException
2081
-     * @throws ReflectionException
2082
-     * @throws InvalidDataTypeException
2083
-     * @throws InvalidInterfaceException
2084
-     * @deprecated 4.9.80.p
2085
-     */
2086
-    public function increase_reserved($qty = 1, $source = 'unknown')
2087
-    {
2088
-        EE_Error::doing_it_wrong(
2089
-            __FUNCTION__,
2090
-            esc_html__('Please use EE_Ticket::increaseReserved() instead', 'event_espresso'),
2091
-            '4.9.80.p',
2092
-            '5.0.0.p'
2093
-        );
2094
-        return $this->increaseReserved($qty);
2095
-    }
2096
-
2097
-
2098
-    /**
2099
-     * Increases sold on related datetimes
2100
-     *
2101
-     * @param int $qty
2102
-     * @return boolean indicating success
2103
-     * @throws EE_Error
2104
-     * @throws InvalidArgumentException
2105
-     * @throws InvalidDataTypeException
2106
-     * @throws InvalidInterfaceException
2107
-     * @throws ReflectionException
2108
-     * @deprecated 4.9.80.p
2109
-     */
2110
-    protected function _increase_reserved_for_datetimes($qty = 1)
2111
-    {
2112
-        EE_Error::doing_it_wrong(
2113
-            __FUNCTION__,
2114
-            esc_html__('Please use EE_Ticket::increaseReservedForDatetimes() instead', 'event_espresso'),
2115
-            '4.9.80.p',
2116
-            '5.0.0.p'
2117
-        );
2118
-        return $this->increaseReservedForDatetimes($qty);
2119
-    }
2120
-
2121
-
2122
-    /**
2123
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
2124
-     *
2125
-     * @param int    $qty
2126
-     * @param bool   $adjust_datetimes
2127
-     * @param string $source
2128
-     * @return void
2129
-     * @throws EE_Error
2130
-     * @throws InvalidArgumentException
2131
-     * @throws ReflectionException
2132
-     * @throws InvalidDataTypeException
2133
-     * @throws InvalidInterfaceException
2134
-     * @deprecated 4.9.80.p
2135
-     */
2136
-    public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
2137
-    {
2138
-        EE_Error::doing_it_wrong(
2139
-            __FUNCTION__,
2140
-            esc_html__('Please use EE_Ticket::decreaseReserved() instead', 'event_espresso'),
2141
-            '4.9.80.p',
2142
-            '5.0.0.p'
2143
-        );
2144
-        $this->decreaseReserved($qty);
2145
-    }
2146
-
2147
-
2148
-    /**
2149
-     * Decreases reserved on related datetimes
2150
-     *
2151
-     * @param int $qty
2152
-     * @return void
2153
-     * @throws EE_Error
2154
-     * @throws InvalidArgumentException
2155
-     * @throws ReflectionException
2156
-     * @throws InvalidDataTypeException
2157
-     * @throws InvalidInterfaceException
2158
-     * @deprecated 4.9.80.p
2159
-     */
2160
-    protected function _decrease_reserved_for_datetimes($qty = 1)
2161
-    {
2162
-        EE_Error::doing_it_wrong(
2163
-            __FUNCTION__,
2164
-            esc_html__('Please use EE_Ticket::decreaseReservedForDatetimes() instead', 'event_espresso'),
2165
-            '4.9.80.p',
2166
-            '5.0.0.p'
2167
-        );
2168
-        $this->decreaseReservedForDatetimes($qty);
2169
-    }
1974
+	/**
1975
+	 * Increments sold by amount passed by $qty AND decrements the reserved count on both this ticket and its
1976
+	 * associated datetimes.
1977
+	 *
1978
+	 * @param int $qty
1979
+	 * @return void
1980
+	 * @throws EE_Error
1981
+	 * @throws InvalidArgumentException
1982
+	 * @throws InvalidDataTypeException
1983
+	 * @throws InvalidInterfaceException
1984
+	 * @throws ReflectionException
1985
+	 * @deprecated 4.9.80.p
1986
+	 */
1987
+	public function increase_sold($qty = 1)
1988
+	{
1989
+		EE_Error::doing_it_wrong(
1990
+			__FUNCTION__,
1991
+			esc_html__('Please use EE_Ticket::increaseSold() instead', 'event_espresso'),
1992
+			'4.9.80.p',
1993
+			'5.0.0.p'
1994
+		);
1995
+		$this->increaseSold($qty);
1996
+	}
1997
+
1998
+
1999
+	/**
2000
+	 * On each datetime related to this ticket, increases its sold count and decreases its reserved count by $qty.
2001
+	 *
2002
+	 * @param int $qty positive or negative. Positive means to increase sold counts (and decrease reserved counts),
2003
+	 *                 Negative means to decreases old counts (and increase reserved counts).
2004
+	 * @throws EE_Error
2005
+	 * @throws InvalidArgumentException
2006
+	 * @throws InvalidDataTypeException
2007
+	 * @throws InvalidInterfaceException
2008
+	 * @throws ReflectionException
2009
+	 * @deprecated 4.9.80.p
2010
+	 */
2011
+	protected function _increase_sold_for_datetimes($qty)
2012
+	{
2013
+		EE_Error::doing_it_wrong(
2014
+			__FUNCTION__,
2015
+			esc_html__('Please use EE_Ticket::increaseSoldForDatetimes() instead', 'event_espresso'),
2016
+			'4.9.80.p',
2017
+			'5.0.0.p'
2018
+		);
2019
+		$this->increaseSoldForDatetimes($qty);
2020
+	}
2021
+
2022
+
2023
+	/**
2024
+	 * Decrements (subtracts) sold by amount passed by $qty on both the ticket and its related datetimes directly in the
2025
+	 * DB and then updates the model objects.
2026
+	 * Does not affect the reserved counts.
2027
+	 *
2028
+	 * @param int $qty
2029
+	 * @return void
2030
+	 * @throws EE_Error
2031
+	 * @throws InvalidArgumentException
2032
+	 * @throws InvalidDataTypeException
2033
+	 * @throws InvalidInterfaceException
2034
+	 * @throws ReflectionException
2035
+	 * @deprecated 4.9.80.p
2036
+	 */
2037
+	public function decrease_sold($qty = 1)
2038
+	{
2039
+		EE_Error::doing_it_wrong(
2040
+			__FUNCTION__,
2041
+			esc_html__('Please use EE_Ticket::decreaseSold() instead', 'event_espresso'),
2042
+			'4.9.80.p',
2043
+			'5.0.0.p'
2044
+		);
2045
+		$this->decreaseSold($qty);
2046
+	}
2047
+
2048
+
2049
+	/**
2050
+	 * Decreases sold on related datetimes
2051
+	 *
2052
+	 * @param int $qty
2053
+	 * @return void
2054
+	 * @throws EE_Error
2055
+	 * @throws InvalidArgumentException
2056
+	 * @throws InvalidDataTypeException
2057
+	 * @throws InvalidInterfaceException
2058
+	 * @throws ReflectionException
2059
+	 * @deprecated 4.9.80.p
2060
+	 */
2061
+	protected function _decrease_sold_for_datetimes($qty = 1)
2062
+	{
2063
+		EE_Error::doing_it_wrong(
2064
+			__FUNCTION__,
2065
+			esc_html__('Please use EE_Ticket::decreaseSoldForDatetimes() instead', 'event_espresso'),
2066
+			'4.9.80.p',
2067
+			'5.0.0.p'
2068
+		);
2069
+		$this->decreaseSoldForDatetimes($qty);
2070
+	}
2071
+
2072
+
2073
+	/**
2074
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
2075
+	 *
2076
+	 * @param int    $qty
2077
+	 * @param string $source
2078
+	 * @return bool whether we successfully reserved the ticket or not.
2079
+	 * @throws EE_Error
2080
+	 * @throws InvalidArgumentException
2081
+	 * @throws ReflectionException
2082
+	 * @throws InvalidDataTypeException
2083
+	 * @throws InvalidInterfaceException
2084
+	 * @deprecated 4.9.80.p
2085
+	 */
2086
+	public function increase_reserved($qty = 1, $source = 'unknown')
2087
+	{
2088
+		EE_Error::doing_it_wrong(
2089
+			__FUNCTION__,
2090
+			esc_html__('Please use EE_Ticket::increaseReserved() instead', 'event_espresso'),
2091
+			'4.9.80.p',
2092
+			'5.0.0.p'
2093
+		);
2094
+		return $this->increaseReserved($qty);
2095
+	}
2096
+
2097
+
2098
+	/**
2099
+	 * Increases sold on related datetimes
2100
+	 *
2101
+	 * @param int $qty
2102
+	 * @return boolean indicating success
2103
+	 * @throws EE_Error
2104
+	 * @throws InvalidArgumentException
2105
+	 * @throws InvalidDataTypeException
2106
+	 * @throws InvalidInterfaceException
2107
+	 * @throws ReflectionException
2108
+	 * @deprecated 4.9.80.p
2109
+	 */
2110
+	protected function _increase_reserved_for_datetimes($qty = 1)
2111
+	{
2112
+		EE_Error::doing_it_wrong(
2113
+			__FUNCTION__,
2114
+			esc_html__('Please use EE_Ticket::increaseReservedForDatetimes() instead', 'event_espresso'),
2115
+			'4.9.80.p',
2116
+			'5.0.0.p'
2117
+		);
2118
+		return $this->increaseReservedForDatetimes($qty);
2119
+	}
2120
+
2121
+
2122
+	/**
2123
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
2124
+	 *
2125
+	 * @param int    $qty
2126
+	 * @param bool   $adjust_datetimes
2127
+	 * @param string $source
2128
+	 * @return void
2129
+	 * @throws EE_Error
2130
+	 * @throws InvalidArgumentException
2131
+	 * @throws ReflectionException
2132
+	 * @throws InvalidDataTypeException
2133
+	 * @throws InvalidInterfaceException
2134
+	 * @deprecated 4.9.80.p
2135
+	 */
2136
+	public function decrease_reserved($qty = 1, $adjust_datetimes = true, $source = 'unknown')
2137
+	{
2138
+		EE_Error::doing_it_wrong(
2139
+			__FUNCTION__,
2140
+			esc_html__('Please use EE_Ticket::decreaseReserved() instead', 'event_espresso'),
2141
+			'4.9.80.p',
2142
+			'5.0.0.p'
2143
+		);
2144
+		$this->decreaseReserved($qty);
2145
+	}
2146
+
2147
+
2148
+	/**
2149
+	 * Decreases reserved on related datetimes
2150
+	 *
2151
+	 * @param int $qty
2152
+	 * @return void
2153
+	 * @throws EE_Error
2154
+	 * @throws InvalidArgumentException
2155
+	 * @throws ReflectionException
2156
+	 * @throws InvalidDataTypeException
2157
+	 * @throws InvalidInterfaceException
2158
+	 * @deprecated 4.9.80.p
2159
+	 */
2160
+	protected function _decrease_reserved_for_datetimes($qty = 1)
2161
+	{
2162
+		EE_Error::doing_it_wrong(
2163
+			__FUNCTION__,
2164
+			esc_html__('Please use EE_Ticket::decreaseReservedForDatetimes() instead', 'event_espresso'),
2165
+			'4.9.80.p',
2166
+			'5.0.0.p'
2167
+		);
2168
+		$this->decreaseReservedForDatetimes($qty);
2169
+	}
2170 2170
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
     public function ticket_status($display = false, $remaining = null)
173 173
     {
174 174
         $remaining = is_bool($remaining) ? $remaining : $this->is_remaining();
175
-        if (! $remaining) {
175
+        if ( ! $remaining) {
176 176
             return $display ? EEH_Template::pretty_status(EE_Ticket::sold_out, false, 'sentence') : EE_Ticket::sold_out;
177 177
         }
178 178
         if ($this->get('TKT_deleted')) {
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
             ? $this->last_datetime()->get_i18n_datetime('DTT_EVT_end', $date_format)
301 301
             : '';
302 302
 
303
-        return $first_date && $last_date ? $first_date . $conjunction . $last_date : '';
303
+        return $first_date && $last_date ? $first_date.$conjunction.$last_date : '';
304 304
     }
305 305
 
306 306
 
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
      */
331 331
     public function datetimes($query_params = [])
332 332
     {
333
-        if (! isset($query_params['order_by'])) {
333
+        if ( ! isset($query_params['order_by'])) {
334 334
             $query_params['order_by']['DTT_order'] = 'ASC';
335 335
         }
336 336
         return $this->get_many_related('Datetime', $query_params);
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
                 if (empty($tickets_sold['datetime'])) {
378 378
                     return $total;
379 379
                 }
380
-                if (! empty($dtt_id) && ! isset($tickets_sold['datetime'][ $dtt_id ])) {
380
+                if ( ! empty($dtt_id) && ! isset($tickets_sold['datetime'][$dtt_id])) {
381 381
                     EE_Error::add_error(
382 382
                         esc_html__(
383 383
                             '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?',
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
                     );
390 390
                     return $total;
391 391
                 }
392
-                return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][ $dtt_id ];
392
+                return empty($dtt_id) ? $tickets_sold['datetime'] : $tickets_sold['datetime'][$dtt_id];
393 393
 
394 394
             default:
395 395
                 return $total;
@@ -408,9 +408,9 @@  discard block
 block discarded – undo
408 408
     {
409 409
         $datetimes    = $this->get_many_related('Datetime');
410 410
         $tickets_sold = [];
411
-        if (! empty($datetimes)) {
411
+        if ( ! empty($datetimes)) {
412 412
             foreach ($datetimes as $datetime) {
413
-                $tickets_sold['datetime'][ $datetime->ID() ] = $datetime->get('DTT_sold');
413
+                $tickets_sold['datetime'][$datetime->ID()] = $datetime->get('DTT_sold');
414 414
             }
415 415
         }
416 416
         // Tickets sold
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
     public function base_price(bool $return_array = false)
431 431
     {
432 432
         $base_price = $this->ticket_price_modifiers->getBasePrice();
433
-        if (! empty($base_price)) {
433
+        if ( ! empty($base_price)) {
434 434
             return $return_array ? $base_price : reset($base_price);
435 435
         }
436 436
         $_where = ['Price_Type.PBT_ID' => EEM_Price_Type::base_type_base_price];
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
         $price_modifiers = $this->usesGlobalTaxes()
453 453
             ? $this->ticket_price_modifiers->getAllDiscountAndSurchargeModifiersForTicket()
454 454
             : $this->ticket_price_modifiers->getAllModifiersForTicket();
455
-        if (! empty($price_modifiers)) {
455
+        if ( ! empty($price_modifiers)) {
456 456
             return $price_modifiers;
457 457
         }
458 458
         return $this->prices(
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
     public function tax_price_modifiers(): array
479 479
     {
480 480
         $tax_price_modifiers = $this->ticket_price_modifiers->getAllTaxesForTicket();
481
-        if (! empty($tax_price_modifiers)) {
481
+        if ( ! empty($tax_price_modifiers)) {
482 482
             return $tax_price_modifiers;
483 483
         }
484 484
         return $this->prices([['Price_Type.PBT_ID' => EEM_Price_Type::base_type_tax]]);
@@ -496,7 +496,7 @@  discard block
 block discarded – undo
496 496
      */
497 497
     public function prices(array $query_params = []): array
498 498
     {
499
-        if (! isset($query_params['order_by'])) {
499
+        if ( ! isset($query_params['order_by'])) {
500 500
             $query_params['order_by']['PRC_order'] = 'ASC';
501 501
         }
502 502
         return $this->get_many_related('Price', $query_params);
@@ -1075,7 +1075,7 @@  discard block
 block discarded – undo
1075 1075
                 'TKT_qty',
1076 1076
                 $qty
1077 1077
             );
1078
-            if (! $success) {
1078
+            if ( ! $success) {
1079 1079
                 // The datetimes were successfully bumped, but not the
1080 1080
                 // ticket. So we need to manually roll back the datetimes.
1081 1081
                 $this->decreaseReservedForDatetimes($qty);
@@ -1687,7 +1687,7 @@  discard block
 block discarded – undo
1687 1687
     {
1688 1688
         // get one datetime to use for getting the event
1689 1689
         $datetime = $this->first_datetime();
1690
-        if (! $datetime instanceof EE_Datetime) {
1690
+        if ( ! $datetime instanceof EE_Datetime) {
1691 1691
             throw new UnexpectedEntityException(
1692 1692
                 $datetime,
1693 1693
                 'EE_Datetime',
@@ -1698,7 +1698,7 @@  discard block
 block discarded – undo
1698 1698
             );
1699 1699
         }
1700 1700
         $event = $datetime->event();
1701
-        if (! $event instanceof EE_Event) {
1701
+        if ( ! $event instanceof EE_Event) {
1702 1702
             throw new UnexpectedEntityException(
1703 1703
                 $event,
1704 1704
                 'EE_Event',
Please login to merge, or discard this patch.
core/domain/entities/shortcodes/EspressoCancelled.php 2 patches
Indentation   +174 added lines, -174 removed lines patch added patch discarded remove patch
@@ -25,178 +25,178 @@
 block discarded – undo
25 25
  */
26 26
 class EspressoCancelled extends EspressoShortcode
27 27
 {
28
-    private ?RequestInterface $request = null;
29
-
30
-
31
-    public function request(): RequestInterface
32
-    {
33
-        if (! $this->request instanceof RequestInterface) {
34
-            $this->request = LoaderFactory::getShared(RequestInterface::class);
35
-        }
36
-        return $this->request;
37
-    }
38
-
39
-
40
-
41
-    /**
42
-     * the actual shortcode tag that gets registered with WordPress
43
-     *
44
-     * @return string
45
-     */
46
-    public function getTag()
47
-    {
48
-        return 'ESPRESSO_CANCELLED';
49
-    }
50
-
51
-
52
-    /**
53
-     * the time in seconds to cache the results of the processShortcode() method
54
-     * 0 means the processShortcode() results will NOT be cached at all
55
-     *
56
-     * @return int
57
-     */
58
-    public function cacheExpiration()
59
-    {
60
-        return 0;
61
-    }
62
-
63
-
64
-    /**
65
-     * a place for adding any initialization code that needs to run prior to wp_header().
66
-     * this may be required for shortcodes that utilize a corresponding module,
67
-     * and need to enqueue assets for that module
68
-     *
69
-     * @return void
70
-     */
71
-    public function initializeShortcode()
72
-    {
73
-        $this->shortcodeHasBeenInitialized();
74
-    }
75
-
76
-
77
-    /**
78
-     * callback that runs when the shortcode is encountered in post content.
79
-     * IMPORTANT !!!
80
-     * remember that shortcode content should be RETURNED and NOT echoed out
81
-     *
82
-     * @param array|string $attributes
83
-     * @return string
84
-     * @throws EE_Error
85
-     * @throws ReflectionException
86
-     */
87
-    public function processShortcode($attributes = array())
88
-    {
89
-        $reg_url_link = $this->request()->getRequestParam('e_reg_url_link', '');
90
-        if (! $reg_url_link) {
91
-            return $this->clearCartAndCancelAllRegistrations();
92
-        }
93
-        $registration = EEM_Registration::instance()->get_registration_for_reg_url_link($reg_url_link);
94
-        if (! $registration instanceof EE_Registration) {
95
-            return sprintf(
96
-                esc_html__(
97
-                    '%1$sCould not find registration for the REG URL link: %2$s',
98
-                    'event_espresso'
99
-                ),
100
-                '<p class="ee-registrations-cancelled-pg ee-attention">',
101
-                $reg_url_link . '</p>'
102
-            );
103
-        }
104
-        $confirmation_code = $this->request()->getRequestParam('confirmation_code', '');
105
-        $confirmation_code = strtoupper((string) $confirmation_code);
106
-        if (! $confirmation_code) {
107
-            return $this->cancelRegistrationConfirmationForm($registration);
108
-        }
109
-        return $this->cancelRegistration($registration, $confirmation_code);
110
-    }
111
-
112
-
113
-    /**
114
-     * @param EE_Registration $registration
115
-     * @return string
116
-     * @throws EE_Error
117
-     * @since 5.0.30.p
118
-     */
119
-    private function cancelRegistrationConfirmationForm(EE_Registration $registration): string
120
-    {
121
-        $form  = new CancelRegistrationForm($registration);
122
-        return $form->display();
123
-    }
124
-
125
-
126
-    /**
127
-     * @param EE_Registration $registration
128
-     * @param string          $confirmation_code
129
-     * @return string
130
-     * @throws EE_Error
131
-     * @throws ReflectionException
132
-     * @since 5.0.30.p
133
-     */
134
-    private function cancelRegistration(EE_Registration $registration, string $confirmation_code): string
135
-    {
136
-        if ($confirmation_code !== $registration->cancelRegistrationConfirmationCode()) {
137
-            return sprintf(
138
-                esc_html__(
139
-                    '%1$sThe confirmation code provided does not match the confirmation code for this registration!%2$s',
140
-                    'event_espresso'
141
-                ),
142
-                '<p class="ee-registrations-cancelled-pg ee-attention">',
143
-                $registration->reg_url_link() . '</p>'
144
-            );
145
-        }
146
-
147
-        try {
148
-            $form   = new CancelRegistrationForm($registration);
149
-            return $form->process($this->request->postParams());
150
-        } catch (Exception $exception) {
151
-            return sprintf(
152
-                esc_html__(
153
-                    '%1$sThe following error occurred and the one or more registrations could not be cancelled:%2$s',
154
-                    'event_espresso'
155
-                ),
156
-                '<p class="ee-registrations-cancelled-pg ee-attention">',
157
-                '<br>' . $exception->getMessage() . '</p>'
158
-            );
159
-        }
160
-    }
161
-
162
-
163
-    /**
164
-     * @return string
165
-     * @throws EE_Error
166
-     * @throws ReflectionException
167
-     * @since 5.0.30.p
168
-     */
169
-    private function clearCartAndCancelAllRegistrations(): string
170
-    {
171
-        $session = LoaderFactory::getShared(EE_Session::class);
172
-        if (! $session instanceof EE_Session) {
173
-            return '';
174
-        }
175
-        $transaction = $session->get_session_data('transaction');
176
-        if ($transaction instanceof EE_Transaction) {
177
-            do_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction', $transaction);
178
-            $registrations = $transaction->registrations();
179
-            foreach ($registrations as $registration) {
180
-                if ($registration instanceof EE_Registration) {
181
-                    do_action('AHEE__EES_Espresso_Cancelled__process_shortcode__registration', $registration);
182
-                }
183
-            }
184
-        }
185
-        do_action('AHEE__EES_Espresso_Cancelled__process_shortcode__clear_session');
186
-        // remove all unwanted records from the db
187
-        if ($session->cart() instanceof EE_Cart) {
188
-            $session->cart()->delete_cart();
189
-        }
190
-        $session->clear_session(__CLASS__, __FUNCTION__);
191
-        // phpcs:disable WordPress.WP.I18n.UnorderedPlaceholdersText
192
-        return sprintf(
193
-            esc_html__(
194
-                '%sAll unsaved registration information entered during this session has been deleted.%s',
195
-                'event_espresso'
196
-            ),
197
-            '<p class="ee-registrations-cancelled-pg ee-attention">',
198
-            '</p>'
199
-        );
200
-        // phpcs:enable
201
-    }
28
+	private ?RequestInterface $request = null;
29
+
30
+
31
+	public function request(): RequestInterface
32
+	{
33
+		if (! $this->request instanceof RequestInterface) {
34
+			$this->request = LoaderFactory::getShared(RequestInterface::class);
35
+		}
36
+		return $this->request;
37
+	}
38
+
39
+
40
+
41
+	/**
42
+	 * the actual shortcode tag that gets registered with WordPress
43
+	 *
44
+	 * @return string
45
+	 */
46
+	public function getTag()
47
+	{
48
+		return 'ESPRESSO_CANCELLED';
49
+	}
50
+
51
+
52
+	/**
53
+	 * the time in seconds to cache the results of the processShortcode() method
54
+	 * 0 means the processShortcode() results will NOT be cached at all
55
+	 *
56
+	 * @return int
57
+	 */
58
+	public function cacheExpiration()
59
+	{
60
+		return 0;
61
+	}
62
+
63
+
64
+	/**
65
+	 * a place for adding any initialization code that needs to run prior to wp_header().
66
+	 * this may be required for shortcodes that utilize a corresponding module,
67
+	 * and need to enqueue assets for that module
68
+	 *
69
+	 * @return void
70
+	 */
71
+	public function initializeShortcode()
72
+	{
73
+		$this->shortcodeHasBeenInitialized();
74
+	}
75
+
76
+
77
+	/**
78
+	 * callback that runs when the shortcode is encountered in post content.
79
+	 * IMPORTANT !!!
80
+	 * remember that shortcode content should be RETURNED and NOT echoed out
81
+	 *
82
+	 * @param array|string $attributes
83
+	 * @return string
84
+	 * @throws EE_Error
85
+	 * @throws ReflectionException
86
+	 */
87
+	public function processShortcode($attributes = array())
88
+	{
89
+		$reg_url_link = $this->request()->getRequestParam('e_reg_url_link', '');
90
+		if (! $reg_url_link) {
91
+			return $this->clearCartAndCancelAllRegistrations();
92
+		}
93
+		$registration = EEM_Registration::instance()->get_registration_for_reg_url_link($reg_url_link);
94
+		if (! $registration instanceof EE_Registration) {
95
+			return sprintf(
96
+				esc_html__(
97
+					'%1$sCould not find registration for the REG URL link: %2$s',
98
+					'event_espresso'
99
+				),
100
+				'<p class="ee-registrations-cancelled-pg ee-attention">',
101
+				$reg_url_link . '</p>'
102
+			);
103
+		}
104
+		$confirmation_code = $this->request()->getRequestParam('confirmation_code', '');
105
+		$confirmation_code = strtoupper((string) $confirmation_code);
106
+		if (! $confirmation_code) {
107
+			return $this->cancelRegistrationConfirmationForm($registration);
108
+		}
109
+		return $this->cancelRegistration($registration, $confirmation_code);
110
+	}
111
+
112
+
113
+	/**
114
+	 * @param EE_Registration $registration
115
+	 * @return string
116
+	 * @throws EE_Error
117
+	 * @since 5.0.30.p
118
+	 */
119
+	private function cancelRegistrationConfirmationForm(EE_Registration $registration): string
120
+	{
121
+		$form  = new CancelRegistrationForm($registration);
122
+		return $form->display();
123
+	}
124
+
125
+
126
+	/**
127
+	 * @param EE_Registration $registration
128
+	 * @param string          $confirmation_code
129
+	 * @return string
130
+	 * @throws EE_Error
131
+	 * @throws ReflectionException
132
+	 * @since 5.0.30.p
133
+	 */
134
+	private function cancelRegistration(EE_Registration $registration, string $confirmation_code): string
135
+	{
136
+		if ($confirmation_code !== $registration->cancelRegistrationConfirmationCode()) {
137
+			return sprintf(
138
+				esc_html__(
139
+					'%1$sThe confirmation code provided does not match the confirmation code for this registration!%2$s',
140
+					'event_espresso'
141
+				),
142
+				'<p class="ee-registrations-cancelled-pg ee-attention">',
143
+				$registration->reg_url_link() . '</p>'
144
+			);
145
+		}
146
+
147
+		try {
148
+			$form   = new CancelRegistrationForm($registration);
149
+			return $form->process($this->request->postParams());
150
+		} catch (Exception $exception) {
151
+			return sprintf(
152
+				esc_html__(
153
+					'%1$sThe following error occurred and the one or more registrations could not be cancelled:%2$s',
154
+					'event_espresso'
155
+				),
156
+				'<p class="ee-registrations-cancelled-pg ee-attention">',
157
+				'<br>' . $exception->getMessage() . '</p>'
158
+			);
159
+		}
160
+	}
161
+
162
+
163
+	/**
164
+	 * @return string
165
+	 * @throws EE_Error
166
+	 * @throws ReflectionException
167
+	 * @since 5.0.30.p
168
+	 */
169
+	private function clearCartAndCancelAllRegistrations(): string
170
+	{
171
+		$session = LoaderFactory::getShared(EE_Session::class);
172
+		if (! $session instanceof EE_Session) {
173
+			return '';
174
+		}
175
+		$transaction = $session->get_session_data('transaction');
176
+		if ($transaction instanceof EE_Transaction) {
177
+			do_action('AHEE__EES_Espresso_Cancelled__process_shortcode__transaction', $transaction);
178
+			$registrations = $transaction->registrations();
179
+			foreach ($registrations as $registration) {
180
+				if ($registration instanceof EE_Registration) {
181
+					do_action('AHEE__EES_Espresso_Cancelled__process_shortcode__registration', $registration);
182
+				}
183
+			}
184
+		}
185
+		do_action('AHEE__EES_Espresso_Cancelled__process_shortcode__clear_session');
186
+		// remove all unwanted records from the db
187
+		if ($session->cart() instanceof EE_Cart) {
188
+			$session->cart()->delete_cart();
189
+		}
190
+		$session->clear_session(__CLASS__, __FUNCTION__);
191
+		// phpcs:disable WordPress.WP.I18n.UnorderedPlaceholdersText
192
+		return sprintf(
193
+			esc_html__(
194
+				'%sAll unsaved registration information entered during this session has been deleted.%s',
195
+				'event_espresso'
196
+			),
197
+			'<p class="ee-registrations-cancelled-pg ee-attention">',
198
+			'</p>'
199
+		);
200
+		// phpcs:enable
201
+	}
202 202
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
 
31 31
     public function request(): RequestInterface
32 32
     {
33
-        if (! $this->request instanceof RequestInterface) {
33
+        if ( ! $this->request instanceof RequestInterface) {
34 34
             $this->request = LoaderFactory::getShared(RequestInterface::class);
35 35
         }
36 36
         return $this->request;
@@ -87,23 +87,23 @@  discard block
 block discarded – undo
87 87
     public function processShortcode($attributes = array())
88 88
     {
89 89
         $reg_url_link = $this->request()->getRequestParam('e_reg_url_link', '');
90
-        if (! $reg_url_link) {
90
+        if ( ! $reg_url_link) {
91 91
             return $this->clearCartAndCancelAllRegistrations();
92 92
         }
93 93
         $registration = EEM_Registration::instance()->get_registration_for_reg_url_link($reg_url_link);
94
-        if (! $registration instanceof EE_Registration) {
94
+        if ( ! $registration instanceof EE_Registration) {
95 95
             return sprintf(
96 96
                 esc_html__(
97 97
                     '%1$sCould not find registration for the REG URL link: %2$s',
98 98
                     'event_espresso'
99 99
                 ),
100 100
                 '<p class="ee-registrations-cancelled-pg ee-attention">',
101
-                $reg_url_link . '</p>'
101
+                $reg_url_link.'</p>'
102 102
             );
103 103
         }
104 104
         $confirmation_code = $this->request()->getRequestParam('confirmation_code', '');
105 105
         $confirmation_code = strtoupper((string) $confirmation_code);
106
-        if (! $confirmation_code) {
106
+        if ( ! $confirmation_code) {
107 107
             return $this->cancelRegistrationConfirmationForm($registration);
108 108
         }
109 109
         return $this->cancelRegistration($registration, $confirmation_code);
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
      */
119 119
     private function cancelRegistrationConfirmationForm(EE_Registration $registration): string
120 120
     {
121
-        $form  = new CancelRegistrationForm($registration);
121
+        $form = new CancelRegistrationForm($registration);
122 122
         return $form->display();
123 123
     }
124 124
 
@@ -140,12 +140,12 @@  discard block
 block discarded – undo
140 140
                     'event_espresso'
141 141
                 ),
142 142
                 '<p class="ee-registrations-cancelled-pg ee-attention">',
143
-                $registration->reg_url_link() . '</p>'
143
+                $registration->reg_url_link().'</p>'
144 144
             );
145 145
         }
146 146
 
147 147
         try {
148
-            $form   = new CancelRegistrationForm($registration);
148
+            $form = new CancelRegistrationForm($registration);
149 149
             return $form->process($this->request->postParams());
150 150
         } catch (Exception $exception) {
151 151
             return sprintf(
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
                     'event_espresso'
155 155
                 ),
156 156
                 '<p class="ee-registrations-cancelled-pg ee-attention">',
157
-                '<br>' . $exception->getMessage() . '</p>'
157
+                '<br>'.$exception->getMessage().'</p>'
158 158
             );
159 159
         }
160 160
     }
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
     private function clearCartAndCancelAllRegistrations(): string
170 170
     {
171 171
         $session = LoaderFactory::getShared(EE_Session::class);
172
-        if (! $session instanceof EE_Session) {
172
+        if ( ! $session instanceof EE_Session) {
173 173
             return '';
174 174
         }
175 175
         $transaction = $session->get_session_data('transaction');
Please login to merge, or discard this patch.