Completed
Branch master (3b2419)
by
unknown
04:08
created
espresso.php 1 patch
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -37,124 +37,124 @@
 block discarded – undo
37 37
  * @since           4.0
38 38
  */
39 39
 if (function_exists('espresso_version')) {
40
-    if (! function_exists('espresso_duplicate_plugin_error')) {
41
-        /**
42
-         *    espresso_duplicate_plugin_error
43
-         *    displays if more than one version of EE is activated at the same time.
44
-         */
45
-        function espresso_duplicate_plugin_error()
46
-        {
47
-            ?>
40
+	if (! function_exists('espresso_duplicate_plugin_error')) {
41
+		/**
42
+		 *    espresso_duplicate_plugin_error
43
+		 *    displays if more than one version of EE is activated at the same time.
44
+		 */
45
+		function espresso_duplicate_plugin_error()
46
+		{
47
+			?>
48 48
 <div class="error">
49 49
 	<p>
50 50
 		<?php
51
-                    echo esc_html__(
52
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
53
-                        'event_espresso'
54
-                    ); ?>
51
+					echo esc_html__(
52
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
53
+						'event_espresso'
54
+					); ?>
55 55
 	</p>
56 56
 </div>
57 57
 <?php
58
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
59
-        }
60
-    }
61
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
58
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
59
+		}
60
+	}
61
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62 62
 } else {
63
-    define('EE_MIN_PHP_VER_REQUIRED', '7.4.0');
64
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
65
-        /**
66
-         * espresso_minimum_php_version_error
67
-         *
68
-         * @return void
69
-         */
70
-        function espresso_minimum_php_version_error()
71
-        {
72
-            ?>
63
+	define('EE_MIN_PHP_VER_REQUIRED', '7.4.0');
64
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
65
+		/**
66
+		 * espresso_minimum_php_version_error
67
+		 *
68
+		 * @return void
69
+		 */
70
+		function espresso_minimum_php_version_error()
71
+		{
72
+			?>
73 73
 <div class="error">
74 74
 	<p>
75 75
 		<?php
76
-                    printf(
77
-                        esc_html__(
78
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
79
-                            'event_espresso'
80
-                        ),
81
-                        EE_MIN_PHP_VER_REQUIRED,
82
-                        PHP_VERSION,
83
-                        '<br/>',
84
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
85
-                    );
86
-                    ?>
76
+					printf(
77
+						esc_html__(
78
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
79
+							'event_espresso'
80
+						),
81
+						EE_MIN_PHP_VER_REQUIRED,
82
+						PHP_VERSION,
83
+						'<br/>',
84
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
85
+					);
86
+					?>
87 87
 	</p>
88 88
 </div>
89 89
 <?php
90
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
91
-        }
90
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
91
+		}
92 92
 
93
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
94
-    } else {
95
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
93
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
94
+	} else {
95
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
96 96
 
97
-        require_once __DIR__ . '/vendor/autoload.php';
98
-        require_once __DIR__ . '/vendor/wp-graphql/wp-graphql/wp-graphql.php';
97
+		require_once __DIR__ . '/vendor/autoload.php';
98
+		require_once __DIR__ . '/vendor/wp-graphql/wp-graphql/wp-graphql.php';
99 99
 
100
-        /**
101
-         * espresso_version
102
-         * Returns the plugin version
103
-         *
104
-         * @return string
105
-         */
106
-        function espresso_version()
107
-        {
108
-            return apply_filters('FHEE__espresso__espresso_version', '5.0.8.rc.000');
109
-        }
100
+		/**
101
+		 * espresso_version
102
+		 * Returns the plugin version
103
+		 *
104
+		 * @return string
105
+		 */
106
+		function espresso_version()
107
+		{
108
+			return apply_filters('FHEE__espresso__espresso_version', '5.0.8.rc.000');
109
+		}
110 110
 
111
-        /**
112
-         * espresso_plugin_activation
113
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
114
-         */
115
-        function espresso_plugin_activation()
116
-        {
117
-            update_option('ee_espresso_activation', true);
118
-            update_option('event-espresso-core_allow_tracking', 'no');
119
-            update_option('event-espresso-core_tracking_notice', 'hide');
120
-            // Run WP GraphQL activation callback
121
-            graphql_activation_callback();
122
-        }
111
+		/**
112
+		 * espresso_plugin_activation
113
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
114
+		 */
115
+		function espresso_plugin_activation()
116
+		{
117
+			update_option('ee_espresso_activation', true);
118
+			update_option('event-espresso-core_allow_tracking', 'no');
119
+			update_option('event-espresso-core_tracking_notice', 'hide');
120
+			// Run WP GraphQL activation callback
121
+			graphql_activation_callback();
122
+		}
123 123
 
124
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
124
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
125 125
 
126
-        /**
127
-         * espresso_plugin_deactivation
128
-         */
129
-        function espresso_plugin_deactivation()
130
-        {
131
-            // Run WP GraphQL deactivation callback
132
-            graphql_deactivation_callback();
133
-            delete_option('event-espresso-core_allow_tracking');
134
-            delete_option('event-espresso-core_tracking_notice');
135
-        }
136
-        register_deactivation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_deactivation');
126
+		/**
127
+		 * espresso_plugin_deactivation
128
+		 */
129
+		function espresso_plugin_deactivation()
130
+		{
131
+			// Run WP GraphQL deactivation callback
132
+			graphql_deactivation_callback();
133
+			delete_option('event-espresso-core_allow_tracking');
134
+			delete_option('event-espresso-core_tracking_notice');
135
+		}
136
+		register_deactivation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_deactivation');
137 137
 
138
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
139
-        bootstrap_espresso();
140
-    }
138
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
139
+		bootstrap_espresso();
140
+	}
141 141
 }
142 142
 
143 143
 if (! function_exists('espresso_deactivate_plugin')) {
144
-    /**
145
-     *    deactivate_plugin
146
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
147
-     *
148
-     * @access public
149
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
150
-     * @return    void
151
-     */
152
-    function espresso_deactivate_plugin($plugin_basename = '')
153
-    {
154
-        if (! function_exists('deactivate_plugins')) {
155
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
156
-        }
157
-        unset($_GET['activate'], $_REQUEST['activate']);
158
-        deactivate_plugins($plugin_basename);
159
-    }
144
+	/**
145
+	 *    deactivate_plugin
146
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
147
+	 *
148
+	 * @access public
149
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
150
+	 * @return    void
151
+	 */
152
+	function espresso_deactivate_plugin($plugin_basename = '')
153
+	{
154
+		if (! function_exists('deactivate_plugins')) {
155
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
156
+		}
157
+		unset($_GET['activate'], $_REQUEST['activate']);
158
+		deactivate_plugins($plugin_basename);
159
+	}
160 160
 }
Please login to merge, or discard this patch.
core/domain/values/BaseFormat.php 2 patches
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -4,44 +4,44 @@
 block discarded – undo
4 4
 
5 5
 abstract class BaseFormat
6 6
 {
7
-    protected string $format;
8
-
9
-    public function __construct(?string $format)
10
-    {
11
-        if (static::$wordpress_format === null) {
12
-            static::$wordpress_format = get_option(static::WORDPRESS_FORMAT_OPTION_NAME);
13
-        }
14
-        $this->format = $this->sanitizeDateFormat($format ?: static::$wordpress_format);
15
-    }
16
-
17
-
18
-    protected function sanitizeDateFormat(string $format): string
19
-    {
20
-        $sanitized_format = '';
21
-        for ($i = 0; $i < strlen($format); $i++) {
22
-            $char = substr($format, $i, 1);
23
-            // first check if the previous character was a backslash
24
-            if (substr($format, $i-1, 1) === '\\') {
25
-                // escaped characters are allowed
26
-                $sanitized_format .= "\\$char";
27
-                continue;
28
-            }
29
-            if (in_array($char, static::$allowed_chars)) {
30
-                $sanitized_format .= $char;
31
-            }
32
-        }
33
-        return $sanitized_format;
34
-    }
35
-
36
-
37
-    public function format(): string
38
-    {
39
-        return $this->format;
40
-    }
41
-
42
-
43
-    public function __toString(): string
44
-    {
45
-        return $this->format();
46
-    }
7
+	protected string $format;
8
+
9
+	public function __construct(?string $format)
10
+	{
11
+		if (static::$wordpress_format === null) {
12
+			static::$wordpress_format = get_option(static::WORDPRESS_FORMAT_OPTION_NAME);
13
+		}
14
+		$this->format = $this->sanitizeDateFormat($format ?: static::$wordpress_format);
15
+	}
16
+
17
+
18
+	protected function sanitizeDateFormat(string $format): string
19
+	{
20
+		$sanitized_format = '';
21
+		for ($i = 0; $i < strlen($format); $i++) {
22
+			$char = substr($format, $i, 1);
23
+			// first check if the previous character was a backslash
24
+			if (substr($format, $i-1, 1) === '\\') {
25
+				// escaped characters are allowed
26
+				$sanitized_format .= "\\$char";
27
+				continue;
28
+			}
29
+			if (in_array($char, static::$allowed_chars)) {
30
+				$sanitized_format .= $char;
31
+			}
32
+		}
33
+		return $sanitized_format;
34
+	}
35
+
36
+
37
+	public function format(): string
38
+	{
39
+		return $this->format;
40
+	}
41
+
42
+
43
+	public function __toString(): string
44
+	{
45
+		return $this->format();
46
+	}
47 47
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -21,7 +21,7 @@
 block discarded – undo
21 21
         for ($i = 0; $i < strlen($format); $i++) {
22 22
             $char = substr($format, $i, 1);
23 23
             // first check if the previous character was a backslash
24
-            if (substr($format, $i-1, 1) === '\\') {
24
+            if (substr($format, $i - 1, 1) === '\\') {
25 25
                 // escaped characters are allowed
26 26
                 $sanitized_format .= "\\$char";
27 27
                 continue;
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +3358 added lines, -3358 removed lines patch added patch discarded remove patch
@@ -15,3374 +15,3374 @@
 block discarded – undo
15 15
  */
16 16
 abstract class EE_Base_Class
17 17
 {
18
-    /**
19
-     * @var EEM_Base|null
20
-     */
21
-    protected $_model = null;
22
-
23
-    /**
24
-     * This is an array of the original properties and values provided during construction
25
-     * of this model object. (keys are model field names, values are their values).
26
-     * This list is important to remember so that when we are merging data from the db, we know
27
-     * which values to override and which to not override.
28
-     *
29
-     * @var array
30
-     */
31
-    protected ?array $_props_n_values_provided_in_constructor = null;
32
-
33
-    /**
34
-     * Timezone
35
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
36
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
37
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
38
-     * access to it.
39
-     *
40
-     * @var string
41
-     */
42
-    protected string $_timezone = '';
43
-
44
-    /**
45
-     * date format
46
-     * pattern or format for displaying dates
47
-     *
48
-     * @var string $_dt_frmt
49
-     */
50
-    protected string $_dt_frmt = '';
51
-
52
-    /**
53
-     * time format
54
-     * pattern or format for displaying time
55
-     *
56
-     * @var string $_tm_frmt
57
-     */
58
-    protected string $_tm_frmt = '';
59
-
60
-    /**
61
-     * This property is for holding a cached array of object properties indexed by property name as the key.
62
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
63
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
64
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
65
-     *
66
-     * @var array
67
-     */
68
-    protected array $_cached_properties = [];
69
-
70
-    /**
71
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
72
-     * single
73
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
74
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
75
-     * all others have an array)
76
-     *
77
-     * @var array
78
-     */
79
-    protected array $_model_relations = [];
80
-
81
-    /**
82
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
83
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
84
-     *
85
-     * @var array
86
-     */
87
-    protected array $_fields = [];
88
-
89
-    /**
90
-     * @var bool indicating whether or not this model object is intended to ever be saved
91
-     * For example, we might create model objects intended to only be used for the duration
92
-     * of this request and to be thrown away, and if they were accidentally saved
93
-     * it would be a bug.
94
-     */
95
-    protected bool $_allow_persist = true;
96
-
97
-    /**
98
-     * @var bool indicating whether or not this model object's properties have changed since construction
99
-     */
100
-    protected bool $_has_changes = false;
101
-
102
-    /**
103
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
104
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
105
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
106
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
107
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
108
-     * array as:
109
-     * array(
110
-     *  'Registration_Count' => 24
111
-     * );
112
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
113
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
114
-     * info)
115
-     *
116
-     * @var array
117
-     */
118
-    protected array $custom_selection_results = [];
119
-
120
-
121
-    /**
122
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
123
-     * play nice
124
-     *
125
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
126
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
127
-     *                                                         TXN_amount, QST_name, etc) and values are their values
128
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
129
-     *                                                         corresponding db model or not.
130
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
131
-     *                                                         be in when instantiating a EE_Base_Class object.
132
-     * @param array   $date_formats                            An array of date formats to set on construct where first
133
-     *                                                         value is the date_format and second value is the time
134
-     *                                                         format.
135
-     * @throws InvalidArgumentException
136
-     * @throws InvalidInterfaceException
137
-     * @throws InvalidDataTypeException
138
-     * @throws EE_Error
139
-     * @throws ReflectionException
140
-     */
141
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
142
-    {
143
-        $className = get_class($this);
144
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
145
-        $model = $this->get_model();
146
-        $model_fields = $model->field_settings(false);
147
-        // ensure $fieldValues is an array
148
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
149
-        // verify client code has not passed any invalid field names
150
-        foreach ($fieldValues as $field_name => $field_value) {
151
-            if (! isset($model_fields[ $field_name ])) {
152
-                throw new EE_Error(
153
-                    sprintf(
154
-                        esc_html__(
155
-                            'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
156
-                            'event_espresso'
157
-                        ),
158
-                        $field_name,
159
-                        get_class($this),
160
-                        implode(', ', array_keys($model_fields))
161
-                    )
162
-                );
163
-            }
164
-        }
165
-
166
-        $date_format = null;
167
-        $time_format = null;
168
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
169
-        if (! empty($date_formats) && is_array($date_formats)) {
170
-            [$date_format, $time_format] = $date_formats;
171
-        }
172
-        $this->set_date_format($date_format);
173
-        $this->set_time_format($time_format);
174
-        // if db model is instantiating
175
-        foreach ($model_fields as $fieldName => $field) {
176
-            if ($bydb) {
177
-                // client code has indicated these field values are from the database
178
-                    $this->set_from_db(
179
-                        $fieldName,
180
-                        $fieldValues[ $fieldName ] ?? null
181
-                    );
182
-            } else {
183
-                // we're constructing a brand new instance of the model object.
184
-                // Generally, this means we'll need to do more field validation
185
-                    $this->set(
186
-                    $fieldName,
187
-                    $fieldValues[ $fieldName ] ?? null,
188
-                    true
189
-                );
190
-            }
191
-        }
192
-        // remember what values were passed to this constructor
193
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
194
-        // remember in entity mapper
195
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
-            $model->add_to_entity_map($this);
197
-        }
198
-        // setup all the relations
199
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
202
-            } else {
203
-                $this->_model_relations[ $relation_name ] = array();
204
-            }
205
-        }
206
-        /**
207
-         * Action done at the end of each model object construction
208
-         *
209
-         * @param EE_Base_Class $this the model object just created
210
-         */
211
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
-    }
213
-
214
-
215
-    /**
216
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
217
-     *
218
-     * @return boolean
219
-     */
220
-    public function allow_persist()
221
-    {
222
-        return $this->_allow_persist;
223
-    }
224
-
225
-
226
-    /**
227
-     * Sets whether or not this model object should be allowed to be saved to the DB.
228
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
-     * you got new information that somehow made you change your mind.
230
-     *
231
-     * @param boolean $allow_persist
232
-     * @return boolean
233
-     */
234
-    public function set_allow_persist($allow_persist)
235
-    {
236
-        return $this->_allow_persist = $allow_persist;
237
-    }
238
-
239
-
240
-    /**
241
-     * Gets the field's original value when this object was constructed during this request.
242
-     * This can be helpful when determining if a model object has changed or not
243
-     *
244
-     * @param string $field_name
245
-     * @return mixed|null
246
-     * @throws ReflectionException
247
-     * @throws InvalidArgumentException
248
-     * @throws InvalidInterfaceException
249
-     * @throws InvalidDataTypeException
250
-     * @throws EE_Error
251
-     */
252
-    public function get_original($field_name)
253
-    {
254
-        if (
255
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
256
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
257
-        ) {
258
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
259
-        }
260
-        return null;
261
-    }
262
-
263
-
264
-    /**
265
-     * @param EE_Base_Class $obj
266
-     * @return string
267
-     */
268
-    public function get_class($obj)
269
-    {
270
-        return get_class($obj);
271
-    }
272
-
273
-
274
-    /**
275
-     * Overrides parent because parent expects old models.
276
-     * This also doesn't do any validation, and won't work for serialized arrays
277
-     *
278
-     * @param string $field_name
279
-     * @param mixed  $field_value
280
-     * @param bool   $use_default
281
-     * @throws InvalidArgumentException
282
-     * @throws InvalidInterfaceException
283
-     * @throws InvalidDataTypeException
284
-     * @throws EE_Error
285
-     * @throws ReflectionException
286
-     * @throws ReflectionException
287
-     * @throws ReflectionException
288
-     */
289
-    public function set(string $field_name, $field_value, bool $use_default = false)
290
-    {
291
-        // if not using default and nothing has changed, and object has already been setup (has ID),
292
-        // then don't do anything
293
-        if (
294
-            ! $use_default
295
-            && $this->_fields[ $field_name ] === $field_value
296
-            && $this->ID()
297
-        ) {
298
-            return;
299
-        }
300
-        $model = $this->get_model();
301
-        $this->_has_changes = true;
302
-        $field_obj = $model->field_settings_for($field_name);
303
-        if (! $field_obj instanceof EE_Model_Field_Base) {
304
-            throw new EE_Error(
305
-                sprintf(
306
-                    esc_html__(
307
-                        'A valid EE_Model_Field_Base could not be found for the given field name: %s',
308
-                        'event_espresso'
309
-                    ),
310
-                    $field_name
311
-                )
312
-            );
313
-        }
314
-        // if ( method_exists( $field_obj, 'set_timezone' )) {
315
-        if ($field_obj instanceof EE_Datetime_Field) {
316
-            $field_obj->set_timezone($this->_timezone);
317
-            $field_obj->set_date_format($this->_dt_frmt);
318
-            $field_obj->set_time_format($this->_tm_frmt);
319
-        }
320
-        $holder_of_value = $field_obj->prepare_for_set($field_value);
321
-        // should the value be null?
322
-        if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
323
-            $this->_fields[ $field_name ] = $field_obj->get_default_value();
324
-            /**
325
-             * To save having to refactor all the models, if a default value is used for a
326
-             * EE_Datetime_Field, and that value is not null nor is it a DateTime
327
-             * object.  Then let's do a set again to ensure that it becomes a DateTime
328
-             * object.
329
-             *
330
-             * @since 4.6.10+
331
-             */
332
-            if (
333
-                $field_obj instanceof EE_Datetime_Field
334
-                && $this->_fields[ $field_name ] !== null
335
-                && ! $this->_fields[ $field_name ] instanceof DateTime
336
-            ) {
337
-                empty($this->_fields[ $field_name ])
338
-                    ? $this->set($field_name, time())
339
-                    : $this->set($field_name, $this->_fields[ $field_name ]);
340
-            }
341
-        } else {
342
-            $this->_fields[ $field_name ] = $holder_of_value;
343
-        }
344
-        // if we're not in the constructor...
345
-        // now check if what we set was a primary key
346
-        if (
18
+	/**
19
+	 * @var EEM_Base|null
20
+	 */
21
+	protected $_model = null;
22
+
23
+	/**
24
+	 * This is an array of the original properties and values provided during construction
25
+	 * of this model object. (keys are model field names, values are their values).
26
+	 * This list is important to remember so that when we are merging data from the db, we know
27
+	 * which values to override and which to not override.
28
+	 *
29
+	 * @var array
30
+	 */
31
+	protected ?array $_props_n_values_provided_in_constructor = null;
32
+
33
+	/**
34
+	 * Timezone
35
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
36
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
37
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
38
+	 * access to it.
39
+	 *
40
+	 * @var string
41
+	 */
42
+	protected string $_timezone = '';
43
+
44
+	/**
45
+	 * date format
46
+	 * pattern or format for displaying dates
47
+	 *
48
+	 * @var string $_dt_frmt
49
+	 */
50
+	protected string $_dt_frmt = '';
51
+
52
+	/**
53
+	 * time format
54
+	 * pattern or format for displaying time
55
+	 *
56
+	 * @var string $_tm_frmt
57
+	 */
58
+	protected string $_tm_frmt = '';
59
+
60
+	/**
61
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
62
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
63
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
64
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
65
+	 *
66
+	 * @var array
67
+	 */
68
+	protected array $_cached_properties = [];
69
+
70
+	/**
71
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
72
+	 * single
73
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
74
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
75
+	 * all others have an array)
76
+	 *
77
+	 * @var array
78
+	 */
79
+	protected array $_model_relations = [];
80
+
81
+	/**
82
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
83
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
84
+	 *
85
+	 * @var array
86
+	 */
87
+	protected array $_fields = [];
88
+
89
+	/**
90
+	 * @var bool indicating whether or not this model object is intended to ever be saved
91
+	 * For example, we might create model objects intended to only be used for the duration
92
+	 * of this request and to be thrown away, and if they were accidentally saved
93
+	 * it would be a bug.
94
+	 */
95
+	protected bool $_allow_persist = true;
96
+
97
+	/**
98
+	 * @var bool indicating whether or not this model object's properties have changed since construction
99
+	 */
100
+	protected bool $_has_changes = false;
101
+
102
+	/**
103
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
104
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
105
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
106
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
107
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
108
+	 * array as:
109
+	 * array(
110
+	 *  'Registration_Count' => 24
111
+	 * );
112
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
113
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
114
+	 * info)
115
+	 *
116
+	 * @var array
117
+	 */
118
+	protected array $custom_selection_results = [];
119
+
120
+
121
+	/**
122
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
123
+	 * play nice
124
+	 *
125
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
126
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
127
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
128
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
129
+	 *                                                         corresponding db model or not.
130
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
131
+	 *                                                         be in when instantiating a EE_Base_Class object.
132
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
133
+	 *                                                         value is the date_format and second value is the time
134
+	 *                                                         format.
135
+	 * @throws InvalidArgumentException
136
+	 * @throws InvalidInterfaceException
137
+	 * @throws InvalidDataTypeException
138
+	 * @throws EE_Error
139
+	 * @throws ReflectionException
140
+	 */
141
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
142
+	{
143
+		$className = get_class($this);
144
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
145
+		$model = $this->get_model();
146
+		$model_fields = $model->field_settings(false);
147
+		// ensure $fieldValues is an array
148
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
149
+		// verify client code has not passed any invalid field names
150
+		foreach ($fieldValues as $field_name => $field_value) {
151
+			if (! isset($model_fields[ $field_name ])) {
152
+				throw new EE_Error(
153
+					sprintf(
154
+						esc_html__(
155
+							'Invalid field (%s) passed to constructor of %s. Allowed fields are :%s',
156
+							'event_espresso'
157
+						),
158
+						$field_name,
159
+						get_class($this),
160
+						implode(', ', array_keys($model_fields))
161
+					)
162
+				);
163
+			}
164
+		}
165
+
166
+		$date_format = null;
167
+		$time_format = null;
168
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
169
+		if (! empty($date_formats) && is_array($date_formats)) {
170
+			[$date_format, $time_format] = $date_formats;
171
+		}
172
+		$this->set_date_format($date_format);
173
+		$this->set_time_format($time_format);
174
+		// if db model is instantiating
175
+		foreach ($model_fields as $fieldName => $field) {
176
+			if ($bydb) {
177
+				// client code has indicated these field values are from the database
178
+					$this->set_from_db(
179
+						$fieldName,
180
+						$fieldValues[ $fieldName ] ?? null
181
+					);
182
+			} else {
183
+				// we're constructing a brand new instance of the model object.
184
+				// Generally, this means we'll need to do more field validation
185
+					$this->set(
186
+					$fieldName,
187
+					$fieldValues[ $fieldName ] ?? null,
188
+					true
189
+				);
190
+			}
191
+		}
192
+		// remember what values were passed to this constructor
193
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
194
+		// remember in entity mapper
195
+		if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
196
+			$model->add_to_entity_map($this);
197
+		}
198
+		// setup all the relations
199
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
+				$this->_model_relations[ $relation_name ] = null;
202
+			} else {
203
+				$this->_model_relations[ $relation_name ] = array();
204
+			}
205
+		}
206
+		/**
207
+		 * Action done at the end of each model object construction
208
+		 *
209
+		 * @param EE_Base_Class $this the model object just created
210
+		 */
211
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
212
+	}
213
+
214
+
215
+	/**
216
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
217
+	 *
218
+	 * @return boolean
219
+	 */
220
+	public function allow_persist()
221
+	{
222
+		return $this->_allow_persist;
223
+	}
224
+
225
+
226
+	/**
227
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
228
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
229
+	 * you got new information that somehow made you change your mind.
230
+	 *
231
+	 * @param boolean $allow_persist
232
+	 * @return boolean
233
+	 */
234
+	public function set_allow_persist($allow_persist)
235
+	{
236
+		return $this->_allow_persist = $allow_persist;
237
+	}
238
+
239
+
240
+	/**
241
+	 * Gets the field's original value when this object was constructed during this request.
242
+	 * This can be helpful when determining if a model object has changed or not
243
+	 *
244
+	 * @param string $field_name
245
+	 * @return mixed|null
246
+	 * @throws ReflectionException
247
+	 * @throws InvalidArgumentException
248
+	 * @throws InvalidInterfaceException
249
+	 * @throws InvalidDataTypeException
250
+	 * @throws EE_Error
251
+	 */
252
+	public function get_original($field_name)
253
+	{
254
+		if (
255
+			isset($this->_props_n_values_provided_in_constructor[ $field_name ])
256
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
257
+		) {
258
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
259
+		}
260
+		return null;
261
+	}
262
+
263
+
264
+	/**
265
+	 * @param EE_Base_Class $obj
266
+	 * @return string
267
+	 */
268
+	public function get_class($obj)
269
+	{
270
+		return get_class($obj);
271
+	}
272
+
273
+
274
+	/**
275
+	 * Overrides parent because parent expects old models.
276
+	 * This also doesn't do any validation, and won't work for serialized arrays
277
+	 *
278
+	 * @param string $field_name
279
+	 * @param mixed  $field_value
280
+	 * @param bool   $use_default
281
+	 * @throws InvalidArgumentException
282
+	 * @throws InvalidInterfaceException
283
+	 * @throws InvalidDataTypeException
284
+	 * @throws EE_Error
285
+	 * @throws ReflectionException
286
+	 * @throws ReflectionException
287
+	 * @throws ReflectionException
288
+	 */
289
+	public function set(string $field_name, $field_value, bool $use_default = false)
290
+	{
291
+		// if not using default and nothing has changed, and object has already been setup (has ID),
292
+		// then don't do anything
293
+		if (
294
+			! $use_default
295
+			&& $this->_fields[ $field_name ] === $field_value
296
+			&& $this->ID()
297
+		) {
298
+			return;
299
+		}
300
+		$model = $this->get_model();
301
+		$this->_has_changes = true;
302
+		$field_obj = $model->field_settings_for($field_name);
303
+		if (! $field_obj instanceof EE_Model_Field_Base) {
304
+			throw new EE_Error(
305
+				sprintf(
306
+					esc_html__(
307
+						'A valid EE_Model_Field_Base could not be found for the given field name: %s',
308
+						'event_espresso'
309
+					),
310
+					$field_name
311
+				)
312
+			);
313
+		}
314
+		// if ( method_exists( $field_obj, 'set_timezone' )) {
315
+		if ($field_obj instanceof EE_Datetime_Field) {
316
+			$field_obj->set_timezone($this->_timezone);
317
+			$field_obj->set_date_format($this->_dt_frmt);
318
+			$field_obj->set_time_format($this->_tm_frmt);
319
+		}
320
+		$holder_of_value = $field_obj->prepare_for_set($field_value);
321
+		// should the value be null?
322
+		if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
323
+			$this->_fields[ $field_name ] = $field_obj->get_default_value();
324
+			/**
325
+			 * To save having to refactor all the models, if a default value is used for a
326
+			 * EE_Datetime_Field, and that value is not null nor is it a DateTime
327
+			 * object.  Then let's do a set again to ensure that it becomes a DateTime
328
+			 * object.
329
+			 *
330
+			 * @since 4.6.10+
331
+			 */
332
+			if (
333
+				$field_obj instanceof EE_Datetime_Field
334
+				&& $this->_fields[ $field_name ] !== null
335
+				&& ! $this->_fields[ $field_name ] instanceof DateTime
336
+			) {
337
+				empty($this->_fields[ $field_name ])
338
+					? $this->set($field_name, time())
339
+					: $this->set($field_name, $this->_fields[ $field_name ]);
340
+			}
341
+		} else {
342
+			$this->_fields[ $field_name ] = $holder_of_value;
343
+		}
344
+		// if we're not in the constructor...
345
+		// now check if what we set was a primary key
346
+		if (
347 347
 // note: props_n_values_provided_in_constructor is only set at the END of the constructor
348
-            $this->_props_n_values_provided_in_constructor
349
-            && $field_value
350
-            && $field_name === $model->primary_key_name()
351
-        ) {
352
-            // if so, we want all this object's fields to be filled either with
353
-            // what we've explicitly set on this model
354
-            // or what we have in the db
355
-            // echo "setting primary key!";
356
-            $fields_on_model = self::_get_model(get_class($this))->field_settings();
357
-            $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
358
-            foreach ($fields_on_model as $field_obj) {
359
-                if (
360
-                    ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
361
-                    && $field_obj->get_name() !== $field_name
362
-                ) {
363
-                    $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
364
-                }
365
-            }
366
-            // oh this model object has an ID? well make sure its in the entity mapper
367
-            $model->add_to_entity_map($this);
368
-        }
369
-        // let's unset any cache for this field_name from the $_cached_properties property.
370
-        $this->_clear_cached_property($field_name);
371
-    }
372
-
373
-
374
-    /**
375
-     * Overrides parent because parent expects old models.
376
-     * This also doesn't do any validation, and won't work for serialized arrays
377
-     *
378
-     * @param string $field_name
379
-     * @param mixed  $field_value_from_db
380
-     * @throws ReflectionException
381
-     * @throws InvalidArgumentException
382
-     * @throws InvalidInterfaceException
383
-     * @throws InvalidDataTypeException
384
-     * @throws EE_Error
385
-     */
386
-    public function set_from_db(string $field_name, $field_value_from_db)
387
-    {
388
-        $field_obj = $this->get_model()->field_settings_for($field_name);
389
-        if ($field_obj instanceof EE_Model_Field_Base) {
390
-            // you would think the DB has no NULLs for non-null label fields right? wrong!
391
-            // eg, a CPT model object could have an entry in the posts table, but no
392
-            // entry in the meta table. Meaning that all its columns in the meta table
393
-            // are null! yikes! so when we find one like that, use defaults for its meta columns
394
-            if ($field_value_from_db === null) {
395
-                if ($field_obj->is_nullable()) {
396
-                    // if the field allows nulls, then let it be null
397
-                    $field_value = null;
398
-                } else {
399
-                    $field_value = $field_obj->get_default_value();
400
-                }
401
-            } else {
402
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
403
-            }
404
-            $this->_fields[ $field_name ] = $field_value;
405
-            $this->_clear_cached_property($field_name);
406
-        }
407
-    }
408
-
409
-
410
-    /**
411
-     * Set custom select values for model.
412
-     *
413
-     * @param array $custom_select_values
414
-     */
415
-    public function setCustomSelectsValues(array $custom_select_values)
416
-    {
417
-        $this->custom_selection_results = $custom_select_values;
418
-    }
419
-
420
-
421
-    /**
422
-     * Returns the custom select value for the provided alias if its set.
423
-     * If not set, returns null.
424
-     *
425
-     * @param string $alias
426
-     * @return string|int|float|null
427
-     */
428
-    public function getCustomSelect($alias)
429
-    {
430
-        return isset($this->custom_selection_results[ $alias ])
431
-            ? $this->custom_selection_results[ $alias ]
432
-            : null;
433
-    }
434
-
435
-
436
-    /**
437
-     * This sets the field value on the db column if it exists for the given $column_name or
438
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
439
-     *
440
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
441
-     * @param string $field_name  Must be the exact column name.
442
-     * @param mixed  $field_value The value to set.
443
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
444
-     * @throws InvalidArgumentException
445
-     * @throws InvalidInterfaceException
446
-     * @throws InvalidDataTypeException
447
-     * @throws EE_Error
448
-     * @throws ReflectionException
449
-     */
450
-    public function set_field_or_extra_meta($field_name, $field_value)
451
-    {
452
-        if ($this->get_model()->has_field($field_name)) {
453
-            $this->set($field_name, $field_value);
454
-            return true;
455
-        }
456
-        // ensure this object is saved first so that extra meta can be properly related.
457
-        $this->save();
458
-        return $this->update_extra_meta($field_name, $field_value);
459
-    }
460
-
461
-
462
-    /**
463
-     * This retrieves the value of the db column set on this class or if that's not present
464
-     * it will attempt to retrieve from extra_meta if found.
465
-     * Example Usage:
466
-     * Via EE_Message child class:
467
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
468
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
469
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
470
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
471
-     * value for those extra fields dynamically via the EE_message object.
472
-     *
473
-     * @param  string $field_name expecting the fully qualified field name.
474
-     * @return mixed|null  value for the field if found.  null if not found.
475
-     * @throws ReflectionException
476
-     * @throws InvalidArgumentException
477
-     * @throws InvalidInterfaceException
478
-     * @throws InvalidDataTypeException
479
-     * @throws EE_Error
480
-     */
481
-    public function get_field_or_extra_meta($field_name)
482
-    {
483
-        if ($this->get_model()->has_field($field_name)) {
484
-            $column_value = $this->get($field_name);
485
-        } else {
486
-            // This isn't a column in the main table, let's see if it is in the extra meta.
487
-            $column_value = $this->get_extra_meta($field_name, true, null);
488
-        }
489
-        return $column_value;
490
-    }
491
-
492
-
493
-    /**
494
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
495
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
496
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
497
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
498
-     *
499
-     * @access public
500
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
501
-     * @return void
502
-     * @throws InvalidArgumentException
503
-     * @throws InvalidInterfaceException
504
-     * @throws InvalidDataTypeException
505
-     * @throws EE_Error
506
-     * @throws ReflectionException
507
-     */
508
-    public function set_timezone($timezone = '')
509
-    {
510
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
511
-        // make sure we clear all cached properties because they won't be relevant now
512
-        $this->_clear_cached_properties();
513
-        // make sure we update field settings and the date for all EE_Datetime_Fields
514
-        $model_fields = $this->get_model()->field_settings(false);
515
-        foreach ($model_fields as $field_name => $field_obj) {
516
-            if ($field_obj instanceof EE_Datetime_Field) {
517
-                $field_obj->set_timezone($this->_timezone);
518
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
519
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
520
-                }
521
-            }
522
-        }
523
-    }
524
-
525
-
526
-    /**
527
-     * This just returns whatever is set for the current timezone.
528
-     *
529
-     * @access public
530
-     * @return string timezone string
531
-     */
532
-    public function get_timezone()
533
-    {
534
-        return $this->_timezone;
535
-    }
536
-
537
-
538
-    /**
539
-     * This sets the internal date format to what is sent in to be used as the new default for the class
540
-     * internally instead of wp set date format options
541
-     *
542
-     * @param string|null $format should be a format recognizable by PHP date() functions.
543
-     * @since 4.6
544
-     */
545
-    public function set_date_format(?string $format = 'Y-m-d')
546
-    {
547
-        $format = $format ?: 'Y-m-d';
548
-        $this->_dt_frmt = new DateFormat($format);
549
-        // clear cached_properties because they won't be relevant now.
550
-        $this->_clear_cached_properties();
551
-    }
552
-
553
-
554
-    /**
555
-     * This sets the internal time format string to what is sent in to be used as the new default for the
556
-     * class internally instead of wp set time format options.
557
-     *
558
-     * @param string|null $format should be a format recognizable by PHP date() functions.
559
-     * @since 4.6
560
-     */
561
-    public function set_time_format(?string $format = 'H:i:s')
562
-    {
563
-        $format = $format ?: 'H:i:s';
564
-        $this->_tm_frmt = new TimeFormat($format);
565
-        // clear cached_properties because they won't be relevant now.
566
-        $this->_clear_cached_properties();
567
-    }
568
-
569
-
570
-    /**
571
-     * This returns the current internal set format for the date and time formats.
572
-     *
573
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
574
-     *                             where the first value is the date format and the second value is the time format.
575
-     * @return mixed string|array
576
-     */
577
-    public function get_format($full = true)
578
-    {
579
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
580
-    }
581
-
582
-
583
-    /**
584
-     * cache
585
-     * stores the passed model object on the current model object.
586
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
587
-     *
588
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
589
-     *                                       'Registration' associated with this model object
590
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
591
-     *                                       that could be a payment or a registration)
592
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
593
-     *                                       items which will be stored in an array on this object
594
-     * @throws ReflectionException
595
-     * @throws InvalidArgumentException
596
-     * @throws InvalidInterfaceException
597
-     * @throws InvalidDataTypeException
598
-     * @throws EE_Error
599
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
600
-     *                                       related thing, no array)
601
-     */
602
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
603
-    {
604
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
605
-        if (! $object_to_cache instanceof EE_Base_Class) {
606
-            return false;
607
-        }
608
-        // also get "how" the object is related, or throw an error
609
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
610
-            throw new EE_Error(
611
-                sprintf(
612
-                    esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
613
-                    $relationName,
614
-                    get_class($this)
615
-                )
616
-            );
617
-        }
618
-        // how many things are related ?
619
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
620
-            // if it's a "belongs to" relationship, then there's only one related model object
621
-            // eg, if this is a registration, there's only 1 attendee for it
622
-            // so for these model objects just set it to be cached
623
-            $this->_model_relations[ $relationName ] = $object_to_cache;
624
-            $return = true;
625
-        } else {
626
-            // otherwise, this is the "many" side of a one to many relationship,
627
-            // so we'll add the object to the array of related objects for that type.
628
-            // eg: if this is an event, there are many registrations for that event,
629
-            // so we cache the registrations in an array
630
-            if (! is_array($this->_model_relations[ $relationName ])) {
631
-                // if for some reason, the cached item is a model object,
632
-                // then stick that in the array, otherwise start with an empty array
633
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
634
-                                                           instanceof
635
-                                                           EE_Base_Class
636
-                    ? array($this->_model_relations[ $relationName ]) : array();
637
-            }
638
-            // first check for a cache_id which is normally empty
639
-            if (! empty($cache_id)) {
640
-                // if the cache_id exists, then it means we are purposely trying to cache this
641
-                // with a known key that can then be used to retrieve the object later on
642
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
643
-                $return = $cache_id;
644
-            } elseif ($object_to_cache->ID()) {
645
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
646
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
647
-                $return = $object_to_cache->ID();
648
-            } else {
649
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
650
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
651
-                // move the internal pointer to the end of the array
652
-                end($this->_model_relations[ $relationName ]);
653
-                // and grab the key so that we can return it
654
-                $return = key($this->_model_relations[ $relationName ]);
655
-            }
656
-        }
657
-        return $return;
658
-    }
659
-
660
-
661
-    /**
662
-     * For adding an item to the cached_properties property.
663
-     *
664
-     * @access protected
665
-     * @param string      $fieldname the property item the corresponding value is for.
666
-     * @param mixed       $value     The value we are caching.
667
-     * @param string|null $cache_type
668
-     * @return void
669
-     * @throws ReflectionException
670
-     * @throws InvalidArgumentException
671
-     * @throws InvalidInterfaceException
672
-     * @throws InvalidDataTypeException
673
-     * @throws EE_Error
674
-     */
675
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
676
-    {
677
-        // first make sure this property exists
678
-        $this->get_model()->field_settings_for($fieldname);
679
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
680
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
681
-    }
682
-
683
-
684
-    /**
685
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
686
-     * This also SETS the cache if we return the actual property!
687
-     *
688
-     * @param string $fieldname        the name of the property we're trying to retrieve
689
-     * @param bool   $pretty
690
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
691
-     *                                 (in cases where the same property may be used for different outputs
692
-     *                                 - i.e. datetime, money etc.)
693
-     *                                 It can also accept certain pre-defined "schema" strings
694
-     *                                 to define how to output the property.
695
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
696
-     * @return mixed                   whatever the value for the property is we're retrieving
697
-     * @throws ReflectionException
698
-     * @throws InvalidArgumentException
699
-     * @throws InvalidInterfaceException
700
-     * @throws InvalidDataTypeException
701
-     * @throws EE_Error
702
-     */
703
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
704
-    {
705
-        // verify the field exists
706
-        $model = $this->get_model();
707
-        $model->field_settings_for($fieldname);
708
-        $cache_type = $pretty ? 'pretty' : 'standard';
709
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
710
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
711
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
712
-        }
713
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
714
-        $this->_set_cached_property($fieldname, $value, $cache_type);
715
-        return $value;
716
-    }
717
-
718
-
719
-    /**
720
-     * If the cache didn't fetch the needed item, this fetches it.
721
-     *
722
-     * @param string $fieldname
723
-     * @param bool   $pretty
724
-     * @param string $extra_cache_ref
725
-     * @return mixed
726
-     * @throws InvalidArgumentException
727
-     * @throws InvalidInterfaceException
728
-     * @throws InvalidDataTypeException
729
-     * @throws EE_Error
730
-     * @throws ReflectionException
731
-     */
732
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
733
-    {
734
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
735
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
736
-        if ($field_obj instanceof EE_Datetime_Field) {
737
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
738
-        }
739
-        if (! isset($this->_fields[ $fieldname ])) {
740
-            $this->_fields[ $fieldname ] = null;
741
-        }
742
-        return $pretty
743
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
744
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
745
-    }
746
-
747
-
748
-    /**
749
-     * set timezone, formats, and output for EE_Datetime_Field objects
750
-     *
751
-     * @param EE_Datetime_Field $datetime_field
752
-     * @param bool              $pretty
753
-     * @param null              $date_or_time
754
-     * @return void
755
-     * @throws InvalidArgumentException
756
-     * @throws InvalidInterfaceException
757
-     * @throws InvalidDataTypeException
758
-     */
759
-    protected function _prepare_datetime_field(
760
-        EE_Datetime_Field $datetime_field,
761
-        $pretty = false,
762
-        $date_or_time = null
763
-    ) {
764
-        $datetime_field->set_timezone($this->_timezone);
765
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
766
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
767
-        // set the output returned
768
-        switch ($date_or_time) {
769
-            case 'D':
770
-                $datetime_field->set_date_time_output('date');
771
-                break;
772
-            case 'T':
773
-                $datetime_field->set_date_time_output('time');
774
-                break;
775
-            default:
776
-                $datetime_field->set_date_time_output();
777
-        }
778
-    }
779
-
780
-
781
-    /**
782
-     * This just takes care of clearing out the cached_properties
783
-     *
784
-     * @return void
785
-     */
786
-    protected function _clear_cached_properties()
787
-    {
788
-        $this->_cached_properties = array();
789
-    }
790
-
791
-
792
-    /**
793
-     * This just clears out ONE property if it exists in the cache
794
-     *
795
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
796
-     * @return void
797
-     */
798
-    protected function _clear_cached_property($property_name)
799
-    {
800
-        if (isset($this->_cached_properties[ $property_name ])) {
801
-            unset($this->_cached_properties[ $property_name ]);
802
-        }
803
-    }
804
-
805
-
806
-    /**
807
-     * Ensures that this related thing is a model object.
808
-     *
809
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
810
-     * @param string $model_name   name of the related thing, eg 'Attendee',
811
-     * @return EE_Base_Class
812
-     * @throws ReflectionException
813
-     * @throws InvalidArgumentException
814
-     * @throws InvalidInterfaceException
815
-     * @throws InvalidDataTypeException
816
-     * @throws EE_Error
817
-     */
818
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
819
-    {
820
-        $other_model_instance = self::_get_model_instance_with_name(
821
-            self::_get_model_classname($model_name),
822
-            $this->_timezone
823
-        );
824
-        return $other_model_instance->ensure_is_obj($object_or_id);
825
-    }
826
-
827
-
828
-    /**
829
-     * Forgets the cached model of the given relation Name. So the next time we request it,
830
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
831
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
832
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
833
-     *
834
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
835
-     *                                                     Eg 'Registration'
836
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
837
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
838
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
839
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
840
-     *                                                     this is HasMany or HABTM.
841
-     * @throws ReflectionException
842
-     * @throws InvalidArgumentException
843
-     * @throws InvalidInterfaceException
844
-     * @throws InvalidDataTypeException
845
-     * @throws EE_Error
846
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
847
-     *                                                     relation from all
848
-     */
849
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
850
-    {
851
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
852
-        $index_in_cache = '';
853
-        if (! $relationship_to_model) {
854
-            throw new EE_Error(
855
-                sprintf(
856
-                    esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
857
-                    $relationName,
858
-                    get_class($this)
859
-                )
860
-            );
861
-        }
862
-        if ($clear_all) {
863
-            $obj_removed = true;
864
-            $this->_model_relations[ $relationName ] = null;
865
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
866
-            $obj_removed = $this->_model_relations[ $relationName ];
867
-            $this->_model_relations[ $relationName ] = null;
868
-        } else {
869
-            if (
870
-                $object_to_remove_or_index_into_array instanceof EE_Base_Class
871
-                && $object_to_remove_or_index_into_array->ID()
872
-            ) {
873
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
874
-                if (
875
-                    is_array($this->_model_relations[ $relationName ])
876
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
877
-                ) {
878
-                    $index_found_at = null;
879
-                    // find this object in the array even though it has a different key
880
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
881
-                        /** @noinspection TypeUnsafeComparisonInspection */
882
-                        if (
883
-                            $obj instanceof EE_Base_Class
884
-                            && (
885
-                                $obj == $object_to_remove_or_index_into_array
886
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
887
-                            )
888
-                        ) {
889
-                            $index_found_at = $index;
890
-                            break;
891
-                        }
892
-                    }
893
-                    if ($index_found_at) {
894
-                        $index_in_cache = $index_found_at;
895
-                    } else {
896
-                        // it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
897
-                        // if it wasn't in it to begin with. So we're done
898
-                        return $object_to_remove_or_index_into_array;
899
-                    }
900
-                }
901
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
902
-                // so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
903
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
904
-                    /** @noinspection TypeUnsafeComparisonInspection */
905
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
906
-                        $index_in_cache = $index;
907
-                    }
908
-                }
909
-            } else {
910
-                $index_in_cache = $object_to_remove_or_index_into_array;
911
-            }
912
-            // supposedly we've found it. But it could just be that the client code
913
-            // provided a bad index/object
914
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
915
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
916
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
917
-            } else {
918
-                // that thing was never cached anyways.
919
-                $obj_removed = null;
920
-            }
921
-        }
922
-        return $obj_removed;
923
-    }
924
-
925
-
926
-    /**
927
-     * update_cache_after_object_save
928
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
929
-     * obtained after being saved to the db
930
-     *
931
-     * @param string        $relationName       - the type of object that is cached
932
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
933
-     * @param string        $current_cache_id   - the ID that was used when originally caching the object
934
-     * @return boolean TRUE on success, FALSE on fail
935
-     * @throws ReflectionException
936
-     * @throws InvalidArgumentException
937
-     * @throws InvalidInterfaceException
938
-     * @throws InvalidDataTypeException
939
-     * @throws EE_Error
940
-     */
941
-    public function update_cache_after_object_save(
942
-        $relationName,
943
-        EE_Base_Class $newly_saved_object,
944
-        $current_cache_id = ''
945
-    ) {
946
-        // verify that incoming object is of the correct type
947
-        $obj_class = 'EE_' . $relationName;
948
-        if ($newly_saved_object instanceof $obj_class) {
949
-            /* @type EE_Base_Class $newly_saved_object */
950
-            // now get the type of relation
951
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
952
-            // if this is a 1:1 relationship
953
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
954
-                // then just replace the cached object with the newly saved object
955
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
956
-                return true;
957
-                // or if it's some kind of sordid feral polyamorous relationship...
958
-            }
959
-            if (
960
-                is_array($this->_model_relations[ $relationName ])
961
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
962
-            ) {
963
-                // then remove the current cached item
964
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
965
-                // and cache the newly saved object using it's new ID
966
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
967
-                return true;
968
-            }
969
-        }
970
-        return false;
971
-    }
972
-
973
-
974
-    /**
975
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
976
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
977
-     *
978
-     * @param string $relationName
979
-     * @return EE_Base_Class
980
-     */
981
-    public function get_one_from_cache($relationName)
982
-    {
983
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
984
-            ? $this->_model_relations[ $relationName ]
985
-            : null;
986
-        if (is_array($cached_array_or_object)) {
987
-            return array_shift($cached_array_or_object);
988
-        }
989
-        return $cached_array_or_object;
990
-    }
991
-
992
-
993
-    /**
994
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
995
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
996
-     *
997
-     * @param string $relationName
998
-     * @throws ReflectionException
999
-     * @throws InvalidArgumentException
1000
-     * @throws InvalidInterfaceException
1001
-     * @throws InvalidDataTypeException
1002
-     * @throws EE_Error
1003
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
1004
-     */
1005
-    public function get_all_from_cache($relationName)
1006
-    {
1007
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
1008
-        // if the result is not an array, but exists, make it an array
1009
-        $objects = is_array($objects) ? $objects : array($objects);
1010
-        // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
1011
-        // basically, if this model object was stored in the session, and these cached model objects
1012
-        // already have IDs, let's make sure they're in their model's entity mapper
1013
-        // otherwise we will have duplicates next time we call
1014
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
1015
-        $model = EE_Registry::instance()->load_model($relationName);
1016
-        foreach ($objects as $model_object) {
1017
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
1018
-                // ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
1019
-                if ($model_object->ID()) {
1020
-                    $model->add_to_entity_map($model_object);
1021
-                }
1022
-            } else {
1023
-                throw new EE_Error(
1024
-                    sprintf(
1025
-                        esc_html__(
1026
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
1027
-                            'event_espresso'
1028
-                        ),
1029
-                        $relationName,
1030
-                        gettype($model_object)
1031
-                    )
1032
-                );
1033
-            }
1034
-        }
1035
-        return $objects;
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1041
-     * matching the given query conditions.
1042
-     *
1043
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1044
-     * @param int   $limit              How many objects to return.
1045
-     * @param array $query_params       Any additional conditions on the query.
1046
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1047
-     *                                  you can indicate just the columns you want returned
1048
-     * @return array|EE_Base_Class[]
1049
-     * @throws ReflectionException
1050
-     * @throws InvalidArgumentException
1051
-     * @throws InvalidInterfaceException
1052
-     * @throws InvalidDataTypeException
1053
-     * @throws EE_Error
1054
-     */
1055
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1056
-    {
1057
-        $model = $this->get_model();
1058
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1059
-            ? $model->get_primary_key_field()->get_name()
1060
-            : $field_to_order_by;
1061
-        $current_value = ! empty($field) ? $this->get($field) : null;
1062
-        if (empty($field) || empty($current_value)) {
1063
-            return array();
1064
-        }
1065
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1066
-    }
1067
-
1068
-
1069
-    /**
1070
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1071
-     * matching the given query conditions.
1072
-     *
1073
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1074
-     * @param int   $limit              How many objects to return.
1075
-     * @param array $query_params       Any additional conditions on the query.
1076
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1077
-     *                                  you can indicate just the columns you want returned
1078
-     * @return array|EE_Base_Class[]
1079
-     * @throws ReflectionException
1080
-     * @throws InvalidArgumentException
1081
-     * @throws InvalidInterfaceException
1082
-     * @throws InvalidDataTypeException
1083
-     * @throws EE_Error
1084
-     */
1085
-    public function previous_x(
1086
-        $field_to_order_by = null,
1087
-        $limit = 1,
1088
-        $query_params = array(),
1089
-        $columns_to_select = null
1090
-    ) {
1091
-        $model = $this->get_model();
1092
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1093
-            ? $model->get_primary_key_field()->get_name()
1094
-            : $field_to_order_by;
1095
-        $current_value = ! empty($field) ? $this->get($field) : null;
1096
-        if (empty($field) || empty($current_value)) {
1097
-            return array();
1098
-        }
1099
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1100
-    }
1101
-
1102
-
1103
-    /**
1104
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1105
-     * matching the given query conditions.
1106
-     *
1107
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1108
-     * @param array $query_params       Any additional conditions on the query.
1109
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1110
-     *                                  you can indicate just the columns you want returned
1111
-     * @return array|EE_Base_Class
1112
-     * @throws ReflectionException
1113
-     * @throws InvalidArgumentException
1114
-     * @throws InvalidInterfaceException
1115
-     * @throws InvalidDataTypeException
1116
-     * @throws EE_Error
1117
-     */
1118
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1119
-    {
1120
-        $model = $this->get_model();
1121
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1122
-            ? $model->get_primary_key_field()->get_name()
1123
-            : $field_to_order_by;
1124
-        $current_value = ! empty($field) ? $this->get($field) : null;
1125
-        if (empty($field) || empty($current_value)) {
1126
-            return array();
1127
-        }
1128
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1129
-    }
1130
-
1131
-
1132
-    /**
1133
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1134
-     * matching the given query conditions.
1135
-     *
1136
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1137
-     * @param array $query_params       Any additional conditions on the query.
1138
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1139
-     *                                  you can indicate just the column you want returned
1140
-     * @return array|EE_Base_Class
1141
-     * @throws ReflectionException
1142
-     * @throws InvalidArgumentException
1143
-     * @throws InvalidInterfaceException
1144
-     * @throws InvalidDataTypeException
1145
-     * @throws EE_Error
1146
-     */
1147
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1148
-    {
1149
-        $model = $this->get_model();
1150
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1151
-            ? $model->get_primary_key_field()->get_name()
1152
-            : $field_to_order_by;
1153
-        $current_value = ! empty($field) ? $this->get($field) : null;
1154
-        if (empty($field) || empty($current_value)) {
1155
-            return array();
1156
-        }
1157
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1158
-    }
1159
-
1160
-
1161
-    /**
1162
-     * verifies that the specified field is of the correct type
1163
-     *
1164
-     * @param string $field_name
1165
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1166
-     *                                (in cases where the same property may be used for different outputs
1167
-     *                                - i.e. datetime, money etc.)
1168
-     * @return mixed
1169
-     * @throws ReflectionException
1170
-     * @throws InvalidArgumentException
1171
-     * @throws InvalidInterfaceException
1172
-     * @throws InvalidDataTypeException
1173
-     * @throws EE_Error
1174
-     */
1175
-    public function get($field_name, $extra_cache_ref = null)
1176
-    {
1177
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * This method simply returns the RAW unprocessed value for the given property in this class
1183
-     *
1184
-     * @param  string $field_name A valid fieldname
1185
-     * @return mixed              Whatever the raw value stored on the property is.
1186
-     * @throws ReflectionException
1187
-     * @throws InvalidArgumentException
1188
-     * @throws InvalidInterfaceException
1189
-     * @throws InvalidDataTypeException
1190
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1191
-     */
1192
-    public function get_raw($field_name)
1193
-    {
1194
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1195
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
-            ? $this->_fields[ $field_name ]->format('U')
1197
-            : $this->_fields[ $field_name ];
1198
-    }
1199
-
1200
-
1201
-    /**
1202
-     * This is used to return the internal DateTime object used for a field that is a
1203
-     * EE_Datetime_Field.
1204
-     *
1205
-     * @param string $field_name               The field name retrieving the DateTime object.
1206
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1207
-     * @throws EE_Error an error is set and false returned.  If the field IS an
1208
-     *                                         EE_Datetime_Field and but the field value is null, then
1209
-     *                                         just null is returned (because that indicates that likely
1210
-     *                                         this field is nullable).
1211
-     * @throws InvalidArgumentException
1212
-     * @throws InvalidDataTypeException
1213
-     * @throws InvalidInterfaceException
1214
-     * @throws ReflectionException
1215
-     */
1216
-    public function get_DateTime_object($field_name)
1217
-    {
1218
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1219
-        if (! $field_settings instanceof EE_Datetime_Field) {
1220
-            EE_Error::add_error(
1221
-                sprintf(
1222
-                    esc_html__(
1223
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1224
-                        'event_espresso'
1225
-                    ),
1226
-                    $field_name
1227
-                ),
1228
-                __FILE__,
1229
-                __FUNCTION__,
1230
-                __LINE__
1231
-            );
1232
-            return false;
1233
-        }
1234
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
-            ? clone $this->_fields[ $field_name ]
1236
-            : null;
1237
-    }
1238
-
1239
-
1240
-    /**
1241
-     * To be used in template to immediately echo out the value, and format it for output.
1242
-     * Eg, should call stripslashes and whatnot before echoing
1243
-     *
1244
-     * @param string $field_name      the name of the field as it appears in the DB
1245
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1246
-     *                                (in cases where the same property may be used for different outputs
1247
-     *                                - i.e. datetime, money etc.)
1248
-     * @return void
1249
-     * @throws ReflectionException
1250
-     * @throws InvalidArgumentException
1251
-     * @throws InvalidInterfaceException
1252
-     * @throws InvalidDataTypeException
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function e($field_name, $extra_cache_ref = null)
1256
-    {
1257
-        echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1258
-    }
1259
-
1260
-
1261
-    /**
1262
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1263
-     * can be easily used as the value of form input.
1264
-     *
1265
-     * @param string $field_name
1266
-     * @return void
1267
-     * @throws ReflectionException
1268
-     * @throws InvalidArgumentException
1269
-     * @throws InvalidInterfaceException
1270
-     * @throws InvalidDataTypeException
1271
-     * @throws EE_Error
1272
-     */
1273
-    public function f($field_name)
1274
-    {
1275
-        $this->e($field_name, 'form_input');
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * Same as `f()` but just returns the value instead of echoing it
1281
-     *
1282
-     * @param string $field_name
1283
-     * @return string
1284
-     * @throws ReflectionException
1285
-     * @throws InvalidArgumentException
1286
-     * @throws InvalidInterfaceException
1287
-     * @throws InvalidDataTypeException
1288
-     * @throws EE_Error
1289
-     */
1290
-    public function get_f($field_name)
1291
-    {
1292
-        return (string) $this->get_pretty($field_name, 'form_input');
1293
-    }
1294
-
1295
-
1296
-    /**
1297
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1298
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1299
-     * to see what options are available.
1300
-     *
1301
-     * @param string $field_name
1302
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1303
-     *                                (in cases where the same property may be used for different outputs
1304
-     *                                - i.e. datetime, money etc.)
1305
-     * @return mixed
1306
-     * @throws ReflectionException
1307
-     * @throws InvalidArgumentException
1308
-     * @throws InvalidInterfaceException
1309
-     * @throws InvalidDataTypeException
1310
-     * @throws EE_Error
1311
-     */
1312
-    public function get_pretty($field_name, $extra_cache_ref = null)
1313
-    {
1314
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1315
-    }
1316
-
1317
-
1318
-    /**
1319
-     * This simply returns the datetime for the given field name
1320
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1321
-     * (and the equivalent e_date, e_time, e_datetime).
1322
-     *
1323
-     * @access   protected
1324
-     * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1325
-     * @param string|null $date_format  valid datetime format used for date
1326
-     *                                  (if '' then we just use the default on the field,
1327
-     *                                  if NULL we use the last-used format)
1328
-     * @param string|null $time_format  Same as above except this is for time format
1329
-     * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1330
-     * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1331
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1332
-     *                                  if field is not a valid dtt field, or void if echoing
1333
-     * @throws EE_Error
1334
-     * @throws ReflectionException
1335
-     */
1336
-    protected function _get_datetime(
1337
-        string $field_name,
1338
-        ?string $date_format = '',
1339
-        ?string $time_format = '',
1340
-        ?string $date_or_time = '',
1341
-        ?bool $echo = false
1342
-    ) {
1343
-        // clear cached property
1344
-        $this->_clear_cached_property($field_name);
1345
-        // reset format properties because they are used in get()
1346
-        $this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1347
-        $this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1348
-        if ($echo) {
1349
-            $this->e($field_name, $date_or_time);
1350
-            return '';
1351
-        }
1352
-        return $this->get($field_name, $date_or_time);
1353
-    }
1354
-
1355
-
1356
-    /**
1357
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1358
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1359
-     * other echoes the pretty value for dtt)
1360
-     *
1361
-     * @param  string $field_name name of model object datetime field holding the value
1362
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1363
-     * @return string            datetime value formatted
1364
-     * @throws ReflectionException
1365
-     * @throws InvalidArgumentException
1366
-     * @throws InvalidInterfaceException
1367
-     * @throws InvalidDataTypeException
1368
-     * @throws EE_Error
1369
-     */
1370
-    public function get_date($field_name, $format = '')
1371
-    {
1372
-        return $this->_get_datetime($field_name, $format, null, 'D');
1373
-    }
1374
-
1375
-
1376
-    /**
1377
-     * @param        $field_name
1378
-     * @param string $format
1379
-     * @throws ReflectionException
1380
-     * @throws InvalidArgumentException
1381
-     * @throws InvalidInterfaceException
1382
-     * @throws InvalidDataTypeException
1383
-     * @throws EE_Error
1384
-     */
1385
-    public function e_date($field_name, $format = '')
1386
-    {
1387
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1388
-    }
1389
-
1390
-
1391
-    /**
1392
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1393
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1394
-     * other echoes the pretty value for dtt)
1395
-     *
1396
-     * @param  string $field_name name of model object datetime field holding the value
1397
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1398
-     * @return string             datetime value formatted
1399
-     * @throws ReflectionException
1400
-     * @throws InvalidArgumentException
1401
-     * @throws InvalidInterfaceException
1402
-     * @throws InvalidDataTypeException
1403
-     * @throws EE_Error
1404
-     */
1405
-    public function get_time($field_name, $format = '')
1406
-    {
1407
-        return $this->_get_datetime($field_name, null, $format, 'T');
1408
-    }
1409
-
1410
-
1411
-    /**
1412
-     * @param        $field_name
1413
-     * @param string $format
1414
-     * @throws ReflectionException
1415
-     * @throws InvalidArgumentException
1416
-     * @throws InvalidInterfaceException
1417
-     * @throws InvalidDataTypeException
1418
-     * @throws EE_Error
1419
-     */
1420
-    public function e_time($field_name, $format = '')
1421
-    {
1422
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1423
-    }
1424
-
1425
-
1426
-    /**
1427
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1428
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1429
-     * other echoes the pretty value for dtt)
1430
-     *
1431
-     * @param  string $field_name name of model object datetime field holding the value
1432
-     * @param  string $date_format    format for the date returned (if NULL we use default in dt_frmt property)
1433
-     * @param  string $time_format    format for the time returned (if NULL we use default in tm_frmt property)
1434
-     * @return string             datetime value formatted
1435
-     * @throws ReflectionException
1436
-     * @throws InvalidArgumentException
1437
-     * @throws InvalidInterfaceException
1438
-     * @throws InvalidDataTypeException
1439
-     * @throws EE_Error
1440
-     */
1441
-    public function get_datetime($field_name, $date_format = '', $time_format = '')
1442
-    {
1443
-        return $this->_get_datetime($field_name, $date_format, $time_format);
1444
-    }
1445
-
1446
-
1447
-    /**
1448
-     * @param string $field_name
1449
-     * @param string $date_format
1450
-     * @param string $time_format
1451
-     * @throws ReflectionException
1452
-     * @throws InvalidArgumentException
1453
-     * @throws InvalidInterfaceException
1454
-     * @throws InvalidDataTypeException
1455
-     * @throws EE_Error
1456
-     */
1457
-    public function e_datetime($field_name, $date_format = '', $time_format = '')
1458
-    {
1459
-        $this->_get_datetime($field_name, $date_format, $time_format, null, true);
1460
-    }
1461
-
1462
-
1463
-    /**
1464
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1465
-     *
1466
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1467
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1468
-     *                           on the object will be used.
1469
-     * @return string Date and time string in set locale or false if no field exists for the given
1470
-     * @throws ReflectionException
1471
-     * @throws InvalidArgumentException
1472
-     * @throws InvalidInterfaceException
1473
-     * @throws InvalidDataTypeException
1474
-     * @throws EE_Error
1475
-     *                           field name.
1476
-     */
1477
-    public function get_i18n_datetime($field_name, $format = '')
1478
-    {
1479
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1480
-        return date_i18n(
1481
-            $format,
1482
-            EEH_DTT_Helper::get_timestamp_with_offset(
1483
-                $this->get_raw($field_name),
1484
-                $this->_timezone
1485
-            )
1486
-        );
1487
-    }
1488
-
1489
-
1490
-    /**
1491
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1492
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1493
-     * thrown.
1494
-     *
1495
-     * @param  string $field_name The field name being checked
1496
-     * @throws ReflectionException
1497
-     * @throws InvalidArgumentException
1498
-     * @throws InvalidInterfaceException
1499
-     * @throws InvalidDataTypeException
1500
-     * @throws EE_Error
1501
-     * @return EE_Datetime_Field
1502
-     */
1503
-    protected function _get_dtt_field_settings($field_name)
1504
-    {
1505
-        $field = $this->get_model()->field_settings_for($field_name);
1506
-        // check if field is dtt
1507
-        if ($field instanceof EE_Datetime_Field) {
1508
-            return $field;
1509
-        }
1510
-        throw new EE_Error(
1511
-            sprintf(
1512
-                esc_html__(
1513
-                    'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1514
-                    'event_espresso'
1515
-                ),
1516
-                $field_name,
1517
-                self::_get_model_classname(get_class($this))
1518
-            )
1519
-        );
1520
-    }
1521
-
1522
-
1523
-
1524
-
1525
-    /**
1526
-     * NOTE ABOUT BELOW:
1527
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1528
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1529
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1530
-     * method and make sure you send the entire datetime value for setting.
1531
-     */
1532
-    /**
1533
-     * sets the time on a datetime property
1534
-     *
1535
-     * @access protected
1536
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1537
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1538
-     * @throws ReflectionException
1539
-     * @throws InvalidArgumentException
1540
-     * @throws InvalidInterfaceException
1541
-     * @throws InvalidDataTypeException
1542
-     * @throws EE_Error
1543
-     */
1544
-    protected function _set_time_for($time, $fieldname)
1545
-    {
1546
-        $this->_set_date_time('T', $time, $fieldname);
1547
-    }
1548
-
1549
-
1550
-    /**
1551
-     * sets the date on a datetime property
1552
-     *
1553
-     * @access protected
1554
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1555
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1556
-     * @throws ReflectionException
1557
-     * @throws InvalidArgumentException
1558
-     * @throws InvalidInterfaceException
1559
-     * @throws InvalidDataTypeException
1560
-     * @throws EE_Error
1561
-     */
1562
-    protected function _set_date_for($date, $fieldname)
1563
-    {
1564
-        $this->_set_date_time('D', $date, $fieldname);
1565
-    }
1566
-
1567
-
1568
-    /**
1569
-     * This takes care of setting a date or time independently on a given model object property. This method also
1570
-     * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1571
-     *
1572
-     * @access protected
1573
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1574
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1575
-     * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1576
-     *                                        EE_Datetime_Field property)
1577
-     * @throws ReflectionException
1578
-     * @throws InvalidArgumentException
1579
-     * @throws InvalidInterfaceException
1580
-     * @throws InvalidDataTypeException
1581
-     * @throws EE_Error
1582
-     */
1583
-    protected function _set_date_time(string $what, $datetime_value, string $field_name)
1584
-    {
1585
-        $field = $this->_get_dtt_field_settings($field_name);
1586
-        $field->set_timezone($this->_timezone);
1587
-        $field->set_date_format($this->_dt_frmt);
1588
-        $field->set_time_format($this->_tm_frmt);
1589
-        switch ($what) {
1590
-            case 'T':
1591
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1592
-                    $datetime_value,
1593
-                    $this->_fields[ $field_name ]
1594
-                );
1595
-                $this->_has_changes = true;
1596
-                break;
1597
-            case 'D':
1598
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1599
-                    $datetime_value,
1600
-                    $this->_fields[ $field_name ]
1601
-                );
1602
-                $this->_has_changes = true;
1603
-                break;
1604
-            case 'B':
1605
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1606
-                $this->_has_changes = true;
1607
-                break;
1608
-        }
1609
-        $this->_clear_cached_property($field_name);
1610
-    }
1611
-
1612
-
1613
-    /**
1614
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1615
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1616
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1617
-     * that could lead to some unexpected results!
1618
-     *
1619
-     * @access public
1620
-     * @param string $field_name               This is the name of the field on the object that contains the date/time
1621
-     *                                         value being returned.
1622
-     * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1623
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1624
-     * @param string $prepend                  You can include something to prepend on the timestamp
1625
-     * @param string $append                   You can include something to append on the timestamp
1626
-     * @throws ReflectionException
1627
-     * @throws InvalidArgumentException
1628
-     * @throws InvalidInterfaceException
1629
-     * @throws InvalidDataTypeException
1630
-     * @throws EE_Error
1631
-     * @return string timestamp
1632
-     */
1633
-    public function display_in_my_timezone(
1634
-        $field_name,
1635
-        $callback = 'get_datetime',
1636
-        $args = null,
1637
-        $prepend = '',
1638
-        $append = ''
1639
-    ) {
1640
-        $timezone = EEH_DTT_Helper::get_timezone();
1641
-        if ($timezone === $this->_timezone) {
1642
-            return '';
1643
-        }
1644
-        $original_timezone = $this->_timezone;
1645
-        $this->set_timezone($timezone);
1646
-        $fn = (array) $field_name;
1647
-        $args = array_merge($fn, (array) $args);
1648
-        if (! method_exists($this, $callback)) {
1649
-            throw new EE_Error(
1650
-                sprintf(
1651
-                    esc_html__(
1652
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1653
-                        'event_espresso'
1654
-                    ),
1655
-                    $callback
1656
-                )
1657
-            );
1658
-        }
1659
-        $args = (array) $args;
1660
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1661
-        $this->set_timezone($original_timezone);
1662
-        return $return;
1663
-    }
1664
-
1665
-
1666
-    /**
1667
-     * Deletes this model object.
1668
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1669
-     * override
1670
-     * `EE_Base_Class::_delete` NOT this class.
1671
-     *
1672
-     * @return boolean | int
1673
-     * @throws ReflectionException
1674
-     * @throws InvalidArgumentException
1675
-     * @throws InvalidInterfaceException
1676
-     * @throws InvalidDataTypeException
1677
-     * @throws EE_Error
1678
-     */
1679
-    public function delete()
1680
-    {
1681
-        /**
1682
-         * Called just before the `EE_Base_Class::_delete` method call.
1683
-         * Note:
1684
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1685
-         * should be aware that `_delete` may not always result in a permanent delete.
1686
-         * For example, `EE_Soft_Delete_Base_Class::_delete`
1687
-         * soft deletes (trash) the object and does not permanently delete it.
1688
-         *
1689
-         * @param EE_Base_Class $model_object about to be 'deleted'
1690
-         */
1691
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1692
-        $result = $this->_delete();
1693
-        /**
1694
-         * Called just after the `EE_Base_Class::_delete` method call.
1695
-         * Note:
1696
-         * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1697
-         * should be aware that `_delete` may not always result in a permanent delete.
1698
-         * For example `EE_Soft_Base_Class::_delete`
1699
-         * soft deletes (trash) the object and does not permanently delete it.
1700
-         *
1701
-         * @param EE_Base_Class $model_object that was just 'deleted'
1702
-         * @param boolean       $result
1703
-         */
1704
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1705
-        return $result;
1706
-    }
1707
-
1708
-
1709
-    /**
1710
-     * Calls the specific delete method for the instantiated class.
1711
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1712
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1713
-     * `EE_Base_Class::delete`
1714
-     *
1715
-     * @return bool|int
1716
-     * @throws ReflectionException
1717
-     * @throws InvalidArgumentException
1718
-     * @throws InvalidInterfaceException
1719
-     * @throws InvalidDataTypeException
1720
-     * @throws EE_Error
1721
-     */
1722
-    protected function _delete()
1723
-    {
1724
-        return $this->delete_permanently();
1725
-    }
1726
-
1727
-
1728
-    /**
1729
-     * Deletes this model object permanently from db
1730
-     * (but keep in mind related models may block the delete and return an error)
1731
-     *
1732
-     * @return bool | int
1733
-     * @throws ReflectionException
1734
-     * @throws InvalidArgumentException
1735
-     * @throws InvalidInterfaceException
1736
-     * @throws InvalidDataTypeException
1737
-     * @throws EE_Error
1738
-     */
1739
-    public function delete_permanently()
1740
-    {
1741
-        /**
1742
-         * Called just before HARD deleting a model object
1743
-         *
1744
-         * @param EE_Base_Class $model_object about to be 'deleted'
1745
-         */
1746
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1747
-        $model = $this->get_model();
1748
-        $result = $model->delete_permanently_by_ID($this->ID());
1749
-        $this->refresh_cache_of_related_objects();
1750
-        /**
1751
-         * Called just after HARD deleting a model object
1752
-         *
1753
-         * @param EE_Base_Class $model_object that was just 'deleted'
1754
-         * @param boolean       $result
1755
-         */
1756
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1757
-        return $result;
1758
-    }
1759
-
1760
-
1761
-    /**
1762
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1763
-     * related model objects
1764
-     *
1765
-     * @throws ReflectionException
1766
-     * @throws InvalidArgumentException
1767
-     * @throws InvalidInterfaceException
1768
-     * @throws InvalidDataTypeException
1769
-     * @throws EE_Error
1770
-     */
1771
-    public function refresh_cache_of_related_objects()
1772
-    {
1773
-        $model = $this->get_model();
1774
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1775
-            if (! empty($this->_model_relations[ $relation_name ])) {
1776
-                $related_objects = $this->_model_relations[ $relation_name ];
1777
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1778
-                    // this relation only stores a single model object, not an array
1779
-                    // but let's make it consistent
1780
-                    $related_objects = array($related_objects);
1781
-                }
1782
-                foreach ($related_objects as $related_object) {
1783
-                    // only refresh their cache if they're in memory
1784
-                    if ($related_object instanceof EE_Base_Class) {
1785
-                        $related_object->clear_cache(
1786
-                            $model->get_this_model_name(),
1787
-                            $this
1788
-                        );
1789
-                    }
1790
-                }
1791
-            }
1792
-        }
1793
-    }
1794
-
1795
-
1796
-    /**
1797
-     *        Saves this object to the database. An array may be supplied to set some values on this
1798
-     * object just before saving.
1799
-     *
1800
-     * @access public
1801
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1802
-     *                                 if provided during the save() method (often client code will change the fields'
1803
-     *                                 values before calling save)
1804
-     * @return bool|int|string         1 on a successful update
1805
-     *                                 the ID of the new entry on insert
1806
-     *                                 0 on failure or if the model object isn't allowed to persist
1807
-     *                                 (as determined by EE_Base_Class::allow_persist())
1808
-     * @throws InvalidInterfaceException
1809
-     * @throws InvalidDataTypeException
1810
-     * @throws EE_Error
1811
-     * @throws InvalidArgumentException
1812
-     * @throws ReflectionException
1813
-     * @throws ReflectionException
1814
-     * @throws ReflectionException
1815
-     */
1816
-    public function save($set_cols_n_values = array())
1817
-    {
1818
-        $model = $this->get_model();
1819
-        /**
1820
-         * Filters the fields we're about to save on the model object
1821
-         *
1822
-         * @param array         $set_cols_n_values
1823
-         * @param EE_Base_Class $model_object
1824
-         */
1825
-        $set_cols_n_values = (array) apply_filters(
1826
-            'FHEE__EE_Base_Class__save__set_cols_n_values',
1827
-            $set_cols_n_values,
1828
-            $this
1829
-        );
1830
-        // set attributes as provided in $set_cols_n_values
1831
-        foreach ($set_cols_n_values as $column => $value) {
1832
-            $this->set($column, $value);
1833
-        }
1834
-        // no changes ? then don't do anything
1835
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1836
-            return 0;
1837
-        }
1838
-        /**
1839
-         * Saving a model object.
1840
-         * Before we perform a save, this action is fired.
1841
-         *
1842
-         * @param EE_Base_Class $model_object the model object about to be saved.
1843
-         */
1844
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1845
-        if (! $this->allow_persist()) {
1846
-            return 0;
1847
-        }
1848
-        // now get current attribute values
1849
-        $save_cols_n_values = $this->_fields;
1850
-        // if the object already has an ID, update it. Otherwise, insert it
1851
-        // also: change the assumption about values passed to the model NOT being prepare dby the model object.
1852
-        // They have been
1853
-        $old_assumption_concerning_value_preparation = $model
1854
-            ->get_assumption_concerning_values_already_prepared_by_model_object();
1855
-        $model->assume_values_already_prepared_by_model_object(true);
1856
-        // does this model have an autoincrement PK?
1857
-        if ($model->has_primary_key_field()) {
1858
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1859
-                // ok check if it's set, if so: update; if not, insert
1860
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1861
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1862
-                } else {
1863
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1864
-                    $results = $model->insert($save_cols_n_values);
1865
-                    if ($results) {
1866
-                        // if successful, set the primary key
1867
-                        // but don't use the normal SET method, because it will check if
1868
-                        // an item with the same ID exists in the mapper & db, then
1869
-                        // will find it in the db (because we just added it) and THAT object
1870
-                        // will get added to the mapper before we can add this one!
1871
-                        // but if we just avoid using the SET method, all that headache can be avoided
1872
-                        $pk_field_name = $model->primary_key_name();
1873
-                        $this->_fields[ $pk_field_name ] = $results;
1874
-                        $this->_clear_cached_property($pk_field_name);
1875
-                        $model->add_to_entity_map($this);
1876
-                        $this->_update_cached_related_model_objs_fks();
1877
-                    }
1878
-                }
1879
-            } else {// PK is NOT auto-increment
1880
-                // so check if one like it already exists in the db
1881
-                if ($model->exists_by_ID($this->ID())) {
1882
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1883
-                        throw new EE_Error(
1884
-                            sprintf(
1885
-                                esc_html__(
1886
-                                    'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1887
-                                    'event_espresso'
1888
-                                ),
1889
-                                get_class($this),
1890
-                                get_class($model) . '::instance()->add_to_entity_map()',
1891
-                                get_class($model) . '::instance()->get_one_by_ID()',
1892
-                                '<br />'
1893
-                            )
1894
-                        );
1895
-                    }
1896
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1897
-                } else {
1898
-                    $results = $model->insert($save_cols_n_values);
1899
-                    $this->_update_cached_related_model_objs_fks();
1900
-                }
1901
-            }
1902
-        } else {// there is NO primary key
1903
-            $already_in_db = false;
1904
-            foreach ($model->unique_indexes() as $index) {
1905
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1906
-                if ($model->exists(array($uniqueness_where_params))) {
1907
-                    $already_in_db = true;
1908
-                }
1909
-            }
1910
-            if ($already_in_db) {
1911
-                $combined_pk_fields_n_values = array_intersect_key(
1912
-                    $save_cols_n_values,
1913
-                    $model->get_combined_primary_key_fields()
1914
-                );
1915
-                $results = $model->update(
1916
-                    $save_cols_n_values,
1917
-                    $combined_pk_fields_n_values
1918
-                );
1919
-            } else {
1920
-                $results = $model->insert($save_cols_n_values);
1921
-            }
1922
-        }
1923
-        // restore the old assumption about values being prepared by the model object
1924
-        $model->assume_values_already_prepared_by_model_object(
1925
-            $old_assumption_concerning_value_preparation
1926
-        );
1927
-        /**
1928
-         * After saving the model object this action is called
1929
-         *
1930
-         * @param EE_Base_Class $model_object which was just saved
1931
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1932
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1933
-         */
1934
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1935
-        $this->_has_changes = false;
1936
-        return $results;
1937
-    }
1938
-
1939
-
1940
-    /**
1941
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1942
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1943
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1944
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1945
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1946
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1947
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1948
-     *
1949
-     * @return void
1950
-     * @throws ReflectionException
1951
-     * @throws InvalidArgumentException
1952
-     * @throws InvalidInterfaceException
1953
-     * @throws InvalidDataTypeException
1954
-     * @throws EE_Error
1955
-     */
1956
-    protected function _update_cached_related_model_objs_fks()
1957
-    {
1958
-        $model = $this->get_model();
1959
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1960
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1961
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1962
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1963
-                        $model->get_this_model_name()
1964
-                    );
1965
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1966
-                    if ($related_model_obj_in_cache->ID()) {
1967
-                        $related_model_obj_in_cache->save();
1968
-                    }
1969
-                }
1970
-            }
1971
-        }
1972
-    }
1973
-
1974
-
1975
-    /**
1976
-     * Saves this model object and its NEW cached relations to the database.
1977
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1978
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1979
-     * because otherwise, there's a potential for infinite looping of saving
1980
-     * Saves the cached related model objects, and ensures the relation between them
1981
-     * and this object and properly setup
1982
-     *
1983
-     * @return int ID of new model object on save; 0 on failure+
1984
-     * @throws ReflectionException
1985
-     * @throws InvalidArgumentException
1986
-     * @throws InvalidInterfaceException
1987
-     * @throws InvalidDataTypeException
1988
-     * @throws EE_Error
1989
-     */
1990
-    public function save_new_cached_related_model_objs()
1991
-    {
1992
-        // make sure this has been saved
1993
-        if (! $this->ID()) {
1994
-            $id = $this->save();
1995
-        } else {
1996
-            $id = $this->ID();
1997
-        }
1998
-        // now save all the NEW cached model objects  (ie they don't exist in the DB)
1999
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
2000
-            if ($this->_model_relations[ $relationName ]) {
2001
-                // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2002
-                // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2003
-                /* @var $related_model_obj EE_Base_Class */
2004
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
2005
-                    // add a relation to that relation type (which saves the appropriate thing in the process)
2006
-                    // but ONLY if it DOES NOT exist in the DB
2007
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2008
-                    // if( ! $related_model_obj->ID()){
2009
-                    $this->_add_relation_to($related_model_obj, $relationName);
2010
-                    $related_model_obj->save_new_cached_related_model_objs();
2011
-                    // }
2012
-                } else {
2013
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2014
-                        // add a relation to that relation type (which saves the appropriate thing in the process)
2015
-                        // but ONLY if it DOES NOT exist in the DB
2016
-                        // if( ! $related_model_obj->ID()){
2017
-                        $this->_add_relation_to($related_model_obj, $relationName);
2018
-                        $related_model_obj->save_new_cached_related_model_objs();
2019
-                        // }
2020
-                    }
2021
-                }
2022
-            }
2023
-        }
2024
-        return $id;
2025
-    }
2026
-
2027
-
2028
-    /**
2029
-     * for getting a model while instantiated.
2030
-     *
2031
-     * @return EEM_Base | EEM_CPT_Base
2032
-     * @throws ReflectionException
2033
-     * @throws InvalidArgumentException
2034
-     * @throws InvalidInterfaceException
2035
-     * @throws InvalidDataTypeException
2036
-     * @throws EE_Error
2037
-     */
2038
-    public function get_model()
2039
-    {
2040
-        if (! $this->_model) {
2041
-            $modelName = self::_get_model_classname(get_class($this));
2042
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2043
-        } else {
2044
-            $this->_model->set_timezone($this->_timezone);
2045
-        }
2046
-        return $this->_model;
2047
-    }
2048
-
2049
-
2050
-    /**
2051
-     * @param $props_n_values
2052
-     * @param $classname
2053
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2054
-     * @throws ReflectionException
2055
-     * @throws InvalidArgumentException
2056
-     * @throws InvalidInterfaceException
2057
-     * @throws InvalidDataTypeException
2058
-     * @throws EE_Error
2059
-     */
2060
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2061
-    {
2062
-        // TODO: will not work for Term_Relationships because they have no PK!
2063
-        $primary_id_ref = self::_get_primary_key_name($classname);
2064
-        if (
2065
-            array_key_exists($primary_id_ref, $props_n_values)
2066
-            && ! empty($props_n_values[ $primary_id_ref ])
2067
-        ) {
2068
-            $id = $props_n_values[ $primary_id_ref ];
2069
-            return self::_get_model($classname)->get_from_entity_map($id);
2070
-        }
2071
-        return false;
2072
-    }
2073
-
2074
-
2075
-    /**
2076
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2077
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2078
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2079
-     * we return false.
2080
-     *
2081
-     * @param  array  $props_n_values   incoming array of properties and their values
2082
-     * @param  string $classname        the classname of the child class
2083
-     * @param null    $timezone
2084
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
2085
-     *                                  date_format and the second value is the time format
2086
-     * @return mixed (EE_Base_Class|bool)
2087
-     * @throws InvalidArgumentException
2088
-     * @throws InvalidInterfaceException
2089
-     * @throws InvalidDataTypeException
2090
-     * @throws EE_Error
2091
-     * @throws ReflectionException
2092
-     * @throws ReflectionException
2093
-     * @throws ReflectionException
2094
-     */
2095
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2096
-    {
2097
-        $existing = null;
2098
-        $model = self::_get_model($classname, $timezone);
2099
-        if ($model->has_primary_key_field()) {
2100
-            $primary_id_ref = self::_get_primary_key_name($classname);
2101
-            if (
2102
-                array_key_exists($primary_id_ref, $props_n_values)
2103
-                && ! empty($props_n_values[ $primary_id_ref ])
2104
-            ) {
2105
-                $existing = $model->get_one_by_ID(
2106
-                    $props_n_values[ $primary_id_ref ]
2107
-                );
2108
-            }
2109
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2110
-            // no primary key on this model, but there's still a matching item in the DB
2111
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2112
-                self::_get_model($classname, $timezone)
2113
-                    ->get_index_primary_key_string($props_n_values)
2114
-            );
2115
-        }
2116
-        if ($existing) {
2117
-            // set date formats if present before setting values
2118
-            if (! empty($date_formats) && is_array($date_formats)) {
2119
-                $existing->set_date_format($date_formats[0]);
2120
-                $existing->set_time_format($date_formats[1]);
2121
-            } else {
2122
-                // set default formats for date and time
2123
-                $existing->set_date_format(get_option('date_format'));
2124
-                $existing->set_time_format(get_option('time_format'));
2125
-            }
2126
-            foreach ($props_n_values as $property => $field_value) {
2127
-                $existing->set($property, $field_value);
2128
-            }
2129
-            return $existing;
2130
-        }
2131
-        return false;
2132
-    }
2133
-
2134
-
2135
-    /**
2136
-     * Gets the EEM_*_Model for this class
2137
-     *
2138
-     * @access public now, as this is more convenient
2139
-     * @param      $classname
2140
-     * @param null $timezone
2141
-     * @throws ReflectionException
2142
-     * @throws InvalidArgumentException
2143
-     * @throws InvalidInterfaceException
2144
-     * @throws InvalidDataTypeException
2145
-     * @throws EE_Error
2146
-     * @return EEM_Base
2147
-     */
2148
-    protected static function _get_model($classname, $timezone = null)
2149
-    {
2150
-        // find model for this class
2151
-        if (! $classname) {
2152
-            throw new EE_Error(
2153
-                sprintf(
2154
-                    esc_html__(
2155
-                        'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2156
-                        'event_espresso'
2157
-                    ),
2158
-                    $classname
2159
-                )
2160
-            );
2161
-        }
2162
-        $modelName = self::_get_model_classname($classname);
2163
-        return self::_get_model_instance_with_name($modelName, $timezone);
2164
-    }
2165
-
2166
-
2167
-    /**
2168
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2169
-     *
2170
-     * @param string $model_classname
2171
-     * @param null   $timezone
2172
-     * @return EEM_Base
2173
-     * @throws ReflectionException
2174
-     * @throws InvalidArgumentException
2175
-     * @throws InvalidInterfaceException
2176
-     * @throws InvalidDataTypeException
2177
-     * @throws EE_Error
2178
-     */
2179
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2180
-    {
2181
-        $model_classname = str_replace('EEM_', '', $model_classname);
2182
-        $model = EE_Registry::instance()->load_model($model_classname);
2183
-        $model->set_timezone($timezone);
2184
-        return $model;
2185
-    }
2186
-
2187
-
2188
-    /**
2189
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2190
-     * Also works if a model class's classname is provided (eg EE_Registration).
2191
-     *
2192
-     * @param string|null $model_name
2193
-     * @return string like EEM_Attendee
2194
-     */
2195
-    private static function _get_model_classname($model_name = '')
2196
-    {
2197
-        return strpos((string) $model_name, 'EE_') === 0
2198
-            ? str_replace('EE_', 'EEM_', $model_name)
2199
-            : 'EEM_' . $model_name;
2200
-    }
2201
-
2202
-
2203
-    /**
2204
-     * returns the name of the primary key attribute
2205
-     *
2206
-     * @param null $classname
2207
-     * @throws ReflectionException
2208
-     * @throws InvalidArgumentException
2209
-     * @throws InvalidInterfaceException
2210
-     * @throws InvalidDataTypeException
2211
-     * @throws EE_Error
2212
-     * @return string
2213
-     */
2214
-    protected static function _get_primary_key_name($classname = null)
2215
-    {
2216
-        if (! $classname) {
2217
-            throw new EE_Error(
2218
-                sprintf(
2219
-                    esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2220
-                    $classname
2221
-                )
2222
-            );
2223
-        }
2224
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2225
-    }
2226
-
2227
-
2228
-    /**
2229
-     * Gets the value of the primary key.
2230
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2231
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2232
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2233
-     *
2234
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2235
-     * @throws ReflectionException
2236
-     * @throws InvalidArgumentException
2237
-     * @throws InvalidInterfaceException
2238
-     * @throws InvalidDataTypeException
2239
-     * @throws EE_Error
2240
-     */
2241
-    public function ID()
2242
-    {
2243
-        $model = $this->get_model();
2244
-        // now that we know the name of the variable, use a variable variable to get its value and return its
2245
-        if ($model->has_primary_key_field()) {
2246
-            return $this->_fields[ $model->primary_key_name() ];
2247
-        }
2248
-        return $model->get_index_primary_key_string($this->_fields);
2249
-    }
2250
-
2251
-
2252
-    /**
2253
-     * @param EE_Base_Class|int|string $otherModelObjectOrID
2254
-     * @param string                   $relationName
2255
-     * @return bool
2256
-     * @throws EE_Error
2257
-     * @throws ReflectionException
2258
-     * @since   5.0.0.p
2259
-     */
2260
-    public function hasRelation($otherModelObjectOrID, string $relationName): bool
2261
-    {
2262
-        $other_model = self::_get_model_instance_with_name(
2263
-            self::_get_model_classname($relationName),
2264
-            $this->_timezone
2265
-        );
2266
-        $primary_key = $other_model->primary_key_name();
2267
-        /** @var EE_Base_Class $otherModelObject */
2268
-        $otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2269
-        return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2270
-    }
2271
-
2272
-
2273
-    /**
2274
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2275
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2276
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2277
-     *
2278
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2279
-     * @param string $relationName                     eg 'Events','Question',etc.
2280
-     *                                                 an attendee to a group, you also want to specify which role they
2281
-     *                                                 will have in that group. So you would use this parameter to
2282
-     *                                                 specify array('role-column-name'=>'role-id')
2283
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2284
-     *                                                 allow you to further constrict the relation to being added.
2285
-     *                                                 However, keep in mind that the columns (keys) given must match a
2286
-     *                                                 column on the JOIN table and currently only the HABTM models
2287
-     *                                                 accept these additional conditions.  Also remember that if an
2288
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2289
-     *                                                 NEW row is created in the join table.
2290
-     * @param null   $cache_id
2291
-     * @throws ReflectionException
2292
-     * @throws InvalidArgumentException
2293
-     * @throws InvalidInterfaceException
2294
-     * @throws InvalidDataTypeException
2295
-     * @throws EE_Error
2296
-     * @return EE_Base_Class the object the relation was added to
2297
-     */
2298
-    public function _add_relation_to(
2299
-        $otherObjectModelObjectOrID,
2300
-        $relationName,
2301
-        $extra_join_model_fields_n_values = array(),
2302
-        $cache_id = null
2303
-    ) {
2304
-        $model = $this->get_model();
2305
-        // if this thing exists in the DB, save the relation to the DB
2306
-        if ($this->ID()) {
2307
-            $otherObject = $model->add_relationship_to(
2308
-                $this,
2309
-                $otherObjectModelObjectOrID,
2310
-                $relationName,
2311
-                $extra_join_model_fields_n_values
2312
-            );
2313
-            // clear cache so future get_many_related and get_first_related() return new results.
2314
-            $this->clear_cache($relationName, $otherObject, true);
2315
-            if ($otherObject instanceof EE_Base_Class) {
2316
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2317
-            }
2318
-        } else {
2319
-            // this thing doesn't exist in the DB,  so just cache it
2320
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2321
-                throw new EE_Error(
2322
-                    sprintf(
2323
-                        esc_html__(
2324
-                            'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2325
-                            'event_espresso'
2326
-                        ),
2327
-                        $otherObjectModelObjectOrID,
2328
-                        get_class($this)
2329
-                    )
2330
-                );
2331
-            }
2332
-            $otherObject = $otherObjectModelObjectOrID;
2333
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2334
-        }
2335
-        if ($otherObject instanceof EE_Base_Class) {
2336
-            // fix the reciprocal relation too
2337
-            if ($otherObject->ID()) {
2338
-                // its saved so assumed relations exist in the DB, so we can just
2339
-                // clear the cache so future queries use the updated info in the DB
2340
-                $otherObject->clear_cache(
2341
-                    $model->get_this_model_name(),
2342
-                    null,
2343
-                    true
2344
-                );
2345
-            } else {
2346
-                // it's not saved, so it caches relations like this
2347
-                $otherObject->cache($model->get_this_model_name(), $this);
2348
-            }
2349
-        }
2350
-        return $otherObject;
2351
-    }
2352
-
2353
-
2354
-    /**
2355
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2356
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2357
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2358
-     * from the cache
2359
-     *
2360
-     * @param mixed  $otherObjectModelObjectOrID
2361
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2362
-     *                to the DB yet
2363
-     * @param string $relationName
2364
-     * @param array  $where_query
2365
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2366
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2367
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2368
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2369
-     *                deleted.
2370
-     * @return EE_Base_Class the relation was removed from
2371
-     * @throws ReflectionException
2372
-     * @throws InvalidArgumentException
2373
-     * @throws InvalidInterfaceException
2374
-     * @throws InvalidDataTypeException
2375
-     * @throws EE_Error
2376
-     */
2377
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2378
-    {
2379
-        if ($this->ID()) {
2380
-            // if this exists in the DB, save the relation change to the DB too
2381
-            $otherObject = $this->get_model()->remove_relationship_to(
2382
-                $this,
2383
-                $otherObjectModelObjectOrID,
2384
-                $relationName,
2385
-                $where_query
2386
-            );
2387
-            $this->clear_cache(
2388
-                $relationName,
2389
-                $otherObject
2390
-            );
2391
-        } else {
2392
-            // this doesn't exist in the DB, just remove it from the cache
2393
-            $otherObject = $this->clear_cache(
2394
-                $relationName,
2395
-                $otherObjectModelObjectOrID
2396
-            );
2397
-        }
2398
-        if ($otherObject instanceof EE_Base_Class) {
2399
-            $otherObject->clear_cache(
2400
-                $this->get_model()->get_this_model_name(),
2401
-                $this
2402
-            );
2403
-        }
2404
-        return $otherObject;
2405
-    }
2406
-
2407
-
2408
-    /**
2409
-     * Removes ALL the related things for the $relationName.
2410
-     *
2411
-     * @param string $relationName
2412
-     * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2413
-     * @return EE_Base_Class
2414
-     * @throws ReflectionException
2415
-     * @throws InvalidArgumentException
2416
-     * @throws InvalidInterfaceException
2417
-     * @throws InvalidDataTypeException
2418
-     * @throws EE_Error
2419
-     */
2420
-    public function _remove_relations($relationName, $where_query_params = array())
2421
-    {
2422
-        if ($this->ID()) {
2423
-            // if this exists in the DB, save the relation change to the DB too
2424
-            $otherObjects = $this->get_model()->remove_relations(
2425
-                $this,
2426
-                $relationName,
2427
-                $where_query_params
2428
-            );
2429
-            $this->clear_cache(
2430
-                $relationName,
2431
-                null,
2432
-                true
2433
-            );
2434
-        } else {
2435
-            // this doesn't exist in the DB, just remove it from the cache
2436
-            $otherObjects = $this->clear_cache(
2437
-                $relationName,
2438
-                null,
2439
-                true
2440
-            );
2441
-        }
2442
-        if (is_array($otherObjects)) {
2443
-            foreach ($otherObjects as $otherObject) {
2444
-                $otherObject->clear_cache(
2445
-                    $this->get_model()->get_this_model_name(),
2446
-                    $this
2447
-                );
2448
-            }
2449
-        }
2450
-        return $otherObjects;
2451
-    }
2452
-
2453
-
2454
-    /**
2455
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2456
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2457
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2458
-     * because we want to get even deleted items etc.
2459
-     *
2460
-     * @param string $relationName key in the model's _model_relations array
2461
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2462
-     * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2463
-     *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2464
-     *                             results if you want IDs
2465
-     * @throws ReflectionException
2466
-     * @throws InvalidArgumentException
2467
-     * @throws InvalidInterfaceException
2468
-     * @throws InvalidDataTypeException
2469
-     * @throws EE_Error
2470
-     */
2471
-    public function get_many_related($relationName, $query_params = array())
2472
-    {
2473
-        if ($this->ID()) {
2474
-            // this exists in the DB, so get the related things from either the cache or the DB
2475
-            // if there are query parameters, forget about caching the related model objects.
2476
-            if ($query_params) {
2477
-                $related_model_objects = $this->get_model()->get_all_related(
2478
-                    $this,
2479
-                    $relationName,
2480
-                    $query_params
2481
-                );
2482
-            } else {
2483
-                // did we already cache the result of this query?
2484
-                $cached_results = $this->get_all_from_cache($relationName);
2485
-                if (! $cached_results) {
2486
-                    $related_model_objects = $this->get_model()->get_all_related(
2487
-                        $this,
2488
-                        $relationName,
2489
-                        $query_params
2490
-                    );
2491
-                    // if no query parameters were passed, then we got all the related model objects
2492
-                    // for that relation. We can cache them then.
2493
-                    foreach ($related_model_objects as $related_model_object) {
2494
-                        $this->cache($relationName, $related_model_object);
2495
-                    }
2496
-                } else {
2497
-                    $related_model_objects = $cached_results;
2498
-                }
2499
-            }
2500
-        } else {
2501
-            // this doesn't exist in the DB, so just get the related things from the cache
2502
-            $related_model_objects = $this->get_all_from_cache($relationName);
2503
-        }
2504
-        return $related_model_objects;
2505
-    }
2506
-
2507
-
2508
-    /**
2509
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2510
-     * unless otherwise specified in the $query_params
2511
-     *
2512
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2513
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2514
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2515
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2516
-     *                               that by the setting $distinct to TRUE;
2517
-     * @return int
2518
-     * @throws ReflectionException
2519
-     * @throws InvalidArgumentException
2520
-     * @throws InvalidInterfaceException
2521
-     * @throws InvalidDataTypeException
2522
-     * @throws EE_Error
2523
-     */
2524
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2525
-    {
2526
-        return $this->get_model()->count_related(
2527
-            $this,
2528
-            $relation_name,
2529
-            $query_params,
2530
-            $field_to_count,
2531
-            $distinct
2532
-        );
2533
-    }
2534
-
2535
-
2536
-    /**
2537
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2538
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2539
-     *
2540
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2541
-     * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2542
-     * @param string $field_to_sum  name of field to count by.
2543
-     *                              By default, uses primary key
2544
-     *                              (which doesn't make much sense, so you should probably change it)
2545
-     * @return int
2546
-     * @throws ReflectionException
2547
-     * @throws InvalidArgumentException
2548
-     * @throws InvalidInterfaceException
2549
-     * @throws InvalidDataTypeException
2550
-     * @throws EE_Error
2551
-     */
2552
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2553
-    {
2554
-        return $this->get_model()->sum_related(
2555
-            $this,
2556
-            $relation_name,
2557
-            $query_params,
2558
-            $field_to_sum
2559
-        );
2560
-    }
2561
-
2562
-
2563
-    /**
2564
-     * Gets the first (ie, one) related model object of the specified type.
2565
-     *
2566
-     * @param string $relationName key in the model's _model_relations array
2567
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2568
-     * @return EE_Base_Class (not an array, a single object)
2569
-     * @throws ReflectionException
2570
-     * @throws InvalidArgumentException
2571
-     * @throws InvalidInterfaceException
2572
-     * @throws InvalidDataTypeException
2573
-     * @throws EE_Error
2574
-     */
2575
-    public function get_first_related($relationName, $query_params = array())
2576
-    {
2577
-        $model = $this->get_model();
2578
-        if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2579
-            // if they've provided some query parameters, don't bother trying to cache the result
2580
-            // also make sure we're not caching the result of get_first_related
2581
-            // on a relation which should have an array of objects (because the cache might have an array of objects)
2582
-            if (
2583
-                $query_params
2584
-                || ! $model->related_settings_for($relationName)
2585
-                     instanceof
2586
-                     EE_Belongs_To_Relation
2587
-            ) {
2588
-                $related_model_object = $model->get_first_related(
2589
-                    $this,
2590
-                    $relationName,
2591
-                    $query_params
2592
-                );
2593
-            } else {
2594
-                // first, check if we've already cached the result of this query
2595
-                $cached_result = $this->get_one_from_cache($relationName);
2596
-                if (! $cached_result) {
2597
-                    $related_model_object = $model->get_first_related(
2598
-                        $this,
2599
-                        $relationName,
2600
-                        $query_params
2601
-                    );
2602
-                    $this->cache($relationName, $related_model_object);
2603
-                } else {
2604
-                    $related_model_object = $cached_result;
2605
-                }
2606
-            }
2607
-        } else {
2608
-            $related_model_object = null;
2609
-            // this doesn't exist in the Db,
2610
-            // but maybe the relation is of type belongs to, and so the related thing might
2611
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2612
-                $related_model_object = $model->get_first_related(
2613
-                    $this,
2614
-                    $relationName,
2615
-                    $query_params
2616
-                );
2617
-            }
2618
-            // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2619
-            // just get what's cached on this object
2620
-            if (! $related_model_object) {
2621
-                $related_model_object = $this->get_one_from_cache($relationName);
2622
-            }
2623
-        }
2624
-        return $related_model_object;
2625
-    }
2626
-
2627
-
2628
-    /**
2629
-     * Does a delete on all related objects of type $relationName and removes
2630
-     * the current model object's relation to them. If they can't be deleted (because
2631
-     * of blocking related model objects) does nothing. If the related model objects are
2632
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2633
-     * If this model object doesn't exist yet in the DB, just removes its related things
2634
-     *
2635
-     * @param string $relationName
2636
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2637
-     * @return int how many deleted
2638
-     * @throws ReflectionException
2639
-     * @throws InvalidArgumentException
2640
-     * @throws InvalidInterfaceException
2641
-     * @throws InvalidDataTypeException
2642
-     * @throws EE_Error
2643
-     */
2644
-    public function delete_related($relationName, $query_params = array())
2645
-    {
2646
-        if ($this->ID()) {
2647
-            $count = $this->get_model()->delete_related(
2648
-                $this,
2649
-                $relationName,
2650
-                $query_params
2651
-            );
2652
-        } else {
2653
-            $count = count($this->get_all_from_cache($relationName));
2654
-            $this->clear_cache($relationName, null, true);
2655
-        }
2656
-        return $count;
2657
-    }
2658
-
2659
-
2660
-    /**
2661
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2662
-     * the current model object's relation to them. If they can't be deleted (because
2663
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2664
-     * If the related thing isn't a soft-deletable model object, this function is identical
2665
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2666
-     *
2667
-     * @param string $relationName
2668
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2669
-     * @return int how many deleted (including those soft deleted)
2670
-     * @throws ReflectionException
2671
-     * @throws InvalidArgumentException
2672
-     * @throws InvalidInterfaceException
2673
-     * @throws InvalidDataTypeException
2674
-     * @throws EE_Error
2675
-     */
2676
-    public function delete_related_permanently($relationName, $query_params = array())
2677
-    {
2678
-        if ($this->ID()) {
2679
-            $count = $this->get_model()->delete_related_permanently(
2680
-                $this,
2681
-                $relationName,
2682
-                $query_params
2683
-            );
2684
-        } else {
2685
-            $count = count($this->get_all_from_cache($relationName));
2686
-        }
2687
-        $this->clear_cache($relationName, null, true);
2688
-        return $count;
2689
-    }
2690
-
2691
-
2692
-    /**
2693
-     * is_set
2694
-     * Just a simple utility function children can use for checking if property exists
2695
-     *
2696
-     * @access  public
2697
-     * @param  string $field_name property to check
2698
-     * @return bool                              TRUE if existing,FALSE if not.
2699
-     */
2700
-    public function is_set($field_name)
2701
-    {
2702
-        return isset($this->_fields[ $field_name ]);
2703
-    }
2704
-
2705
-
2706
-    /**
2707
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2708
-     * EE_Error exception if they don't
2709
-     *
2710
-     * @param  mixed (string|array) $properties properties to check
2711
-     * @throws EE_Error
2712
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2713
-     */
2714
-    protected function _property_exists($properties)
2715
-    {
2716
-        foreach ((array) $properties as $property_name) {
2717
-            // first make sure this property exists
2718
-            if (! $this->_fields[ $property_name ]) {
2719
-                throw new EE_Error(
2720
-                    sprintf(
2721
-                        esc_html__(
2722
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2723
-                            'event_espresso'
2724
-                        ),
2725
-                        $property_name
2726
-                    )
2727
-                );
2728
-            }
2729
-        }
2730
-        return true;
2731
-    }
2732
-
2733
-
2734
-    /**
2735
-     * This simply returns an array of model fields for this object
2736
-     *
2737
-     * @return array
2738
-     * @throws ReflectionException
2739
-     * @throws InvalidArgumentException
2740
-     * @throws InvalidInterfaceException
2741
-     * @throws InvalidDataTypeException
2742
-     * @throws EE_Error
2743
-     */
2744
-    public function model_field_array()
2745
-    {
2746
-        $fields = $this->get_model()->field_settings(false);
2747
-        $properties = array();
2748
-        // remove prepended underscore
2749
-        foreach ($fields as $field_name => $settings) {
2750
-            $properties[ $field_name ] = $this->get($field_name);
2751
-        }
2752
-        return $properties;
2753
-    }
2754
-
2755
-
2756
-    /**
2757
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2758
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2759
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2760
-     * Instead of requiring a plugin to extend the EE_Base_Class
2761
-     * (which works fine is there's only 1 plugin, but when will that happen?)
2762
-     * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2763
-     * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2764
-     * and accepts 2 arguments: the object on which the function was called,
2765
-     * and an array of the original arguments passed to the function.
2766
-     * Whatever their callback function returns will be returned by this function.
2767
-     * Example: in functions.php (or in a plugin):
2768
-     *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2769
-     *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2770
-     *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2771
-     *          return $previousReturnValue.$returnString;
2772
-     *      }
2773
-     * require('EE_Answer.class.php');
2774
-     * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2775
-     *      ->my_callback('monkeys',100);
2776
-     * // will output "you called my_callback! and passed args:monkeys,100"
2777
-     *
2778
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2779
-     * @param array  $args       array of original arguments passed to the function
2780
-     * @throws EE_Error
2781
-     * @return mixed whatever the plugin which calls add_filter decides
2782
-     */
2783
-    public function __call($methodName, $args)
2784
-    {
2785
-        $className = get_class($this);
2786
-        $tagName = "FHEE__{$className}__{$methodName}";
2787
-        if (! has_filter($tagName)) {
2788
-            throw new EE_Error(
2789
-                sprintf(
2790
-                    esc_html__(
2791
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2792
-                        'event_espresso'
2793
-                    ),
2794
-                    $methodName,
2795
-                    $className,
2796
-                    $tagName
2797
-                )
2798
-            );
2799
-        }
2800
-        return apply_filters($tagName, null, $this, $args);
2801
-    }
2802
-
2803
-
2804
-    /**
2805
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2806
-     * A $previous_value can be specified in case there are many meta rows with the same key
2807
-     *
2808
-     * @param string $meta_key
2809
-     * @param mixed  $meta_value
2810
-     * @param mixed  $previous_value
2811
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2812
-     *                  NOTE: if the values haven't changed, returns 0
2813
-     * @throws InvalidArgumentException
2814
-     * @throws InvalidInterfaceException
2815
-     * @throws InvalidDataTypeException
2816
-     * @throws EE_Error
2817
-     * @throws ReflectionException
2818
-     */
2819
-    public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2820
-    {
2821
-        $query_params = [
2822
-            [
2823
-                'EXM_key'  => $meta_key,
2824
-                'OBJ_ID'   => $this->ID(),
2825
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2826
-            ],
2827
-        ];
2828
-        if ($previous_value !== null) {
2829
-            $query_params[0]['EXM_value'] = $meta_value;
2830
-        }
2831
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2832
-        if (! $existing_rows_like_that) {
2833
-            return $this->add_extra_meta($meta_key, $meta_value);
2834
-        }
2835
-        foreach ($existing_rows_like_that as $existing_row) {
2836
-            $existing_row->save(['EXM_value' => $meta_value]);
2837
-        }
2838
-        return count($existing_rows_like_that);
2839
-    }
2840
-
2841
-
2842
-    /**
2843
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2844
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2845
-     * extra meta row was entered, false if not
2846
-     *
2847
-     * @param string $meta_key
2848
-     * @param mixed  $meta_value
2849
-     * @param bool   $unique
2850
-     * @return bool
2851
-     * @throws InvalidArgumentException
2852
-     * @throws InvalidInterfaceException
2853
-     * @throws InvalidDataTypeException
2854
-     * @throws EE_Error
2855
-     * @throws ReflectionException
2856
-     * @throws ReflectionException
2857
-     */
2858
-    public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2859
-    {
2860
-        if ($unique) {
2861
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2862
-                [
2863
-                    [
2864
-                        'EXM_key'  => $meta_key,
2865
-                        'OBJ_ID'   => $this->ID(),
2866
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2867
-                    ],
2868
-                ]
2869
-            );
2870
-            if ($existing_extra_meta) {
2871
-                return false;
2872
-            }
2873
-        }
2874
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2875
-            [
2876
-                'EXM_key'   => $meta_key,
2877
-                'EXM_value' => $meta_value,
2878
-                'OBJ_ID'    => $this->ID(),
2879
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2880
-            ]
2881
-        );
2882
-        $new_extra_meta->save();
2883
-        return true;
2884
-    }
2885
-
2886
-
2887
-    /**
2888
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2889
-     * is specified, only deletes extra meta records with that value.
2890
-     *
2891
-     * @param string $meta_key
2892
-     * @param mixed  $meta_value
2893
-     * @return int|bool number of extra meta rows deleted
2894
-     * @throws InvalidArgumentException
2895
-     * @throws InvalidInterfaceException
2896
-     * @throws InvalidDataTypeException
2897
-     * @throws EE_Error
2898
-     * @throws ReflectionException
2899
-     */
2900
-    public function delete_extra_meta(string $meta_key, $meta_value = null)
2901
-    {
2902
-        $query_params = [
2903
-            [
2904
-                'EXM_key'  => $meta_key,
2905
-                'OBJ_ID'   => $this->ID(),
2906
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2907
-            ],
2908
-        ];
2909
-        if ($meta_value !== null) {
2910
-            $query_params[0]['EXM_value'] = $meta_value;
2911
-        }
2912
-        return EEM_Extra_Meta::instance()->delete($query_params);
2913
-    }
2914
-
2915
-
2916
-    /**
2917
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2918
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2919
-     * You can specify $default is case you haven't found the extra meta
2920
-     *
2921
-     * @param string     $meta_key
2922
-     * @param bool       $single
2923
-     * @param mixed      $default if we don't find anything, what should we return?
2924
-     * @param array|null $extra_where
2925
-     * @return mixed single value if $single; array if ! $single
2926
-     * @throws ReflectionException
2927
-     * @throws EE_Error
2928
-     */
2929
-    public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2930
-    {
2931
-        $query_params = [ $extra_where + ['EXM_key' => $meta_key] ];
2932
-        if ($single) {
2933
-            $result = $this->get_first_related('Extra_Meta', $query_params);
2934
-            if ($result instanceof EE_Extra_Meta) {
2935
-                return $result->value();
2936
-            }
2937
-        } else {
2938
-            $results = $this->get_many_related('Extra_Meta', $query_params);
2939
-            if ($results) {
2940
-                $values = [];
2941
-                foreach ($results as $result) {
2942
-                    if ($result instanceof EE_Extra_Meta) {
2943
-                        $values[ $result->ID() ] = $result->value();
2944
-                    }
2945
-                }
2946
-                return $values;
2947
-            }
2948
-        }
2949
-        // if nothing discovered yet return default.
2950
-        return apply_filters(
2951
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2952
-            $default,
2953
-            $meta_key,
2954
-            $single,
2955
-            $this
2956
-        );
2957
-    }
2958
-
2959
-
2960
-    /**
2961
-     * Returns a simple array of all the extra meta associated with this model object.
2962
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2963
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2964
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2965
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2966
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2967
-     * finally the extra meta's value as each sub-value. (eg
2968
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2969
-     *
2970
-     * @param bool $one_of_each_key
2971
-     * @return array
2972
-     * @throws ReflectionException
2973
-     * @throws InvalidArgumentException
2974
-     * @throws InvalidInterfaceException
2975
-     * @throws InvalidDataTypeException
2976
-     * @throws EE_Error
2977
-     */
2978
-    public function all_extra_meta_array(bool $one_of_each_key = true): array
2979
-    {
2980
-        $return_array = [];
2981
-        if ($one_of_each_key) {
2982
-            $extra_meta_objs = $this->get_many_related(
2983
-                'Extra_Meta',
2984
-                ['group_by' => 'EXM_key']
2985
-            );
2986
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2987
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2988
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2989
-                }
2990
-            }
2991
-        } else {
2992
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2993
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2994
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2995
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2996
-                        $return_array[ $extra_meta_obj->key() ] = [];
2997
-                    }
2998
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2999
-                }
3000
-            }
3001
-        }
3002
-        return $return_array;
3003
-    }
3004
-
3005
-
3006
-    /**
3007
-     * Gets a pretty nice displayable nice for this model object. Often overridden
3008
-     *
3009
-     * @return string
3010
-     * @throws ReflectionException
3011
-     * @throws InvalidArgumentException
3012
-     * @throws InvalidInterfaceException
3013
-     * @throws InvalidDataTypeException
3014
-     * @throws EE_Error
3015
-     */
3016
-    public function name()
3017
-    {
3018
-        // find a field that's not a text field
3019
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3020
-        if ($field_we_can_use) {
3021
-            return $this->get($field_we_can_use->get_name());
3022
-        }
3023
-        $first_few_properties = $this->model_field_array();
3024
-        $first_few_properties = array_slice($first_few_properties, 0, 3);
3025
-        $name_parts = array();
3026
-        foreach ($first_few_properties as $name => $value) {
3027
-            $name_parts[] = "$name:$value";
3028
-        }
3029
-        return implode(',', $name_parts);
3030
-    }
3031
-
3032
-
3033
-    /**
3034
-     * in_entity_map
3035
-     * Checks if this model object has been proven to already be in the entity map
3036
-     *
3037
-     * @return boolean
3038
-     * @throws ReflectionException
3039
-     * @throws InvalidArgumentException
3040
-     * @throws InvalidInterfaceException
3041
-     * @throws InvalidDataTypeException
3042
-     * @throws EE_Error
3043
-     */
3044
-    public function in_entity_map()
3045
-    {
3046
-        // well, if we looked, did we find it in the entity map?
3047
-        return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3048
-    }
3049
-
3050
-
3051
-    /**
3052
-     * refresh_from_db
3053
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
3054
-     *
3055
-     * @throws ReflectionException
3056
-     * @throws InvalidArgumentException
3057
-     * @throws InvalidInterfaceException
3058
-     * @throws InvalidDataTypeException
3059
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3060
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3061
-     */
3062
-    public function refresh_from_db()
3063
-    {
3064
-        if ($this->ID() && $this->in_entity_map()) {
3065
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
3066
-        } else {
3067
-            // if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3068
-            // if it has an ID but it's not in the map, and you're asking me to refresh it
3069
-            // that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3070
-            // absolutely nothing in it for this ID
3071
-            if (WP_DEBUG) {
3072
-                throw new EE_Error(
3073
-                    sprintf(
3074
-                        esc_html__(
3075
-                            'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3076
-                            'event_espresso'
3077
-                        ),
3078
-                        $this->ID(),
3079
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3080
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3081
-                    )
3082
-                );
3083
-            }
3084
-        }
3085
-    }
3086
-
3087
-
3088
-    /**
3089
-     * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3090
-     *
3091
-     * @since 4.9.80.p
3092
-     * @param EE_Model_Field_Base[] $fields
3093
-     * @param string $new_value_sql
3094
-     *      example: 'column_name=123',
3095
-     *      or 'column_name=column_name+1',
3096
-     *      or 'column_name= CASE
3097
-     *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3098
-     *          THEN `column_name` + 5
3099
-     *          ELSE `column_name`
3100
-     *      END'
3101
-     *      Also updates $field on this model object with the latest value from the database.
3102
-     * @return bool
3103
-     * @throws EE_Error
3104
-     * @throws InvalidArgumentException
3105
-     * @throws InvalidDataTypeException
3106
-     * @throws InvalidInterfaceException
3107
-     * @throws ReflectionException
3108
-     */
3109
-    protected function updateFieldsInDB($fields, $new_value_sql)
3110
-    {
3111
-        // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3112
-        // if it wasn't even there to start off.
3113
-        if (! $this->ID()) {
3114
-            $this->save();
3115
-        }
3116
-        global $wpdb;
3117
-        if (empty($fields)) {
3118
-            throw new InvalidArgumentException(
3119
-                esc_html__(
3120
-                    'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3121
-                    'event_espresso'
3122
-                )
3123
-            );
3124
-        }
3125
-        $first_field = reset($fields);
3126
-        $table_alias = $first_field->get_table_alias();
3127
-        foreach ($fields as $field) {
3128
-            if ($table_alias !== $field->get_table_alias()) {
3129
-                throw new InvalidArgumentException(
3130
-                    sprintf(
3131
-                        esc_html__(
3132
-                            // @codingStandardsIgnoreStart
3133
-                            'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3134
-                            // @codingStandardsIgnoreEnd
3135
-                            'event_espresso'
3136
-                        ),
3137
-                        $table_alias,
3138
-                        $field->get_table_alias()
3139
-                    )
3140
-                );
3141
-            }
3142
-        }
3143
-        // Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3144
-        $table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3145
-        $table_pk_value = $this->ID();
3146
-        $table_name = $table_obj->get_table_name();
3147
-        if ($table_obj instanceof EE_Secondary_Table) {
3148
-            $table_pk_field_name = $table_obj->get_fk_on_table();
3149
-        } else {
3150
-            $table_pk_field_name = $table_obj->get_pk_column();
3151
-        }
3152
-
3153
-        $query =
3154
-            "UPDATE `{$table_name}`
348
+			$this->_props_n_values_provided_in_constructor
349
+			&& $field_value
350
+			&& $field_name === $model->primary_key_name()
351
+		) {
352
+			// if so, we want all this object's fields to be filled either with
353
+			// what we've explicitly set on this model
354
+			// or what we have in the db
355
+			// echo "setting primary key!";
356
+			$fields_on_model = self::_get_model(get_class($this))->field_settings();
357
+			$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
358
+			foreach ($fields_on_model as $field_obj) {
359
+				if (
360
+					! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
361
+					&& $field_obj->get_name() !== $field_name
362
+				) {
363
+					$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
364
+				}
365
+			}
366
+			// oh this model object has an ID? well make sure its in the entity mapper
367
+			$model->add_to_entity_map($this);
368
+		}
369
+		// let's unset any cache for this field_name from the $_cached_properties property.
370
+		$this->_clear_cached_property($field_name);
371
+	}
372
+
373
+
374
+	/**
375
+	 * Overrides parent because parent expects old models.
376
+	 * This also doesn't do any validation, and won't work for serialized arrays
377
+	 *
378
+	 * @param string $field_name
379
+	 * @param mixed  $field_value_from_db
380
+	 * @throws ReflectionException
381
+	 * @throws InvalidArgumentException
382
+	 * @throws InvalidInterfaceException
383
+	 * @throws InvalidDataTypeException
384
+	 * @throws EE_Error
385
+	 */
386
+	public function set_from_db(string $field_name, $field_value_from_db)
387
+	{
388
+		$field_obj = $this->get_model()->field_settings_for($field_name);
389
+		if ($field_obj instanceof EE_Model_Field_Base) {
390
+			// you would think the DB has no NULLs for non-null label fields right? wrong!
391
+			// eg, a CPT model object could have an entry in the posts table, but no
392
+			// entry in the meta table. Meaning that all its columns in the meta table
393
+			// are null! yikes! so when we find one like that, use defaults for its meta columns
394
+			if ($field_value_from_db === null) {
395
+				if ($field_obj->is_nullable()) {
396
+					// if the field allows nulls, then let it be null
397
+					$field_value = null;
398
+				} else {
399
+					$field_value = $field_obj->get_default_value();
400
+				}
401
+			} else {
402
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
403
+			}
404
+			$this->_fields[ $field_name ] = $field_value;
405
+			$this->_clear_cached_property($field_name);
406
+		}
407
+	}
408
+
409
+
410
+	/**
411
+	 * Set custom select values for model.
412
+	 *
413
+	 * @param array $custom_select_values
414
+	 */
415
+	public function setCustomSelectsValues(array $custom_select_values)
416
+	{
417
+		$this->custom_selection_results = $custom_select_values;
418
+	}
419
+
420
+
421
+	/**
422
+	 * Returns the custom select value for the provided alias if its set.
423
+	 * If not set, returns null.
424
+	 *
425
+	 * @param string $alias
426
+	 * @return string|int|float|null
427
+	 */
428
+	public function getCustomSelect($alias)
429
+	{
430
+		return isset($this->custom_selection_results[ $alias ])
431
+			? $this->custom_selection_results[ $alias ]
432
+			: null;
433
+	}
434
+
435
+
436
+	/**
437
+	 * This sets the field value on the db column if it exists for the given $column_name or
438
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
439
+	 *
440
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
441
+	 * @param string $field_name  Must be the exact column name.
442
+	 * @param mixed  $field_value The value to set.
443
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
444
+	 * @throws InvalidArgumentException
445
+	 * @throws InvalidInterfaceException
446
+	 * @throws InvalidDataTypeException
447
+	 * @throws EE_Error
448
+	 * @throws ReflectionException
449
+	 */
450
+	public function set_field_or_extra_meta($field_name, $field_value)
451
+	{
452
+		if ($this->get_model()->has_field($field_name)) {
453
+			$this->set($field_name, $field_value);
454
+			return true;
455
+		}
456
+		// ensure this object is saved first so that extra meta can be properly related.
457
+		$this->save();
458
+		return $this->update_extra_meta($field_name, $field_value);
459
+	}
460
+
461
+
462
+	/**
463
+	 * This retrieves the value of the db column set on this class or if that's not present
464
+	 * it will attempt to retrieve from extra_meta if found.
465
+	 * Example Usage:
466
+	 * Via EE_Message child class:
467
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
468
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
469
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
470
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
471
+	 * value for those extra fields dynamically via the EE_message object.
472
+	 *
473
+	 * @param  string $field_name expecting the fully qualified field name.
474
+	 * @return mixed|null  value for the field if found.  null if not found.
475
+	 * @throws ReflectionException
476
+	 * @throws InvalidArgumentException
477
+	 * @throws InvalidInterfaceException
478
+	 * @throws InvalidDataTypeException
479
+	 * @throws EE_Error
480
+	 */
481
+	public function get_field_or_extra_meta($field_name)
482
+	{
483
+		if ($this->get_model()->has_field($field_name)) {
484
+			$column_value = $this->get($field_name);
485
+		} else {
486
+			// This isn't a column in the main table, let's see if it is in the extra meta.
487
+			$column_value = $this->get_extra_meta($field_name, true, null);
488
+		}
489
+		return $column_value;
490
+	}
491
+
492
+
493
+	/**
494
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
495
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
496
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
497
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
498
+	 *
499
+	 * @access public
500
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
501
+	 * @return void
502
+	 * @throws InvalidArgumentException
503
+	 * @throws InvalidInterfaceException
504
+	 * @throws InvalidDataTypeException
505
+	 * @throws EE_Error
506
+	 * @throws ReflectionException
507
+	 */
508
+	public function set_timezone($timezone = '')
509
+	{
510
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
511
+		// make sure we clear all cached properties because they won't be relevant now
512
+		$this->_clear_cached_properties();
513
+		// make sure we update field settings and the date for all EE_Datetime_Fields
514
+		$model_fields = $this->get_model()->field_settings(false);
515
+		foreach ($model_fields as $field_name => $field_obj) {
516
+			if ($field_obj instanceof EE_Datetime_Field) {
517
+				$field_obj->set_timezone($this->_timezone);
518
+				if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
519
+					EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
520
+				}
521
+			}
522
+		}
523
+	}
524
+
525
+
526
+	/**
527
+	 * This just returns whatever is set for the current timezone.
528
+	 *
529
+	 * @access public
530
+	 * @return string timezone string
531
+	 */
532
+	public function get_timezone()
533
+	{
534
+		return $this->_timezone;
535
+	}
536
+
537
+
538
+	/**
539
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
540
+	 * internally instead of wp set date format options
541
+	 *
542
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
543
+	 * @since 4.6
544
+	 */
545
+	public function set_date_format(?string $format = 'Y-m-d')
546
+	{
547
+		$format = $format ?: 'Y-m-d';
548
+		$this->_dt_frmt = new DateFormat($format);
549
+		// clear cached_properties because they won't be relevant now.
550
+		$this->_clear_cached_properties();
551
+	}
552
+
553
+
554
+	/**
555
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
556
+	 * class internally instead of wp set time format options.
557
+	 *
558
+	 * @param string|null $format should be a format recognizable by PHP date() functions.
559
+	 * @since 4.6
560
+	 */
561
+	public function set_time_format(?string $format = 'H:i:s')
562
+	{
563
+		$format = $format ?: 'H:i:s';
564
+		$this->_tm_frmt = new TimeFormat($format);
565
+		// clear cached_properties because they won't be relevant now.
566
+		$this->_clear_cached_properties();
567
+	}
568
+
569
+
570
+	/**
571
+	 * This returns the current internal set format for the date and time formats.
572
+	 *
573
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
574
+	 *                             where the first value is the date format and the second value is the time format.
575
+	 * @return mixed string|array
576
+	 */
577
+	public function get_format($full = true)
578
+	{
579
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
580
+	}
581
+
582
+
583
+	/**
584
+	 * cache
585
+	 * stores the passed model object on the current model object.
586
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
587
+	 *
588
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
589
+	 *                                       'Registration' associated with this model object
590
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
591
+	 *                                       that could be a payment or a registration)
592
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
593
+	 *                                       items which will be stored in an array on this object
594
+	 * @throws ReflectionException
595
+	 * @throws InvalidArgumentException
596
+	 * @throws InvalidInterfaceException
597
+	 * @throws InvalidDataTypeException
598
+	 * @throws EE_Error
599
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
600
+	 *                                       related thing, no array)
601
+	 */
602
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
603
+	{
604
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
605
+		if (! $object_to_cache instanceof EE_Base_Class) {
606
+			return false;
607
+		}
608
+		// also get "how" the object is related, or throw an error
609
+		if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
610
+			throw new EE_Error(
611
+				sprintf(
612
+					esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
613
+					$relationName,
614
+					get_class($this)
615
+				)
616
+			);
617
+		}
618
+		// how many things are related ?
619
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
620
+			// if it's a "belongs to" relationship, then there's only one related model object
621
+			// eg, if this is a registration, there's only 1 attendee for it
622
+			// so for these model objects just set it to be cached
623
+			$this->_model_relations[ $relationName ] = $object_to_cache;
624
+			$return = true;
625
+		} else {
626
+			// otherwise, this is the "many" side of a one to many relationship,
627
+			// so we'll add the object to the array of related objects for that type.
628
+			// eg: if this is an event, there are many registrations for that event,
629
+			// so we cache the registrations in an array
630
+			if (! is_array($this->_model_relations[ $relationName ])) {
631
+				// if for some reason, the cached item is a model object,
632
+				// then stick that in the array, otherwise start with an empty array
633
+				$this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
634
+														   instanceof
635
+														   EE_Base_Class
636
+					? array($this->_model_relations[ $relationName ]) : array();
637
+			}
638
+			// first check for a cache_id which is normally empty
639
+			if (! empty($cache_id)) {
640
+				// if the cache_id exists, then it means we are purposely trying to cache this
641
+				// with a known key that can then be used to retrieve the object later on
642
+				$this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
643
+				$return = $cache_id;
644
+			} elseif ($object_to_cache->ID()) {
645
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
646
+				$this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
647
+				$return = $object_to_cache->ID();
648
+			} else {
649
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
650
+				$this->_model_relations[ $relationName ][] = $object_to_cache;
651
+				// move the internal pointer to the end of the array
652
+				end($this->_model_relations[ $relationName ]);
653
+				// and grab the key so that we can return it
654
+				$return = key($this->_model_relations[ $relationName ]);
655
+			}
656
+		}
657
+		return $return;
658
+	}
659
+
660
+
661
+	/**
662
+	 * For adding an item to the cached_properties property.
663
+	 *
664
+	 * @access protected
665
+	 * @param string      $fieldname the property item the corresponding value is for.
666
+	 * @param mixed       $value     The value we are caching.
667
+	 * @param string|null $cache_type
668
+	 * @return void
669
+	 * @throws ReflectionException
670
+	 * @throws InvalidArgumentException
671
+	 * @throws InvalidInterfaceException
672
+	 * @throws InvalidDataTypeException
673
+	 * @throws EE_Error
674
+	 */
675
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
676
+	{
677
+		// first make sure this property exists
678
+		$this->get_model()->field_settings_for($fieldname);
679
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
680
+		$this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
681
+	}
682
+
683
+
684
+	/**
685
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
686
+	 * This also SETS the cache if we return the actual property!
687
+	 *
688
+	 * @param string $fieldname        the name of the property we're trying to retrieve
689
+	 * @param bool   $pretty
690
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
691
+	 *                                 (in cases where the same property may be used for different outputs
692
+	 *                                 - i.e. datetime, money etc.)
693
+	 *                                 It can also accept certain pre-defined "schema" strings
694
+	 *                                 to define how to output the property.
695
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
696
+	 * @return mixed                   whatever the value for the property is we're retrieving
697
+	 * @throws ReflectionException
698
+	 * @throws InvalidArgumentException
699
+	 * @throws InvalidInterfaceException
700
+	 * @throws InvalidDataTypeException
701
+	 * @throws EE_Error
702
+	 */
703
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
704
+	{
705
+		// verify the field exists
706
+		$model = $this->get_model();
707
+		$model->field_settings_for($fieldname);
708
+		$cache_type = $pretty ? 'pretty' : 'standard';
709
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
710
+		if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
711
+			return $this->_cached_properties[ $fieldname ][ $cache_type ];
712
+		}
713
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
714
+		$this->_set_cached_property($fieldname, $value, $cache_type);
715
+		return $value;
716
+	}
717
+
718
+
719
+	/**
720
+	 * If the cache didn't fetch the needed item, this fetches it.
721
+	 *
722
+	 * @param string $fieldname
723
+	 * @param bool   $pretty
724
+	 * @param string $extra_cache_ref
725
+	 * @return mixed
726
+	 * @throws InvalidArgumentException
727
+	 * @throws InvalidInterfaceException
728
+	 * @throws InvalidDataTypeException
729
+	 * @throws EE_Error
730
+	 * @throws ReflectionException
731
+	 */
732
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
733
+	{
734
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
735
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
736
+		if ($field_obj instanceof EE_Datetime_Field) {
737
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
738
+		}
739
+		if (! isset($this->_fields[ $fieldname ])) {
740
+			$this->_fields[ $fieldname ] = null;
741
+		}
742
+		return $pretty
743
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
744
+			: $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
745
+	}
746
+
747
+
748
+	/**
749
+	 * set timezone, formats, and output for EE_Datetime_Field objects
750
+	 *
751
+	 * @param EE_Datetime_Field $datetime_field
752
+	 * @param bool              $pretty
753
+	 * @param null              $date_or_time
754
+	 * @return void
755
+	 * @throws InvalidArgumentException
756
+	 * @throws InvalidInterfaceException
757
+	 * @throws InvalidDataTypeException
758
+	 */
759
+	protected function _prepare_datetime_field(
760
+		EE_Datetime_Field $datetime_field,
761
+		$pretty = false,
762
+		$date_or_time = null
763
+	) {
764
+		$datetime_field->set_timezone($this->_timezone);
765
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
766
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
767
+		// set the output returned
768
+		switch ($date_or_time) {
769
+			case 'D':
770
+				$datetime_field->set_date_time_output('date');
771
+				break;
772
+			case 'T':
773
+				$datetime_field->set_date_time_output('time');
774
+				break;
775
+			default:
776
+				$datetime_field->set_date_time_output();
777
+		}
778
+	}
779
+
780
+
781
+	/**
782
+	 * This just takes care of clearing out the cached_properties
783
+	 *
784
+	 * @return void
785
+	 */
786
+	protected function _clear_cached_properties()
787
+	{
788
+		$this->_cached_properties = array();
789
+	}
790
+
791
+
792
+	/**
793
+	 * This just clears out ONE property if it exists in the cache
794
+	 *
795
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
796
+	 * @return void
797
+	 */
798
+	protected function _clear_cached_property($property_name)
799
+	{
800
+		if (isset($this->_cached_properties[ $property_name ])) {
801
+			unset($this->_cached_properties[ $property_name ]);
802
+		}
803
+	}
804
+
805
+
806
+	/**
807
+	 * Ensures that this related thing is a model object.
808
+	 *
809
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
810
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
811
+	 * @return EE_Base_Class
812
+	 * @throws ReflectionException
813
+	 * @throws InvalidArgumentException
814
+	 * @throws InvalidInterfaceException
815
+	 * @throws InvalidDataTypeException
816
+	 * @throws EE_Error
817
+	 */
818
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
819
+	{
820
+		$other_model_instance = self::_get_model_instance_with_name(
821
+			self::_get_model_classname($model_name),
822
+			$this->_timezone
823
+		);
824
+		return $other_model_instance->ensure_is_obj($object_or_id);
825
+	}
826
+
827
+
828
+	/**
829
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
830
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
831
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
832
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
833
+	 *
834
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
835
+	 *                                                     Eg 'Registration'
836
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
837
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
838
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
839
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
840
+	 *                                                     this is HasMany or HABTM.
841
+	 * @throws ReflectionException
842
+	 * @throws InvalidArgumentException
843
+	 * @throws InvalidInterfaceException
844
+	 * @throws InvalidDataTypeException
845
+	 * @throws EE_Error
846
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
847
+	 *                                                     relation from all
848
+	 */
849
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
850
+	{
851
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
852
+		$index_in_cache = '';
853
+		if (! $relationship_to_model) {
854
+			throw new EE_Error(
855
+				sprintf(
856
+					esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
857
+					$relationName,
858
+					get_class($this)
859
+				)
860
+			);
861
+		}
862
+		if ($clear_all) {
863
+			$obj_removed = true;
864
+			$this->_model_relations[ $relationName ] = null;
865
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
866
+			$obj_removed = $this->_model_relations[ $relationName ];
867
+			$this->_model_relations[ $relationName ] = null;
868
+		} else {
869
+			if (
870
+				$object_to_remove_or_index_into_array instanceof EE_Base_Class
871
+				&& $object_to_remove_or_index_into_array->ID()
872
+			) {
873
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
874
+				if (
875
+					is_array($this->_model_relations[ $relationName ])
876
+					&& ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
877
+				) {
878
+					$index_found_at = null;
879
+					// find this object in the array even though it has a different key
880
+					foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
881
+						/** @noinspection TypeUnsafeComparisonInspection */
882
+						if (
883
+							$obj instanceof EE_Base_Class
884
+							&& (
885
+								$obj == $object_to_remove_or_index_into_array
886
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
887
+							)
888
+						) {
889
+							$index_found_at = $index;
890
+							break;
891
+						}
892
+					}
893
+					if ($index_found_at) {
894
+						$index_in_cache = $index_found_at;
895
+					} else {
896
+						// it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
897
+						// if it wasn't in it to begin with. So we're done
898
+						return $object_to_remove_or_index_into_array;
899
+					}
900
+				}
901
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
902
+				// so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
903
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
904
+					/** @noinspection TypeUnsafeComparisonInspection */
905
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
906
+						$index_in_cache = $index;
907
+					}
908
+				}
909
+			} else {
910
+				$index_in_cache = $object_to_remove_or_index_into_array;
911
+			}
912
+			// supposedly we've found it. But it could just be that the client code
913
+			// provided a bad index/object
914
+			if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
915
+				$obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
916
+				unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
917
+			} else {
918
+				// that thing was never cached anyways.
919
+				$obj_removed = null;
920
+			}
921
+		}
922
+		return $obj_removed;
923
+	}
924
+
925
+
926
+	/**
927
+	 * update_cache_after_object_save
928
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
929
+	 * obtained after being saved to the db
930
+	 *
931
+	 * @param string        $relationName       - the type of object that is cached
932
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
933
+	 * @param string        $current_cache_id   - the ID that was used when originally caching the object
934
+	 * @return boolean TRUE on success, FALSE on fail
935
+	 * @throws ReflectionException
936
+	 * @throws InvalidArgumentException
937
+	 * @throws InvalidInterfaceException
938
+	 * @throws InvalidDataTypeException
939
+	 * @throws EE_Error
940
+	 */
941
+	public function update_cache_after_object_save(
942
+		$relationName,
943
+		EE_Base_Class $newly_saved_object,
944
+		$current_cache_id = ''
945
+	) {
946
+		// verify that incoming object is of the correct type
947
+		$obj_class = 'EE_' . $relationName;
948
+		if ($newly_saved_object instanceof $obj_class) {
949
+			/* @type EE_Base_Class $newly_saved_object */
950
+			// now get the type of relation
951
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
952
+			// if this is a 1:1 relationship
953
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
954
+				// then just replace the cached object with the newly saved object
955
+				$this->_model_relations[ $relationName ] = $newly_saved_object;
956
+				return true;
957
+				// or if it's some kind of sordid feral polyamorous relationship...
958
+			}
959
+			if (
960
+				is_array($this->_model_relations[ $relationName ])
961
+				&& isset($this->_model_relations[ $relationName ][ $current_cache_id ])
962
+			) {
963
+				// then remove the current cached item
964
+				unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
965
+				// and cache the newly saved object using it's new ID
966
+				$this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
967
+				return true;
968
+			}
969
+		}
970
+		return false;
971
+	}
972
+
973
+
974
+	/**
975
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
976
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
977
+	 *
978
+	 * @param string $relationName
979
+	 * @return EE_Base_Class
980
+	 */
981
+	public function get_one_from_cache($relationName)
982
+	{
983
+		$cached_array_or_object = isset($this->_model_relations[ $relationName ])
984
+			? $this->_model_relations[ $relationName ]
985
+			: null;
986
+		if (is_array($cached_array_or_object)) {
987
+			return array_shift($cached_array_or_object);
988
+		}
989
+		return $cached_array_or_object;
990
+	}
991
+
992
+
993
+	/**
994
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
995
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
996
+	 *
997
+	 * @param string $relationName
998
+	 * @throws ReflectionException
999
+	 * @throws InvalidArgumentException
1000
+	 * @throws InvalidInterfaceException
1001
+	 * @throws InvalidDataTypeException
1002
+	 * @throws EE_Error
1003
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
1004
+	 */
1005
+	public function get_all_from_cache($relationName)
1006
+	{
1007
+		$objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
1008
+		// if the result is not an array, but exists, make it an array
1009
+		$objects = is_array($objects) ? $objects : array($objects);
1010
+		// bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
1011
+		// basically, if this model object was stored in the session, and these cached model objects
1012
+		// already have IDs, let's make sure they're in their model's entity mapper
1013
+		// otherwise we will have duplicates next time we call
1014
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
1015
+		$model = EE_Registry::instance()->load_model($relationName);
1016
+		foreach ($objects as $model_object) {
1017
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
1018
+				// ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
1019
+				if ($model_object->ID()) {
1020
+					$model->add_to_entity_map($model_object);
1021
+				}
1022
+			} else {
1023
+				throw new EE_Error(
1024
+					sprintf(
1025
+						esc_html__(
1026
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
1027
+							'event_espresso'
1028
+						),
1029
+						$relationName,
1030
+						gettype($model_object)
1031
+					)
1032
+				);
1033
+			}
1034
+		}
1035
+		return $objects;
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
1041
+	 * matching the given query conditions.
1042
+	 *
1043
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1044
+	 * @param int   $limit              How many objects to return.
1045
+	 * @param array $query_params       Any additional conditions on the query.
1046
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1047
+	 *                                  you can indicate just the columns you want returned
1048
+	 * @return array|EE_Base_Class[]
1049
+	 * @throws ReflectionException
1050
+	 * @throws InvalidArgumentException
1051
+	 * @throws InvalidInterfaceException
1052
+	 * @throws InvalidDataTypeException
1053
+	 * @throws EE_Error
1054
+	 */
1055
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
1056
+	{
1057
+		$model = $this->get_model();
1058
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1059
+			? $model->get_primary_key_field()->get_name()
1060
+			: $field_to_order_by;
1061
+		$current_value = ! empty($field) ? $this->get($field) : null;
1062
+		if (empty($field) || empty($current_value)) {
1063
+			return array();
1064
+		}
1065
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
1066
+	}
1067
+
1068
+
1069
+	/**
1070
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
1071
+	 * matching the given query conditions.
1072
+	 *
1073
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1074
+	 * @param int   $limit              How many objects to return.
1075
+	 * @param array $query_params       Any additional conditions on the query.
1076
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1077
+	 *                                  you can indicate just the columns you want returned
1078
+	 * @return array|EE_Base_Class[]
1079
+	 * @throws ReflectionException
1080
+	 * @throws InvalidArgumentException
1081
+	 * @throws InvalidInterfaceException
1082
+	 * @throws InvalidDataTypeException
1083
+	 * @throws EE_Error
1084
+	 */
1085
+	public function previous_x(
1086
+		$field_to_order_by = null,
1087
+		$limit = 1,
1088
+		$query_params = array(),
1089
+		$columns_to_select = null
1090
+	) {
1091
+		$model = $this->get_model();
1092
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1093
+			? $model->get_primary_key_field()->get_name()
1094
+			: $field_to_order_by;
1095
+		$current_value = ! empty($field) ? $this->get($field) : null;
1096
+		if (empty($field) || empty($current_value)) {
1097
+			return array();
1098
+		}
1099
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1100
+	}
1101
+
1102
+
1103
+	/**
1104
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1105
+	 * matching the given query conditions.
1106
+	 *
1107
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1108
+	 * @param array $query_params       Any additional conditions on the query.
1109
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1110
+	 *                                  you can indicate just the columns you want returned
1111
+	 * @return array|EE_Base_Class
1112
+	 * @throws ReflectionException
1113
+	 * @throws InvalidArgumentException
1114
+	 * @throws InvalidInterfaceException
1115
+	 * @throws InvalidDataTypeException
1116
+	 * @throws EE_Error
1117
+	 */
1118
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1119
+	{
1120
+		$model = $this->get_model();
1121
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1122
+			? $model->get_primary_key_field()->get_name()
1123
+			: $field_to_order_by;
1124
+		$current_value = ! empty($field) ? $this->get($field) : null;
1125
+		if (empty($field) || empty($current_value)) {
1126
+			return array();
1127
+		}
1128
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1129
+	}
1130
+
1131
+
1132
+	/**
1133
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1134
+	 * matching the given query conditions.
1135
+	 *
1136
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1137
+	 * @param array $query_params       Any additional conditions on the query.
1138
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1139
+	 *                                  you can indicate just the column you want returned
1140
+	 * @return array|EE_Base_Class
1141
+	 * @throws ReflectionException
1142
+	 * @throws InvalidArgumentException
1143
+	 * @throws InvalidInterfaceException
1144
+	 * @throws InvalidDataTypeException
1145
+	 * @throws EE_Error
1146
+	 */
1147
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1148
+	{
1149
+		$model = $this->get_model();
1150
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1151
+			? $model->get_primary_key_field()->get_name()
1152
+			: $field_to_order_by;
1153
+		$current_value = ! empty($field) ? $this->get($field) : null;
1154
+		if (empty($field) || empty($current_value)) {
1155
+			return array();
1156
+		}
1157
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1158
+	}
1159
+
1160
+
1161
+	/**
1162
+	 * verifies that the specified field is of the correct type
1163
+	 *
1164
+	 * @param string $field_name
1165
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1166
+	 *                                (in cases where the same property may be used for different outputs
1167
+	 *                                - i.e. datetime, money etc.)
1168
+	 * @return mixed
1169
+	 * @throws ReflectionException
1170
+	 * @throws InvalidArgumentException
1171
+	 * @throws InvalidInterfaceException
1172
+	 * @throws InvalidDataTypeException
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	public function get($field_name, $extra_cache_ref = null)
1176
+	{
1177
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1183
+	 *
1184
+	 * @param  string $field_name A valid fieldname
1185
+	 * @return mixed              Whatever the raw value stored on the property is.
1186
+	 * @throws ReflectionException
1187
+	 * @throws InvalidArgumentException
1188
+	 * @throws InvalidInterfaceException
1189
+	 * @throws InvalidDataTypeException
1190
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1191
+	 */
1192
+	public function get_raw($field_name)
1193
+	{
1194
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1195
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
+			? $this->_fields[ $field_name ]->format('U')
1197
+			: $this->_fields[ $field_name ];
1198
+	}
1199
+
1200
+
1201
+	/**
1202
+	 * This is used to return the internal DateTime object used for a field that is a
1203
+	 * EE_Datetime_Field.
1204
+	 *
1205
+	 * @param string $field_name               The field name retrieving the DateTime object.
1206
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1207
+	 * @throws EE_Error an error is set and false returned.  If the field IS an
1208
+	 *                                         EE_Datetime_Field and but the field value is null, then
1209
+	 *                                         just null is returned (because that indicates that likely
1210
+	 *                                         this field is nullable).
1211
+	 * @throws InvalidArgumentException
1212
+	 * @throws InvalidDataTypeException
1213
+	 * @throws InvalidInterfaceException
1214
+	 * @throws ReflectionException
1215
+	 */
1216
+	public function get_DateTime_object($field_name)
1217
+	{
1218
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1219
+		if (! $field_settings instanceof EE_Datetime_Field) {
1220
+			EE_Error::add_error(
1221
+				sprintf(
1222
+					esc_html__(
1223
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1224
+						'event_espresso'
1225
+					),
1226
+					$field_name
1227
+				),
1228
+				__FILE__,
1229
+				__FUNCTION__,
1230
+				__LINE__
1231
+			);
1232
+			return false;
1233
+		}
1234
+		return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
+			? clone $this->_fields[ $field_name ]
1236
+			: null;
1237
+	}
1238
+
1239
+
1240
+	/**
1241
+	 * To be used in template to immediately echo out the value, and format it for output.
1242
+	 * Eg, should call stripslashes and whatnot before echoing
1243
+	 *
1244
+	 * @param string $field_name      the name of the field as it appears in the DB
1245
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1246
+	 *                                (in cases where the same property may be used for different outputs
1247
+	 *                                - i.e. datetime, money etc.)
1248
+	 * @return void
1249
+	 * @throws ReflectionException
1250
+	 * @throws InvalidArgumentException
1251
+	 * @throws InvalidInterfaceException
1252
+	 * @throws InvalidDataTypeException
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function e($field_name, $extra_cache_ref = null)
1256
+	{
1257
+		echo wp_kses($this->get_pretty($field_name, $extra_cache_ref), AllowedTags::getWithFormTags());
1258
+	}
1259
+
1260
+
1261
+	/**
1262
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1263
+	 * can be easily used as the value of form input.
1264
+	 *
1265
+	 * @param string $field_name
1266
+	 * @return void
1267
+	 * @throws ReflectionException
1268
+	 * @throws InvalidArgumentException
1269
+	 * @throws InvalidInterfaceException
1270
+	 * @throws InvalidDataTypeException
1271
+	 * @throws EE_Error
1272
+	 */
1273
+	public function f($field_name)
1274
+	{
1275
+		$this->e($field_name, 'form_input');
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * Same as `f()` but just returns the value instead of echoing it
1281
+	 *
1282
+	 * @param string $field_name
1283
+	 * @return string
1284
+	 * @throws ReflectionException
1285
+	 * @throws InvalidArgumentException
1286
+	 * @throws InvalidInterfaceException
1287
+	 * @throws InvalidDataTypeException
1288
+	 * @throws EE_Error
1289
+	 */
1290
+	public function get_f($field_name)
1291
+	{
1292
+		return (string) $this->get_pretty($field_name, 'form_input');
1293
+	}
1294
+
1295
+
1296
+	/**
1297
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1298
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1299
+	 * to see what options are available.
1300
+	 *
1301
+	 * @param string $field_name
1302
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1303
+	 *                                (in cases where the same property may be used for different outputs
1304
+	 *                                - i.e. datetime, money etc.)
1305
+	 * @return mixed
1306
+	 * @throws ReflectionException
1307
+	 * @throws InvalidArgumentException
1308
+	 * @throws InvalidInterfaceException
1309
+	 * @throws InvalidDataTypeException
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	public function get_pretty($field_name, $extra_cache_ref = null)
1313
+	{
1314
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1315
+	}
1316
+
1317
+
1318
+	/**
1319
+	 * This simply returns the datetime for the given field name
1320
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1321
+	 * (and the equivalent e_date, e_time, e_datetime).
1322
+	 *
1323
+	 * @access   protected
1324
+	 * @param string      $field_name   Field on the instantiated EE_Base_Class child object
1325
+	 * @param string|null $date_format  valid datetime format used for date
1326
+	 *                                  (if '' then we just use the default on the field,
1327
+	 *                                  if NULL we use the last-used format)
1328
+	 * @param string|null $time_format  Same as above except this is for time format
1329
+	 * @param string|null $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1330
+	 * @param bool|null   $echo         Whether the datetime is pretty echoing or just returned using vanilla get
1331
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1332
+	 *                                  if field is not a valid dtt field, or void if echoing
1333
+	 * @throws EE_Error
1334
+	 * @throws ReflectionException
1335
+	 */
1336
+	protected function _get_datetime(
1337
+		string $field_name,
1338
+		?string $date_format = '',
1339
+		?string $time_format = '',
1340
+		?string $date_or_time = '',
1341
+		?bool $echo = false
1342
+	) {
1343
+		// clear cached property
1344
+		$this->_clear_cached_property($field_name);
1345
+		// reset format properties because they are used in get()
1346
+		$this->_dt_frmt = $date_format ?: $this->_dt_frmt;
1347
+		$this->_tm_frmt = $time_format ?: $this->_tm_frmt;
1348
+		if ($echo) {
1349
+			$this->e($field_name, $date_or_time);
1350
+			return '';
1351
+		}
1352
+		return $this->get($field_name, $date_or_time);
1353
+	}
1354
+
1355
+
1356
+	/**
1357
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1358
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1359
+	 * other echoes the pretty value for dtt)
1360
+	 *
1361
+	 * @param  string $field_name name of model object datetime field holding the value
1362
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1363
+	 * @return string            datetime value formatted
1364
+	 * @throws ReflectionException
1365
+	 * @throws InvalidArgumentException
1366
+	 * @throws InvalidInterfaceException
1367
+	 * @throws InvalidDataTypeException
1368
+	 * @throws EE_Error
1369
+	 */
1370
+	public function get_date($field_name, $format = '')
1371
+	{
1372
+		return $this->_get_datetime($field_name, $format, null, 'D');
1373
+	}
1374
+
1375
+
1376
+	/**
1377
+	 * @param        $field_name
1378
+	 * @param string $format
1379
+	 * @throws ReflectionException
1380
+	 * @throws InvalidArgumentException
1381
+	 * @throws InvalidInterfaceException
1382
+	 * @throws InvalidDataTypeException
1383
+	 * @throws EE_Error
1384
+	 */
1385
+	public function e_date($field_name, $format = '')
1386
+	{
1387
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1388
+	}
1389
+
1390
+
1391
+	/**
1392
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1393
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1394
+	 * other echoes the pretty value for dtt)
1395
+	 *
1396
+	 * @param  string $field_name name of model object datetime field holding the value
1397
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1398
+	 * @return string             datetime value formatted
1399
+	 * @throws ReflectionException
1400
+	 * @throws InvalidArgumentException
1401
+	 * @throws InvalidInterfaceException
1402
+	 * @throws InvalidDataTypeException
1403
+	 * @throws EE_Error
1404
+	 */
1405
+	public function get_time($field_name, $format = '')
1406
+	{
1407
+		return $this->_get_datetime($field_name, null, $format, 'T');
1408
+	}
1409
+
1410
+
1411
+	/**
1412
+	 * @param        $field_name
1413
+	 * @param string $format
1414
+	 * @throws ReflectionException
1415
+	 * @throws InvalidArgumentException
1416
+	 * @throws InvalidInterfaceException
1417
+	 * @throws InvalidDataTypeException
1418
+	 * @throws EE_Error
1419
+	 */
1420
+	public function e_time($field_name, $format = '')
1421
+	{
1422
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1423
+	}
1424
+
1425
+
1426
+	/**
1427
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1428
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1429
+	 * other echoes the pretty value for dtt)
1430
+	 *
1431
+	 * @param  string $field_name name of model object datetime field holding the value
1432
+	 * @param  string $date_format    format for the date returned (if NULL we use default in dt_frmt property)
1433
+	 * @param  string $time_format    format for the time returned (if NULL we use default in tm_frmt property)
1434
+	 * @return string             datetime value formatted
1435
+	 * @throws ReflectionException
1436
+	 * @throws InvalidArgumentException
1437
+	 * @throws InvalidInterfaceException
1438
+	 * @throws InvalidDataTypeException
1439
+	 * @throws EE_Error
1440
+	 */
1441
+	public function get_datetime($field_name, $date_format = '', $time_format = '')
1442
+	{
1443
+		return $this->_get_datetime($field_name, $date_format, $time_format);
1444
+	}
1445
+
1446
+
1447
+	/**
1448
+	 * @param string $field_name
1449
+	 * @param string $date_format
1450
+	 * @param string $time_format
1451
+	 * @throws ReflectionException
1452
+	 * @throws InvalidArgumentException
1453
+	 * @throws InvalidInterfaceException
1454
+	 * @throws InvalidDataTypeException
1455
+	 * @throws EE_Error
1456
+	 */
1457
+	public function e_datetime($field_name, $date_format = '', $time_format = '')
1458
+	{
1459
+		$this->_get_datetime($field_name, $date_format, $time_format, null, true);
1460
+	}
1461
+
1462
+
1463
+	/**
1464
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1465
+	 *
1466
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1467
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1468
+	 *                           on the object will be used.
1469
+	 * @return string Date and time string in set locale or false if no field exists for the given
1470
+	 * @throws ReflectionException
1471
+	 * @throws InvalidArgumentException
1472
+	 * @throws InvalidInterfaceException
1473
+	 * @throws InvalidDataTypeException
1474
+	 * @throws EE_Error
1475
+	 *                           field name.
1476
+	 */
1477
+	public function get_i18n_datetime($field_name, $format = '')
1478
+	{
1479
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1480
+		return date_i18n(
1481
+			$format,
1482
+			EEH_DTT_Helper::get_timestamp_with_offset(
1483
+				$this->get_raw($field_name),
1484
+				$this->_timezone
1485
+			)
1486
+		);
1487
+	}
1488
+
1489
+
1490
+	/**
1491
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1492
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1493
+	 * thrown.
1494
+	 *
1495
+	 * @param  string $field_name The field name being checked
1496
+	 * @throws ReflectionException
1497
+	 * @throws InvalidArgumentException
1498
+	 * @throws InvalidInterfaceException
1499
+	 * @throws InvalidDataTypeException
1500
+	 * @throws EE_Error
1501
+	 * @return EE_Datetime_Field
1502
+	 */
1503
+	protected function _get_dtt_field_settings($field_name)
1504
+	{
1505
+		$field = $this->get_model()->field_settings_for($field_name);
1506
+		// check if field is dtt
1507
+		if ($field instanceof EE_Datetime_Field) {
1508
+			return $field;
1509
+		}
1510
+		throw new EE_Error(
1511
+			sprintf(
1512
+				esc_html__(
1513
+					'The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1514
+					'event_espresso'
1515
+				),
1516
+				$field_name,
1517
+				self::_get_model_classname(get_class($this))
1518
+			)
1519
+		);
1520
+	}
1521
+
1522
+
1523
+
1524
+
1525
+	/**
1526
+	 * NOTE ABOUT BELOW:
1527
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1528
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1529
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1530
+	 * method and make sure you send the entire datetime value for setting.
1531
+	 */
1532
+	/**
1533
+	 * sets the time on a datetime property
1534
+	 *
1535
+	 * @access protected
1536
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1537
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1538
+	 * @throws ReflectionException
1539
+	 * @throws InvalidArgumentException
1540
+	 * @throws InvalidInterfaceException
1541
+	 * @throws InvalidDataTypeException
1542
+	 * @throws EE_Error
1543
+	 */
1544
+	protected function _set_time_for($time, $fieldname)
1545
+	{
1546
+		$this->_set_date_time('T', $time, $fieldname);
1547
+	}
1548
+
1549
+
1550
+	/**
1551
+	 * sets the date on a datetime property
1552
+	 *
1553
+	 * @access protected
1554
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1555
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1556
+	 * @throws ReflectionException
1557
+	 * @throws InvalidArgumentException
1558
+	 * @throws InvalidInterfaceException
1559
+	 * @throws InvalidDataTypeException
1560
+	 * @throws EE_Error
1561
+	 */
1562
+	protected function _set_date_for($date, $fieldname)
1563
+	{
1564
+		$this->_set_date_time('D', $date, $fieldname);
1565
+	}
1566
+
1567
+
1568
+	/**
1569
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1570
+	 * verifies that the given field_name matches a model object property and is for a EE_Datetime_Field field
1571
+	 *
1572
+	 * @access protected
1573
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1574
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1575
+	 * @param string          $field_name     the name of the field the date OR time is being set on (must match a
1576
+	 *                                        EE_Datetime_Field property)
1577
+	 * @throws ReflectionException
1578
+	 * @throws InvalidArgumentException
1579
+	 * @throws InvalidInterfaceException
1580
+	 * @throws InvalidDataTypeException
1581
+	 * @throws EE_Error
1582
+	 */
1583
+	protected function _set_date_time(string $what, $datetime_value, string $field_name)
1584
+	{
1585
+		$field = $this->_get_dtt_field_settings($field_name);
1586
+		$field->set_timezone($this->_timezone);
1587
+		$field->set_date_format($this->_dt_frmt);
1588
+		$field->set_time_format($this->_tm_frmt);
1589
+		switch ($what) {
1590
+			case 'T':
1591
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1592
+					$datetime_value,
1593
+					$this->_fields[ $field_name ]
1594
+				);
1595
+				$this->_has_changes = true;
1596
+				break;
1597
+			case 'D':
1598
+				$this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1599
+					$datetime_value,
1600
+					$this->_fields[ $field_name ]
1601
+				);
1602
+				$this->_has_changes = true;
1603
+				break;
1604
+			case 'B':
1605
+				$this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1606
+				$this->_has_changes = true;
1607
+				break;
1608
+		}
1609
+		$this->_clear_cached_property($field_name);
1610
+	}
1611
+
1612
+
1613
+	/**
1614
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1615
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1616
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1617
+	 * that could lead to some unexpected results!
1618
+	 *
1619
+	 * @access public
1620
+	 * @param string $field_name               This is the name of the field on the object that contains the date/time
1621
+	 *                                         value being returned.
1622
+	 * @param string $callback                 must match a valid method in this class (defaults to get_datetime)
1623
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1624
+	 * @param string $prepend                  You can include something to prepend on the timestamp
1625
+	 * @param string $append                   You can include something to append on the timestamp
1626
+	 * @throws ReflectionException
1627
+	 * @throws InvalidArgumentException
1628
+	 * @throws InvalidInterfaceException
1629
+	 * @throws InvalidDataTypeException
1630
+	 * @throws EE_Error
1631
+	 * @return string timestamp
1632
+	 */
1633
+	public function display_in_my_timezone(
1634
+		$field_name,
1635
+		$callback = 'get_datetime',
1636
+		$args = null,
1637
+		$prepend = '',
1638
+		$append = ''
1639
+	) {
1640
+		$timezone = EEH_DTT_Helper::get_timezone();
1641
+		if ($timezone === $this->_timezone) {
1642
+			return '';
1643
+		}
1644
+		$original_timezone = $this->_timezone;
1645
+		$this->set_timezone($timezone);
1646
+		$fn = (array) $field_name;
1647
+		$args = array_merge($fn, (array) $args);
1648
+		if (! method_exists($this, $callback)) {
1649
+			throw new EE_Error(
1650
+				sprintf(
1651
+					esc_html__(
1652
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1653
+						'event_espresso'
1654
+					),
1655
+					$callback
1656
+				)
1657
+			);
1658
+		}
1659
+		$args = (array) $args;
1660
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1661
+		$this->set_timezone($original_timezone);
1662
+		return $return;
1663
+	}
1664
+
1665
+
1666
+	/**
1667
+	 * Deletes this model object.
1668
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1669
+	 * override
1670
+	 * `EE_Base_Class::_delete` NOT this class.
1671
+	 *
1672
+	 * @return boolean | int
1673
+	 * @throws ReflectionException
1674
+	 * @throws InvalidArgumentException
1675
+	 * @throws InvalidInterfaceException
1676
+	 * @throws InvalidDataTypeException
1677
+	 * @throws EE_Error
1678
+	 */
1679
+	public function delete()
1680
+	{
1681
+		/**
1682
+		 * Called just before the `EE_Base_Class::_delete` method call.
1683
+		 * Note:
1684
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1685
+		 * should be aware that `_delete` may not always result in a permanent delete.
1686
+		 * For example, `EE_Soft_Delete_Base_Class::_delete`
1687
+		 * soft deletes (trash) the object and does not permanently delete it.
1688
+		 *
1689
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1690
+		 */
1691
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1692
+		$result = $this->_delete();
1693
+		/**
1694
+		 * Called just after the `EE_Base_Class::_delete` method call.
1695
+		 * Note:
1696
+		 * `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1697
+		 * should be aware that `_delete` may not always result in a permanent delete.
1698
+		 * For example `EE_Soft_Base_Class::_delete`
1699
+		 * soft deletes (trash) the object and does not permanently delete it.
1700
+		 *
1701
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1702
+		 * @param boolean       $result
1703
+		 */
1704
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1705
+		return $result;
1706
+	}
1707
+
1708
+
1709
+	/**
1710
+	 * Calls the specific delete method for the instantiated class.
1711
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1712
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1713
+	 * `EE_Base_Class::delete`
1714
+	 *
1715
+	 * @return bool|int
1716
+	 * @throws ReflectionException
1717
+	 * @throws InvalidArgumentException
1718
+	 * @throws InvalidInterfaceException
1719
+	 * @throws InvalidDataTypeException
1720
+	 * @throws EE_Error
1721
+	 */
1722
+	protected function _delete()
1723
+	{
1724
+		return $this->delete_permanently();
1725
+	}
1726
+
1727
+
1728
+	/**
1729
+	 * Deletes this model object permanently from db
1730
+	 * (but keep in mind related models may block the delete and return an error)
1731
+	 *
1732
+	 * @return bool | int
1733
+	 * @throws ReflectionException
1734
+	 * @throws InvalidArgumentException
1735
+	 * @throws InvalidInterfaceException
1736
+	 * @throws InvalidDataTypeException
1737
+	 * @throws EE_Error
1738
+	 */
1739
+	public function delete_permanently()
1740
+	{
1741
+		/**
1742
+		 * Called just before HARD deleting a model object
1743
+		 *
1744
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1745
+		 */
1746
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1747
+		$model = $this->get_model();
1748
+		$result = $model->delete_permanently_by_ID($this->ID());
1749
+		$this->refresh_cache_of_related_objects();
1750
+		/**
1751
+		 * Called just after HARD deleting a model object
1752
+		 *
1753
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1754
+		 * @param boolean       $result
1755
+		 */
1756
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1757
+		return $result;
1758
+	}
1759
+
1760
+
1761
+	/**
1762
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1763
+	 * related model objects
1764
+	 *
1765
+	 * @throws ReflectionException
1766
+	 * @throws InvalidArgumentException
1767
+	 * @throws InvalidInterfaceException
1768
+	 * @throws InvalidDataTypeException
1769
+	 * @throws EE_Error
1770
+	 */
1771
+	public function refresh_cache_of_related_objects()
1772
+	{
1773
+		$model = $this->get_model();
1774
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1775
+			if (! empty($this->_model_relations[ $relation_name ])) {
1776
+				$related_objects = $this->_model_relations[ $relation_name ];
1777
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1778
+					// this relation only stores a single model object, not an array
1779
+					// but let's make it consistent
1780
+					$related_objects = array($related_objects);
1781
+				}
1782
+				foreach ($related_objects as $related_object) {
1783
+					// only refresh their cache if they're in memory
1784
+					if ($related_object instanceof EE_Base_Class) {
1785
+						$related_object->clear_cache(
1786
+							$model->get_this_model_name(),
1787
+							$this
1788
+						);
1789
+					}
1790
+				}
1791
+			}
1792
+		}
1793
+	}
1794
+
1795
+
1796
+	/**
1797
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1798
+	 * object just before saving.
1799
+	 *
1800
+	 * @access public
1801
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1802
+	 *                                 if provided during the save() method (often client code will change the fields'
1803
+	 *                                 values before calling save)
1804
+	 * @return bool|int|string         1 on a successful update
1805
+	 *                                 the ID of the new entry on insert
1806
+	 *                                 0 on failure or if the model object isn't allowed to persist
1807
+	 *                                 (as determined by EE_Base_Class::allow_persist())
1808
+	 * @throws InvalidInterfaceException
1809
+	 * @throws InvalidDataTypeException
1810
+	 * @throws EE_Error
1811
+	 * @throws InvalidArgumentException
1812
+	 * @throws ReflectionException
1813
+	 * @throws ReflectionException
1814
+	 * @throws ReflectionException
1815
+	 */
1816
+	public function save($set_cols_n_values = array())
1817
+	{
1818
+		$model = $this->get_model();
1819
+		/**
1820
+		 * Filters the fields we're about to save on the model object
1821
+		 *
1822
+		 * @param array         $set_cols_n_values
1823
+		 * @param EE_Base_Class $model_object
1824
+		 */
1825
+		$set_cols_n_values = (array) apply_filters(
1826
+			'FHEE__EE_Base_Class__save__set_cols_n_values',
1827
+			$set_cols_n_values,
1828
+			$this
1829
+		);
1830
+		// set attributes as provided in $set_cols_n_values
1831
+		foreach ($set_cols_n_values as $column => $value) {
1832
+			$this->set($column, $value);
1833
+		}
1834
+		// no changes ? then don't do anything
1835
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1836
+			return 0;
1837
+		}
1838
+		/**
1839
+		 * Saving a model object.
1840
+		 * Before we perform a save, this action is fired.
1841
+		 *
1842
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1843
+		 */
1844
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1845
+		if (! $this->allow_persist()) {
1846
+			return 0;
1847
+		}
1848
+		// now get current attribute values
1849
+		$save_cols_n_values = $this->_fields;
1850
+		// if the object already has an ID, update it. Otherwise, insert it
1851
+		// also: change the assumption about values passed to the model NOT being prepare dby the model object.
1852
+		// They have been
1853
+		$old_assumption_concerning_value_preparation = $model
1854
+			->get_assumption_concerning_values_already_prepared_by_model_object();
1855
+		$model->assume_values_already_prepared_by_model_object(true);
1856
+		// does this model have an autoincrement PK?
1857
+		if ($model->has_primary_key_field()) {
1858
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1859
+				// ok check if it's set, if so: update; if not, insert
1860
+				if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1861
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1862
+				} else {
1863
+					unset($save_cols_n_values[ $model->primary_key_name() ]);
1864
+					$results = $model->insert($save_cols_n_values);
1865
+					if ($results) {
1866
+						// if successful, set the primary key
1867
+						// but don't use the normal SET method, because it will check if
1868
+						// an item with the same ID exists in the mapper & db, then
1869
+						// will find it in the db (because we just added it) and THAT object
1870
+						// will get added to the mapper before we can add this one!
1871
+						// but if we just avoid using the SET method, all that headache can be avoided
1872
+						$pk_field_name = $model->primary_key_name();
1873
+						$this->_fields[ $pk_field_name ] = $results;
1874
+						$this->_clear_cached_property($pk_field_name);
1875
+						$model->add_to_entity_map($this);
1876
+						$this->_update_cached_related_model_objs_fks();
1877
+					}
1878
+				}
1879
+			} else {// PK is NOT auto-increment
1880
+				// so check if one like it already exists in the db
1881
+				if ($model->exists_by_ID($this->ID())) {
1882
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1883
+						throw new EE_Error(
1884
+							sprintf(
1885
+								esc_html__(
1886
+									'Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1887
+									'event_espresso'
1888
+								),
1889
+								get_class($this),
1890
+								get_class($model) . '::instance()->add_to_entity_map()',
1891
+								get_class($model) . '::instance()->get_one_by_ID()',
1892
+								'<br />'
1893
+							)
1894
+						);
1895
+					}
1896
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1897
+				} else {
1898
+					$results = $model->insert($save_cols_n_values);
1899
+					$this->_update_cached_related_model_objs_fks();
1900
+				}
1901
+			}
1902
+		} else {// there is NO primary key
1903
+			$already_in_db = false;
1904
+			foreach ($model->unique_indexes() as $index) {
1905
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1906
+				if ($model->exists(array($uniqueness_where_params))) {
1907
+					$already_in_db = true;
1908
+				}
1909
+			}
1910
+			if ($already_in_db) {
1911
+				$combined_pk_fields_n_values = array_intersect_key(
1912
+					$save_cols_n_values,
1913
+					$model->get_combined_primary_key_fields()
1914
+				);
1915
+				$results = $model->update(
1916
+					$save_cols_n_values,
1917
+					$combined_pk_fields_n_values
1918
+				);
1919
+			} else {
1920
+				$results = $model->insert($save_cols_n_values);
1921
+			}
1922
+		}
1923
+		// restore the old assumption about values being prepared by the model object
1924
+		$model->assume_values_already_prepared_by_model_object(
1925
+			$old_assumption_concerning_value_preparation
1926
+		);
1927
+		/**
1928
+		 * After saving the model object this action is called
1929
+		 *
1930
+		 * @param EE_Base_Class $model_object which was just saved
1931
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1932
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1933
+		 */
1934
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1935
+		$this->_has_changes = false;
1936
+		return $results;
1937
+	}
1938
+
1939
+
1940
+	/**
1941
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1942
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1943
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1944
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1945
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1946
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1947
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1948
+	 *
1949
+	 * @return void
1950
+	 * @throws ReflectionException
1951
+	 * @throws InvalidArgumentException
1952
+	 * @throws InvalidInterfaceException
1953
+	 * @throws InvalidDataTypeException
1954
+	 * @throws EE_Error
1955
+	 */
1956
+	protected function _update_cached_related_model_objs_fks()
1957
+	{
1958
+		$model = $this->get_model();
1959
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1960
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1961
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1962
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1963
+						$model->get_this_model_name()
1964
+					);
1965
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1966
+					if ($related_model_obj_in_cache->ID()) {
1967
+						$related_model_obj_in_cache->save();
1968
+					}
1969
+				}
1970
+			}
1971
+		}
1972
+	}
1973
+
1974
+
1975
+	/**
1976
+	 * Saves this model object and its NEW cached relations to the database.
1977
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1978
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1979
+	 * because otherwise, there's a potential for infinite looping of saving
1980
+	 * Saves the cached related model objects, and ensures the relation between them
1981
+	 * and this object and properly setup
1982
+	 *
1983
+	 * @return int ID of new model object on save; 0 on failure+
1984
+	 * @throws ReflectionException
1985
+	 * @throws InvalidArgumentException
1986
+	 * @throws InvalidInterfaceException
1987
+	 * @throws InvalidDataTypeException
1988
+	 * @throws EE_Error
1989
+	 */
1990
+	public function save_new_cached_related_model_objs()
1991
+	{
1992
+		// make sure this has been saved
1993
+		if (! $this->ID()) {
1994
+			$id = $this->save();
1995
+		} else {
1996
+			$id = $this->ID();
1997
+		}
1998
+		// now save all the NEW cached model objects  (ie they don't exist in the DB)
1999
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
2000
+			if ($this->_model_relations[ $relationName ]) {
2001
+				// is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2002
+				// or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2003
+				/* @var $related_model_obj EE_Base_Class */
2004
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
2005
+					// add a relation to that relation type (which saves the appropriate thing in the process)
2006
+					// but ONLY if it DOES NOT exist in the DB
2007
+					$related_model_obj = $this->_model_relations[ $relationName ];
2008
+					// if( ! $related_model_obj->ID()){
2009
+					$this->_add_relation_to($related_model_obj, $relationName);
2010
+					$related_model_obj->save_new_cached_related_model_objs();
2011
+					// }
2012
+				} else {
2013
+					foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2014
+						// add a relation to that relation type (which saves the appropriate thing in the process)
2015
+						// but ONLY if it DOES NOT exist in the DB
2016
+						// if( ! $related_model_obj->ID()){
2017
+						$this->_add_relation_to($related_model_obj, $relationName);
2018
+						$related_model_obj->save_new_cached_related_model_objs();
2019
+						// }
2020
+					}
2021
+				}
2022
+			}
2023
+		}
2024
+		return $id;
2025
+	}
2026
+
2027
+
2028
+	/**
2029
+	 * for getting a model while instantiated.
2030
+	 *
2031
+	 * @return EEM_Base | EEM_CPT_Base
2032
+	 * @throws ReflectionException
2033
+	 * @throws InvalidArgumentException
2034
+	 * @throws InvalidInterfaceException
2035
+	 * @throws InvalidDataTypeException
2036
+	 * @throws EE_Error
2037
+	 */
2038
+	public function get_model()
2039
+	{
2040
+		if (! $this->_model) {
2041
+			$modelName = self::_get_model_classname(get_class($this));
2042
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2043
+		} else {
2044
+			$this->_model->set_timezone($this->_timezone);
2045
+		}
2046
+		return $this->_model;
2047
+	}
2048
+
2049
+
2050
+	/**
2051
+	 * @param $props_n_values
2052
+	 * @param $classname
2053
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
2054
+	 * @throws ReflectionException
2055
+	 * @throws InvalidArgumentException
2056
+	 * @throws InvalidInterfaceException
2057
+	 * @throws InvalidDataTypeException
2058
+	 * @throws EE_Error
2059
+	 */
2060
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
2061
+	{
2062
+		// TODO: will not work for Term_Relationships because they have no PK!
2063
+		$primary_id_ref = self::_get_primary_key_name($classname);
2064
+		if (
2065
+			array_key_exists($primary_id_ref, $props_n_values)
2066
+			&& ! empty($props_n_values[ $primary_id_ref ])
2067
+		) {
2068
+			$id = $props_n_values[ $primary_id_ref ];
2069
+			return self::_get_model($classname)->get_from_entity_map($id);
2070
+		}
2071
+		return false;
2072
+	}
2073
+
2074
+
2075
+	/**
2076
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
2077
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
2078
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
2079
+	 * we return false.
2080
+	 *
2081
+	 * @param  array  $props_n_values   incoming array of properties and their values
2082
+	 * @param  string $classname        the classname of the child class
2083
+	 * @param null    $timezone
2084
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
2085
+	 *                                  date_format and the second value is the time format
2086
+	 * @return mixed (EE_Base_Class|bool)
2087
+	 * @throws InvalidArgumentException
2088
+	 * @throws InvalidInterfaceException
2089
+	 * @throws InvalidDataTypeException
2090
+	 * @throws EE_Error
2091
+	 * @throws ReflectionException
2092
+	 * @throws ReflectionException
2093
+	 * @throws ReflectionException
2094
+	 */
2095
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
2096
+	{
2097
+		$existing = null;
2098
+		$model = self::_get_model($classname, $timezone);
2099
+		if ($model->has_primary_key_field()) {
2100
+			$primary_id_ref = self::_get_primary_key_name($classname);
2101
+			if (
2102
+				array_key_exists($primary_id_ref, $props_n_values)
2103
+				&& ! empty($props_n_values[ $primary_id_ref ])
2104
+			) {
2105
+				$existing = $model->get_one_by_ID(
2106
+					$props_n_values[ $primary_id_ref ]
2107
+				);
2108
+			}
2109
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
2110
+			// no primary key on this model, but there's still a matching item in the DB
2111
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
2112
+				self::_get_model($classname, $timezone)
2113
+					->get_index_primary_key_string($props_n_values)
2114
+			);
2115
+		}
2116
+		if ($existing) {
2117
+			// set date formats if present before setting values
2118
+			if (! empty($date_formats) && is_array($date_formats)) {
2119
+				$existing->set_date_format($date_formats[0]);
2120
+				$existing->set_time_format($date_formats[1]);
2121
+			} else {
2122
+				// set default formats for date and time
2123
+				$existing->set_date_format(get_option('date_format'));
2124
+				$existing->set_time_format(get_option('time_format'));
2125
+			}
2126
+			foreach ($props_n_values as $property => $field_value) {
2127
+				$existing->set($property, $field_value);
2128
+			}
2129
+			return $existing;
2130
+		}
2131
+		return false;
2132
+	}
2133
+
2134
+
2135
+	/**
2136
+	 * Gets the EEM_*_Model for this class
2137
+	 *
2138
+	 * @access public now, as this is more convenient
2139
+	 * @param      $classname
2140
+	 * @param null $timezone
2141
+	 * @throws ReflectionException
2142
+	 * @throws InvalidArgumentException
2143
+	 * @throws InvalidInterfaceException
2144
+	 * @throws InvalidDataTypeException
2145
+	 * @throws EE_Error
2146
+	 * @return EEM_Base
2147
+	 */
2148
+	protected static function _get_model($classname, $timezone = null)
2149
+	{
2150
+		// find model for this class
2151
+		if (! $classname) {
2152
+			throw new EE_Error(
2153
+				sprintf(
2154
+					esc_html__(
2155
+						'What were you thinking calling _get_model(%s)?? You need to specify the class name',
2156
+						'event_espresso'
2157
+					),
2158
+					$classname
2159
+				)
2160
+			);
2161
+		}
2162
+		$modelName = self::_get_model_classname($classname);
2163
+		return self::_get_model_instance_with_name($modelName, $timezone);
2164
+	}
2165
+
2166
+
2167
+	/**
2168
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
2169
+	 *
2170
+	 * @param string $model_classname
2171
+	 * @param null   $timezone
2172
+	 * @return EEM_Base
2173
+	 * @throws ReflectionException
2174
+	 * @throws InvalidArgumentException
2175
+	 * @throws InvalidInterfaceException
2176
+	 * @throws InvalidDataTypeException
2177
+	 * @throws EE_Error
2178
+	 */
2179
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
2180
+	{
2181
+		$model_classname = str_replace('EEM_', '', $model_classname);
2182
+		$model = EE_Registry::instance()->load_model($model_classname);
2183
+		$model->set_timezone($timezone);
2184
+		return $model;
2185
+	}
2186
+
2187
+
2188
+	/**
2189
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2190
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2191
+	 *
2192
+	 * @param string|null $model_name
2193
+	 * @return string like EEM_Attendee
2194
+	 */
2195
+	private static function _get_model_classname($model_name = '')
2196
+	{
2197
+		return strpos((string) $model_name, 'EE_') === 0
2198
+			? str_replace('EE_', 'EEM_', $model_name)
2199
+			: 'EEM_' . $model_name;
2200
+	}
2201
+
2202
+
2203
+	/**
2204
+	 * returns the name of the primary key attribute
2205
+	 *
2206
+	 * @param null $classname
2207
+	 * @throws ReflectionException
2208
+	 * @throws InvalidArgumentException
2209
+	 * @throws InvalidInterfaceException
2210
+	 * @throws InvalidDataTypeException
2211
+	 * @throws EE_Error
2212
+	 * @return string
2213
+	 */
2214
+	protected static function _get_primary_key_name($classname = null)
2215
+	{
2216
+		if (! $classname) {
2217
+			throw new EE_Error(
2218
+				sprintf(
2219
+					esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
2220
+					$classname
2221
+				)
2222
+			);
2223
+		}
2224
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2225
+	}
2226
+
2227
+
2228
+	/**
2229
+	 * Gets the value of the primary key.
2230
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2231
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2232
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2233
+	 *
2234
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2235
+	 * @throws ReflectionException
2236
+	 * @throws InvalidArgumentException
2237
+	 * @throws InvalidInterfaceException
2238
+	 * @throws InvalidDataTypeException
2239
+	 * @throws EE_Error
2240
+	 */
2241
+	public function ID()
2242
+	{
2243
+		$model = $this->get_model();
2244
+		// now that we know the name of the variable, use a variable variable to get its value and return its
2245
+		if ($model->has_primary_key_field()) {
2246
+			return $this->_fields[ $model->primary_key_name() ];
2247
+		}
2248
+		return $model->get_index_primary_key_string($this->_fields);
2249
+	}
2250
+
2251
+
2252
+	/**
2253
+	 * @param EE_Base_Class|int|string $otherModelObjectOrID
2254
+	 * @param string                   $relationName
2255
+	 * @return bool
2256
+	 * @throws EE_Error
2257
+	 * @throws ReflectionException
2258
+	 * @since   5.0.0.p
2259
+	 */
2260
+	public function hasRelation($otherModelObjectOrID, string $relationName): bool
2261
+	{
2262
+		$other_model = self::_get_model_instance_with_name(
2263
+			self::_get_model_classname($relationName),
2264
+			$this->_timezone
2265
+		);
2266
+		$primary_key = $other_model->primary_key_name();
2267
+		/** @var EE_Base_Class $otherModelObject */
2268
+		$otherModelObject = $other_model->ensure_is_obj($otherModelObjectOrID, $relationName);
2269
+		return $this->count_related($relationName, [[$primary_key => $otherModelObject->ID()]]) > 0;
2270
+	}
2271
+
2272
+
2273
+	/**
2274
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2275
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2276
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2277
+	 *
2278
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2279
+	 * @param string $relationName                     eg 'Events','Question',etc.
2280
+	 *                                                 an attendee to a group, you also want to specify which role they
2281
+	 *                                                 will have in that group. So you would use this parameter to
2282
+	 *                                                 specify array('role-column-name'=>'role-id')
2283
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2284
+	 *                                                 allow you to further constrict the relation to being added.
2285
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2286
+	 *                                                 column on the JOIN table and currently only the HABTM models
2287
+	 *                                                 accept these additional conditions.  Also remember that if an
2288
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2289
+	 *                                                 NEW row is created in the join table.
2290
+	 * @param null   $cache_id
2291
+	 * @throws ReflectionException
2292
+	 * @throws InvalidArgumentException
2293
+	 * @throws InvalidInterfaceException
2294
+	 * @throws InvalidDataTypeException
2295
+	 * @throws EE_Error
2296
+	 * @return EE_Base_Class the object the relation was added to
2297
+	 */
2298
+	public function _add_relation_to(
2299
+		$otherObjectModelObjectOrID,
2300
+		$relationName,
2301
+		$extra_join_model_fields_n_values = array(),
2302
+		$cache_id = null
2303
+	) {
2304
+		$model = $this->get_model();
2305
+		// if this thing exists in the DB, save the relation to the DB
2306
+		if ($this->ID()) {
2307
+			$otherObject = $model->add_relationship_to(
2308
+				$this,
2309
+				$otherObjectModelObjectOrID,
2310
+				$relationName,
2311
+				$extra_join_model_fields_n_values
2312
+			);
2313
+			// clear cache so future get_many_related and get_first_related() return new results.
2314
+			$this->clear_cache($relationName, $otherObject, true);
2315
+			if ($otherObject instanceof EE_Base_Class) {
2316
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2317
+			}
2318
+		} else {
2319
+			// this thing doesn't exist in the DB,  so just cache it
2320
+			if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2321
+				throw new EE_Error(
2322
+					sprintf(
2323
+						esc_html__(
2324
+							'Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2325
+							'event_espresso'
2326
+						),
2327
+						$otherObjectModelObjectOrID,
2328
+						get_class($this)
2329
+					)
2330
+				);
2331
+			}
2332
+			$otherObject = $otherObjectModelObjectOrID;
2333
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2334
+		}
2335
+		if ($otherObject instanceof EE_Base_Class) {
2336
+			// fix the reciprocal relation too
2337
+			if ($otherObject->ID()) {
2338
+				// its saved so assumed relations exist in the DB, so we can just
2339
+				// clear the cache so future queries use the updated info in the DB
2340
+				$otherObject->clear_cache(
2341
+					$model->get_this_model_name(),
2342
+					null,
2343
+					true
2344
+				);
2345
+			} else {
2346
+				// it's not saved, so it caches relations like this
2347
+				$otherObject->cache($model->get_this_model_name(), $this);
2348
+			}
2349
+		}
2350
+		return $otherObject;
2351
+	}
2352
+
2353
+
2354
+	/**
2355
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2356
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2357
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2358
+	 * from the cache
2359
+	 *
2360
+	 * @param mixed  $otherObjectModelObjectOrID
2361
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2362
+	 *                to the DB yet
2363
+	 * @param string $relationName
2364
+	 * @param array  $where_query
2365
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2366
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2367
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2368
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then no row is
2369
+	 *                deleted.
2370
+	 * @return EE_Base_Class the relation was removed from
2371
+	 * @throws ReflectionException
2372
+	 * @throws InvalidArgumentException
2373
+	 * @throws InvalidInterfaceException
2374
+	 * @throws InvalidDataTypeException
2375
+	 * @throws EE_Error
2376
+	 */
2377
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2378
+	{
2379
+		if ($this->ID()) {
2380
+			// if this exists in the DB, save the relation change to the DB too
2381
+			$otherObject = $this->get_model()->remove_relationship_to(
2382
+				$this,
2383
+				$otherObjectModelObjectOrID,
2384
+				$relationName,
2385
+				$where_query
2386
+			);
2387
+			$this->clear_cache(
2388
+				$relationName,
2389
+				$otherObject
2390
+			);
2391
+		} else {
2392
+			// this doesn't exist in the DB, just remove it from the cache
2393
+			$otherObject = $this->clear_cache(
2394
+				$relationName,
2395
+				$otherObjectModelObjectOrID
2396
+			);
2397
+		}
2398
+		if ($otherObject instanceof EE_Base_Class) {
2399
+			$otherObject->clear_cache(
2400
+				$this->get_model()->get_this_model_name(),
2401
+				$this
2402
+			);
2403
+		}
2404
+		return $otherObject;
2405
+	}
2406
+
2407
+
2408
+	/**
2409
+	 * Removes ALL the related things for the $relationName.
2410
+	 *
2411
+	 * @param string $relationName
2412
+	 * @param array  $where_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2413
+	 * @return EE_Base_Class
2414
+	 * @throws ReflectionException
2415
+	 * @throws InvalidArgumentException
2416
+	 * @throws InvalidInterfaceException
2417
+	 * @throws InvalidDataTypeException
2418
+	 * @throws EE_Error
2419
+	 */
2420
+	public function _remove_relations($relationName, $where_query_params = array())
2421
+	{
2422
+		if ($this->ID()) {
2423
+			// if this exists in the DB, save the relation change to the DB too
2424
+			$otherObjects = $this->get_model()->remove_relations(
2425
+				$this,
2426
+				$relationName,
2427
+				$where_query_params
2428
+			);
2429
+			$this->clear_cache(
2430
+				$relationName,
2431
+				null,
2432
+				true
2433
+			);
2434
+		} else {
2435
+			// this doesn't exist in the DB, just remove it from the cache
2436
+			$otherObjects = $this->clear_cache(
2437
+				$relationName,
2438
+				null,
2439
+				true
2440
+			);
2441
+		}
2442
+		if (is_array($otherObjects)) {
2443
+			foreach ($otherObjects as $otherObject) {
2444
+				$otherObject->clear_cache(
2445
+					$this->get_model()->get_this_model_name(),
2446
+					$this
2447
+				);
2448
+			}
2449
+		}
2450
+		return $otherObjects;
2451
+	}
2452
+
2453
+
2454
+	/**
2455
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2456
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2457
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2458
+	 * because we want to get even deleted items etc.
2459
+	 *
2460
+	 * @param string $relationName key in the model's _model_relations array
2461
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2462
+	 * @return EE_Base_Class[]     Results not necessarily indexed by IDs, because some results might not have primary
2463
+	 *                             keys or might not be saved yet. Consider using EEM_Base::get_IDs() on these
2464
+	 *                             results if you want IDs
2465
+	 * @throws ReflectionException
2466
+	 * @throws InvalidArgumentException
2467
+	 * @throws InvalidInterfaceException
2468
+	 * @throws InvalidDataTypeException
2469
+	 * @throws EE_Error
2470
+	 */
2471
+	public function get_many_related($relationName, $query_params = array())
2472
+	{
2473
+		if ($this->ID()) {
2474
+			// this exists in the DB, so get the related things from either the cache or the DB
2475
+			// if there are query parameters, forget about caching the related model objects.
2476
+			if ($query_params) {
2477
+				$related_model_objects = $this->get_model()->get_all_related(
2478
+					$this,
2479
+					$relationName,
2480
+					$query_params
2481
+				);
2482
+			} else {
2483
+				// did we already cache the result of this query?
2484
+				$cached_results = $this->get_all_from_cache($relationName);
2485
+				if (! $cached_results) {
2486
+					$related_model_objects = $this->get_model()->get_all_related(
2487
+						$this,
2488
+						$relationName,
2489
+						$query_params
2490
+					);
2491
+					// if no query parameters were passed, then we got all the related model objects
2492
+					// for that relation. We can cache them then.
2493
+					foreach ($related_model_objects as $related_model_object) {
2494
+						$this->cache($relationName, $related_model_object);
2495
+					}
2496
+				} else {
2497
+					$related_model_objects = $cached_results;
2498
+				}
2499
+			}
2500
+		} else {
2501
+			// this doesn't exist in the DB, so just get the related things from the cache
2502
+			$related_model_objects = $this->get_all_from_cache($relationName);
2503
+		}
2504
+		return $related_model_objects;
2505
+	}
2506
+
2507
+
2508
+	/**
2509
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2510
+	 * unless otherwise specified in the $query_params
2511
+	 *
2512
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2513
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2514
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2515
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2516
+	 *                               that by the setting $distinct to TRUE;
2517
+	 * @return int
2518
+	 * @throws ReflectionException
2519
+	 * @throws InvalidArgumentException
2520
+	 * @throws InvalidInterfaceException
2521
+	 * @throws InvalidDataTypeException
2522
+	 * @throws EE_Error
2523
+	 */
2524
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2525
+	{
2526
+		return $this->get_model()->count_related(
2527
+			$this,
2528
+			$relation_name,
2529
+			$query_params,
2530
+			$field_to_count,
2531
+			$distinct
2532
+		);
2533
+	}
2534
+
2535
+
2536
+	/**
2537
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2538
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2539
+	 *
2540
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2541
+	 * @param array  $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2542
+	 * @param string $field_to_sum  name of field to count by.
2543
+	 *                              By default, uses primary key
2544
+	 *                              (which doesn't make much sense, so you should probably change it)
2545
+	 * @return int
2546
+	 * @throws ReflectionException
2547
+	 * @throws InvalidArgumentException
2548
+	 * @throws InvalidInterfaceException
2549
+	 * @throws InvalidDataTypeException
2550
+	 * @throws EE_Error
2551
+	 */
2552
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2553
+	{
2554
+		return $this->get_model()->sum_related(
2555
+			$this,
2556
+			$relation_name,
2557
+			$query_params,
2558
+			$field_to_sum
2559
+		);
2560
+	}
2561
+
2562
+
2563
+	/**
2564
+	 * Gets the first (ie, one) related model object of the specified type.
2565
+	 *
2566
+	 * @param string $relationName key in the model's _model_relations array
2567
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2568
+	 * @return EE_Base_Class (not an array, a single object)
2569
+	 * @throws ReflectionException
2570
+	 * @throws InvalidArgumentException
2571
+	 * @throws InvalidInterfaceException
2572
+	 * @throws InvalidDataTypeException
2573
+	 * @throws EE_Error
2574
+	 */
2575
+	public function get_first_related($relationName, $query_params = array())
2576
+	{
2577
+		$model = $this->get_model();
2578
+		if ($this->ID()) {// this exists in the DB, get from the cache OR the DB
2579
+			// if they've provided some query parameters, don't bother trying to cache the result
2580
+			// also make sure we're not caching the result of get_first_related
2581
+			// on a relation which should have an array of objects (because the cache might have an array of objects)
2582
+			if (
2583
+				$query_params
2584
+				|| ! $model->related_settings_for($relationName)
2585
+					 instanceof
2586
+					 EE_Belongs_To_Relation
2587
+			) {
2588
+				$related_model_object = $model->get_first_related(
2589
+					$this,
2590
+					$relationName,
2591
+					$query_params
2592
+				);
2593
+			} else {
2594
+				// first, check if we've already cached the result of this query
2595
+				$cached_result = $this->get_one_from_cache($relationName);
2596
+				if (! $cached_result) {
2597
+					$related_model_object = $model->get_first_related(
2598
+						$this,
2599
+						$relationName,
2600
+						$query_params
2601
+					);
2602
+					$this->cache($relationName, $related_model_object);
2603
+				} else {
2604
+					$related_model_object = $cached_result;
2605
+				}
2606
+			}
2607
+		} else {
2608
+			$related_model_object = null;
2609
+			// this doesn't exist in the Db,
2610
+			// but maybe the relation is of type belongs to, and so the related thing might
2611
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2612
+				$related_model_object = $model->get_first_related(
2613
+					$this,
2614
+					$relationName,
2615
+					$query_params
2616
+				);
2617
+			}
2618
+			// this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2619
+			// just get what's cached on this object
2620
+			if (! $related_model_object) {
2621
+				$related_model_object = $this->get_one_from_cache($relationName);
2622
+			}
2623
+		}
2624
+		return $related_model_object;
2625
+	}
2626
+
2627
+
2628
+	/**
2629
+	 * Does a delete on all related objects of type $relationName and removes
2630
+	 * the current model object's relation to them. If they can't be deleted (because
2631
+	 * of blocking related model objects) does nothing. If the related model objects are
2632
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2633
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2634
+	 *
2635
+	 * @param string $relationName
2636
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2637
+	 * @return int how many deleted
2638
+	 * @throws ReflectionException
2639
+	 * @throws InvalidArgumentException
2640
+	 * @throws InvalidInterfaceException
2641
+	 * @throws InvalidDataTypeException
2642
+	 * @throws EE_Error
2643
+	 */
2644
+	public function delete_related($relationName, $query_params = array())
2645
+	{
2646
+		if ($this->ID()) {
2647
+			$count = $this->get_model()->delete_related(
2648
+				$this,
2649
+				$relationName,
2650
+				$query_params
2651
+			);
2652
+		} else {
2653
+			$count = count($this->get_all_from_cache($relationName));
2654
+			$this->clear_cache($relationName, null, true);
2655
+		}
2656
+		return $count;
2657
+	}
2658
+
2659
+
2660
+	/**
2661
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2662
+	 * the current model object's relation to them. If they can't be deleted (because
2663
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2664
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2665
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2666
+	 *
2667
+	 * @param string $relationName
2668
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2669
+	 * @return int how many deleted (including those soft deleted)
2670
+	 * @throws ReflectionException
2671
+	 * @throws InvalidArgumentException
2672
+	 * @throws InvalidInterfaceException
2673
+	 * @throws InvalidDataTypeException
2674
+	 * @throws EE_Error
2675
+	 */
2676
+	public function delete_related_permanently($relationName, $query_params = array())
2677
+	{
2678
+		if ($this->ID()) {
2679
+			$count = $this->get_model()->delete_related_permanently(
2680
+				$this,
2681
+				$relationName,
2682
+				$query_params
2683
+			);
2684
+		} else {
2685
+			$count = count($this->get_all_from_cache($relationName));
2686
+		}
2687
+		$this->clear_cache($relationName, null, true);
2688
+		return $count;
2689
+	}
2690
+
2691
+
2692
+	/**
2693
+	 * is_set
2694
+	 * Just a simple utility function children can use for checking if property exists
2695
+	 *
2696
+	 * @access  public
2697
+	 * @param  string $field_name property to check
2698
+	 * @return bool                              TRUE if existing,FALSE if not.
2699
+	 */
2700
+	public function is_set($field_name)
2701
+	{
2702
+		return isset($this->_fields[ $field_name ]);
2703
+	}
2704
+
2705
+
2706
+	/**
2707
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2708
+	 * EE_Error exception if they don't
2709
+	 *
2710
+	 * @param  mixed (string|array) $properties properties to check
2711
+	 * @throws EE_Error
2712
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2713
+	 */
2714
+	protected function _property_exists($properties)
2715
+	{
2716
+		foreach ((array) $properties as $property_name) {
2717
+			// first make sure this property exists
2718
+			if (! $this->_fields[ $property_name ]) {
2719
+				throw new EE_Error(
2720
+					sprintf(
2721
+						esc_html__(
2722
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2723
+							'event_espresso'
2724
+						),
2725
+						$property_name
2726
+					)
2727
+				);
2728
+			}
2729
+		}
2730
+		return true;
2731
+	}
2732
+
2733
+
2734
+	/**
2735
+	 * This simply returns an array of model fields for this object
2736
+	 *
2737
+	 * @return array
2738
+	 * @throws ReflectionException
2739
+	 * @throws InvalidArgumentException
2740
+	 * @throws InvalidInterfaceException
2741
+	 * @throws InvalidDataTypeException
2742
+	 * @throws EE_Error
2743
+	 */
2744
+	public function model_field_array()
2745
+	{
2746
+		$fields = $this->get_model()->field_settings(false);
2747
+		$properties = array();
2748
+		// remove prepended underscore
2749
+		foreach ($fields as $field_name => $settings) {
2750
+			$properties[ $field_name ] = $this->get($field_name);
2751
+		}
2752
+		return $properties;
2753
+	}
2754
+
2755
+
2756
+	/**
2757
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2758
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2759
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments.
2760
+	 * Instead of requiring a plugin to extend the EE_Base_Class
2761
+	 * (which works fine is there's only 1 plugin, but when will that happen?)
2762
+	 * they can add a hook onto 'filters_hook_espresso__{className}__{methodName}'
2763
+	 * (eg, filters_hook_espresso__EE_Answer__my_great_function)
2764
+	 * and accepts 2 arguments: the object on which the function was called,
2765
+	 * and an array of the original arguments passed to the function.
2766
+	 * Whatever their callback function returns will be returned by this function.
2767
+	 * Example: in functions.php (or in a plugin):
2768
+	 *      add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3);
2769
+	 *      function my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2770
+	 *          $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2771
+	 *          return $previousReturnValue.$returnString;
2772
+	 *      }
2773
+	 * require('EE_Answer.class.php');
2774
+	 * echo EE_Answer::new_instance(['REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'])
2775
+	 *      ->my_callback('monkeys',100);
2776
+	 * // will output "you called my_callback! and passed args:monkeys,100"
2777
+	 *
2778
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2779
+	 * @param array  $args       array of original arguments passed to the function
2780
+	 * @throws EE_Error
2781
+	 * @return mixed whatever the plugin which calls add_filter decides
2782
+	 */
2783
+	public function __call($methodName, $args)
2784
+	{
2785
+		$className = get_class($this);
2786
+		$tagName = "FHEE__{$className}__{$methodName}";
2787
+		if (! has_filter($tagName)) {
2788
+			throw new EE_Error(
2789
+				sprintf(
2790
+					esc_html__(
2791
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2792
+						'event_espresso'
2793
+					),
2794
+					$methodName,
2795
+					$className,
2796
+					$tagName
2797
+				)
2798
+			);
2799
+		}
2800
+		return apply_filters($tagName, null, $this, $args);
2801
+	}
2802
+
2803
+
2804
+	/**
2805
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2806
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2807
+	 *
2808
+	 * @param string $meta_key
2809
+	 * @param mixed  $meta_value
2810
+	 * @param mixed  $previous_value
2811
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2812
+	 *                  NOTE: if the values haven't changed, returns 0
2813
+	 * @throws InvalidArgumentException
2814
+	 * @throws InvalidInterfaceException
2815
+	 * @throws InvalidDataTypeException
2816
+	 * @throws EE_Error
2817
+	 * @throws ReflectionException
2818
+	 */
2819
+	public function update_extra_meta(string $meta_key, $meta_value, $previous_value = null)
2820
+	{
2821
+		$query_params = [
2822
+			[
2823
+				'EXM_key'  => $meta_key,
2824
+				'OBJ_ID'   => $this->ID(),
2825
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2826
+			],
2827
+		];
2828
+		if ($previous_value !== null) {
2829
+			$query_params[0]['EXM_value'] = $meta_value;
2830
+		}
2831
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2832
+		if (! $existing_rows_like_that) {
2833
+			return $this->add_extra_meta($meta_key, $meta_value);
2834
+		}
2835
+		foreach ($existing_rows_like_that as $existing_row) {
2836
+			$existing_row->save(['EXM_value' => $meta_value]);
2837
+		}
2838
+		return count($existing_rows_like_that);
2839
+	}
2840
+
2841
+
2842
+	/**
2843
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2844
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2845
+	 * extra meta row was entered, false if not
2846
+	 *
2847
+	 * @param string $meta_key
2848
+	 * @param mixed  $meta_value
2849
+	 * @param bool   $unique
2850
+	 * @return bool
2851
+	 * @throws InvalidArgumentException
2852
+	 * @throws InvalidInterfaceException
2853
+	 * @throws InvalidDataTypeException
2854
+	 * @throws EE_Error
2855
+	 * @throws ReflectionException
2856
+	 * @throws ReflectionException
2857
+	 */
2858
+	public function add_extra_meta(string $meta_key, $meta_value, bool $unique = false): bool
2859
+	{
2860
+		if ($unique) {
2861
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2862
+				[
2863
+					[
2864
+						'EXM_key'  => $meta_key,
2865
+						'OBJ_ID'   => $this->ID(),
2866
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2867
+					],
2868
+				]
2869
+			);
2870
+			if ($existing_extra_meta) {
2871
+				return false;
2872
+			}
2873
+		}
2874
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2875
+			[
2876
+				'EXM_key'   => $meta_key,
2877
+				'EXM_value' => $meta_value,
2878
+				'OBJ_ID'    => $this->ID(),
2879
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2880
+			]
2881
+		);
2882
+		$new_extra_meta->save();
2883
+		return true;
2884
+	}
2885
+
2886
+
2887
+	/**
2888
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2889
+	 * is specified, only deletes extra meta records with that value.
2890
+	 *
2891
+	 * @param string $meta_key
2892
+	 * @param mixed  $meta_value
2893
+	 * @return int|bool number of extra meta rows deleted
2894
+	 * @throws InvalidArgumentException
2895
+	 * @throws InvalidInterfaceException
2896
+	 * @throws InvalidDataTypeException
2897
+	 * @throws EE_Error
2898
+	 * @throws ReflectionException
2899
+	 */
2900
+	public function delete_extra_meta(string $meta_key, $meta_value = null)
2901
+	{
2902
+		$query_params = [
2903
+			[
2904
+				'EXM_key'  => $meta_key,
2905
+				'OBJ_ID'   => $this->ID(),
2906
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2907
+			],
2908
+		];
2909
+		if ($meta_value !== null) {
2910
+			$query_params[0]['EXM_value'] = $meta_value;
2911
+		}
2912
+		return EEM_Extra_Meta::instance()->delete($query_params);
2913
+	}
2914
+
2915
+
2916
+	/**
2917
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2918
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2919
+	 * You can specify $default is case you haven't found the extra meta
2920
+	 *
2921
+	 * @param string     $meta_key
2922
+	 * @param bool       $single
2923
+	 * @param mixed      $default if we don't find anything, what should we return?
2924
+	 * @param array|null $extra_where
2925
+	 * @return mixed single value if $single; array if ! $single
2926
+	 * @throws ReflectionException
2927
+	 * @throws EE_Error
2928
+	 */
2929
+	public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2930
+	{
2931
+		$query_params = [ $extra_where + ['EXM_key' => $meta_key] ];
2932
+		if ($single) {
2933
+			$result = $this->get_first_related('Extra_Meta', $query_params);
2934
+			if ($result instanceof EE_Extra_Meta) {
2935
+				return $result->value();
2936
+			}
2937
+		} else {
2938
+			$results = $this->get_many_related('Extra_Meta', $query_params);
2939
+			if ($results) {
2940
+				$values = [];
2941
+				foreach ($results as $result) {
2942
+					if ($result instanceof EE_Extra_Meta) {
2943
+						$values[ $result->ID() ] = $result->value();
2944
+					}
2945
+				}
2946
+				return $values;
2947
+			}
2948
+		}
2949
+		// if nothing discovered yet return default.
2950
+		return apply_filters(
2951
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2952
+			$default,
2953
+			$meta_key,
2954
+			$single,
2955
+			$this
2956
+		);
2957
+	}
2958
+
2959
+
2960
+	/**
2961
+	 * Returns a simple array of all the extra meta associated with this model object.
2962
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2963
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2964
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2965
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2966
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2967
+	 * finally the extra meta's value as each sub-value. (eg
2968
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2969
+	 *
2970
+	 * @param bool $one_of_each_key
2971
+	 * @return array
2972
+	 * @throws ReflectionException
2973
+	 * @throws InvalidArgumentException
2974
+	 * @throws InvalidInterfaceException
2975
+	 * @throws InvalidDataTypeException
2976
+	 * @throws EE_Error
2977
+	 */
2978
+	public function all_extra_meta_array(bool $one_of_each_key = true): array
2979
+	{
2980
+		$return_array = [];
2981
+		if ($one_of_each_key) {
2982
+			$extra_meta_objs = $this->get_many_related(
2983
+				'Extra_Meta',
2984
+				['group_by' => 'EXM_key']
2985
+			);
2986
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2987
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2988
+					$return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2989
+				}
2990
+			}
2991
+		} else {
2992
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2993
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2994
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2995
+					if (! isset($return_array[ $extra_meta_obj->key() ])) {
2996
+						$return_array[ $extra_meta_obj->key() ] = [];
2997
+					}
2998
+					$return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2999
+				}
3000
+			}
3001
+		}
3002
+		return $return_array;
3003
+	}
3004
+
3005
+
3006
+	/**
3007
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
3008
+	 *
3009
+	 * @return string
3010
+	 * @throws ReflectionException
3011
+	 * @throws InvalidArgumentException
3012
+	 * @throws InvalidInterfaceException
3013
+	 * @throws InvalidDataTypeException
3014
+	 * @throws EE_Error
3015
+	 */
3016
+	public function name()
3017
+	{
3018
+		// find a field that's not a text field
3019
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
3020
+		if ($field_we_can_use) {
3021
+			return $this->get($field_we_can_use->get_name());
3022
+		}
3023
+		$first_few_properties = $this->model_field_array();
3024
+		$first_few_properties = array_slice($first_few_properties, 0, 3);
3025
+		$name_parts = array();
3026
+		foreach ($first_few_properties as $name => $value) {
3027
+			$name_parts[] = "$name:$value";
3028
+		}
3029
+		return implode(',', $name_parts);
3030
+	}
3031
+
3032
+
3033
+	/**
3034
+	 * in_entity_map
3035
+	 * Checks if this model object has been proven to already be in the entity map
3036
+	 *
3037
+	 * @return boolean
3038
+	 * @throws ReflectionException
3039
+	 * @throws InvalidArgumentException
3040
+	 * @throws InvalidInterfaceException
3041
+	 * @throws InvalidDataTypeException
3042
+	 * @throws EE_Error
3043
+	 */
3044
+	public function in_entity_map()
3045
+	{
3046
+		// well, if we looked, did we find it in the entity map?
3047
+		return $this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this;
3048
+	}
3049
+
3050
+
3051
+	/**
3052
+	 * refresh_from_db
3053
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
3054
+	 *
3055
+	 * @throws ReflectionException
3056
+	 * @throws InvalidArgumentException
3057
+	 * @throws InvalidInterfaceException
3058
+	 * @throws InvalidDataTypeException
3059
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
3060
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
3061
+	 */
3062
+	public function refresh_from_db()
3063
+	{
3064
+		if ($this->ID() && $this->in_entity_map()) {
3065
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
3066
+		} else {
3067
+			// if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
3068
+			// if it has an ID but it's not in the map, and you're asking me to refresh it
3069
+			// that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
3070
+			// absolutely nothing in it for this ID
3071
+			if (WP_DEBUG) {
3072
+				throw new EE_Error(
3073
+					sprintf(
3074
+						esc_html__(
3075
+							'Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
3076
+							'event_espresso'
3077
+						),
3078
+						$this->ID(),
3079
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3080
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3081
+					)
3082
+				);
3083
+			}
3084
+		}
3085
+	}
3086
+
3087
+
3088
+	/**
3089
+	 * Change $fields' values to $new_value_sql (which is a string of raw SQL)
3090
+	 *
3091
+	 * @since 4.9.80.p
3092
+	 * @param EE_Model_Field_Base[] $fields
3093
+	 * @param string $new_value_sql
3094
+	 *      example: 'column_name=123',
3095
+	 *      or 'column_name=column_name+1',
3096
+	 *      or 'column_name= CASE
3097
+	 *          WHEN (`column_name` + `other_column` + 5) <= `yet_another_column`
3098
+	 *          THEN `column_name` + 5
3099
+	 *          ELSE `column_name`
3100
+	 *      END'
3101
+	 *      Also updates $field on this model object with the latest value from the database.
3102
+	 * @return bool
3103
+	 * @throws EE_Error
3104
+	 * @throws InvalidArgumentException
3105
+	 * @throws InvalidDataTypeException
3106
+	 * @throws InvalidInterfaceException
3107
+	 * @throws ReflectionException
3108
+	 */
3109
+	protected function updateFieldsInDB($fields, $new_value_sql)
3110
+	{
3111
+		// First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3112
+		// if it wasn't even there to start off.
3113
+		if (! $this->ID()) {
3114
+			$this->save();
3115
+		}
3116
+		global $wpdb;
3117
+		if (empty($fields)) {
3118
+			throw new InvalidArgumentException(
3119
+				esc_html__(
3120
+					'EE_Base_Class::updateFieldsInDB was passed an empty array of fields.',
3121
+					'event_espresso'
3122
+				)
3123
+			);
3124
+		}
3125
+		$first_field = reset($fields);
3126
+		$table_alias = $first_field->get_table_alias();
3127
+		foreach ($fields as $field) {
3128
+			if ($table_alias !== $field->get_table_alias()) {
3129
+				throw new InvalidArgumentException(
3130
+					sprintf(
3131
+						esc_html__(
3132
+							// @codingStandardsIgnoreStart
3133
+							'EE_Base_Class::updateFieldsInDB was passed fields for different tables ("%1$s" and "%2$s"), which is not supported. Instead, please call the method multiple times.',
3134
+							// @codingStandardsIgnoreEnd
3135
+							'event_espresso'
3136
+						),
3137
+						$table_alias,
3138
+						$field->get_table_alias()
3139
+					)
3140
+				);
3141
+			}
3142
+		}
3143
+		// Ok the fields are now known to all be for the same table. Proceed with creating the SQL to update it.
3144
+		$table_obj = $this->get_model()->get_table_obj_by_alias($table_alias);
3145
+		$table_pk_value = $this->ID();
3146
+		$table_name = $table_obj->get_table_name();
3147
+		if ($table_obj instanceof EE_Secondary_Table) {
3148
+			$table_pk_field_name = $table_obj->get_fk_on_table();
3149
+		} else {
3150
+			$table_pk_field_name = $table_obj->get_pk_column();
3151
+		}
3152
+
3153
+		$query =
3154
+			"UPDATE `{$table_name}`
3155 3155
             SET "
3156
-            . $new_value_sql
3157
-            . $wpdb->prepare(
3158
-                "
3156
+			. $new_value_sql
3157
+			. $wpdb->prepare(
3158
+				"
3159 3159
             WHERE `{$table_pk_field_name}` = %d;",
3160
-                $table_pk_value
3161
-            );
3162
-        $result = $wpdb->query($query);
3163
-        foreach ($fields as $field) {
3164
-            // If it was successful, we'd like to know the new value.
3165
-            // If it failed, we'd also like to know the new value.
3166
-            $new_value = $this->get_model()->get_var(
3167
-                $this->get_model()->alter_query_params_to_restrict_by_ID(
3168
-                    $this->get_model()->get_index_primary_key_string(
3169
-                        $this->model_field_array()
3170
-                    ),
3171
-                    array(
3172
-                        'default_where_conditions' => 'minimum',
3173
-                    )
3174
-                ),
3175
-                $field->get_name()
3176
-            );
3177
-            $this->set_from_db(
3178
-                $field->get_name(),
3179
-                $new_value
3180
-            );
3181
-        }
3182
-        return (bool) $result;
3183
-    }
3184
-
3185
-
3186
-    /**
3187
-     * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3188
-     * Does not allow negative values, however.
3189
-     *
3190
-     * @since 4.9.80.p
3191
-     * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3192
-     *                                   (positive or negative). One important gotcha: all these values must be
3193
-     *                                   on the same table (eg don't pass in one field for the posts table and
3194
-     *                                   another for the event meta table.)
3195
-     * @return bool
3196
-     * @throws EE_Error
3197
-     * @throws InvalidArgumentException
3198
-     * @throws InvalidDataTypeException
3199
-     * @throws InvalidInterfaceException
3200
-     * @throws ReflectionException
3201
-     */
3202
-    public function adjustNumericFieldsInDb(array $fields_n_quantities)
3203
-    {
3204
-        global $wpdb;
3205
-        if (empty($fields_n_quantities)) {
3206
-            // No fields to update? Well sure, we updated them to that value just fine.
3207
-            return true;
3208
-        }
3209
-        $fields = [];
3210
-        $set_sql_statements = [];
3211
-        foreach ($fields_n_quantities as $field_name => $quantity) {
3212
-            $field = $this->get_model()->field_settings_for($field_name, true);
3213
-            $fields[] = $field;
3214
-            $column_name = $field->get_table_column();
3215
-
3216
-            $abs_qty = absint($quantity);
3217
-            if ($quantity > 0) {
3218
-                // don't let the value be negative as often these fields are unsigned
3219
-                $set_sql_statements[] = $wpdb->prepare(
3220
-                    "`{$column_name}` = `{$column_name}` + %d",
3221
-                    $abs_qty
3222
-                );
3223
-            } else {
3224
-                $set_sql_statements[] = $wpdb->prepare(
3225
-                    "`{$column_name}` = CASE
3160
+				$table_pk_value
3161
+			);
3162
+		$result = $wpdb->query($query);
3163
+		foreach ($fields as $field) {
3164
+			// If it was successful, we'd like to know the new value.
3165
+			// If it failed, we'd also like to know the new value.
3166
+			$new_value = $this->get_model()->get_var(
3167
+				$this->get_model()->alter_query_params_to_restrict_by_ID(
3168
+					$this->get_model()->get_index_primary_key_string(
3169
+						$this->model_field_array()
3170
+					),
3171
+					array(
3172
+						'default_where_conditions' => 'minimum',
3173
+					)
3174
+				),
3175
+				$field->get_name()
3176
+			);
3177
+			$this->set_from_db(
3178
+				$field->get_name(),
3179
+				$new_value
3180
+			);
3181
+		}
3182
+		return (bool) $result;
3183
+	}
3184
+
3185
+
3186
+	/**
3187
+	 * Nudges $field_name's value by $quantity, without any conditionals (in comparison to bumpConditionally()).
3188
+	 * Does not allow negative values, however.
3189
+	 *
3190
+	 * @since 4.9.80.p
3191
+	 * @param array $fields_n_quantities keys are the field names, and values are the amount by which to bump them
3192
+	 *                                   (positive or negative). One important gotcha: all these values must be
3193
+	 *                                   on the same table (eg don't pass in one field for the posts table and
3194
+	 *                                   another for the event meta table.)
3195
+	 * @return bool
3196
+	 * @throws EE_Error
3197
+	 * @throws InvalidArgumentException
3198
+	 * @throws InvalidDataTypeException
3199
+	 * @throws InvalidInterfaceException
3200
+	 * @throws ReflectionException
3201
+	 */
3202
+	public function adjustNumericFieldsInDb(array $fields_n_quantities)
3203
+	{
3204
+		global $wpdb;
3205
+		if (empty($fields_n_quantities)) {
3206
+			// No fields to update? Well sure, we updated them to that value just fine.
3207
+			return true;
3208
+		}
3209
+		$fields = [];
3210
+		$set_sql_statements = [];
3211
+		foreach ($fields_n_quantities as $field_name => $quantity) {
3212
+			$field = $this->get_model()->field_settings_for($field_name, true);
3213
+			$fields[] = $field;
3214
+			$column_name = $field->get_table_column();
3215
+
3216
+			$abs_qty = absint($quantity);
3217
+			if ($quantity > 0) {
3218
+				// don't let the value be negative as often these fields are unsigned
3219
+				$set_sql_statements[] = $wpdb->prepare(
3220
+					"`{$column_name}` = `{$column_name}` + %d",
3221
+					$abs_qty
3222
+				);
3223
+			} else {
3224
+				$set_sql_statements[] = $wpdb->prepare(
3225
+					"`{$column_name}` = CASE
3226 3226
                        WHEN (`{$column_name}` >= %d)
3227 3227
                        THEN `{$column_name}` - %d
3228 3228
                        ELSE 0
3229 3229
                     END",
3230
-                    $abs_qty,
3231
-                    $abs_qty
3232
-                );
3233
-            }
3234
-        }
3235
-        return $this->updateFieldsInDB(
3236
-            $fields,
3237
-            implode(', ', $set_sql_statements)
3238
-        );
3239
-    }
3240
-
3241
-
3242
-    /**
3243
-     * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3244
-     * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3245
-     * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3246
-     * Returns true if the value was successfully bumped, and updates the value on this model object.
3247
-     * Otherwise returns false.
3248
-     *
3249
-     * @since 4.9.80.p
3250
-     * @param string $field_name_to_bump
3251
-     * @param string $field_name_affecting_total
3252
-     * @param string $limit_field_name
3253
-     * @param int    $quantity
3254
-     * @return bool
3255
-     * @throws EE_Error
3256
-     * @throws InvalidArgumentException
3257
-     * @throws InvalidDataTypeException
3258
-     * @throws InvalidInterfaceException
3259
-     * @throws ReflectionException
3260
-     */
3261
-    public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3262
-    {
3263
-        global $wpdb;
3264
-        $field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3265
-        $column_name = $field->get_table_column();
3266
-
3267
-        $field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3268
-        $column_affecting_total = $field_affecting_total->get_table_column();
3269
-
3270
-        $limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3271
-        $limiting_column = $limiting_field->get_table_column();
3272
-        return $this->updateFieldsInDB(
3273
-            [$field],
3274
-            $wpdb->prepare(
3275
-                "`{$column_name}` =
3230
+					$abs_qty,
3231
+					$abs_qty
3232
+				);
3233
+			}
3234
+		}
3235
+		return $this->updateFieldsInDB(
3236
+			$fields,
3237
+			implode(', ', $set_sql_statements)
3238
+		);
3239
+	}
3240
+
3241
+
3242
+	/**
3243
+	 * Increases the value of the field $field_name_to_bump by $quantity, but only if the values of
3244
+	 * $field_name_to_bump plus $field_name_affecting_total and $quantity won't exceed $limit_field_name's value.
3245
+	 * For example, this is useful when bumping the value of TKT_reserved, TKT_sold, DTT_reserved or DTT_sold.
3246
+	 * Returns true if the value was successfully bumped, and updates the value on this model object.
3247
+	 * Otherwise returns false.
3248
+	 *
3249
+	 * @since 4.9.80.p
3250
+	 * @param string $field_name_to_bump
3251
+	 * @param string $field_name_affecting_total
3252
+	 * @param string $limit_field_name
3253
+	 * @param int    $quantity
3254
+	 * @return bool
3255
+	 * @throws EE_Error
3256
+	 * @throws InvalidArgumentException
3257
+	 * @throws InvalidDataTypeException
3258
+	 * @throws InvalidInterfaceException
3259
+	 * @throws ReflectionException
3260
+	 */
3261
+	public function incrementFieldConditionallyInDb($field_name_to_bump, $field_name_affecting_total, $limit_field_name, $quantity)
3262
+	{
3263
+		global $wpdb;
3264
+		$field = $this->get_model()->field_settings_for($field_name_to_bump, true);
3265
+		$column_name = $field->get_table_column();
3266
+
3267
+		$field_affecting_total = $this->get_model()->field_settings_for($field_name_affecting_total, true);
3268
+		$column_affecting_total = $field_affecting_total->get_table_column();
3269
+
3270
+		$limiting_field = $this->get_model()->field_settings_for($limit_field_name, true);
3271
+		$limiting_column = $limiting_field->get_table_column();
3272
+		return $this->updateFieldsInDB(
3273
+			[$field],
3274
+			$wpdb->prepare(
3275
+				"`{$column_name}` =
3276 3276
             CASE
3277 3277
                WHEN ((`{$column_name}` + `{$column_affecting_total}` + %d) <= `{$limiting_column}`) OR `{$limiting_column}` = %d
3278 3278
                THEN `{$column_name}` + %d
3279 3279
                ELSE `{$column_name}`
3280 3280
             END",
3281
-                $quantity,
3282
-                EE_INF_IN_DB,
3283
-                $quantity
3284
-            )
3285
-        );
3286
-    }
3287
-
3288
-
3289
-    /**
3290
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3291
-     * (probably a bad assumption they have made, oh well)
3292
-     *
3293
-     * @return string
3294
-     */
3295
-    public function __toString()
3296
-    {
3297
-        try {
3298
-            return sprintf('%s (%s)', $this->name(), $this->ID());
3299
-        } catch (Exception $e) {
3300
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3301
-            return '';
3302
-        }
3303
-    }
3304
-
3305
-
3306
-    /**
3307
-     * Clear related model objects if they're already in the DB, because otherwise when we
3308
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
3309
-     * This means if we have made changes to those related model objects, and want to unserialize
3310
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
3311
-     * Instead, those related model objects should be directly serialized and stored.
3312
-     * Eg, the following won't work:
3313
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3314
-     * $att = $reg->attendee();
3315
-     * $att->set( 'ATT_fname', 'Dirk' );
3316
-     * update_option( 'my_option', serialize( $reg ) );
3317
-     * //END REQUEST
3318
-     * //START NEXT REQUEST
3319
-     * $reg = get_option( 'my_option' );
3320
-     * $reg->attendee()->save();
3321
-     * And would need to be replace with:
3322
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3323
-     * $att = $reg->attendee();
3324
-     * $att->set( 'ATT_fname', 'Dirk' );
3325
-     * update_option( 'my_option', serialize( $reg ) );
3326
-     * //END REQUEST
3327
-     * //START NEXT REQUEST
3328
-     * $att = get_option( 'my_option' );
3329
-     * $att->save();
3330
-     *
3331
-     * @return array
3332
-     * @throws ReflectionException
3333
-     * @throws InvalidArgumentException
3334
-     * @throws InvalidInterfaceException
3335
-     * @throws InvalidDataTypeException
3336
-     * @throws EE_Error
3337
-     */
3338
-    public function __sleep()
3339
-    {
3340
-        $model = $this->get_model();
3341
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3342
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
3343
-                $classname = 'EE_' . $model->get_this_model_name();
3344
-                if (
3345
-                    $this->get_one_from_cache($relation_name) instanceof $classname
3346
-                    && $this->get_one_from_cache($relation_name)->ID()
3347
-                ) {
3348
-                    $this->clear_cache(
3349
-                        $relation_name,
3350
-                        $this->get_one_from_cache($relation_name)->ID()
3351
-                    );
3352
-                }
3353
-            }
3354
-        }
3355
-        $this->_props_n_values_provided_in_constructor = array();
3356
-        $properties_to_serialize = get_object_vars($this);
3357
-        // don't serialize the model. It's big and that risks recursion
3358
-        unset($properties_to_serialize['_model']);
3359
-        return array_keys($properties_to_serialize);
3360
-    }
3361
-
3362
-
3363
-    /**
3364
-     * restore _props_n_values_provided_in_constructor
3365
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3366
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
3367
-     * At best, you would only be able to detect if state change has occurred during THIS request.
3368
-     */
3369
-    public function __wakeup()
3370
-    {
3371
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
3372
-    }
3373
-
3374
-
3375
-    /**
3376
-     * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3377
-     * distinct with the clone host instance are also cloned.
3378
-     */
3379
-    public function __clone()
3380
-    {
3381
-        // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3382
-        foreach ($this->_fields as $field => $value) {
3383
-            if ($value instanceof DateTime) {
3384
-                $this->_fields[ $field ] = clone $value;
3385
-            }
3386
-        }
3387
-    }
3281
+				$quantity,
3282
+				EE_INF_IN_DB,
3283
+				$quantity
3284
+			)
3285
+		);
3286
+	}
3287
+
3288
+
3289
+	/**
3290
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
3291
+	 * (probably a bad assumption they have made, oh well)
3292
+	 *
3293
+	 * @return string
3294
+	 */
3295
+	public function __toString()
3296
+	{
3297
+		try {
3298
+			return sprintf('%s (%s)', $this->name(), $this->ID());
3299
+		} catch (Exception $e) {
3300
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
3301
+			return '';
3302
+		}
3303
+	}
3304
+
3305
+
3306
+	/**
3307
+	 * Clear related model objects if they're already in the DB, because otherwise when we
3308
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
3309
+	 * This means if we have made changes to those related model objects, and want to unserialize
3310
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
3311
+	 * Instead, those related model objects should be directly serialized and stored.
3312
+	 * Eg, the following won't work:
3313
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3314
+	 * $att = $reg->attendee();
3315
+	 * $att->set( 'ATT_fname', 'Dirk' );
3316
+	 * update_option( 'my_option', serialize( $reg ) );
3317
+	 * //END REQUEST
3318
+	 * //START NEXT REQUEST
3319
+	 * $reg = get_option( 'my_option' );
3320
+	 * $reg->attendee()->save();
3321
+	 * And would need to be replace with:
3322
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
3323
+	 * $att = $reg->attendee();
3324
+	 * $att->set( 'ATT_fname', 'Dirk' );
3325
+	 * update_option( 'my_option', serialize( $reg ) );
3326
+	 * //END REQUEST
3327
+	 * //START NEXT REQUEST
3328
+	 * $att = get_option( 'my_option' );
3329
+	 * $att->save();
3330
+	 *
3331
+	 * @return array
3332
+	 * @throws ReflectionException
3333
+	 * @throws InvalidArgumentException
3334
+	 * @throws InvalidInterfaceException
3335
+	 * @throws InvalidDataTypeException
3336
+	 * @throws EE_Error
3337
+	 */
3338
+	public function __sleep()
3339
+	{
3340
+		$model = $this->get_model();
3341
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3342
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
3343
+				$classname = 'EE_' . $model->get_this_model_name();
3344
+				if (
3345
+					$this->get_one_from_cache($relation_name) instanceof $classname
3346
+					&& $this->get_one_from_cache($relation_name)->ID()
3347
+				) {
3348
+					$this->clear_cache(
3349
+						$relation_name,
3350
+						$this->get_one_from_cache($relation_name)->ID()
3351
+					);
3352
+				}
3353
+			}
3354
+		}
3355
+		$this->_props_n_values_provided_in_constructor = array();
3356
+		$properties_to_serialize = get_object_vars($this);
3357
+		// don't serialize the model. It's big and that risks recursion
3358
+		unset($properties_to_serialize['_model']);
3359
+		return array_keys($properties_to_serialize);
3360
+	}
3361
+
3362
+
3363
+	/**
3364
+	 * restore _props_n_values_provided_in_constructor
3365
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
3366
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
3367
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
3368
+	 */
3369
+	public function __wakeup()
3370
+	{
3371
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
3372
+	}
3373
+
3374
+
3375
+	/**
3376
+	 * Usage of this magic method is to ensure any internally cached references to object instances that must remain
3377
+	 * distinct with the clone host instance are also cloned.
3378
+	 */
3379
+	public function __clone()
3380
+	{
3381
+		// handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3382
+		foreach ($this->_fields as $field => $value) {
3383
+			if ($value instanceof DateTime) {
3384
+				$this->_fields[ $field ] = clone $value;
3385
+			}
3386
+		}
3387
+	}
3388 3388
 }
Please login to merge, or discard this patch.
Spacing   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
         $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
149 149
         // verify client code has not passed any invalid field names
150 150
         foreach ($fieldValues as $field_name => $field_value) {
151
-            if (! isset($model_fields[ $field_name ])) {
151
+            if ( ! isset($model_fields[$field_name])) {
152 152
                 throw new EE_Error(
153 153
                     sprintf(
154 154
                         esc_html__(
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
         $date_format = null;
167 167
         $time_format = null;
168 168
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
169
-        if (! empty($date_formats) && is_array($date_formats)) {
169
+        if ( ! empty($date_formats) && is_array($date_formats)) {
170 170
             [$date_format, $time_format] = $date_formats;
171 171
         }
172 172
         $this->set_date_format($date_format);
@@ -177,14 +177,14 @@  discard block
 block discarded – undo
177 177
                 // client code has indicated these field values are from the database
178 178
                     $this->set_from_db(
179 179
                         $fieldName,
180
-                        $fieldValues[ $fieldName ] ?? null
180
+                        $fieldValues[$fieldName] ?? null
181 181
                     );
182 182
             } else {
183 183
                 // we're constructing a brand new instance of the model object.
184 184
                 // Generally, this means we'll need to do more field validation
185 185
                     $this->set(
186 186
                     $fieldName,
187
-                    $fieldValues[ $fieldName ] ?? null,
187
+                    $fieldValues[$fieldName] ?? null,
188 188
                     true
189 189
                 );
190 190
             }
@@ -192,15 +192,15 @@  discard block
 block discarded – undo
192 192
         // remember what values were passed to this constructor
193 193
         $this->_props_n_values_provided_in_constructor = $fieldValues;
194 194
         // remember in entity mapper
195
-        if (! $bydb && $model->has_primary_key_field() && $this->ID()) {
195
+        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
196 196
             $model->add_to_entity_map($this);
197 197
         }
198 198
         // setup all the relations
199 199
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
200 200
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
201
-                $this->_model_relations[ $relation_name ] = null;
201
+                $this->_model_relations[$relation_name] = null;
202 202
             } else {
203
-                $this->_model_relations[ $relation_name ] = array();
203
+                $this->_model_relations[$relation_name] = array();
204 204
             }
205 205
         }
206 206
         /**
@@ -252,10 +252,10 @@  discard block
 block discarded – undo
252 252
     public function get_original($field_name)
253 253
     {
254 254
         if (
255
-            isset($this->_props_n_values_provided_in_constructor[ $field_name ])
255
+            isset($this->_props_n_values_provided_in_constructor[$field_name])
256 256
             && $field_settings = $this->get_model()->field_settings_for($field_name)
257 257
         ) {
258
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[ $field_name ]);
258
+            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
259 259
         }
260 260
         return null;
261 261
     }
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
         // then don't do anything
293 293
         if (
294 294
             ! $use_default
295
-            && $this->_fields[ $field_name ] === $field_value
295
+            && $this->_fields[$field_name] === $field_value
296 296
             && $this->ID()
297 297
         ) {
298 298
             return;
@@ -300,7 +300,7 @@  discard block
 block discarded – undo
300 300
         $model = $this->get_model();
301 301
         $this->_has_changes = true;
302 302
         $field_obj = $model->field_settings_for($field_name);
303
-        if (! $field_obj instanceof EE_Model_Field_Base) {
303
+        if ( ! $field_obj instanceof EE_Model_Field_Base) {
304 304
             throw new EE_Error(
305 305
                 sprintf(
306 306
                     esc_html__(
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
         $holder_of_value = $field_obj->prepare_for_set($field_value);
321 321
         // should the value be null?
322 322
         if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
323
-            $this->_fields[ $field_name ] = $field_obj->get_default_value();
323
+            $this->_fields[$field_name] = $field_obj->get_default_value();
324 324
             /**
325 325
              * To save having to refactor all the models, if a default value is used for a
326 326
              * EE_Datetime_Field, and that value is not null nor is it a DateTime
@@ -331,15 +331,15 @@  discard block
 block discarded – undo
331 331
              */
332 332
             if (
333 333
                 $field_obj instanceof EE_Datetime_Field
334
-                && $this->_fields[ $field_name ] !== null
335
-                && ! $this->_fields[ $field_name ] instanceof DateTime
334
+                && $this->_fields[$field_name] !== null
335
+                && ! $this->_fields[$field_name] instanceof DateTime
336 336
             ) {
337
-                empty($this->_fields[ $field_name ])
337
+                empty($this->_fields[$field_name])
338 338
                     ? $this->set($field_name, time())
339
-                    : $this->set($field_name, $this->_fields[ $field_name ]);
339
+                    : $this->set($field_name, $this->_fields[$field_name]);
340 340
             }
341 341
         } else {
342
-            $this->_fields[ $field_name ] = $holder_of_value;
342
+            $this->_fields[$field_name] = $holder_of_value;
343 343
         }
344 344
         // if we're not in the constructor...
345 345
         // now check if what we set was a primary key
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
             } else {
402 402
                 $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
403 403
             }
404
-            $this->_fields[ $field_name ] = $field_value;
404
+            $this->_fields[$field_name] = $field_value;
405 405
             $this->_clear_cached_property($field_name);
406 406
         }
407 407
     }
@@ -427,8 +427,8 @@  discard block
 block discarded – undo
427 427
      */
428 428
     public function getCustomSelect($alias)
429 429
     {
430
-        return isset($this->custom_selection_results[ $alias ])
431
-            ? $this->custom_selection_results[ $alias ]
430
+        return isset($this->custom_selection_results[$alias])
431
+            ? $this->custom_selection_results[$alias]
432 432
             : null;
433 433
     }
434 434
 
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
         foreach ($model_fields as $field_name => $field_obj) {
516 516
             if ($field_obj instanceof EE_Datetime_Field) {
517 517
                 $field_obj->set_timezone($this->_timezone);
518
-                if (isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime) {
519
-                    EEH_DTT_Helper::setTimezone($this->_fields[ $field_name ], new DateTimeZone($this->_timezone));
518
+                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
519
+                    EEH_DTT_Helper::setTimezone($this->_fields[$field_name], new DateTimeZone($this->_timezone));
520 520
                 }
521 521
             }
522 522
         }
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
      */
577 577
     public function get_format($full = true)
578 578
     {
579
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
579
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
580 580
     }
581 581
 
582 582
 
@@ -602,11 +602,11 @@  discard block
 block discarded – undo
602 602
     public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
603 603
     {
604 604
         // its entirely possible that there IS no related object yet in which case there is nothing to cache.
605
-        if (! $object_to_cache instanceof EE_Base_Class) {
605
+        if ( ! $object_to_cache instanceof EE_Base_Class) {
606 606
             return false;
607 607
         }
608 608
         // also get "how" the object is related, or throw an error
609
-        if (! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
609
+        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
610 610
             throw new EE_Error(
611 611
                 sprintf(
612 612
                     esc_html__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
@@ -620,38 +620,38 @@  discard block
 block discarded – undo
620 620
             // if it's a "belongs to" relationship, then there's only one related model object
621 621
             // eg, if this is a registration, there's only 1 attendee for it
622 622
             // so for these model objects just set it to be cached
623
-            $this->_model_relations[ $relationName ] = $object_to_cache;
623
+            $this->_model_relations[$relationName] = $object_to_cache;
624 624
             $return = true;
625 625
         } else {
626 626
             // otherwise, this is the "many" side of a one to many relationship,
627 627
             // so we'll add the object to the array of related objects for that type.
628 628
             // eg: if this is an event, there are many registrations for that event,
629 629
             // so we cache the registrations in an array
630
-            if (! is_array($this->_model_relations[ $relationName ])) {
630
+            if ( ! is_array($this->_model_relations[$relationName])) {
631 631
                 // if for some reason, the cached item is a model object,
632 632
                 // then stick that in the array, otherwise start with an empty array
633
-                $this->_model_relations[ $relationName ] = $this->_model_relations[ $relationName ]
633
+                $this->_model_relations[$relationName] = $this->_model_relations[$relationName]
634 634
                                                            instanceof
635 635
                                                            EE_Base_Class
636
-                    ? array($this->_model_relations[ $relationName ]) : array();
636
+                    ? array($this->_model_relations[$relationName]) : array();
637 637
             }
638 638
             // first check for a cache_id which is normally empty
639
-            if (! empty($cache_id)) {
639
+            if ( ! empty($cache_id)) {
640 640
                 // if the cache_id exists, then it means we are purposely trying to cache this
641 641
                 // with a known key that can then be used to retrieve the object later on
642
-                $this->_model_relations[ $relationName ][ $cache_id ] = $object_to_cache;
642
+                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
643 643
                 $return = $cache_id;
644 644
             } elseif ($object_to_cache->ID()) {
645 645
                 // OR the cached object originally came from the db, so let's just use it's PK for an ID
646
-                $this->_model_relations[ $relationName ][ $object_to_cache->ID() ] = $object_to_cache;
646
+                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
647 647
                 $return = $object_to_cache->ID();
648 648
             } else {
649 649
                 // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
650
-                $this->_model_relations[ $relationName ][] = $object_to_cache;
650
+                $this->_model_relations[$relationName][] = $object_to_cache;
651 651
                 // move the internal pointer to the end of the array
652
-                end($this->_model_relations[ $relationName ]);
652
+                end($this->_model_relations[$relationName]);
653 653
                 // and grab the key so that we can return it
654
-                $return = key($this->_model_relations[ $relationName ]);
654
+                $return = key($this->_model_relations[$relationName]);
655 655
             }
656 656
         }
657 657
         return $return;
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
         // first make sure this property exists
678 678
         $this->get_model()->field_settings_for($fieldname);
679 679
         $cache_type = empty($cache_type) ? 'standard' : $cache_type;
680
-        $this->_cached_properties[ $fieldname ][ $cache_type ] = $value;
680
+        $this->_cached_properties[$fieldname][$cache_type] = $value;
681 681
     }
682 682
 
683 683
 
@@ -706,9 +706,9 @@  discard block
 block discarded – undo
706 706
         $model = $this->get_model();
707 707
         $model->field_settings_for($fieldname);
708 708
         $cache_type = $pretty ? 'pretty' : 'standard';
709
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
710
-        if (isset($this->_cached_properties[ $fieldname ][ $cache_type ])) {
711
-            return $this->_cached_properties[ $fieldname ][ $cache_type ];
709
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
710
+        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
711
+            return $this->_cached_properties[$fieldname][$cache_type];
712 712
         }
713 713
         $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
714 714
         $this->_set_cached_property($fieldname, $value, $cache_type);
@@ -736,12 +736,12 @@  discard block
 block discarded – undo
736 736
         if ($field_obj instanceof EE_Datetime_Field) {
737 737
             $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
738 738
         }
739
-        if (! isset($this->_fields[ $fieldname ])) {
740
-            $this->_fields[ $fieldname ] = null;
739
+        if ( ! isset($this->_fields[$fieldname])) {
740
+            $this->_fields[$fieldname] = null;
741 741
         }
742 742
         return $pretty
743
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[ $fieldname ], $extra_cache_ref)
744
-            : $field_obj->prepare_for_get($this->_fields[ $fieldname ]);
743
+            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
744
+            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
745 745
     }
746 746
 
747 747
 
@@ -797,8 +797,8 @@  discard block
 block discarded – undo
797 797
      */
798 798
     protected function _clear_cached_property($property_name)
799 799
     {
800
-        if (isset($this->_cached_properties[ $property_name ])) {
801
-            unset($this->_cached_properties[ $property_name ]);
800
+        if (isset($this->_cached_properties[$property_name])) {
801
+            unset($this->_cached_properties[$property_name]);
802 802
         }
803 803
     }
804 804
 
@@ -850,7 +850,7 @@  discard block
 block discarded – undo
850 850
     {
851 851
         $relationship_to_model = $this->get_model()->related_settings_for($relationName);
852 852
         $index_in_cache = '';
853
-        if (! $relationship_to_model) {
853
+        if ( ! $relationship_to_model) {
854 854
             throw new EE_Error(
855 855
                 sprintf(
856 856
                     esc_html__('There is no relationship to %s on a %s. Cannot clear that cache', 'event_espresso'),
@@ -861,10 +861,10 @@  discard block
 block discarded – undo
861 861
         }
862 862
         if ($clear_all) {
863 863
             $obj_removed = true;
864
-            $this->_model_relations[ $relationName ] = null;
864
+            $this->_model_relations[$relationName] = null;
865 865
         } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
866
-            $obj_removed = $this->_model_relations[ $relationName ];
867
-            $this->_model_relations[ $relationName ] = null;
866
+            $obj_removed = $this->_model_relations[$relationName];
867
+            $this->_model_relations[$relationName] = null;
868 868
         } else {
869 869
             if (
870 870
                 $object_to_remove_or_index_into_array instanceof EE_Base_Class
@@ -872,12 +872,12 @@  discard block
 block discarded – undo
872 872
             ) {
873 873
                 $index_in_cache = $object_to_remove_or_index_into_array->ID();
874 874
                 if (
875
-                    is_array($this->_model_relations[ $relationName ])
876
-                    && ! isset($this->_model_relations[ $relationName ][ $index_in_cache ])
875
+                    is_array($this->_model_relations[$relationName])
876
+                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
877 877
                 ) {
878 878
                     $index_found_at = null;
879 879
                     // find this object in the array even though it has a different key
880
-                    foreach ($this->_model_relations[ $relationName ] as $index => $obj) {
880
+                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
881 881
                         /** @noinspection TypeUnsafeComparisonInspection */
882 882
                         if (
883 883
                             $obj instanceof EE_Base_Class
@@ -911,9 +911,9 @@  discard block
 block discarded – undo
911 911
             }
912 912
             // supposedly we've found it. But it could just be that the client code
913 913
             // provided a bad index/object
914
-            if (isset($this->_model_relations[ $relationName ][ $index_in_cache ])) {
915
-                $obj_removed = $this->_model_relations[ $relationName ][ $index_in_cache ];
916
-                unset($this->_model_relations[ $relationName ][ $index_in_cache ]);
914
+            if (isset($this->_model_relations[$relationName][$index_in_cache])) {
915
+                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
916
+                unset($this->_model_relations[$relationName][$index_in_cache]);
917 917
             } else {
918 918
                 // that thing was never cached anyways.
919 919
                 $obj_removed = null;
@@ -944,7 +944,7 @@  discard block
 block discarded – undo
944 944
         $current_cache_id = ''
945 945
     ) {
946 946
         // verify that incoming object is of the correct type
947
-        $obj_class = 'EE_' . $relationName;
947
+        $obj_class = 'EE_'.$relationName;
948 948
         if ($newly_saved_object instanceof $obj_class) {
949 949
             /* @type EE_Base_Class $newly_saved_object */
950 950
             // now get the type of relation
@@ -952,18 +952,18 @@  discard block
 block discarded – undo
952 952
             // if this is a 1:1 relationship
953 953
             if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
954 954
                 // then just replace the cached object with the newly saved object
955
-                $this->_model_relations[ $relationName ] = $newly_saved_object;
955
+                $this->_model_relations[$relationName] = $newly_saved_object;
956 956
                 return true;
957 957
                 // or if it's some kind of sordid feral polyamorous relationship...
958 958
             }
959 959
             if (
960
-                is_array($this->_model_relations[ $relationName ])
961
-                && isset($this->_model_relations[ $relationName ][ $current_cache_id ])
960
+                is_array($this->_model_relations[$relationName])
961
+                && isset($this->_model_relations[$relationName][$current_cache_id])
962 962
             ) {
963 963
                 // then remove the current cached item
964
-                unset($this->_model_relations[ $relationName ][ $current_cache_id ]);
964
+                unset($this->_model_relations[$relationName][$current_cache_id]);
965 965
                 // and cache the newly saved object using it's new ID
966
-                $this->_model_relations[ $relationName ][ $newly_saved_object->ID() ] = $newly_saved_object;
966
+                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
967 967
                 return true;
968 968
             }
969 969
         }
@@ -980,8 +980,8 @@  discard block
 block discarded – undo
980 980
      */
981 981
     public function get_one_from_cache($relationName)
982 982
     {
983
-        $cached_array_or_object = isset($this->_model_relations[ $relationName ])
984
-            ? $this->_model_relations[ $relationName ]
983
+        $cached_array_or_object = isset($this->_model_relations[$relationName])
984
+            ? $this->_model_relations[$relationName]
985 985
             : null;
986 986
         if (is_array($cached_array_or_object)) {
987 987
             return array_shift($cached_array_or_object);
@@ -1004,7 +1004,7 @@  discard block
 block discarded – undo
1004 1004
      */
1005 1005
     public function get_all_from_cache($relationName)
1006 1006
     {
1007
-        $objects = isset($this->_model_relations[ $relationName ]) ? $this->_model_relations[ $relationName ] : array();
1007
+        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
1008 1008
         // if the result is not an array, but exists, make it an array
1009 1009
         $objects = is_array($objects) ? $objects : array($objects);
1010 1010
         // bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
@@ -1192,9 +1192,9 @@  discard block
 block discarded – undo
1192 1192
     public function get_raw($field_name)
1193 1193
     {
1194 1194
         $field_settings = $this->get_model()->field_settings_for($field_name);
1195
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[ $field_name ] instanceof DateTime
1196
-            ? $this->_fields[ $field_name ]->format('U')
1197
-            : $this->_fields[ $field_name ];
1195
+        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1196
+            ? $this->_fields[$field_name]->format('U')
1197
+            : $this->_fields[$field_name];
1198 1198
     }
1199 1199
 
1200 1200
 
@@ -1216,7 +1216,7 @@  discard block
 block discarded – undo
1216 1216
     public function get_DateTime_object($field_name)
1217 1217
     {
1218 1218
         $field_settings = $this->get_model()->field_settings_for($field_name);
1219
-        if (! $field_settings instanceof EE_Datetime_Field) {
1219
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1220 1220
             EE_Error::add_error(
1221 1221
                 sprintf(
1222 1222
                     esc_html__(
@@ -1231,8 +1231,8 @@  discard block
 block discarded – undo
1231 1231
             );
1232 1232
             return false;
1233 1233
         }
1234
-        return isset($this->_fields[ $field_name ]) && $this->_fields[ $field_name ] instanceof DateTime
1235
-            ? clone $this->_fields[ $field_name ]
1234
+        return isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime
1235
+            ? clone $this->_fields[$field_name]
1236 1236
             : null;
1237 1237
     }
1238 1238
 
@@ -1476,7 +1476,7 @@  discard block
 block discarded – undo
1476 1476
      */
1477 1477
     public function get_i18n_datetime($field_name, $format = '')
1478 1478
     {
1479
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1479
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1480 1480
         return date_i18n(
1481 1481
             $format,
1482 1482
             EEH_DTT_Helper::get_timestamp_with_offset(
@@ -1588,21 +1588,21 @@  discard block
 block discarded – undo
1588 1588
         $field->set_time_format($this->_tm_frmt);
1589 1589
         switch ($what) {
1590 1590
             case 'T':
1591
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_time(
1591
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_time(
1592 1592
                     $datetime_value,
1593
-                    $this->_fields[ $field_name ]
1593
+                    $this->_fields[$field_name]
1594 1594
                 );
1595 1595
                 $this->_has_changes = true;
1596 1596
                 break;
1597 1597
             case 'D':
1598
-                $this->_fields[ $field_name ] = $field->prepare_for_set_with_new_date(
1598
+                $this->_fields[$field_name] = $field->prepare_for_set_with_new_date(
1599 1599
                     $datetime_value,
1600
-                    $this->_fields[ $field_name ]
1600
+                    $this->_fields[$field_name]
1601 1601
                 );
1602 1602
                 $this->_has_changes = true;
1603 1603
                 break;
1604 1604
             case 'B':
1605
-                $this->_fields[ $field_name ] = $field->prepare_for_set($datetime_value);
1605
+                $this->_fields[$field_name] = $field->prepare_for_set($datetime_value);
1606 1606
                 $this->_has_changes = true;
1607 1607
                 break;
1608 1608
         }
@@ -1645,7 +1645,7 @@  discard block
 block discarded – undo
1645 1645
         $this->set_timezone($timezone);
1646 1646
         $fn = (array) $field_name;
1647 1647
         $args = array_merge($fn, (array) $args);
1648
-        if (! method_exists($this, $callback)) {
1648
+        if ( ! method_exists($this, $callback)) {
1649 1649
             throw new EE_Error(
1650 1650
                 sprintf(
1651 1651
                     esc_html__(
@@ -1657,7 +1657,7 @@  discard block
 block discarded – undo
1657 1657
             );
1658 1658
         }
1659 1659
         $args = (array) $args;
1660
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1660
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1661 1661
         $this->set_timezone($original_timezone);
1662 1662
         return $return;
1663 1663
     }
@@ -1772,8 +1772,8 @@  discard block
 block discarded – undo
1772 1772
     {
1773 1773
         $model = $this->get_model();
1774 1774
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1775
-            if (! empty($this->_model_relations[ $relation_name ])) {
1776
-                $related_objects = $this->_model_relations[ $relation_name ];
1775
+            if ( ! empty($this->_model_relations[$relation_name])) {
1776
+                $related_objects = $this->_model_relations[$relation_name];
1777 1777
                 if ($relation_obj instanceof EE_Belongs_To_Relation) {
1778 1778
                     // this relation only stores a single model object, not an array
1779 1779
                     // but let's make it consistent
@@ -1832,7 +1832,7 @@  discard block
 block discarded – undo
1832 1832
             $this->set($column, $value);
1833 1833
         }
1834 1834
         // no changes ? then don't do anything
1835
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1835
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1836 1836
             return 0;
1837 1837
         }
1838 1838
         /**
@@ -1842,7 +1842,7 @@  discard block
 block discarded – undo
1842 1842
          * @param EE_Base_Class $model_object the model object about to be saved.
1843 1843
          */
1844 1844
         do_action('AHEE__EE_Base_Class__save__begin', $this);
1845
-        if (! $this->allow_persist()) {
1845
+        if ( ! $this->allow_persist()) {
1846 1846
             return 0;
1847 1847
         }
1848 1848
         // now get current attribute values
@@ -1857,10 +1857,10 @@  discard block
 block discarded – undo
1857 1857
         if ($model->has_primary_key_field()) {
1858 1858
             if ($model->get_primary_key_field()->is_auto_increment()) {
1859 1859
                 // ok check if it's set, if so: update; if not, insert
1860
-                if (! empty($save_cols_n_values[ $model->primary_key_name() ])) {
1860
+                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1861 1861
                     $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1862 1862
                 } else {
1863
-                    unset($save_cols_n_values[ $model->primary_key_name() ]);
1863
+                    unset($save_cols_n_values[$model->primary_key_name()]);
1864 1864
                     $results = $model->insert($save_cols_n_values);
1865 1865
                     if ($results) {
1866 1866
                         // if successful, set the primary key
@@ -1870,7 +1870,7 @@  discard block
 block discarded – undo
1870 1870
                         // will get added to the mapper before we can add this one!
1871 1871
                         // but if we just avoid using the SET method, all that headache can be avoided
1872 1872
                         $pk_field_name = $model->primary_key_name();
1873
-                        $this->_fields[ $pk_field_name ] = $results;
1873
+                        $this->_fields[$pk_field_name] = $results;
1874 1874
                         $this->_clear_cached_property($pk_field_name);
1875 1875
                         $model->add_to_entity_map($this);
1876 1876
                         $this->_update_cached_related_model_objs_fks();
@@ -1887,8 +1887,8 @@  discard block
 block discarded – undo
1887 1887
                                     'event_espresso'
1888 1888
                                 ),
1889 1889
                                 get_class($this),
1890
-                                get_class($model) . '::instance()->add_to_entity_map()',
1891
-                                get_class($model) . '::instance()->get_one_by_ID()',
1890
+                                get_class($model).'::instance()->add_to_entity_map()',
1891
+                                get_class($model).'::instance()->get_one_by_ID()',
1892 1892
                                 '<br />'
1893 1893
                             )
1894 1894
                         );
@@ -1990,27 +1990,27 @@  discard block
 block discarded – undo
1990 1990
     public function save_new_cached_related_model_objs()
1991 1991
     {
1992 1992
         // make sure this has been saved
1993
-        if (! $this->ID()) {
1993
+        if ( ! $this->ID()) {
1994 1994
             $id = $this->save();
1995 1995
         } else {
1996 1996
             $id = $this->ID();
1997 1997
         }
1998 1998
         // now save all the NEW cached model objects  (ie they don't exist in the DB)
1999 1999
         foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
2000
-            if ($this->_model_relations[ $relationName ]) {
2000
+            if ($this->_model_relations[$relationName]) {
2001 2001
                 // is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
2002 2002
                 // or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
2003 2003
                 /* @var $related_model_obj EE_Base_Class */
2004 2004
                 if ($relationObj instanceof EE_Belongs_To_Relation) {
2005 2005
                     // add a relation to that relation type (which saves the appropriate thing in the process)
2006 2006
                     // but ONLY if it DOES NOT exist in the DB
2007
-                    $related_model_obj = $this->_model_relations[ $relationName ];
2007
+                    $related_model_obj = $this->_model_relations[$relationName];
2008 2008
                     // if( ! $related_model_obj->ID()){
2009 2009
                     $this->_add_relation_to($related_model_obj, $relationName);
2010 2010
                     $related_model_obj->save_new_cached_related_model_objs();
2011 2011
                     // }
2012 2012
                 } else {
2013
-                    foreach ($this->_model_relations[ $relationName ] as $related_model_obj) {
2013
+                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
2014 2014
                         // add a relation to that relation type (which saves the appropriate thing in the process)
2015 2015
                         // but ONLY if it DOES NOT exist in the DB
2016 2016
                         // if( ! $related_model_obj->ID()){
@@ -2037,7 +2037,7 @@  discard block
 block discarded – undo
2037 2037
      */
2038 2038
     public function get_model()
2039 2039
     {
2040
-        if (! $this->_model) {
2040
+        if ( ! $this->_model) {
2041 2041
             $modelName = self::_get_model_classname(get_class($this));
2042 2042
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
2043 2043
         } else {
@@ -2063,9 +2063,9 @@  discard block
 block discarded – undo
2063 2063
         $primary_id_ref = self::_get_primary_key_name($classname);
2064 2064
         if (
2065 2065
             array_key_exists($primary_id_ref, $props_n_values)
2066
-            && ! empty($props_n_values[ $primary_id_ref ])
2066
+            && ! empty($props_n_values[$primary_id_ref])
2067 2067
         ) {
2068
-            $id = $props_n_values[ $primary_id_ref ];
2068
+            $id = $props_n_values[$primary_id_ref];
2069 2069
             return self::_get_model($classname)->get_from_entity_map($id);
2070 2070
         }
2071 2071
         return false;
@@ -2100,10 +2100,10 @@  discard block
 block discarded – undo
2100 2100
             $primary_id_ref = self::_get_primary_key_name($classname);
2101 2101
             if (
2102 2102
                 array_key_exists($primary_id_ref, $props_n_values)
2103
-                && ! empty($props_n_values[ $primary_id_ref ])
2103
+                && ! empty($props_n_values[$primary_id_ref])
2104 2104
             ) {
2105 2105
                 $existing = $model->get_one_by_ID(
2106
-                    $props_n_values[ $primary_id_ref ]
2106
+                    $props_n_values[$primary_id_ref]
2107 2107
                 );
2108 2108
             }
2109 2109
         } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
@@ -2115,7 +2115,7 @@  discard block
 block discarded – undo
2115 2115
         }
2116 2116
         if ($existing) {
2117 2117
             // set date formats if present before setting values
2118
-            if (! empty($date_formats) && is_array($date_formats)) {
2118
+            if ( ! empty($date_formats) && is_array($date_formats)) {
2119 2119
                 $existing->set_date_format($date_formats[0]);
2120 2120
                 $existing->set_time_format($date_formats[1]);
2121 2121
             } else {
@@ -2148,7 +2148,7 @@  discard block
 block discarded – undo
2148 2148
     protected static function _get_model($classname, $timezone = null)
2149 2149
     {
2150 2150
         // find model for this class
2151
-        if (! $classname) {
2151
+        if ( ! $classname) {
2152 2152
             throw new EE_Error(
2153 2153
                 sprintf(
2154 2154
                     esc_html__(
@@ -2196,7 +2196,7 @@  discard block
 block discarded – undo
2196 2196
     {
2197 2197
         return strpos((string) $model_name, 'EE_') === 0
2198 2198
             ? str_replace('EE_', 'EEM_', $model_name)
2199
-            : 'EEM_' . $model_name;
2199
+            : 'EEM_'.$model_name;
2200 2200
     }
2201 2201
 
2202 2202
 
@@ -2213,7 +2213,7 @@  discard block
 block discarded – undo
2213 2213
      */
2214 2214
     protected static function _get_primary_key_name($classname = null)
2215 2215
     {
2216
-        if (! $classname) {
2216
+        if ( ! $classname) {
2217 2217
             throw new EE_Error(
2218 2218
                 sprintf(
2219 2219
                     esc_html__('What were you thinking calling _get_primary_key_name(%s)', 'event_espresso'),
@@ -2243,7 +2243,7 @@  discard block
 block discarded – undo
2243 2243
         $model = $this->get_model();
2244 2244
         // now that we know the name of the variable, use a variable variable to get its value and return its
2245 2245
         if ($model->has_primary_key_field()) {
2246
-            return $this->_fields[ $model->primary_key_name() ];
2246
+            return $this->_fields[$model->primary_key_name()];
2247 2247
         }
2248 2248
         return $model->get_index_primary_key_string($this->_fields);
2249 2249
     }
@@ -2317,7 +2317,7 @@  discard block
 block discarded – undo
2317 2317
             }
2318 2318
         } else {
2319 2319
             // this thing doesn't exist in the DB,  so just cache it
2320
-            if (! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2320
+            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2321 2321
                 throw new EE_Error(
2322 2322
                     sprintf(
2323 2323
                         esc_html__(
@@ -2482,7 +2482,7 @@  discard block
 block discarded – undo
2482 2482
             } else {
2483 2483
                 // did we already cache the result of this query?
2484 2484
                 $cached_results = $this->get_all_from_cache($relationName);
2485
-                if (! $cached_results) {
2485
+                if ( ! $cached_results) {
2486 2486
                     $related_model_objects = $this->get_model()->get_all_related(
2487 2487
                         $this,
2488 2488
                         $relationName,
@@ -2593,7 +2593,7 @@  discard block
 block discarded – undo
2593 2593
             } else {
2594 2594
                 // first, check if we've already cached the result of this query
2595 2595
                 $cached_result = $this->get_one_from_cache($relationName);
2596
-                if (! $cached_result) {
2596
+                if ( ! $cached_result) {
2597 2597
                     $related_model_object = $model->get_first_related(
2598 2598
                         $this,
2599 2599
                         $relationName,
@@ -2617,7 +2617,7 @@  discard block
 block discarded – undo
2617 2617
             }
2618 2618
             // this doesn't exist in the DB and apparently the thing it belongs to doesn't either,
2619 2619
             // just get what's cached on this object
2620
-            if (! $related_model_object) {
2620
+            if ( ! $related_model_object) {
2621 2621
                 $related_model_object = $this->get_one_from_cache($relationName);
2622 2622
             }
2623 2623
         }
@@ -2699,7 +2699,7 @@  discard block
 block discarded – undo
2699 2699
      */
2700 2700
     public function is_set($field_name)
2701 2701
     {
2702
-        return isset($this->_fields[ $field_name ]);
2702
+        return isset($this->_fields[$field_name]);
2703 2703
     }
2704 2704
 
2705 2705
 
@@ -2715,7 +2715,7 @@  discard block
 block discarded – undo
2715 2715
     {
2716 2716
         foreach ((array) $properties as $property_name) {
2717 2717
             // first make sure this property exists
2718
-            if (! $this->_fields[ $property_name ]) {
2718
+            if ( ! $this->_fields[$property_name]) {
2719 2719
                 throw new EE_Error(
2720 2720
                     sprintf(
2721 2721
                         esc_html__(
@@ -2747,7 +2747,7 @@  discard block
 block discarded – undo
2747 2747
         $properties = array();
2748 2748
         // remove prepended underscore
2749 2749
         foreach ($fields as $field_name => $settings) {
2750
-            $properties[ $field_name ] = $this->get($field_name);
2750
+            $properties[$field_name] = $this->get($field_name);
2751 2751
         }
2752 2752
         return $properties;
2753 2753
     }
@@ -2784,7 +2784,7 @@  discard block
 block discarded – undo
2784 2784
     {
2785 2785
         $className = get_class($this);
2786 2786
         $tagName = "FHEE__{$className}__{$methodName}";
2787
-        if (! has_filter($tagName)) {
2787
+        if ( ! has_filter($tagName)) {
2788 2788
             throw new EE_Error(
2789 2789
                 sprintf(
2790 2790
                     esc_html__(
@@ -2829,7 +2829,7 @@  discard block
 block discarded – undo
2829 2829
             $query_params[0]['EXM_value'] = $meta_value;
2830 2830
         }
2831 2831
         $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2832
-        if (! $existing_rows_like_that) {
2832
+        if ( ! $existing_rows_like_that) {
2833 2833
             return $this->add_extra_meta($meta_key, $meta_value);
2834 2834
         }
2835 2835
         foreach ($existing_rows_like_that as $existing_row) {
@@ -2928,7 +2928,7 @@  discard block
 block discarded – undo
2928 2928
      */
2929 2929
     public function get_extra_meta(string $meta_key, bool $single = false, $default = null, ?array $extra_where = [])
2930 2930
     {
2931
-        $query_params = [ $extra_where + ['EXM_key' => $meta_key] ];
2931
+        $query_params = [$extra_where + ['EXM_key' => $meta_key]];
2932 2932
         if ($single) {
2933 2933
             $result = $this->get_first_related('Extra_Meta', $query_params);
2934 2934
             if ($result instanceof EE_Extra_Meta) {
@@ -2940,7 +2940,7 @@  discard block
 block discarded – undo
2940 2940
                 $values = [];
2941 2941
                 foreach ($results as $result) {
2942 2942
                     if ($result instanceof EE_Extra_Meta) {
2943
-                        $values[ $result->ID() ] = $result->value();
2943
+                        $values[$result->ID()] = $result->value();
2944 2944
                     }
2945 2945
                 }
2946 2946
                 return $values;
@@ -2985,17 +2985,17 @@  discard block
 block discarded – undo
2985 2985
             );
2986 2986
             foreach ($extra_meta_objs as $extra_meta_obj) {
2987 2987
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2988
-                    $return_array[ $extra_meta_obj->key() ] = $extra_meta_obj->value();
2988
+                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2989 2989
                 }
2990 2990
             }
2991 2991
         } else {
2992 2992
             $extra_meta_objs = $this->get_many_related('Extra_Meta');
2993 2993
             foreach ($extra_meta_objs as $extra_meta_obj) {
2994 2994
                 if ($extra_meta_obj instanceof EE_Extra_Meta) {
2995
-                    if (! isset($return_array[ $extra_meta_obj->key() ])) {
2996
-                        $return_array[ $extra_meta_obj->key() ] = [];
2995
+                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2996
+                        $return_array[$extra_meta_obj->key()] = [];
2997 2997
                     }
2998
-                    $return_array[ $extra_meta_obj->key() ][ $extra_meta_obj->ID() ] = $extra_meta_obj->value();
2998
+                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2999 2999
                 }
3000 3000
             }
3001 3001
         }
@@ -3076,8 +3076,8 @@  discard block
 block discarded – undo
3076 3076
                             'event_espresso'
3077 3077
                         ),
3078 3078
                         $this->ID(),
3079
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
3080
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
3079
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
3080
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
3081 3081
                     )
3082 3082
                 );
3083 3083
             }
@@ -3110,7 +3110,7 @@  discard block
 block discarded – undo
3110 3110
     {
3111 3111
         // First make sure this model object actually exists in the DB. It would be silly to try to update it in the DB
3112 3112
         // if it wasn't even there to start off.
3113
-        if (! $this->ID()) {
3113
+        if ( ! $this->ID()) {
3114 3114
             $this->save();
3115 3115
         }
3116 3116
         global $wpdb;
@@ -3340,7 +3340,7 @@  discard block
 block discarded – undo
3340 3340
         $model = $this->get_model();
3341 3341
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
3342 3342
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
3343
-                $classname = 'EE_' . $model->get_this_model_name();
3343
+                $classname = 'EE_'.$model->get_this_model_name();
3344 3344
                 if (
3345 3345
                     $this->get_one_from_cache($relation_name) instanceof $classname
3346 3346
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -3381,7 +3381,7 @@  discard block
 block discarded – undo
3381 3381
         // handle DateTimes (this is handled in here because there's no one specific child class that uses datetimes).
3382 3382
         foreach ($this->_fields as $field => $value) {
3383 3383
             if ($value instanceof DateTime) {
3384
-                $this->_fields[ $field ] = clone $value;
3384
+                $this->_fields[$field] = clone $value;
3385 3385
             }
3386 3386
         }
3387 3387
     }
Please login to merge, or discard this patch.
caffeinated/admin/new/pricing/Pricing_Admin_Page.core.php 2 patches
Indentation   +1283 added lines, -1283 removed lines patch added patch discarded remove patch
@@ -12,1178 +12,1178 @@  discard block
 block discarded – undo
12 12
  */
13 13
 class Pricing_Admin_Page extends EE_Admin_Page
14 14
 {
15
-    protected function _init_page_props()
16
-    {
17
-        $this->page_slug        = PRICING_PG_SLUG;
18
-        $this->page_label       = PRICING_LABEL;
19
-        $this->_admin_base_url  = PRICING_ADMIN_URL;
20
-        $this->_admin_base_path = PRICING_ADMIN;
21
-    }
22
-
23
-
24
-    protected function _ajax_hooks()
25
-    {
26
-        add_action('wp_ajax_espresso_update_prices_order', [$this, 'update_price_order']);
27
-    }
28
-
29
-
30
-    protected function _define_page_props()
31
-    {
32
-        $this->_admin_page_title = PRICING_LABEL;
33
-        $this->_labels           = [
34
-            'buttons' => [
35
-                'add'         => esc_html__('Add New Default Price', 'event_espresso'),
36
-                'edit'        => esc_html__('Edit Default Price', 'event_espresso'),
37
-                'delete'      => esc_html__('Delete Default Price', 'event_espresso'),
38
-                'add_type'    => esc_html__('Add New Default Price Type', 'event_espresso'),
39
-                'edit_type'   => esc_html__('Edit Price Type', 'event_espresso'),
40
-                'delete_type' => esc_html__('Delete Price Type', 'event_espresso'),
41
-            ],
42
-            'publishbox' => [
43
-                'add_new_price'      => esc_html__('Add New Default Price', 'event_espresso'),
44
-                'edit_price'         => esc_html__('Edit Default Price', 'event_espresso'),
45
-                'add_new_price_type' => esc_html__('Add New Default Price Type', 'event_espresso'),
46
-                'edit_price_type'    => esc_html__('Edit Price Type', 'event_espresso'),
47
-            ],
48
-        ];
49
-    }
50
-
51
-
52
-    /**
53
-     * an array for storing request actions and their corresponding methods
54
-     *
55
-     * @return void
56
-     */
57
-    protected function _set_page_routes()
58
-    {
59
-        $PRC_ID             = $this->request->getRequestParam('PRC_ID', 0, DataType::INTEGER);
60
-        $PRT_ID             = $this->request->getRequestParam('PRT_ID', 0, DataType::INTEGER);
61
-        $this->_page_routes = [
62
-            'default'                     => [
63
-                'func'       => [$this, '_price_overview_list_table'],
64
-                'capability' => 'ee_read_default_prices',
65
-            ],
66
-            'add_new_price'               => [
67
-                'func'       => [$this, '_edit_price_details'],
68
-                'capability' => 'ee_edit_default_prices',
69
-            ],
70
-            'edit_price'                  => [
71
-                'func'       => [$this, '_edit_price_details'],
72
-                'capability' => 'ee_edit_default_price',
73
-                'obj_id'     => $PRC_ID,
74
-            ],
75
-            'insert_price'                => [
76
-                'func'       => [$this, '_insert_or_update_price'],
77
-                'args'       => ['insert' => true],
78
-                'noheader'   => true,
79
-                'capability' => 'ee_edit_default_prices',
80
-            ],
81
-            'update_price'                => [
82
-                'func'       => [$this, '_insert_or_update_price'],
83
-                'args'       => ['insert' => false],
84
-                'noheader'   => true,
85
-                'capability' => 'ee_edit_default_price',
86
-                'obj_id'     => $PRC_ID,
87
-            ],
88
-            'trash_price'                 => [
89
-                'func'       => [$this, '_trash_or_restore_price'],
90
-                'args'       => ['trash' => true],
91
-                'noheader'   => true,
92
-                'capability' => 'ee_delete_default_price',
93
-                'obj_id'     => $PRC_ID,
94
-            ],
95
-            'restore_price'               => [
96
-                'func'       => [$this, '_trash_or_restore_price'],
97
-                'args'       => ['trash' => false],
98
-                'noheader'   => true,
99
-                'capability' => 'ee_delete_default_price',
100
-                'obj_id'     => $PRC_ID,
101
-            ],
102
-            'delete_price'                => [
103
-                'func'       => [$this, '_delete_price'],
104
-                'noheader'   => true,
105
-                'capability' => 'ee_delete_default_price',
106
-                'obj_id'     => $PRC_ID,
107
-            ],
108
-            'espresso_update_price_order' => [
109
-                'func'       => [$this, 'update_price_order'],
110
-                'noheader'   => true,
111
-                'capability' => 'ee_edit_default_prices',
112
-            ],
113
-            // price types
114
-            'price_types'                 => [
115
-                'func'       => [$this, '_price_types_overview_list_table'],
116
-                'capability' => 'ee_read_default_price_types',
117
-            ],
118
-            'add_new_price_type'          => [
119
-                'func'       => [$this, '_edit_price_type_details'],
120
-                'capability' => 'ee_edit_default_price_types',
121
-            ],
122
-            'edit_price_type'             => [
123
-                'func'       => [$this, '_edit_price_type_details'],
124
-                'capability' => 'ee_edit_default_price_type',
125
-                'obj_id'     => $PRT_ID,
126
-            ],
127
-            'insert_price_type'           => [
128
-                'func'       => [$this, '_insert_or_update_price_type'],
129
-                'args'       => ['new_price_type' => true],
130
-                'noheader'   => true,
131
-                'capability' => 'ee_edit_default_price_types',
132
-            ],
133
-            'update_price_type'           => [
134
-                'func'       => [$this, '_insert_or_update_price_type'],
135
-                'args'       => ['new_price_type' => false],
136
-                'noheader'   => true,
137
-                'capability' => 'ee_edit_default_price_type',
138
-                'obj_id'     => $PRT_ID,
139
-            ],
140
-            'trash_price_type'            => [
141
-                'func'       => [$this, '_trash_or_restore_price_type'],
142
-                'args'       => ['trash' => true],
143
-                'noheader'   => true,
144
-                'capability' => 'ee_delete_default_price_type',
145
-                'obj_id'     => $PRT_ID,
146
-            ],
147
-            'restore_price_type'          => [
148
-                'func'       => [$this, '_trash_or_restore_price_type'],
149
-                'args'       => ['trash' => false],
150
-                'noheader'   => true,
151
-                'capability' => 'ee_delete_default_price_type',
152
-                'obj_id'     => $PRT_ID,
153
-            ],
154
-            'delete_price_type'           => [
155
-                'func'       => [$this, '_delete_price_type'],
156
-                'noheader'   => true,
157
-                'capability' => 'ee_delete_default_price_type',
158
-                'obj_id'     => $PRT_ID,
159
-            ],
160
-            'tax_settings'                => [
161
-                'func'       => [$this, '_tax_settings'],
162
-                'capability' => 'manage_options',
163
-            ],
164
-            'update_tax_settings'         => [
165
-                'func'       => [$this, '_update_tax_settings'],
166
-                'capability' => 'manage_options',
167
-                'noheader'   => true,
168
-            ],
169
-        ];
170
-    }
171
-
172
-
173
-    protected function _set_page_config()
174
-    {
175
-        $PRC_ID             = $this->request->getRequestParam('id', 0, DataType::INTEGER);
176
-        $this->_page_config = [
177
-            'default'            => [
178
-                'nav'           => [
179
-                    'label' => esc_html__('Default Pricing', 'event_espresso'),
180
-                    'icon' => 'dashicons-money-alt',
181
-                    'order' => 10,
182
-                ],
183
-                'list_table'    => 'Prices_List_Table',
184
-                'metaboxes'     => $this->_default_espresso_metaboxes,
185
-                'help_tabs'     => [
186
-                    'pricing_default_pricing_help_tab'                           => [
187
-                        'title'    => esc_html__('Default Pricing', 'event_espresso'),
188
-                        'filename' => 'pricing_default_pricing',
189
-                    ],
190
-                    'pricing_default_pricing_table_column_headings_help_tab'     => [
191
-                        'title'    => esc_html__('Default Pricing Table Column Headings', 'event_espresso'),
192
-                        'filename' => 'pricing_default_pricing_table_column_headings',
193
-                    ],
194
-                    'pricing_default_pricing_views_bulk_actions_search_help_tab' => [
195
-                        'title'    => esc_html__('Default Pricing Views & Bulk Actions & Search', 'event_espresso'),
196
-                        'filename' => 'pricing_default_pricing_views_bulk_actions_search',
197
-                    ],
198
-                ],
199
-                'require_nonce' => false,
200
-            ],
201
-            'add_new_price'      => [
202
-                'nav'           => [
203
-                    'label'      => esc_html__('Add New Default Price', 'event_espresso'),
204
-                    'icon' => 'dashicons-plus-alt',
205
-                    'order'      => 20,
206
-                    'persistent' => false,
207
-                ],
208
-                'help_tabs'     => [
209
-                    'add_new_default_price_help_tab' => [
210
-                        'title'    => esc_html__('Add New Default Price', 'event_espresso'),
211
-                        'filename' => 'pricing_add_new_default_price',
212
-                    ],
213
-                ],
214
-                'metaboxes'     => array_merge(
215
-                    ['_publish_post_box'],
216
-                    $this->_default_espresso_metaboxes
217
-                ),
218
-                'require_nonce' => false,
219
-            ],
220
-            'edit_price'         => [
221
-                'nav'           => [
222
-                    'label'      => esc_html__('Edit Default Price', 'event_espresso'),
223
-                    'icon' => 'dashicons-edit-large',
224
-                    'order'      => 20,
225
-                    'url'        => $PRC_ID
226
-                        ? add_query_arg(['id' => $PRC_ID], $this->_current_page_view_url)
227
-                        : $this->_admin_base_url,
228
-                    'persistent' => false,
229
-                ],
230
-                'metaboxes'     => array_merge(
231
-                    ['_publish_post_box'],
232
-                    $this->_default_espresso_metaboxes
233
-                ),
234
-                'help_tabs'     => [
235
-                    'edit_default_price_help_tab' => [
236
-                        'title'    => esc_html__('Edit Default Price', 'event_espresso'),
237
-                        'filename' => 'pricing_edit_default_price',
238
-                    ],
239
-                ],
240
-                'require_nonce' => false,
241
-            ],
242
-            'price_types'        => [
243
-                'nav'           => [
244
-                    'label' => esc_html__('Price Types', 'event_espresso'),
245
-                    'icon' => 'dashicons-networking',
246
-                    'order' => 30,
247
-                ],
248
-                'list_table'    => 'Price_Types_List_Table',
249
-                'help_tabs'     => [
250
-                    'pricing_price_types_help_tab'                           => [
251
-                        'title'    => esc_html__('Price Types', 'event_espresso'),
252
-                        'filename' => 'pricing_price_types',
253
-                    ],
254
-                    'pricing_price_types_table_column_headings_help_tab'     => [
255
-                        'title'    => esc_html__('Price Types Table Column Headings', 'event_espresso'),
256
-                        'filename' => 'pricing_price_types_table_column_headings',
257
-                    ],
258
-                    'pricing_price_types_views_bulk_actions_search_help_tab' => [
259
-                        'title'    => esc_html__('Price Types Views & Bulk Actions & Search', 'event_espresso'),
260
-                        'filename' => 'pricing_price_types_views_bulk_actions_search',
261
-                    ],
262
-                ],
263
-                'metaboxes'     => $this->_default_espresso_metaboxes,
264
-                'require_nonce' => false,
265
-            ],
266
-            'add_new_price_type' => [
267
-                'nav'           => [
268
-                    'label'      => esc_html__('Add New Price Type', 'event_espresso'),
269
-                    'icon' => 'dashicons-plus-alt',
270
-                    'order'      => 40,
271
-                    'persistent' => false,
272
-                ],
273
-                'help_tabs'     => [
274
-                    'add_new_price_type_help_tab' => [
275
-                        'title'    => esc_html__('Add New Price Type', 'event_espresso'),
276
-                        'filename' => 'pricing_add_new_price_type',
277
-                    ],
278
-                ],
279
-                'metaboxes'     => array_merge(
280
-                    ['_publish_post_box'],
281
-                    $this->_default_espresso_metaboxes
282
-                ),
283
-                'require_nonce' => false,
284
-            ],
285
-            'edit_price_type'    => [
286
-                'nav'           => [
287
-                    'label'      => esc_html__('Edit Price Type', 'event_espresso'),
288
-                    'icon' => 'dashicons-edit-large',
289
-                    'order'      => 40,
290
-                    'persistent' => false,
291
-                ],
292
-                'help_tabs'     => [
293
-                    'edit_price_type_help_tab' => [
294
-                        'title'    => esc_html__('Edit Price Type', 'event_espresso'),
295
-                        'filename' => 'pricing_edit_price_type',
296
-                    ],
297
-                ],
298
-                'metaboxes'     => array_merge(
299
-                    ['_publish_post_box'],
300
-                    $this->_default_espresso_metaboxes
301
-                ),
302
-                'require_nonce' => false,
303
-            ],
304
-            'tax_settings'       => [
305
-                'nav' => [
306
-                    'label' => esc_html__('Tax Settings', 'event_espresso'),
307
-                    'icon' => 'dashicons-sticky',
308
-                    'order' => 50,
309
-                ],
310
-                'labels'        => [
311
-                    'publishbox' => esc_html__('Update Tax Settings', 'event_espresso'),
312
-                ],
313
-                'metaboxes'     => array_merge(
314
-                    ['_publish_post_box'],
315
-                    $this->_default_espresso_metaboxes
316
-                ),
317
-                'require_nonce' => true,
318
-            ],
319
-        ];
320
-    }
321
-
322
-
323
-    protected function _add_screen_options()
324
-    {
325
-        // todo
326
-    }
327
-
328
-
329
-    protected function _add_screen_options_default()
330
-    {
331
-        $this->_per_page_screen_option();
332
-    }
333
-
334
-
335
-    protected function _add_screen_options_price_types()
336
-    {
337
-        $page_title              = $this->_admin_page_title;
338
-        $this->_admin_page_title = esc_html__('Price Types', 'event_espresso');
339
-        $this->_per_page_screen_option();
340
-        $this->_admin_page_title = $page_title;
341
-    }
342
-
343
-
344
-    protected function _add_feature_pointers()
345
-    {
346
-    }
347
-
348
-
349
-    public function load_scripts_styles()
350
-    {
351
-        // styles
352
-        wp_enqueue_style('espresso-ui-theme');
353
-        wp_register_style(
354
-            'espresso_pricing_css',
355
-            PRICING_ASSETS_URL . 'espresso_pricing_admin.css',
356
-            [EspressoLegacyAdminAssetManager::CSS_HANDLE_EE_ADMIN],
357
-            EVENT_ESPRESSO_VERSION
358
-        );
359
-        wp_enqueue_style('espresso_pricing_css');
360
-
361
-        // scripts
362
-        wp_enqueue_script('ee_admin_js');
363
-        wp_enqueue_script('jquery-ui-position');
364
-        wp_enqueue_script('jquery-ui-widget');
365
-        wp_register_script(
366
-            'espresso_pricing_js',
367
-            PRICING_ASSETS_URL . 'espresso_pricing_admin.js',
368
-            ['jquery'],
369
-            EVENT_ESPRESSO_VERSION,
370
-            true
371
-        );
372
-        wp_enqueue_script('espresso_pricing_js');
373
-    }
374
-
375
-
376
-    public function load_scripts_styles_default()
377
-    {
378
-        wp_enqueue_script('espresso_ajax_table_sorting');
379
-    }
380
-
381
-
382
-    public function admin_footer_scripts()
383
-    {
384
-    }
385
-
386
-
387
-    public function admin_init()
388
-    {
389
-    }
390
-
391
-
392
-    public function admin_notices()
393
-    {
394
-    }
395
-
396
-
397
-    protected function _set_list_table_views_default()
398
-    {
399
-        $this->_views = [
400
-            'all' => [
401
-                'slug'        => 'all',
402
-                'label'       => esc_html__('View All Default Pricing', 'event_espresso'),
403
-                'count'       => 0,
404
-                'bulk_action' => [
405
-                    'trash_price' => esc_html__('Move to Trash', 'event_espresso'),
406
-                ],
407
-            ],
408
-        ];
409
-
410
-        if (EE_Registry::instance()->CAP->current_user_can('ee_delete_default_prices', 'pricing_trash_price')) {
411
-            $this->_views['trashed'] = [
412
-                'slug'        => 'trashed',
413
-                'label'       => esc_html__('Trash', 'event_espresso'),
414
-                'count'       => 0,
415
-                'bulk_action' => [
416
-                    'restore_price' => esc_html__('Restore from Trash', 'event_espresso'),
417
-                    'delete_price'  => esc_html__('Delete Permanently', 'event_espresso'),
418
-                ],
419
-            ];
420
-        }
421
-    }
422
-
423
-
424
-    protected function _set_list_table_views_price_types()
425
-    {
426
-        $this->_views = [
427
-            'all' => [
428
-                'slug'        => 'all',
429
-                'label'       => esc_html__('All', 'event_espresso'),
430
-                'count'       => 0,
431
-                'bulk_action' => [
432
-                    'trash_price_type' => esc_html__('Move to Trash', 'event_espresso'),
433
-                ],
434
-            ],
435
-        ];
436
-
437
-        if (
438
-            EE_Registry::instance()->CAP->current_user_can(
439
-                'ee_delete_default_price_types',
440
-                'pricing_trash_price_type'
441
-            )
442
-        ) {
443
-            $this->_views['trashed'] = [
444
-                'slug'        => 'trashed',
445
-                'label'       => esc_html__('Trash', 'event_espresso'),
446
-                'count'       => 0,
447
-                'bulk_action' => [
448
-                    'restore_price_type' => esc_html__('Restore from Trash', 'event_espresso'),
449
-                    'delete_price_type'  => esc_html__('Delete Permanently', 'event_espresso'),
450
-                ],
451
-            ];
452
-        }
453
-    }
454
-
455
-
456
-    /**
457
-     * generates HTML for main Prices Admin page
458
-     *
459
-     * @return void
460
-     * @throws EE_Error
461
-     */
462
-    protected function _price_overview_list_table()
463
-    {
464
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
465
-            'add_new_price',
466
-            'add',
467
-            [],
468
-            'add-new-h2'
469
-        );
470
-        $this->_admin_page_title .= $this->_learn_more_about_pricing_link();
471
-        $this->_search_btn_label = esc_html__('Default Prices', 'event_espresso');
472
-        $this->display_admin_list_table_page_with_sidebar();
473
-    }
474
-
475
-
476
-    /**
477
-     * retrieve data for Prices List table
478
-     *
479
-     * @param int  $per_page how many prices displayed per page
480
-     * @param bool $count    return the count or objects
481
-     * @param bool $trashed  whether the current view is of the trash can - eww yuck!
482
-     * @return EE_Soft_Delete_Base_Class[]|int int = count || array of price objects
483
-     * @throws EE_Error
484
-     * @throws ReflectionException
485
-     */
486
-    public function get_prices_overview_data(int $per_page = 10, bool $count = false, bool $trashed = false)
487
-    {
488
-        // start with an empty array
489
-        $event_pricing = [];
490
-
491
-        require_once(PRICING_ADMIN . 'Prices_List_Table.class.php');
492
-
493
-        $orderby = $this->request->getRequestParam('orderby', '');
494
-        $order   = $this->request->getRequestParam('order', 'ASC');
495
-
496
-        switch ($orderby) {
497
-            case 'name':
498
-                $orderby = ['PRC_name' => $order];
499
-                break;
500
-            case 'type':
501
-                $orderby = ['Price_Type.PRT_name' => $order];
502
-                break;
503
-            case 'amount':
504
-                $orderby = ['PRC_amount' => $order];
505
-                break;
506
-            default:
507
-                $orderby = ['PRC_order' => $order, 'Price_Type.PRT_order' => $order, 'PRC_ID' => $order];
508
-        }
509
-
510
-        $current_page = $this->request->getRequestParam('paged', 1, DataType::INTEGER);
511
-        $per_page     = $this->request->getRequestParam('perpage', $per_page, DataType::INTEGER);
512
-
513
-        $where = [
514
-            'PRC_is_default' => 1,
515
-            'PRC_deleted'    => $trashed,
516
-        ];
517
-
518
-        $offset = ($current_page - 1) * $per_page;
519
-        $limit  = [$offset, $per_page];
520
-
521
-        $search_term = $this->request->getRequestParam('s');
522
-        if ($search_term) {
523
-            $search_term = "%{$search_term}%";
524
-            $where['OR'] = [
525
-                'PRC_name'            => ['LIKE', $search_term],
526
-                'PRC_desc'            => ['LIKE', $search_term],
527
-                'PRC_amount'          => ['LIKE', $search_term],
528
-                'Price_Type.PRT_name' => ['LIKE', $search_term],
529
-            ];
530
-        }
531
-
532
-        $query_params = [
533
-            $where,
534
-            'order_by' => $orderby,
535
-            'limit'    => $limit,
536
-            'group_by' => 'PRC_ID',
537
-        ];
538
-
539
-        if ($count) {
540
-            return $trashed
541
-                ? EEM_Price::instance()->count([$where])
542
-                : EEM_Price::instance()->count_deleted_and_undeleted([$where]);
543
-        }
544
-        return EEM_Price::instance()->get_all_deleted_and_undeleted($query_params);
545
-    }
546
-
547
-
548
-    /**
549
-     * @return void
550
-     * @throws EE_Error
551
-     * @throws ReflectionException
552
-     */
553
-    protected function _edit_price_details()
554
-    {
555
-        // grab price ID
556
-        $PRC_ID = $this->request->getRequestParam('id', 0, DataType::INTEGER);
557
-        // change page title based on request action
558
-        switch ($this->_req_action) {
559
-            case 'add_new_price':
560
-                $this->_admin_page_title = esc_html__('Add New Price', 'event_espresso');
561
-                break;
562
-            case 'edit_price':
563
-                $this->_admin_page_title = esc_html__('Edit Price', 'event_espresso');
564
-                break;
565
-            default:
566
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
567
-        }
568
-        // add PRC_ID to title if editing
569
-        $this->_admin_page_title = $PRC_ID ? $this->_admin_page_title . ' # ' . $PRC_ID : $this->_admin_page_title;
570
-
571
-        if ($PRC_ID) {
572
-            $price                    = EEM_Price::instance()->get_one_by_ID($PRC_ID);
573
-            $additional_hidden_fields = [
574
-                'PRC_ID' => ['type' => 'hidden', 'value' => $PRC_ID],
575
-            ];
576
-            $this->_set_add_edit_form_tags('update_price', $additional_hidden_fields);
577
-        } else {
578
-            $price = EEM_Price::instance()->get_new_price();
579
-            $this->_set_add_edit_form_tags('insert_price');
580
-        }
581
-
582
-        if (! $price instanceof EE_Price) {
583
-            throw new RuntimeException(
584
-                sprintf(
585
-                    esc_html__(
586
-                        'A valid Price could not be retrieved from the database with ID: %1$s',
587
-                        'event_espresso'
588
-                    ),
589
-                    $PRC_ID
590
-                )
591
-            );
592
-        }
593
-
594
-        $this->_template_args['PRC_ID'] = $PRC_ID;
595
-        $this->_template_args['price']  = $price;
596
-
597
-        $default_base_price = $price->type_obj() && $price->type_obj()->base_type() === 1;
598
-
599
-        $this->_template_args['default_base_price'] = $default_base_price;
600
-
601
-        // get price types
602
-        $price_types = EEM_Price_Type::instance()->get_all([['PBT_ID' => ['!=', 1]]]);
603
-        if (empty($price_types)) {
604
-            $msg = esc_html__(
605
-                'You have no price types defined. Please add a price type before adding a price.',
606
-                'event_espresso'
607
-            );
608
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
609
-            $this->display_admin_page_with_sidebar();
610
-        }
611
-        $attributes       = [];
612
-        $price_type_names = [];
613
-        $attributes[]     = 'id="PRT_ID"';
614
-        if ($default_base_price) {
615
-            $attributes[]       = 'disabled="disabled"';
616
-            $price_type_names[] = ['id' => 1, 'text' => esc_html__('Base Price', 'event_espresso')];
617
-        }
618
-        foreach ($price_types as $type) {
619
-            $price_type_names[] = ['id' => $type->ID(), 'text' => $type->name()];
620
-        }
621
-        $this->_template_args['attributes']  = implode(' ', $attributes);
622
-        $this->_template_args['price_types'] = $price_type_names;
623
-
624
-        $this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
625
-        $this->_template_args['admin_page_content']            = $this->_edit_price_details_meta_box();
626
-
627
-        $this->_set_publish_post_box_vars('id', $PRC_ID, '', '', true);
628
-        // the details template wrapper
629
-        $this->display_admin_page_with_sidebar();
630
-    }
631
-
632
-
633
-    /**
634
-     *
635
-     * @return string
636
-     */
637
-    public function _edit_price_details_meta_box(): string
638
-    {
639
-        return EEH_Template::display_template(
640
-            PRICING_TEMPLATE_PATH . 'pricing_details_main_meta_box.template.php',
641
-            $this->_template_args,
642
-            true
643
-        );
644
-    }
645
-
646
-
647
-    /**
648
-     * @return array
649
-     * @throws EE_Error
650
-     * @throws ReflectionException
651
-     */
652
-    protected function set_price_column_values(): array
653
-    {
654
-        $PRC_order = 0;
655
-        $PRT_ID    = $this->request->getRequestParam('PRT_ID', 0, DataType::INTEGER);
656
-        if ($PRT_ID) {
657
-            /** @var EE_Price_Type $price_type */
658
-            $price_type = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
659
-            if ($price_type instanceof EE_Price_Type) {
660
-                $PRC_order = $price_type->order();
661
-            }
662
-        }
663
-        return [
664
-            'PRT_ID'         => $PRT_ID,
665
-            'PRC_amount'     => $this->request->getRequestParam('PRC_amount', 0, DataType::FLOAT),
666
-            'PRC_name'       => $this->request->getRequestParam('PRC_name'),
667
-            'PRC_desc'       => $this->request->getRequestParam('PRC_desc'),
668
-            'PRC_is_default' => 1,
669
-            'PRC_overrides'  => null,
670
-            'PRC_order'      => $PRC_order,
671
-            'PRC_deleted'    => 0,
672
-            'PRC_parent'     => 0,
673
-        ];
674
-    }
675
-
676
-
677
-    /**
678
-     * @param bool $insert - whether to insert or update
679
-     * @return void
680
-     * @throws EE_Error
681
-     * @throws ReflectionException
682
-     */
683
-    protected function _insert_or_update_price(bool $insert = false)
684
-    {
685
-        // why be so pessimistic ???  : (
686
-        $updated = 0;
687
-
688
-        $set_column_values = $this->set_price_column_values();
689
-        // is this a new Price ?
690
-        if ($insert) {
691
-            // run the insert
692
-            $PRC_ID = EEM_Price::instance()->insert($set_column_values);
693
-            if ($PRC_ID) {
694
-                // make sure this new price modifier is attached to the ticket but ONLY if it is not a tax type
695
-                $price = EEM_price::instance()->get_one_by_ID($PRC_ID);
696
-                if (
697
-                    $price instanceof EE_Price
698
-                    && $price->type_obj() instanceof EE_Price_type
699
-                    && $price->type_obj()->base_type() !== EEM_Price_Type::base_type_tax
700
-                ) {
701
-                    $ticket = EEM_Ticket::instance()->get_one_by_ID(1);
702
-                    $ticket->_add_relation_to($price, 'Price');
703
-                    $ticket->save();
704
-                }
705
-                $updated = 1;
706
-            }
707
-            $action_desc = 'created';
708
-        } else {
709
-            $PRC_ID = $this->request->getRequestParam('PRC_ID', 0, DataType::INTEGER);
710
-            // run the update
711
-            $where_cols_n_values = ['PRC_ID' => $PRC_ID];
712
-            $updated             = EEM_Price::instance()->update($set_column_values, [$where_cols_n_values]);
713
-
714
-            $price = EEM_Price::instance()->get_one_by_ID($PRC_ID);
715
-            if ($price instanceof EE_Price && $price->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
716
-                // if this is $PRC_ID == 1,
717
-                // then we need to update the default ticket attached to this price so the TKT_price value is updated.
718
-                if ($PRC_ID === 1) {
719
-                    $ticket = $price->get_first_related('Ticket');
720
-                    if ($ticket) {
721
-                        $ticket->set('TKT_price', $price->get('PRC_amount'));
722
-                        $ticket->set('TKT_name', $price->get('PRC_name'));
723
-                        $ticket->set('TKT_description', $price->get('PRC_desc'));
724
-                        $ticket->save();
725
-                    }
726
-                } else {
727
-                    // we make sure this price is attached to base ticket. but ONLY if it's not a tax ticket type.
728
-                    $ticket = EEM_Ticket::instance()->get_one_by_ID(1);
729
-                    if ($ticket instanceof EE_Ticket) {
730
-                        $ticket->_add_relation_to($PRC_ID, 'Price');
731
-                        $ticket->save();
732
-                    }
733
-                }
734
-            }
735
-
736
-            $action_desc = 'updated';
737
-        }
738
-
739
-        $query_args = ['action' => 'edit_price', 'id' => $PRC_ID];
740
-
741
-        $this->_redirect_after_action($updated, 'Prices', $action_desc, $query_args);
742
-    }
743
-
744
-
745
-    /**
746
-     * @param bool $trash - whether to move item to trash (TRUE) or restore it (FALSE)
747
-     * @return void
748
-     * @throws EE_Error
749
-     */
750
-    protected function _trash_or_restore_price($trash = true)
751
-    {
752
-        $entity_model = EEM_Price::instance();
753
-        $action       = $trash ? EE_Admin_List_Table::ACTION_TRASH : EE_Admin_List_Table::ACTION_RESTORE;
754
-        $result       = $this->trashRestoreDeleteEntities(
755
-            $entity_model,
756
-            'id',
757
-            $action,
758
-            'PRC_deleted',
759
-            [$this, 'adjustTicketRelations']
760
-        );
761
-
762
-        if ($result) {
763
-            $msg = $trash
764
-                ? esc_html(
765
-                    _n(
766
-                        'The Price has been trashed',
767
-                        'The Prices have been trashed',
768
-                        $result,
769
-                        'event_espresso'
770
-                    )
771
-                )
772
-                : esc_html(
773
-                    _n(
774
-                        'The Price has been restored',
775
-                        'The Prices have been restored',
776
-                        $result,
777
-                        'event_espresso'
778
-                    )
779
-                );
780
-            EE_Error::add_success($msg);
781
-        }
782
-
783
-        $this->_redirect_after_action(
784
-            $result,
785
-            _n('Price', 'Prices', $result, 'event_espresso'),
786
-            $trash ? 'trashed' : 'restored',
787
-            ['action' => 'default'],
788
-            true
789
-        );
790
-    }
791
-
792
-
793
-    /**
794
-     * @param EEM_Base   $entity_model
795
-     * @param int|string $entity_ID
796
-     * @param string     $action
797
-     * @param int        $result
798
-     * @throws EE_Error
799
-     * @throws ReflectionException
800
-     * @since 4.10.30.p
801
-     */
802
-    public function adjustTicketRelations(
803
-        EEM_Base $entity_model,
804
-        $entity_ID,
805
-        string $action,
806
-        int $result
807
-    ) {
808
-        if (! $entity_ID || (float) $result < 1) {
809
-            return;
810
-        }
811
-
812
-        $entity = $entity_model->get_one_by_ID($entity_ID);
813
-        if (! $entity instanceof EE_Price || $entity->type_obj()->base_type() === EEM_Price_Type::base_type_tax) {
814
-            return;
815
-        }
816
-
817
-        // get default tickets for updating
818
-        $default_tickets = EEM_Ticket::instance()->get_all_default_tickets();
819
-        foreach ($default_tickets as $default_ticket) {
820
-            if (! $default_ticket instanceof EE_Ticket) {
821
-                continue;
822
-            }
823
-            switch ($action) {
824
-                case EE_Admin_List_Table::ACTION_DELETE:
825
-                case EE_Admin_List_Table::ACTION_TRASH:
826
-                    // if trashing then remove relations to base default ticket.
827
-                    $default_ticket->_remove_relation_to($entity_ID, 'Price');
828
-                    break;
829
-                case EE_Admin_List_Table::ACTION_RESTORE:
830
-                    // if restoring then add back to base default ticket
831
-                    $default_ticket->_add_relation_to($entity_ID, 'Price');
832
-                    break;
833
-            }
834
-            $default_ticket->save();
835
-        }
836
-    }
837
-
838
-
839
-    /**
840
-     * @return void
841
-     * @throws EE_Error
842
-     * @throws ReflectionException
843
-     */
844
-    protected function _delete_price()
845
-    {
846
-        $entity_model = EEM_Price::instance();
847
-        $deleted      = $this->trashRestoreDeleteEntities($entity_model, 'id');
848
-        $entity       = $entity_model->item_name($deleted);
849
-        $this->_redirect_after_action(
850
-            $deleted,
851
-            $entity,
852
-            'deleted',
853
-            ['action' => 'default']
854
-        );
855
-    }
856
-
857
-
858
-    /**
859
-     * @throws EE_Error
860
-     * @throws ReflectionException
861
-     */
862
-    public function update_price_order()
863
-    {
864
-        // grab our row IDs
865
-        $row_ids = $this->request->getRequestParam('row_ids', '');
866
-        $row_ids = explode(',', rtrim($row_ids, ','));
867
-
868
-        $all_updated = true;
869
-        foreach ($row_ids as $i => $row_id) {
870
-            // Update the prices when re-ordering
871
-            $fields_n_values = ['PRC_order' => $i + 1];
872
-            $query_params    = [['PRC_ID' => absint($row_id)]];
873
-            // any failure will toggle $all_updated to false
874
-            $all_updated = $row_id && EEM_Price::instance()->update($fields_n_values, $query_params) !== false
875
-                ? $all_updated
876
-                : false;
877
-        }
878
-        $success = $all_updated
879
-            ? esc_html__('Price order was updated successfully.', 'event_espresso')
880
-            : false;
881
-        $errors  = ! $all_updated
882
-            ? esc_html__('An error occurred. The price order was not updated.', 'event_espresso')
883
-            : false;
884
-
885
-        echo wp_json_encode(['return_data' => false, 'success' => $success, 'errors' => $errors]);
886
-        die();
887
-    }
888
-
889
-
890
-    /******************************************************************************************************************
15
+	protected function _init_page_props()
16
+	{
17
+		$this->page_slug        = PRICING_PG_SLUG;
18
+		$this->page_label       = PRICING_LABEL;
19
+		$this->_admin_base_url  = PRICING_ADMIN_URL;
20
+		$this->_admin_base_path = PRICING_ADMIN;
21
+	}
22
+
23
+
24
+	protected function _ajax_hooks()
25
+	{
26
+		add_action('wp_ajax_espresso_update_prices_order', [$this, 'update_price_order']);
27
+	}
28
+
29
+
30
+	protected function _define_page_props()
31
+	{
32
+		$this->_admin_page_title = PRICING_LABEL;
33
+		$this->_labels           = [
34
+			'buttons' => [
35
+				'add'         => esc_html__('Add New Default Price', 'event_espresso'),
36
+				'edit'        => esc_html__('Edit Default Price', 'event_espresso'),
37
+				'delete'      => esc_html__('Delete Default Price', 'event_espresso'),
38
+				'add_type'    => esc_html__('Add New Default Price Type', 'event_espresso'),
39
+				'edit_type'   => esc_html__('Edit Price Type', 'event_espresso'),
40
+				'delete_type' => esc_html__('Delete Price Type', 'event_espresso'),
41
+			],
42
+			'publishbox' => [
43
+				'add_new_price'      => esc_html__('Add New Default Price', 'event_espresso'),
44
+				'edit_price'         => esc_html__('Edit Default Price', 'event_espresso'),
45
+				'add_new_price_type' => esc_html__('Add New Default Price Type', 'event_espresso'),
46
+				'edit_price_type'    => esc_html__('Edit Price Type', 'event_espresso'),
47
+			],
48
+		];
49
+	}
50
+
51
+
52
+	/**
53
+	 * an array for storing request actions and their corresponding methods
54
+	 *
55
+	 * @return void
56
+	 */
57
+	protected function _set_page_routes()
58
+	{
59
+		$PRC_ID             = $this->request->getRequestParam('PRC_ID', 0, DataType::INTEGER);
60
+		$PRT_ID             = $this->request->getRequestParam('PRT_ID', 0, DataType::INTEGER);
61
+		$this->_page_routes = [
62
+			'default'                     => [
63
+				'func'       => [$this, '_price_overview_list_table'],
64
+				'capability' => 'ee_read_default_prices',
65
+			],
66
+			'add_new_price'               => [
67
+				'func'       => [$this, '_edit_price_details'],
68
+				'capability' => 'ee_edit_default_prices',
69
+			],
70
+			'edit_price'                  => [
71
+				'func'       => [$this, '_edit_price_details'],
72
+				'capability' => 'ee_edit_default_price',
73
+				'obj_id'     => $PRC_ID,
74
+			],
75
+			'insert_price'                => [
76
+				'func'       => [$this, '_insert_or_update_price'],
77
+				'args'       => ['insert' => true],
78
+				'noheader'   => true,
79
+				'capability' => 'ee_edit_default_prices',
80
+			],
81
+			'update_price'                => [
82
+				'func'       => [$this, '_insert_or_update_price'],
83
+				'args'       => ['insert' => false],
84
+				'noheader'   => true,
85
+				'capability' => 'ee_edit_default_price',
86
+				'obj_id'     => $PRC_ID,
87
+			],
88
+			'trash_price'                 => [
89
+				'func'       => [$this, '_trash_or_restore_price'],
90
+				'args'       => ['trash' => true],
91
+				'noheader'   => true,
92
+				'capability' => 'ee_delete_default_price',
93
+				'obj_id'     => $PRC_ID,
94
+			],
95
+			'restore_price'               => [
96
+				'func'       => [$this, '_trash_or_restore_price'],
97
+				'args'       => ['trash' => false],
98
+				'noheader'   => true,
99
+				'capability' => 'ee_delete_default_price',
100
+				'obj_id'     => $PRC_ID,
101
+			],
102
+			'delete_price'                => [
103
+				'func'       => [$this, '_delete_price'],
104
+				'noheader'   => true,
105
+				'capability' => 'ee_delete_default_price',
106
+				'obj_id'     => $PRC_ID,
107
+			],
108
+			'espresso_update_price_order' => [
109
+				'func'       => [$this, 'update_price_order'],
110
+				'noheader'   => true,
111
+				'capability' => 'ee_edit_default_prices',
112
+			],
113
+			// price types
114
+			'price_types'                 => [
115
+				'func'       => [$this, '_price_types_overview_list_table'],
116
+				'capability' => 'ee_read_default_price_types',
117
+			],
118
+			'add_new_price_type'          => [
119
+				'func'       => [$this, '_edit_price_type_details'],
120
+				'capability' => 'ee_edit_default_price_types',
121
+			],
122
+			'edit_price_type'             => [
123
+				'func'       => [$this, '_edit_price_type_details'],
124
+				'capability' => 'ee_edit_default_price_type',
125
+				'obj_id'     => $PRT_ID,
126
+			],
127
+			'insert_price_type'           => [
128
+				'func'       => [$this, '_insert_or_update_price_type'],
129
+				'args'       => ['new_price_type' => true],
130
+				'noheader'   => true,
131
+				'capability' => 'ee_edit_default_price_types',
132
+			],
133
+			'update_price_type'           => [
134
+				'func'       => [$this, '_insert_or_update_price_type'],
135
+				'args'       => ['new_price_type' => false],
136
+				'noheader'   => true,
137
+				'capability' => 'ee_edit_default_price_type',
138
+				'obj_id'     => $PRT_ID,
139
+			],
140
+			'trash_price_type'            => [
141
+				'func'       => [$this, '_trash_or_restore_price_type'],
142
+				'args'       => ['trash' => true],
143
+				'noheader'   => true,
144
+				'capability' => 'ee_delete_default_price_type',
145
+				'obj_id'     => $PRT_ID,
146
+			],
147
+			'restore_price_type'          => [
148
+				'func'       => [$this, '_trash_or_restore_price_type'],
149
+				'args'       => ['trash' => false],
150
+				'noheader'   => true,
151
+				'capability' => 'ee_delete_default_price_type',
152
+				'obj_id'     => $PRT_ID,
153
+			],
154
+			'delete_price_type'           => [
155
+				'func'       => [$this, '_delete_price_type'],
156
+				'noheader'   => true,
157
+				'capability' => 'ee_delete_default_price_type',
158
+				'obj_id'     => $PRT_ID,
159
+			],
160
+			'tax_settings'                => [
161
+				'func'       => [$this, '_tax_settings'],
162
+				'capability' => 'manage_options',
163
+			],
164
+			'update_tax_settings'         => [
165
+				'func'       => [$this, '_update_tax_settings'],
166
+				'capability' => 'manage_options',
167
+				'noheader'   => true,
168
+			],
169
+		];
170
+	}
171
+
172
+
173
+	protected function _set_page_config()
174
+	{
175
+		$PRC_ID             = $this->request->getRequestParam('id', 0, DataType::INTEGER);
176
+		$this->_page_config = [
177
+			'default'            => [
178
+				'nav'           => [
179
+					'label' => esc_html__('Default Pricing', 'event_espresso'),
180
+					'icon' => 'dashicons-money-alt',
181
+					'order' => 10,
182
+				],
183
+				'list_table'    => 'Prices_List_Table',
184
+				'metaboxes'     => $this->_default_espresso_metaboxes,
185
+				'help_tabs'     => [
186
+					'pricing_default_pricing_help_tab'                           => [
187
+						'title'    => esc_html__('Default Pricing', 'event_espresso'),
188
+						'filename' => 'pricing_default_pricing',
189
+					],
190
+					'pricing_default_pricing_table_column_headings_help_tab'     => [
191
+						'title'    => esc_html__('Default Pricing Table Column Headings', 'event_espresso'),
192
+						'filename' => 'pricing_default_pricing_table_column_headings',
193
+					],
194
+					'pricing_default_pricing_views_bulk_actions_search_help_tab' => [
195
+						'title'    => esc_html__('Default Pricing Views & Bulk Actions & Search', 'event_espresso'),
196
+						'filename' => 'pricing_default_pricing_views_bulk_actions_search',
197
+					],
198
+				],
199
+				'require_nonce' => false,
200
+			],
201
+			'add_new_price'      => [
202
+				'nav'           => [
203
+					'label'      => esc_html__('Add New Default Price', 'event_espresso'),
204
+					'icon' => 'dashicons-plus-alt',
205
+					'order'      => 20,
206
+					'persistent' => false,
207
+				],
208
+				'help_tabs'     => [
209
+					'add_new_default_price_help_tab' => [
210
+						'title'    => esc_html__('Add New Default Price', 'event_espresso'),
211
+						'filename' => 'pricing_add_new_default_price',
212
+					],
213
+				],
214
+				'metaboxes'     => array_merge(
215
+					['_publish_post_box'],
216
+					$this->_default_espresso_metaboxes
217
+				),
218
+				'require_nonce' => false,
219
+			],
220
+			'edit_price'         => [
221
+				'nav'           => [
222
+					'label'      => esc_html__('Edit Default Price', 'event_espresso'),
223
+					'icon' => 'dashicons-edit-large',
224
+					'order'      => 20,
225
+					'url'        => $PRC_ID
226
+						? add_query_arg(['id' => $PRC_ID], $this->_current_page_view_url)
227
+						: $this->_admin_base_url,
228
+					'persistent' => false,
229
+				],
230
+				'metaboxes'     => array_merge(
231
+					['_publish_post_box'],
232
+					$this->_default_espresso_metaboxes
233
+				),
234
+				'help_tabs'     => [
235
+					'edit_default_price_help_tab' => [
236
+						'title'    => esc_html__('Edit Default Price', 'event_espresso'),
237
+						'filename' => 'pricing_edit_default_price',
238
+					],
239
+				],
240
+				'require_nonce' => false,
241
+			],
242
+			'price_types'        => [
243
+				'nav'           => [
244
+					'label' => esc_html__('Price Types', 'event_espresso'),
245
+					'icon' => 'dashicons-networking',
246
+					'order' => 30,
247
+				],
248
+				'list_table'    => 'Price_Types_List_Table',
249
+				'help_tabs'     => [
250
+					'pricing_price_types_help_tab'                           => [
251
+						'title'    => esc_html__('Price Types', 'event_espresso'),
252
+						'filename' => 'pricing_price_types',
253
+					],
254
+					'pricing_price_types_table_column_headings_help_tab'     => [
255
+						'title'    => esc_html__('Price Types Table Column Headings', 'event_espresso'),
256
+						'filename' => 'pricing_price_types_table_column_headings',
257
+					],
258
+					'pricing_price_types_views_bulk_actions_search_help_tab' => [
259
+						'title'    => esc_html__('Price Types Views & Bulk Actions & Search', 'event_espresso'),
260
+						'filename' => 'pricing_price_types_views_bulk_actions_search',
261
+					],
262
+				],
263
+				'metaboxes'     => $this->_default_espresso_metaboxes,
264
+				'require_nonce' => false,
265
+			],
266
+			'add_new_price_type' => [
267
+				'nav'           => [
268
+					'label'      => esc_html__('Add New Price Type', 'event_espresso'),
269
+					'icon' => 'dashicons-plus-alt',
270
+					'order'      => 40,
271
+					'persistent' => false,
272
+				],
273
+				'help_tabs'     => [
274
+					'add_new_price_type_help_tab' => [
275
+						'title'    => esc_html__('Add New Price Type', 'event_espresso'),
276
+						'filename' => 'pricing_add_new_price_type',
277
+					],
278
+				],
279
+				'metaboxes'     => array_merge(
280
+					['_publish_post_box'],
281
+					$this->_default_espresso_metaboxes
282
+				),
283
+				'require_nonce' => false,
284
+			],
285
+			'edit_price_type'    => [
286
+				'nav'           => [
287
+					'label'      => esc_html__('Edit Price Type', 'event_espresso'),
288
+					'icon' => 'dashicons-edit-large',
289
+					'order'      => 40,
290
+					'persistent' => false,
291
+				],
292
+				'help_tabs'     => [
293
+					'edit_price_type_help_tab' => [
294
+						'title'    => esc_html__('Edit Price Type', 'event_espresso'),
295
+						'filename' => 'pricing_edit_price_type',
296
+					],
297
+				],
298
+				'metaboxes'     => array_merge(
299
+					['_publish_post_box'],
300
+					$this->_default_espresso_metaboxes
301
+				),
302
+				'require_nonce' => false,
303
+			],
304
+			'tax_settings'       => [
305
+				'nav' => [
306
+					'label' => esc_html__('Tax Settings', 'event_espresso'),
307
+					'icon' => 'dashicons-sticky',
308
+					'order' => 50,
309
+				],
310
+				'labels'        => [
311
+					'publishbox' => esc_html__('Update Tax Settings', 'event_espresso'),
312
+				],
313
+				'metaboxes'     => array_merge(
314
+					['_publish_post_box'],
315
+					$this->_default_espresso_metaboxes
316
+				),
317
+				'require_nonce' => true,
318
+			],
319
+		];
320
+	}
321
+
322
+
323
+	protected function _add_screen_options()
324
+	{
325
+		// todo
326
+	}
327
+
328
+
329
+	protected function _add_screen_options_default()
330
+	{
331
+		$this->_per_page_screen_option();
332
+	}
333
+
334
+
335
+	protected function _add_screen_options_price_types()
336
+	{
337
+		$page_title              = $this->_admin_page_title;
338
+		$this->_admin_page_title = esc_html__('Price Types', 'event_espresso');
339
+		$this->_per_page_screen_option();
340
+		$this->_admin_page_title = $page_title;
341
+	}
342
+
343
+
344
+	protected function _add_feature_pointers()
345
+	{
346
+	}
347
+
348
+
349
+	public function load_scripts_styles()
350
+	{
351
+		// styles
352
+		wp_enqueue_style('espresso-ui-theme');
353
+		wp_register_style(
354
+			'espresso_pricing_css',
355
+			PRICING_ASSETS_URL . 'espresso_pricing_admin.css',
356
+			[EspressoLegacyAdminAssetManager::CSS_HANDLE_EE_ADMIN],
357
+			EVENT_ESPRESSO_VERSION
358
+		);
359
+		wp_enqueue_style('espresso_pricing_css');
360
+
361
+		// scripts
362
+		wp_enqueue_script('ee_admin_js');
363
+		wp_enqueue_script('jquery-ui-position');
364
+		wp_enqueue_script('jquery-ui-widget');
365
+		wp_register_script(
366
+			'espresso_pricing_js',
367
+			PRICING_ASSETS_URL . 'espresso_pricing_admin.js',
368
+			['jquery'],
369
+			EVENT_ESPRESSO_VERSION,
370
+			true
371
+		);
372
+		wp_enqueue_script('espresso_pricing_js');
373
+	}
374
+
375
+
376
+	public function load_scripts_styles_default()
377
+	{
378
+		wp_enqueue_script('espresso_ajax_table_sorting');
379
+	}
380
+
381
+
382
+	public function admin_footer_scripts()
383
+	{
384
+	}
385
+
386
+
387
+	public function admin_init()
388
+	{
389
+	}
390
+
391
+
392
+	public function admin_notices()
393
+	{
394
+	}
395
+
396
+
397
+	protected function _set_list_table_views_default()
398
+	{
399
+		$this->_views = [
400
+			'all' => [
401
+				'slug'        => 'all',
402
+				'label'       => esc_html__('View All Default Pricing', 'event_espresso'),
403
+				'count'       => 0,
404
+				'bulk_action' => [
405
+					'trash_price' => esc_html__('Move to Trash', 'event_espresso'),
406
+				],
407
+			],
408
+		];
409
+
410
+		if (EE_Registry::instance()->CAP->current_user_can('ee_delete_default_prices', 'pricing_trash_price')) {
411
+			$this->_views['trashed'] = [
412
+				'slug'        => 'trashed',
413
+				'label'       => esc_html__('Trash', 'event_espresso'),
414
+				'count'       => 0,
415
+				'bulk_action' => [
416
+					'restore_price' => esc_html__('Restore from Trash', 'event_espresso'),
417
+					'delete_price'  => esc_html__('Delete Permanently', 'event_espresso'),
418
+				],
419
+			];
420
+		}
421
+	}
422
+
423
+
424
+	protected function _set_list_table_views_price_types()
425
+	{
426
+		$this->_views = [
427
+			'all' => [
428
+				'slug'        => 'all',
429
+				'label'       => esc_html__('All', 'event_espresso'),
430
+				'count'       => 0,
431
+				'bulk_action' => [
432
+					'trash_price_type' => esc_html__('Move to Trash', 'event_espresso'),
433
+				],
434
+			],
435
+		];
436
+
437
+		if (
438
+			EE_Registry::instance()->CAP->current_user_can(
439
+				'ee_delete_default_price_types',
440
+				'pricing_trash_price_type'
441
+			)
442
+		) {
443
+			$this->_views['trashed'] = [
444
+				'slug'        => 'trashed',
445
+				'label'       => esc_html__('Trash', 'event_espresso'),
446
+				'count'       => 0,
447
+				'bulk_action' => [
448
+					'restore_price_type' => esc_html__('Restore from Trash', 'event_espresso'),
449
+					'delete_price_type'  => esc_html__('Delete Permanently', 'event_espresso'),
450
+				],
451
+			];
452
+		}
453
+	}
454
+
455
+
456
+	/**
457
+	 * generates HTML for main Prices Admin page
458
+	 *
459
+	 * @return void
460
+	 * @throws EE_Error
461
+	 */
462
+	protected function _price_overview_list_table()
463
+	{
464
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
465
+			'add_new_price',
466
+			'add',
467
+			[],
468
+			'add-new-h2'
469
+		);
470
+		$this->_admin_page_title .= $this->_learn_more_about_pricing_link();
471
+		$this->_search_btn_label = esc_html__('Default Prices', 'event_espresso');
472
+		$this->display_admin_list_table_page_with_sidebar();
473
+	}
474
+
475
+
476
+	/**
477
+	 * retrieve data for Prices List table
478
+	 *
479
+	 * @param int  $per_page how many prices displayed per page
480
+	 * @param bool $count    return the count or objects
481
+	 * @param bool $trashed  whether the current view is of the trash can - eww yuck!
482
+	 * @return EE_Soft_Delete_Base_Class[]|int int = count || array of price objects
483
+	 * @throws EE_Error
484
+	 * @throws ReflectionException
485
+	 */
486
+	public function get_prices_overview_data(int $per_page = 10, bool $count = false, bool $trashed = false)
487
+	{
488
+		// start with an empty array
489
+		$event_pricing = [];
490
+
491
+		require_once(PRICING_ADMIN . 'Prices_List_Table.class.php');
492
+
493
+		$orderby = $this->request->getRequestParam('orderby', '');
494
+		$order   = $this->request->getRequestParam('order', 'ASC');
495
+
496
+		switch ($orderby) {
497
+			case 'name':
498
+				$orderby = ['PRC_name' => $order];
499
+				break;
500
+			case 'type':
501
+				$orderby = ['Price_Type.PRT_name' => $order];
502
+				break;
503
+			case 'amount':
504
+				$orderby = ['PRC_amount' => $order];
505
+				break;
506
+			default:
507
+				$orderby = ['PRC_order' => $order, 'Price_Type.PRT_order' => $order, 'PRC_ID' => $order];
508
+		}
509
+
510
+		$current_page = $this->request->getRequestParam('paged', 1, DataType::INTEGER);
511
+		$per_page     = $this->request->getRequestParam('perpage', $per_page, DataType::INTEGER);
512
+
513
+		$where = [
514
+			'PRC_is_default' => 1,
515
+			'PRC_deleted'    => $trashed,
516
+		];
517
+
518
+		$offset = ($current_page - 1) * $per_page;
519
+		$limit  = [$offset, $per_page];
520
+
521
+		$search_term = $this->request->getRequestParam('s');
522
+		if ($search_term) {
523
+			$search_term = "%{$search_term}%";
524
+			$where['OR'] = [
525
+				'PRC_name'            => ['LIKE', $search_term],
526
+				'PRC_desc'            => ['LIKE', $search_term],
527
+				'PRC_amount'          => ['LIKE', $search_term],
528
+				'Price_Type.PRT_name' => ['LIKE', $search_term],
529
+			];
530
+		}
531
+
532
+		$query_params = [
533
+			$where,
534
+			'order_by' => $orderby,
535
+			'limit'    => $limit,
536
+			'group_by' => 'PRC_ID',
537
+		];
538
+
539
+		if ($count) {
540
+			return $trashed
541
+				? EEM_Price::instance()->count([$where])
542
+				: EEM_Price::instance()->count_deleted_and_undeleted([$where]);
543
+		}
544
+		return EEM_Price::instance()->get_all_deleted_and_undeleted($query_params);
545
+	}
546
+
547
+
548
+	/**
549
+	 * @return void
550
+	 * @throws EE_Error
551
+	 * @throws ReflectionException
552
+	 */
553
+	protected function _edit_price_details()
554
+	{
555
+		// grab price ID
556
+		$PRC_ID = $this->request->getRequestParam('id', 0, DataType::INTEGER);
557
+		// change page title based on request action
558
+		switch ($this->_req_action) {
559
+			case 'add_new_price':
560
+				$this->_admin_page_title = esc_html__('Add New Price', 'event_espresso');
561
+				break;
562
+			case 'edit_price':
563
+				$this->_admin_page_title = esc_html__('Edit Price', 'event_espresso');
564
+				break;
565
+			default:
566
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
567
+		}
568
+		// add PRC_ID to title if editing
569
+		$this->_admin_page_title = $PRC_ID ? $this->_admin_page_title . ' # ' . $PRC_ID : $this->_admin_page_title;
570
+
571
+		if ($PRC_ID) {
572
+			$price                    = EEM_Price::instance()->get_one_by_ID($PRC_ID);
573
+			$additional_hidden_fields = [
574
+				'PRC_ID' => ['type' => 'hidden', 'value' => $PRC_ID],
575
+			];
576
+			$this->_set_add_edit_form_tags('update_price', $additional_hidden_fields);
577
+		} else {
578
+			$price = EEM_Price::instance()->get_new_price();
579
+			$this->_set_add_edit_form_tags('insert_price');
580
+		}
581
+
582
+		if (! $price instanceof EE_Price) {
583
+			throw new RuntimeException(
584
+				sprintf(
585
+					esc_html__(
586
+						'A valid Price could not be retrieved from the database with ID: %1$s',
587
+						'event_espresso'
588
+					),
589
+					$PRC_ID
590
+				)
591
+			);
592
+		}
593
+
594
+		$this->_template_args['PRC_ID'] = $PRC_ID;
595
+		$this->_template_args['price']  = $price;
596
+
597
+		$default_base_price = $price->type_obj() && $price->type_obj()->base_type() === 1;
598
+
599
+		$this->_template_args['default_base_price'] = $default_base_price;
600
+
601
+		// get price types
602
+		$price_types = EEM_Price_Type::instance()->get_all([['PBT_ID' => ['!=', 1]]]);
603
+		if (empty($price_types)) {
604
+			$msg = esc_html__(
605
+				'You have no price types defined. Please add a price type before adding a price.',
606
+				'event_espresso'
607
+			);
608
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
609
+			$this->display_admin_page_with_sidebar();
610
+		}
611
+		$attributes       = [];
612
+		$price_type_names = [];
613
+		$attributes[]     = 'id="PRT_ID"';
614
+		if ($default_base_price) {
615
+			$attributes[]       = 'disabled="disabled"';
616
+			$price_type_names[] = ['id' => 1, 'text' => esc_html__('Base Price', 'event_espresso')];
617
+		}
618
+		foreach ($price_types as $type) {
619
+			$price_type_names[] = ['id' => $type->ID(), 'text' => $type->name()];
620
+		}
621
+		$this->_template_args['attributes']  = implode(' ', $attributes);
622
+		$this->_template_args['price_types'] = $price_type_names;
623
+
624
+		$this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
625
+		$this->_template_args['admin_page_content']            = $this->_edit_price_details_meta_box();
626
+
627
+		$this->_set_publish_post_box_vars('id', $PRC_ID, '', '', true);
628
+		// the details template wrapper
629
+		$this->display_admin_page_with_sidebar();
630
+	}
631
+
632
+
633
+	/**
634
+	 *
635
+	 * @return string
636
+	 */
637
+	public function _edit_price_details_meta_box(): string
638
+	{
639
+		return EEH_Template::display_template(
640
+			PRICING_TEMPLATE_PATH . 'pricing_details_main_meta_box.template.php',
641
+			$this->_template_args,
642
+			true
643
+		);
644
+	}
645
+
646
+
647
+	/**
648
+	 * @return array
649
+	 * @throws EE_Error
650
+	 * @throws ReflectionException
651
+	 */
652
+	protected function set_price_column_values(): array
653
+	{
654
+		$PRC_order = 0;
655
+		$PRT_ID    = $this->request->getRequestParam('PRT_ID', 0, DataType::INTEGER);
656
+		if ($PRT_ID) {
657
+			/** @var EE_Price_Type $price_type */
658
+			$price_type = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
659
+			if ($price_type instanceof EE_Price_Type) {
660
+				$PRC_order = $price_type->order();
661
+			}
662
+		}
663
+		return [
664
+			'PRT_ID'         => $PRT_ID,
665
+			'PRC_amount'     => $this->request->getRequestParam('PRC_amount', 0, DataType::FLOAT),
666
+			'PRC_name'       => $this->request->getRequestParam('PRC_name'),
667
+			'PRC_desc'       => $this->request->getRequestParam('PRC_desc'),
668
+			'PRC_is_default' => 1,
669
+			'PRC_overrides'  => null,
670
+			'PRC_order'      => $PRC_order,
671
+			'PRC_deleted'    => 0,
672
+			'PRC_parent'     => 0,
673
+		];
674
+	}
675
+
676
+
677
+	/**
678
+	 * @param bool $insert - whether to insert or update
679
+	 * @return void
680
+	 * @throws EE_Error
681
+	 * @throws ReflectionException
682
+	 */
683
+	protected function _insert_or_update_price(bool $insert = false)
684
+	{
685
+		// why be so pessimistic ???  : (
686
+		$updated = 0;
687
+
688
+		$set_column_values = $this->set_price_column_values();
689
+		// is this a new Price ?
690
+		if ($insert) {
691
+			// run the insert
692
+			$PRC_ID = EEM_Price::instance()->insert($set_column_values);
693
+			if ($PRC_ID) {
694
+				// make sure this new price modifier is attached to the ticket but ONLY if it is not a tax type
695
+				$price = EEM_price::instance()->get_one_by_ID($PRC_ID);
696
+				if (
697
+					$price instanceof EE_Price
698
+					&& $price->type_obj() instanceof EE_Price_type
699
+					&& $price->type_obj()->base_type() !== EEM_Price_Type::base_type_tax
700
+				) {
701
+					$ticket = EEM_Ticket::instance()->get_one_by_ID(1);
702
+					$ticket->_add_relation_to($price, 'Price');
703
+					$ticket->save();
704
+				}
705
+				$updated = 1;
706
+			}
707
+			$action_desc = 'created';
708
+		} else {
709
+			$PRC_ID = $this->request->getRequestParam('PRC_ID', 0, DataType::INTEGER);
710
+			// run the update
711
+			$where_cols_n_values = ['PRC_ID' => $PRC_ID];
712
+			$updated             = EEM_Price::instance()->update($set_column_values, [$where_cols_n_values]);
713
+
714
+			$price = EEM_Price::instance()->get_one_by_ID($PRC_ID);
715
+			if ($price instanceof EE_Price && $price->type_obj()->base_type() !== EEM_Price_Type::base_type_tax) {
716
+				// if this is $PRC_ID == 1,
717
+				// then we need to update the default ticket attached to this price so the TKT_price value is updated.
718
+				if ($PRC_ID === 1) {
719
+					$ticket = $price->get_first_related('Ticket');
720
+					if ($ticket) {
721
+						$ticket->set('TKT_price', $price->get('PRC_amount'));
722
+						$ticket->set('TKT_name', $price->get('PRC_name'));
723
+						$ticket->set('TKT_description', $price->get('PRC_desc'));
724
+						$ticket->save();
725
+					}
726
+				} else {
727
+					// we make sure this price is attached to base ticket. but ONLY if it's not a tax ticket type.
728
+					$ticket = EEM_Ticket::instance()->get_one_by_ID(1);
729
+					if ($ticket instanceof EE_Ticket) {
730
+						$ticket->_add_relation_to($PRC_ID, 'Price');
731
+						$ticket->save();
732
+					}
733
+				}
734
+			}
735
+
736
+			$action_desc = 'updated';
737
+		}
738
+
739
+		$query_args = ['action' => 'edit_price', 'id' => $PRC_ID];
740
+
741
+		$this->_redirect_after_action($updated, 'Prices', $action_desc, $query_args);
742
+	}
743
+
744
+
745
+	/**
746
+	 * @param bool $trash - whether to move item to trash (TRUE) or restore it (FALSE)
747
+	 * @return void
748
+	 * @throws EE_Error
749
+	 */
750
+	protected function _trash_or_restore_price($trash = true)
751
+	{
752
+		$entity_model = EEM_Price::instance();
753
+		$action       = $trash ? EE_Admin_List_Table::ACTION_TRASH : EE_Admin_List_Table::ACTION_RESTORE;
754
+		$result       = $this->trashRestoreDeleteEntities(
755
+			$entity_model,
756
+			'id',
757
+			$action,
758
+			'PRC_deleted',
759
+			[$this, 'adjustTicketRelations']
760
+		);
761
+
762
+		if ($result) {
763
+			$msg = $trash
764
+				? esc_html(
765
+					_n(
766
+						'The Price has been trashed',
767
+						'The Prices have been trashed',
768
+						$result,
769
+						'event_espresso'
770
+					)
771
+				)
772
+				: esc_html(
773
+					_n(
774
+						'The Price has been restored',
775
+						'The Prices have been restored',
776
+						$result,
777
+						'event_espresso'
778
+					)
779
+				);
780
+			EE_Error::add_success($msg);
781
+		}
782
+
783
+		$this->_redirect_after_action(
784
+			$result,
785
+			_n('Price', 'Prices', $result, 'event_espresso'),
786
+			$trash ? 'trashed' : 'restored',
787
+			['action' => 'default'],
788
+			true
789
+		);
790
+	}
791
+
792
+
793
+	/**
794
+	 * @param EEM_Base   $entity_model
795
+	 * @param int|string $entity_ID
796
+	 * @param string     $action
797
+	 * @param int        $result
798
+	 * @throws EE_Error
799
+	 * @throws ReflectionException
800
+	 * @since 4.10.30.p
801
+	 */
802
+	public function adjustTicketRelations(
803
+		EEM_Base $entity_model,
804
+		$entity_ID,
805
+		string $action,
806
+		int $result
807
+	) {
808
+		if (! $entity_ID || (float) $result < 1) {
809
+			return;
810
+		}
811
+
812
+		$entity = $entity_model->get_one_by_ID($entity_ID);
813
+		if (! $entity instanceof EE_Price || $entity->type_obj()->base_type() === EEM_Price_Type::base_type_tax) {
814
+			return;
815
+		}
816
+
817
+		// get default tickets for updating
818
+		$default_tickets = EEM_Ticket::instance()->get_all_default_tickets();
819
+		foreach ($default_tickets as $default_ticket) {
820
+			if (! $default_ticket instanceof EE_Ticket) {
821
+				continue;
822
+			}
823
+			switch ($action) {
824
+				case EE_Admin_List_Table::ACTION_DELETE:
825
+				case EE_Admin_List_Table::ACTION_TRASH:
826
+					// if trashing then remove relations to base default ticket.
827
+					$default_ticket->_remove_relation_to($entity_ID, 'Price');
828
+					break;
829
+				case EE_Admin_List_Table::ACTION_RESTORE:
830
+					// if restoring then add back to base default ticket
831
+					$default_ticket->_add_relation_to($entity_ID, 'Price');
832
+					break;
833
+			}
834
+			$default_ticket->save();
835
+		}
836
+	}
837
+
838
+
839
+	/**
840
+	 * @return void
841
+	 * @throws EE_Error
842
+	 * @throws ReflectionException
843
+	 */
844
+	protected function _delete_price()
845
+	{
846
+		$entity_model = EEM_Price::instance();
847
+		$deleted      = $this->trashRestoreDeleteEntities($entity_model, 'id');
848
+		$entity       = $entity_model->item_name($deleted);
849
+		$this->_redirect_after_action(
850
+			$deleted,
851
+			$entity,
852
+			'deleted',
853
+			['action' => 'default']
854
+		);
855
+	}
856
+
857
+
858
+	/**
859
+	 * @throws EE_Error
860
+	 * @throws ReflectionException
861
+	 */
862
+	public function update_price_order()
863
+	{
864
+		// grab our row IDs
865
+		$row_ids = $this->request->getRequestParam('row_ids', '');
866
+		$row_ids = explode(',', rtrim($row_ids, ','));
867
+
868
+		$all_updated = true;
869
+		foreach ($row_ids as $i => $row_id) {
870
+			// Update the prices when re-ordering
871
+			$fields_n_values = ['PRC_order' => $i + 1];
872
+			$query_params    = [['PRC_ID' => absint($row_id)]];
873
+			// any failure will toggle $all_updated to false
874
+			$all_updated = $row_id && EEM_Price::instance()->update($fields_n_values, $query_params) !== false
875
+				? $all_updated
876
+				: false;
877
+		}
878
+		$success = $all_updated
879
+			? esc_html__('Price order was updated successfully.', 'event_espresso')
880
+			: false;
881
+		$errors  = ! $all_updated
882
+			? esc_html__('An error occurred. The price order was not updated.', 'event_espresso')
883
+			: false;
884
+
885
+		echo wp_json_encode(['return_data' => false, 'success' => $success, 'errors' => $errors]);
886
+		die();
887
+	}
888
+
889
+
890
+	/******************************************************************************************************************
891 891
      ***********************************************  TICKET PRICE TYPES  *********************************************
892 892
      ******************************************************************************************************************/
893 893
 
894 894
 
895
-    /**
896
-     * generates HTML for main Prices Admin page
897
-     *
898
-     * @return void
899
-     * @throws EE_Error
900
-     */
901
-    protected function _price_types_overview_list_table()
902
-    {
903
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
904
-            'add_new_price_type',
905
-            'add_type',
906
-            [],
907
-            'add-new-h2'
908
-        );
909
-        $this->_admin_page_title .= $this->_learn_more_about_pricing_link();
910
-        $this->_search_btn_label = esc_html__('Price Types', 'event_espresso');
911
-        $this->display_admin_list_table_page_with_sidebar();
912
-    }
913
-
914
-
915
-    /**
916
-     * retrieve data for Price Types List table
917
-     *
918
-     * @param int  $per_page how many prices displayed per page
919
-     * @param bool $count    return the count or objects
920
-     * @param bool $trashed  whether the current view is of the trash can - eww yuck!
921
-     * @return EE_Soft_Delete_Base_Class[]|int int = count || array of price objects
922
-     * @throws EE_Error
923
-     * @throws ReflectionException
924
-     */
925
-    public function get_price_types_overview_data(int $per_page = 10, bool $count = false, bool $trashed = false)
926
-    {
927
-        // start with an empty array
928
-        require_once(PRICING_ADMIN . 'Price_Types_List_Table.class.php');
929
-
930
-        $orderby = $this->request->getRequestParam('orderby', '');
931
-        $order   = $this->request->getRequestParam('order', 'ASC');
932
-
933
-        switch ($orderby) {
934
-            case 'name':
935
-                $orderby = ['PRT_name' => $order];
936
-                break;
937
-            default:
938
-                $orderby = ['PRT_order' => $order];
939
-        }
940
-
941
-        $current_page = $this->request->getRequestParam('paged', 1, DataType::INTEGER);
942
-        $per_page     = $this->request->getRequestParam('perpage', $per_page, DataType::INTEGER);
943
-
944
-        $offset = ($current_page - 1) * $per_page;
945
-        $limit  = [$offset, $per_page];
946
-
947
-        $where = ['PRT_deleted' => $trashed, 'PBT_ID' => ['!=', 1]];
948
-
949
-        $search_term = $this->request->getRequestParam('s');
950
-        if ($search_term) {
951
-            $where['OR'] = [
952
-                'PRT_name' => ['LIKE', "%{$search_term}%"],
953
-            ];
954
-        }
955
-        $query_params = [
956
-            $where,
957
-            'order_by' => $orderby,
958
-            'limit'    => $limit,
959
-        ];
960
-        return $count
961
-            ? EEM_Price_Type::instance()->count_deleted_and_undeleted($query_params)
962
-            : EEM_Price_Type::instance()->get_all_deleted_and_undeleted($query_params);
963
-    }
964
-
965
-
966
-    /**
967
-     * _edit_price_type_details
968
-     *
969
-     * @return void
970
-     * @throws EE_Error
971
-     * @throws ReflectionException
972
-     */
973
-    protected function _edit_price_type_details()
974
-    {
975
-        // grab price type ID
976
-        $PRT_ID = $this->request->getRequestParam('id', 0, DataType::INTEGER);
977
-        // change page title based on request action
978
-        switch ($this->_req_action) {
979
-            case 'add_new_price_type':
980
-                $this->_admin_page_title = esc_html__('Add New Price Type', 'event_espresso');
981
-                break;
982
-            case 'edit_price_type':
983
-                $this->_admin_page_title = esc_html__('Edit Price Type', 'event_espresso');
984
-                break;
985
-            default:
986
-                $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
987
-        }
988
-        // add PRT_ID to title if editing
989
-        $this->_admin_page_title = $PRT_ID ? $this->_admin_page_title . ' # ' . $PRT_ID : $this->_admin_page_title;
990
-
991
-        if ($PRT_ID) {
992
-            $price_type               = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
993
-            $additional_hidden_fields = ['PRT_ID' => ['type' => 'hidden', 'value' => $PRT_ID]];
994
-            $this->_set_add_edit_form_tags('update_price_type', $additional_hidden_fields);
995
-        } else {
996
-            $price_type = EEM_Price_Type::instance()->get_new_price_type();
997
-            $this->_set_add_edit_form_tags('insert_price_type');
998
-        }
999
-
1000
-        if (! $price_type instanceof EE_Price_Type) {
1001
-            throw new RuntimeException(
1002
-                sprintf(
1003
-                    esc_html__(
1004
-                        'A valid Price Type could not be retrieved from the database with ID: %1$s',
1005
-                        'event_espresso'
1006
-                    ),
1007
-                    $PRT_ID
1008
-                )
1009
-            );
1010
-        }
1011
-
1012
-        $this->_template_args['PRT_ID']     = $PRT_ID;
1013
-        $this->_template_args['price_type'] = $price_type;
1014
-
1015
-        $base_types    = EEM_Price_Type::instance()->get_base_types();
1016
-        $select_values = [];
1017
-        foreach ($base_types as $ref => $text) {
1018
-            if ($ref == EEM_Price_Type::base_type_base_price) {
1019
-                // do not allow creation of base_type_base_prices because that's a system only base type.
1020
-                continue;
1021
-            }
1022
-            $select_values[] = ['id' => $ref, 'text' => $text];
1023
-        }
1024
-
1025
-        $this->_template_args['base_type_select'] = EEH_Form_Fields::select_input(
1026
-            'base_type',
1027
-            $select_values,
1028
-            $price_type->base_type(),
1029
-            'id="price-type-base-type-slct"'
1030
-        );
1031
-
1032
-        $this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
1033
-        $this->_template_args['admin_page_content']            = $this->_edit_price_type_details_meta_box();
1034
-
1035
-        $redirect_URL = add_query_arg(['action' => 'price_types'], $this->_admin_base_url);
1036
-        $this->_set_publish_post_box_vars('id', $PRT_ID, false, $redirect_URL, true);
1037
-        // the details template wrapper
1038
-        $this->display_admin_page_with_sidebar();
1039
-    }
1040
-
1041
-
1042
-    /**
1043
-     * _edit_price_type_details_meta_box
1044
-     *
1045
-     * @return string
1046
-     */
1047
-    public function _edit_price_type_details_meta_box(): string
1048
-    {
1049
-        return EEH_Template::display_template(
1050
-            PRICING_TEMPLATE_PATH . 'pricing_type_details_main_meta_box.template.php',
1051
-            $this->_template_args,
1052
-            true
1053
-        );
1054
-    }
1055
-
1056
-
1057
-    /**
1058
-     * @return array
1059
-     */
1060
-    protected function set_price_type_column_values(): array
1061
-    {
1062
-        $base_type  = $this->request->getRequestParam(
1063
-            'base_type',
1064
-            EEM_Price_Type::base_type_base_price,
1065
-            DataType::INTEGER
1066
-        );
1067
-        $is_percent = $this->request->getRequestParam('PRT_is_percent', 0, DataType::INTEGER);
1068
-        $order      = $this->request->getRequestParam('PRT_order', 0, DataType::INTEGER);
1069
-        switch ($base_type) {
1070
-            case EEM_Price_Type::base_type_base_price:
1071
-                $is_percent = 0;
1072
-                $order      = 0;
1073
-                break;
1074
-
1075
-            case EEM_Price_Type::base_type_discount:
1076
-            case EEM_Price_Type::base_type_surcharge:
1077
-                break;
1078
-
1079
-            case EEM_Price_Type::base_type_tax:
1080
-                $is_percent = 1;
1081
-                break;
1082
-        }
1083
-
1084
-        return [
1085
-            'PBT_ID'         => $base_type,
1086
-            'PRT_name'       => $this->request->getRequestParam('PRT_name', ''),
1087
-            'PRT_is_percent' => $is_percent,
1088
-            'PRT_order'      => $order,
1089
-            'PRT_deleted'    => 0,
1090
-        ];
1091
-    }
1092
-
1093
-
1094
-    /**
1095
-     * @param bool $new_price_type - whether to insert or update
1096
-     * @return void
1097
-     * @throws EE_Error
1098
-     * @throws ReflectionException
1099
-     */
1100
-    protected function _insert_or_update_price_type(bool $new_price_type = false)
1101
-    {
1102
-        // why be so pessimistic ???  : (
1103
-        $success = 0;
1104
-
1105
-        $set_column_values = $this->set_price_type_column_values();
1106
-        // is this a new Price ?
1107
-        if ($new_price_type) {
1108
-            // run the insert
1109
-            if ($PRT_ID = EEM_Price_Type::instance()->insert($set_column_values)) {
1110
-                $success = 1;
1111
-            }
1112
-            $action_desc = 'created';
1113
-        } else {
1114
-            $PRT_ID = $this->request->getRequestParam('PRT_ID', 0, DataType::INTEGER);
1115
-            // run the update
1116
-            $where_cols_n_values = ['PRT_ID' => $PRT_ID];
1117
-            if (EEM_Price_Type::instance()->update($set_column_values, [$where_cols_n_values])) {
1118
-                $success = 1;
1119
-            }
1120
-            $action_desc = 'updated';
1121
-        }
1122
-
1123
-        $query_args = ['action' => 'edit_price_type', 'id' => $PRT_ID];
1124
-        $this->_redirect_after_action($success, 'Price Type', $action_desc, $query_args);
1125
-    }
1126
-
1127
-
1128
-    /**
1129
-     * @param bool $trash - whether to move item to trash (TRUE) or restore it (FALSE)
1130
-     * @return void
1131
-     * @throws EE_Error
1132
-     * @throws ReflectionException
1133
-     */
1134
-    protected function _trash_or_restore_price_type(bool $trash = true)
1135
-    {
1136
-        $entity_model = EEM_Price_Type::instance();
1137
-        $action       = $trash ? EE_Admin_List_Table::ACTION_TRASH : EE_Admin_List_Table::ACTION_RESTORE;
1138
-        $success      = $this->trashRestoreDeleteEntities($entity_model, 'id', $action, 'PRT_deleted');
1139
-        if ($success) {
1140
-            $msg = $trash
1141
-                ? esc_html(
1142
-                    _n(
1143
-                        'The Price Type has been trashed',
1144
-                        'The Price Types have been trashed',
1145
-                        $success,
1146
-                        'event_espresso'
1147
-                    )
1148
-                )
1149
-                : esc_html(
1150
-                    _n(
1151
-                        'The Price Type has been restored',
1152
-                        'The Price Types have been restored',
1153
-                        $success,
1154
-                        'event_espresso'
1155
-                    )
1156
-                );
1157
-            EE_Error::add_success($msg);
1158
-        }
1159
-        $this->_redirect_after_action('', '', '', ['action' => 'price_types'], true);
1160
-    }
1161
-
1162
-
1163
-    /**
1164
-     * @return void
1165
-     * @throws EE_Error
1166
-     * @throws ReflectionException
1167
-     */
1168
-    protected function _delete_price_type()
1169
-    {
1170
-        $entity_model = EEM_Price_Type::instance();
1171
-        $deleted      = $this->trashRestoreDeleteEntities($entity_model, 'id');
1172
-        $this->_redirect_after_action(
1173
-            $deleted,
1174
-            $entity_model->item_name($deleted),
1175
-            'deleted',
1176
-            ['action' => 'price_types']
1177
-        );
1178
-    }
1179
-
1180
-
1181
-    /**
1182
-     * @return string
1183
-     */
1184
-    protected function _learn_more_about_pricing_link(): string
1185
-    {
1186
-        return '
895
+	/**
896
+	 * generates HTML for main Prices Admin page
897
+	 *
898
+	 * @return void
899
+	 * @throws EE_Error
900
+	 */
901
+	protected function _price_types_overview_list_table()
902
+	{
903
+		$this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
904
+			'add_new_price_type',
905
+			'add_type',
906
+			[],
907
+			'add-new-h2'
908
+		);
909
+		$this->_admin_page_title .= $this->_learn_more_about_pricing_link();
910
+		$this->_search_btn_label = esc_html__('Price Types', 'event_espresso');
911
+		$this->display_admin_list_table_page_with_sidebar();
912
+	}
913
+
914
+
915
+	/**
916
+	 * retrieve data for Price Types List table
917
+	 *
918
+	 * @param int  $per_page how many prices displayed per page
919
+	 * @param bool $count    return the count or objects
920
+	 * @param bool $trashed  whether the current view is of the trash can - eww yuck!
921
+	 * @return EE_Soft_Delete_Base_Class[]|int int = count || array of price objects
922
+	 * @throws EE_Error
923
+	 * @throws ReflectionException
924
+	 */
925
+	public function get_price_types_overview_data(int $per_page = 10, bool $count = false, bool $trashed = false)
926
+	{
927
+		// start with an empty array
928
+		require_once(PRICING_ADMIN . 'Price_Types_List_Table.class.php');
929
+
930
+		$orderby = $this->request->getRequestParam('orderby', '');
931
+		$order   = $this->request->getRequestParam('order', 'ASC');
932
+
933
+		switch ($orderby) {
934
+			case 'name':
935
+				$orderby = ['PRT_name' => $order];
936
+				break;
937
+			default:
938
+				$orderby = ['PRT_order' => $order];
939
+		}
940
+
941
+		$current_page = $this->request->getRequestParam('paged', 1, DataType::INTEGER);
942
+		$per_page     = $this->request->getRequestParam('perpage', $per_page, DataType::INTEGER);
943
+
944
+		$offset = ($current_page - 1) * $per_page;
945
+		$limit  = [$offset, $per_page];
946
+
947
+		$where = ['PRT_deleted' => $trashed, 'PBT_ID' => ['!=', 1]];
948
+
949
+		$search_term = $this->request->getRequestParam('s');
950
+		if ($search_term) {
951
+			$where['OR'] = [
952
+				'PRT_name' => ['LIKE', "%{$search_term}%"],
953
+			];
954
+		}
955
+		$query_params = [
956
+			$where,
957
+			'order_by' => $orderby,
958
+			'limit'    => $limit,
959
+		];
960
+		return $count
961
+			? EEM_Price_Type::instance()->count_deleted_and_undeleted($query_params)
962
+			: EEM_Price_Type::instance()->get_all_deleted_and_undeleted($query_params);
963
+	}
964
+
965
+
966
+	/**
967
+	 * _edit_price_type_details
968
+	 *
969
+	 * @return void
970
+	 * @throws EE_Error
971
+	 * @throws ReflectionException
972
+	 */
973
+	protected function _edit_price_type_details()
974
+	{
975
+		// grab price type ID
976
+		$PRT_ID = $this->request->getRequestParam('id', 0, DataType::INTEGER);
977
+		// change page title based on request action
978
+		switch ($this->_req_action) {
979
+			case 'add_new_price_type':
980
+				$this->_admin_page_title = esc_html__('Add New Price Type', 'event_espresso');
981
+				break;
982
+			case 'edit_price_type':
983
+				$this->_admin_page_title = esc_html__('Edit Price Type', 'event_espresso');
984
+				break;
985
+			default:
986
+				$this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
987
+		}
988
+		// add PRT_ID to title if editing
989
+		$this->_admin_page_title = $PRT_ID ? $this->_admin_page_title . ' # ' . $PRT_ID : $this->_admin_page_title;
990
+
991
+		if ($PRT_ID) {
992
+			$price_type               = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
993
+			$additional_hidden_fields = ['PRT_ID' => ['type' => 'hidden', 'value' => $PRT_ID]];
994
+			$this->_set_add_edit_form_tags('update_price_type', $additional_hidden_fields);
995
+		} else {
996
+			$price_type = EEM_Price_Type::instance()->get_new_price_type();
997
+			$this->_set_add_edit_form_tags('insert_price_type');
998
+		}
999
+
1000
+		if (! $price_type instanceof EE_Price_Type) {
1001
+			throw new RuntimeException(
1002
+				sprintf(
1003
+					esc_html__(
1004
+						'A valid Price Type could not be retrieved from the database with ID: %1$s',
1005
+						'event_espresso'
1006
+					),
1007
+					$PRT_ID
1008
+				)
1009
+			);
1010
+		}
1011
+
1012
+		$this->_template_args['PRT_ID']     = $PRT_ID;
1013
+		$this->_template_args['price_type'] = $price_type;
1014
+
1015
+		$base_types    = EEM_Price_Type::instance()->get_base_types();
1016
+		$select_values = [];
1017
+		foreach ($base_types as $ref => $text) {
1018
+			if ($ref == EEM_Price_Type::base_type_base_price) {
1019
+				// do not allow creation of base_type_base_prices because that's a system only base type.
1020
+				continue;
1021
+			}
1022
+			$select_values[] = ['id' => $ref, 'text' => $text];
1023
+		}
1024
+
1025
+		$this->_template_args['base_type_select'] = EEH_Form_Fields::select_input(
1026
+			'base_type',
1027
+			$select_values,
1028
+			$price_type->base_type(),
1029
+			'id="price-type-base-type-slct"'
1030
+		);
1031
+
1032
+		$this->_template_args['learn_more_about_pricing_link'] = $this->_learn_more_about_pricing_link();
1033
+		$this->_template_args['admin_page_content']            = $this->_edit_price_type_details_meta_box();
1034
+
1035
+		$redirect_URL = add_query_arg(['action' => 'price_types'], $this->_admin_base_url);
1036
+		$this->_set_publish_post_box_vars('id', $PRT_ID, false, $redirect_URL, true);
1037
+		// the details template wrapper
1038
+		$this->display_admin_page_with_sidebar();
1039
+	}
1040
+
1041
+
1042
+	/**
1043
+	 * _edit_price_type_details_meta_box
1044
+	 *
1045
+	 * @return string
1046
+	 */
1047
+	public function _edit_price_type_details_meta_box(): string
1048
+	{
1049
+		return EEH_Template::display_template(
1050
+			PRICING_TEMPLATE_PATH . 'pricing_type_details_main_meta_box.template.php',
1051
+			$this->_template_args,
1052
+			true
1053
+		);
1054
+	}
1055
+
1056
+
1057
+	/**
1058
+	 * @return array
1059
+	 */
1060
+	protected function set_price_type_column_values(): array
1061
+	{
1062
+		$base_type  = $this->request->getRequestParam(
1063
+			'base_type',
1064
+			EEM_Price_Type::base_type_base_price,
1065
+			DataType::INTEGER
1066
+		);
1067
+		$is_percent = $this->request->getRequestParam('PRT_is_percent', 0, DataType::INTEGER);
1068
+		$order      = $this->request->getRequestParam('PRT_order', 0, DataType::INTEGER);
1069
+		switch ($base_type) {
1070
+			case EEM_Price_Type::base_type_base_price:
1071
+				$is_percent = 0;
1072
+				$order      = 0;
1073
+				break;
1074
+
1075
+			case EEM_Price_Type::base_type_discount:
1076
+			case EEM_Price_Type::base_type_surcharge:
1077
+				break;
1078
+
1079
+			case EEM_Price_Type::base_type_tax:
1080
+				$is_percent = 1;
1081
+				break;
1082
+		}
1083
+
1084
+		return [
1085
+			'PBT_ID'         => $base_type,
1086
+			'PRT_name'       => $this->request->getRequestParam('PRT_name', ''),
1087
+			'PRT_is_percent' => $is_percent,
1088
+			'PRT_order'      => $order,
1089
+			'PRT_deleted'    => 0,
1090
+		];
1091
+	}
1092
+
1093
+
1094
+	/**
1095
+	 * @param bool $new_price_type - whether to insert or update
1096
+	 * @return void
1097
+	 * @throws EE_Error
1098
+	 * @throws ReflectionException
1099
+	 */
1100
+	protected function _insert_or_update_price_type(bool $new_price_type = false)
1101
+	{
1102
+		// why be so pessimistic ???  : (
1103
+		$success = 0;
1104
+
1105
+		$set_column_values = $this->set_price_type_column_values();
1106
+		// is this a new Price ?
1107
+		if ($new_price_type) {
1108
+			// run the insert
1109
+			if ($PRT_ID = EEM_Price_Type::instance()->insert($set_column_values)) {
1110
+				$success = 1;
1111
+			}
1112
+			$action_desc = 'created';
1113
+		} else {
1114
+			$PRT_ID = $this->request->getRequestParam('PRT_ID', 0, DataType::INTEGER);
1115
+			// run the update
1116
+			$where_cols_n_values = ['PRT_ID' => $PRT_ID];
1117
+			if (EEM_Price_Type::instance()->update($set_column_values, [$where_cols_n_values])) {
1118
+				$success = 1;
1119
+			}
1120
+			$action_desc = 'updated';
1121
+		}
1122
+
1123
+		$query_args = ['action' => 'edit_price_type', 'id' => $PRT_ID];
1124
+		$this->_redirect_after_action($success, 'Price Type', $action_desc, $query_args);
1125
+	}
1126
+
1127
+
1128
+	/**
1129
+	 * @param bool $trash - whether to move item to trash (TRUE) or restore it (FALSE)
1130
+	 * @return void
1131
+	 * @throws EE_Error
1132
+	 * @throws ReflectionException
1133
+	 */
1134
+	protected function _trash_or_restore_price_type(bool $trash = true)
1135
+	{
1136
+		$entity_model = EEM_Price_Type::instance();
1137
+		$action       = $trash ? EE_Admin_List_Table::ACTION_TRASH : EE_Admin_List_Table::ACTION_RESTORE;
1138
+		$success      = $this->trashRestoreDeleteEntities($entity_model, 'id', $action, 'PRT_deleted');
1139
+		if ($success) {
1140
+			$msg = $trash
1141
+				? esc_html(
1142
+					_n(
1143
+						'The Price Type has been trashed',
1144
+						'The Price Types have been trashed',
1145
+						$success,
1146
+						'event_espresso'
1147
+					)
1148
+				)
1149
+				: esc_html(
1150
+					_n(
1151
+						'The Price Type has been restored',
1152
+						'The Price Types have been restored',
1153
+						$success,
1154
+						'event_espresso'
1155
+					)
1156
+				);
1157
+			EE_Error::add_success($msg);
1158
+		}
1159
+		$this->_redirect_after_action('', '', '', ['action' => 'price_types'], true);
1160
+	}
1161
+
1162
+
1163
+	/**
1164
+	 * @return void
1165
+	 * @throws EE_Error
1166
+	 * @throws ReflectionException
1167
+	 */
1168
+	protected function _delete_price_type()
1169
+	{
1170
+		$entity_model = EEM_Price_Type::instance();
1171
+		$deleted      = $this->trashRestoreDeleteEntities($entity_model, 'id');
1172
+		$this->_redirect_after_action(
1173
+			$deleted,
1174
+			$entity_model->item_name($deleted),
1175
+			'deleted',
1176
+			['action' => 'price_types']
1177
+		);
1178
+	}
1179
+
1180
+
1181
+	/**
1182
+	 * @return string
1183
+	 */
1184
+	protected function _learn_more_about_pricing_link(): string
1185
+	{
1186
+		return '
1187 1187
             <a
1188 1188
                 href="https://eventespresso.com/2019/08/how-to-leverage-pricing-and-packaging-to-sell-out-your-next-event/"
1189 1189
                 target="_blank"
@@ -1191,119 +1191,119 @@  discard block
 block discarded – undo
1191 1191
             >
1192 1192
                 ' . esc_html__('learn more about how pricing works', 'event_espresso') . '
1193 1193
             </a>';
1194
-    }
1195
-
1196
-
1197
-    /**
1198
-     * @throws EE_Error
1199
-     */
1200
-    protected function _tax_settings()
1201
-    {
1202
-        $this->_set_add_edit_form_tags('update_tax_settings');
1203
-        $this->_set_publish_post_box_vars();
1204
-        $this->_template_args['admin_page_content'] = $this->tax_settings_form()->get_html();
1205
-        $this->display_admin_page_with_sidebar();
1206
-    }
1207
-
1208
-
1209
-    /**
1210
-     * @return EE_Form_Section_Proper
1211
-     * @throws EE_Error
1212
-     */
1213
-    protected function tax_settings_form(): EE_Form_Section_Proper
1214
-    {
1215
-        $tax_settings = EE_Config::instance()->tax_settings;
1216
-        return new EE_Form_Section_Proper(
1217
-            [
1218
-                'name'            => 'tax_settings_form',
1219
-                'html_id'         => 'tax_settings_form',
1220
-                'html_class'      => 'padding',
1221
-                'layout_strategy' => new EE_Div_Per_Section_Layout(),
1222
-                'subsections'     => apply_filters(
1223
-                    'FHEE__Pricing_Admin_Page__tax_settings_form__form_subsections',
1224
-                    [
1225
-                        'tax_settings' => new EE_Form_Section_Proper(
1226
-                            [
1227
-                                'name'            => 'tax_settings_tbl',
1228
-                                'html_id'         => 'tax_settings_tbl',
1229
-                                'html_class'      => 'form-table',
1230
-                                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1231
-                                'subsections'     => [
1232
-                                    'prices_displayed_including_taxes' => new EE_Yes_No_Input(
1233
-                                        [
1234
-                                            'html_label_text'         => esc_html__(
1235
-                                                'Show Prices With Taxes Included?',
1236
-                                                'event_espresso'
1237
-                                            ),
1238
-                                            'html_help_text'          => esc_html__(
1239
-                                                'Indicates whether or not to display prices with the taxes included',
1240
-                                                'event_espresso'
1241
-                                            ),
1242
-                                            'default'                 => $tax_settings->prices_displayed_including_taxes
1243
-                                                                         ?? true,
1244
-                                            'display_html_label_text' => false,
1245
-                                        ]
1246
-                                    ),
1247
-                                ],
1248
-                            ]
1249
-                        ),
1250
-                    ]
1251
-                ),
1252
-            ]
1253
-        );
1254
-    }
1255
-
1256
-
1257
-    /**
1258
-     * _update_tax_settings
1259
-     *
1260
-     * @return void
1261
-     * @throws EE_Error
1262
-     * @throws ReflectionException
1263
-     * @since 4.9.13
1264
-     */
1265
-    public function _update_tax_settings()
1266
-    {
1267
-        $tax_settings = EE_Config::instance()->tax_settings;
1268
-        if (! $tax_settings instanceof EE_Tax_Config) {
1269
-            $tax_settings = new EE_Tax_Config();
1270
-        }
1271
-        try {
1272
-            $tax_form = $this->tax_settings_form();
1273
-            // check for form submission
1274
-            if ($tax_form->was_submitted()) {
1275
-                // capture form data
1276
-                $tax_form->receive_form_submission();
1277
-                // validate form data
1278
-                if ($tax_form->is_valid()) {
1279
-                    // grab validated data from form
1280
-                    $valid_data = $tax_form->valid_data();
1281
-                    // set data on config
1282
-                    $tax_settings->prices_displayed_including_taxes =
1283
-                        $valid_data['tax_settings']['prices_displayed_including_taxes'];
1284
-                } else {
1285
-                    if ($tax_form->submission_error_message() !== '') {
1286
-                        EE_Error::add_error(
1287
-                            $tax_form->submission_error_message(),
1288
-                            __FILE__,
1289
-                            __FUNCTION__,
1290
-                            __LINE__
1291
-                        );
1292
-                    }
1293
-                }
1294
-            }
1295
-        } catch (EE_Error $e) {
1296
-            EE_Error::add_error($e->get_error(), __FILE__, __FUNCTION__, __LINE__);
1297
-        }
1298
-
1299
-        $what    = 'Tax Settings';
1300
-        $success = $this->_update_espresso_configuration(
1301
-            $what,
1302
-            $tax_settings,
1303
-            __FILE__,
1304
-            __FUNCTION__,
1305
-            __LINE__
1306
-        );
1307
-        $this->_redirect_after_action($success, $what, 'updated', ['action' => 'tax_settings']);
1308
-    }
1194
+	}
1195
+
1196
+
1197
+	/**
1198
+	 * @throws EE_Error
1199
+	 */
1200
+	protected function _tax_settings()
1201
+	{
1202
+		$this->_set_add_edit_form_tags('update_tax_settings');
1203
+		$this->_set_publish_post_box_vars();
1204
+		$this->_template_args['admin_page_content'] = $this->tax_settings_form()->get_html();
1205
+		$this->display_admin_page_with_sidebar();
1206
+	}
1207
+
1208
+
1209
+	/**
1210
+	 * @return EE_Form_Section_Proper
1211
+	 * @throws EE_Error
1212
+	 */
1213
+	protected function tax_settings_form(): EE_Form_Section_Proper
1214
+	{
1215
+		$tax_settings = EE_Config::instance()->tax_settings;
1216
+		return new EE_Form_Section_Proper(
1217
+			[
1218
+				'name'            => 'tax_settings_form',
1219
+				'html_id'         => 'tax_settings_form',
1220
+				'html_class'      => 'padding',
1221
+				'layout_strategy' => new EE_Div_Per_Section_Layout(),
1222
+				'subsections'     => apply_filters(
1223
+					'FHEE__Pricing_Admin_Page__tax_settings_form__form_subsections',
1224
+					[
1225
+						'tax_settings' => new EE_Form_Section_Proper(
1226
+							[
1227
+								'name'            => 'tax_settings_tbl',
1228
+								'html_id'         => 'tax_settings_tbl',
1229
+								'html_class'      => 'form-table',
1230
+								'layout_strategy' => new EE_Admin_Two_Column_Layout(),
1231
+								'subsections'     => [
1232
+									'prices_displayed_including_taxes' => new EE_Yes_No_Input(
1233
+										[
1234
+											'html_label_text'         => esc_html__(
1235
+												'Show Prices With Taxes Included?',
1236
+												'event_espresso'
1237
+											),
1238
+											'html_help_text'          => esc_html__(
1239
+												'Indicates whether or not to display prices with the taxes included',
1240
+												'event_espresso'
1241
+											),
1242
+											'default'                 => $tax_settings->prices_displayed_including_taxes
1243
+																		 ?? true,
1244
+											'display_html_label_text' => false,
1245
+										]
1246
+									),
1247
+								],
1248
+							]
1249
+						),
1250
+					]
1251
+				),
1252
+			]
1253
+		);
1254
+	}
1255
+
1256
+
1257
+	/**
1258
+	 * _update_tax_settings
1259
+	 *
1260
+	 * @return void
1261
+	 * @throws EE_Error
1262
+	 * @throws ReflectionException
1263
+	 * @since 4.9.13
1264
+	 */
1265
+	public function _update_tax_settings()
1266
+	{
1267
+		$tax_settings = EE_Config::instance()->tax_settings;
1268
+		if (! $tax_settings instanceof EE_Tax_Config) {
1269
+			$tax_settings = new EE_Tax_Config();
1270
+		}
1271
+		try {
1272
+			$tax_form = $this->tax_settings_form();
1273
+			// check for form submission
1274
+			if ($tax_form->was_submitted()) {
1275
+				// capture form data
1276
+				$tax_form->receive_form_submission();
1277
+				// validate form data
1278
+				if ($tax_form->is_valid()) {
1279
+					// grab validated data from form
1280
+					$valid_data = $tax_form->valid_data();
1281
+					// set data on config
1282
+					$tax_settings->prices_displayed_including_taxes =
1283
+						$valid_data['tax_settings']['prices_displayed_including_taxes'];
1284
+				} else {
1285
+					if ($tax_form->submission_error_message() !== '') {
1286
+						EE_Error::add_error(
1287
+							$tax_form->submission_error_message(),
1288
+							__FILE__,
1289
+							__FUNCTION__,
1290
+							__LINE__
1291
+						);
1292
+					}
1293
+				}
1294
+			}
1295
+		} catch (EE_Error $e) {
1296
+			EE_Error::add_error($e->get_error(), __FILE__, __FUNCTION__, __LINE__);
1297
+		}
1298
+
1299
+		$what    = 'Tax Settings';
1300
+		$success = $this->_update_espresso_configuration(
1301
+			$what,
1302
+			$tax_settings,
1303
+			__FILE__,
1304
+			__FUNCTION__,
1305
+			__LINE__
1306
+		);
1307
+		$this->_redirect_after_action($success, $what, 'updated', ['action' => 'tax_settings']);
1308
+	}
1309 1309
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
         wp_enqueue_style('espresso-ui-theme');
353 353
         wp_register_style(
354 354
             'espresso_pricing_css',
355
-            PRICING_ASSETS_URL . 'espresso_pricing_admin.css',
355
+            PRICING_ASSETS_URL.'espresso_pricing_admin.css',
356 356
             [EspressoLegacyAdminAssetManager::CSS_HANDLE_EE_ADMIN],
357 357
             EVENT_ESPRESSO_VERSION
358 358
         );
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
         wp_enqueue_script('jquery-ui-widget');
365 365
         wp_register_script(
366 366
             'espresso_pricing_js',
367
-            PRICING_ASSETS_URL . 'espresso_pricing_admin.js',
367
+            PRICING_ASSETS_URL.'espresso_pricing_admin.js',
368 368
             ['jquery'],
369 369
             EVENT_ESPRESSO_VERSION,
370 370
             true
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
      */
462 462
     protected function _price_overview_list_table()
463 463
     {
464
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
464
+        $this->_admin_page_title .= ' '.$this->get_action_link_or_button(
465 465
             'add_new_price',
466 466
             'add',
467 467
             [],
@@ -488,7 +488,7 @@  discard block
 block discarded – undo
488 488
         // start with an empty array
489 489
         $event_pricing = [];
490 490
 
491
-        require_once(PRICING_ADMIN . 'Prices_List_Table.class.php');
491
+        require_once(PRICING_ADMIN.'Prices_List_Table.class.php');
492 492
 
493 493
         $orderby = $this->request->getRequestParam('orderby', '');
494 494
         $order   = $this->request->getRequestParam('order', 'ASC');
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
                 $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
567 567
         }
568 568
         // add PRC_ID to title if editing
569
-        $this->_admin_page_title = $PRC_ID ? $this->_admin_page_title . ' # ' . $PRC_ID : $this->_admin_page_title;
569
+        $this->_admin_page_title = $PRC_ID ? $this->_admin_page_title.' # '.$PRC_ID : $this->_admin_page_title;
570 570
 
571 571
         if ($PRC_ID) {
572 572
             $price                    = EEM_Price::instance()->get_one_by_ID($PRC_ID);
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
             $this->_set_add_edit_form_tags('insert_price');
580 580
         }
581 581
 
582
-        if (! $price instanceof EE_Price) {
582
+        if ( ! $price instanceof EE_Price) {
583 583
             throw new RuntimeException(
584 584
                 sprintf(
585 585
                     esc_html__(
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
     public function _edit_price_details_meta_box(): string
638 638
     {
639 639
         return EEH_Template::display_template(
640
-            PRICING_TEMPLATE_PATH . 'pricing_details_main_meta_box.template.php',
640
+            PRICING_TEMPLATE_PATH.'pricing_details_main_meta_box.template.php',
641 641
             $this->_template_args,
642 642
             true
643 643
         );
@@ -805,19 +805,19 @@  discard block
 block discarded – undo
805 805
         string $action,
806 806
         int $result
807 807
     ) {
808
-        if (! $entity_ID || (float) $result < 1) {
808
+        if ( ! $entity_ID || (float) $result < 1) {
809 809
             return;
810 810
         }
811 811
 
812 812
         $entity = $entity_model->get_one_by_ID($entity_ID);
813
-        if (! $entity instanceof EE_Price || $entity->type_obj()->base_type() === EEM_Price_Type::base_type_tax) {
813
+        if ( ! $entity instanceof EE_Price || $entity->type_obj()->base_type() === EEM_Price_Type::base_type_tax) {
814 814
             return;
815 815
         }
816 816
 
817 817
         // get default tickets for updating
818 818
         $default_tickets = EEM_Ticket::instance()->get_all_default_tickets();
819 819
         foreach ($default_tickets as $default_ticket) {
820
-            if (! $default_ticket instanceof EE_Ticket) {
820
+            if ( ! $default_ticket instanceof EE_Ticket) {
821 821
                 continue;
822 822
             }
823 823
             switch ($action) {
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
      */
901 901
     protected function _price_types_overview_list_table()
902 902
     {
903
-        $this->_admin_page_title .= ' ' . $this->get_action_link_or_button(
903
+        $this->_admin_page_title .= ' '.$this->get_action_link_or_button(
904 904
             'add_new_price_type',
905 905
             'add_type',
906 906
             [],
@@ -925,7 +925,7 @@  discard block
 block discarded – undo
925 925
     public function get_price_types_overview_data(int $per_page = 10, bool $count = false, bool $trashed = false)
926 926
     {
927 927
         // start with an empty array
928
-        require_once(PRICING_ADMIN . 'Price_Types_List_Table.class.php');
928
+        require_once(PRICING_ADMIN.'Price_Types_List_Table.class.php');
929 929
 
930 930
         $orderby = $this->request->getRequestParam('orderby', '');
931 931
         $order   = $this->request->getRequestParam('order', 'ASC');
@@ -986,7 +986,7 @@  discard block
 block discarded – undo
986 986
                 $this->_admin_page_title = ucwords(str_replace('_', ' ', $this->_req_action));
987 987
         }
988 988
         // add PRT_ID to title if editing
989
-        $this->_admin_page_title = $PRT_ID ? $this->_admin_page_title . ' # ' . $PRT_ID : $this->_admin_page_title;
989
+        $this->_admin_page_title = $PRT_ID ? $this->_admin_page_title.' # '.$PRT_ID : $this->_admin_page_title;
990 990
 
991 991
         if ($PRT_ID) {
992 992
             $price_type               = EEM_Price_Type::instance()->get_one_by_ID($PRT_ID);
@@ -997,7 +997,7 @@  discard block
 block discarded – undo
997 997
             $this->_set_add_edit_form_tags('insert_price_type');
998 998
         }
999 999
 
1000
-        if (! $price_type instanceof EE_Price_Type) {
1000
+        if ( ! $price_type instanceof EE_Price_Type) {
1001 1001
             throw new RuntimeException(
1002 1002
                 sprintf(
1003 1003
                     esc_html__(
@@ -1047,7 +1047,7 @@  discard block
 block discarded – undo
1047 1047
     public function _edit_price_type_details_meta_box(): string
1048 1048
     {
1049 1049
         return EEH_Template::display_template(
1050
-            PRICING_TEMPLATE_PATH . 'pricing_type_details_main_meta_box.template.php',
1050
+            PRICING_TEMPLATE_PATH.'pricing_type_details_main_meta_box.template.php',
1051 1051
             $this->_template_args,
1052 1052
             true
1053 1053
         );
@@ -1059,7 +1059,7 @@  discard block
 block discarded – undo
1059 1059
      */
1060 1060
     protected function set_price_type_column_values(): array
1061 1061
     {
1062
-        $base_type  = $this->request->getRequestParam(
1062
+        $base_type = $this->request->getRequestParam(
1063 1063
             'base_type',
1064 1064
             EEM_Price_Type::base_type_base_price,
1065 1065
             DataType::INTEGER
@@ -1189,7 +1189,7 @@  discard block
 block discarded – undo
1189 1189
                 target="_blank"
1190 1190
                 class="ee-price-guide-link"
1191 1191
             >
1192
-                ' . esc_html__('learn more about how pricing works', 'event_espresso') . '
1192
+                ' . esc_html__('learn more about how pricing works', 'event_espresso').'
1193 1193
             </a>';
1194 1194
     }
1195 1195
 
@@ -1265,7 +1265,7 @@  discard block
 block discarded – undo
1265 1265
     public function _update_tax_settings()
1266 1266
     {
1267 1267
         $tax_settings = EE_Config::instance()->tax_settings;
1268
-        if (! $tax_settings instanceof EE_Tax_Config) {
1268
+        if ( ! $tax_settings instanceof EE_Tax_Config) {
1269 1269
             $tax_settings = new EE_Tax_Config();
1270 1270
         }
1271 1271
         try {
Please login to merge, or discard this patch.