Completed
Branch FET/11129/facilitate-stripe-an... (2acfaf)
by
unknown
136:34 queued 124:19
created
core/db_models/fields/EE_Money_Field.php 2 patches
Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -18,256 +18,256 @@
 block discarded – undo
18 18
 class EE_Money_Field extends EE_Float_Field
19 19
 {
20 20
 
21
-    /**
22
-     * @var $money_factory MoneyFactory
23
-     */
24
-    protected $money_factory;
21
+	/**
22
+	 * @var $money_factory MoneyFactory
23
+	 */
24
+	protected $money_factory;
25 25
 
26
-    /**
27
-     * @var $money_formatter MoneyFormatter
28
-     */
29
-    protected $money_formatter;
26
+	/**
27
+	 * @var $money_formatter MoneyFormatter
28
+	 */
29
+	protected $money_formatter;
30 30
 
31 31
 
32
-    /**
33
-     * @param string       $table_column
34
-     * @param string       $nicename
35
-     * @param bool         $nullable
36
-     * @param null         $default_value
37
-     * @param MoneyFactory $factory
38
-     * @param MoneyFormatter $money_formatter
39
-     * @throws InvalidArgumentException
40
-     * @throws InvalidInterfaceException
41
-     * @throws InvalidDataTypeException
42
-     */
43
-    public function __construct(
44
-        $table_column,
45
-        $nicename,
46
-        $nullable,
47
-        $default_value = null,
48
-        MoneyFactory $factory = null,
49
-        MoneyFormatter $money_formatter = null
50
-    ) {
51
-        if (! $factory instanceof MoneyFactory) {
52
-            $factory = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\currency\MoneyFactory');
53
-        }
54
-        $this->money_factory = $factory;
55
-        if (! $money_formatter instanceof MoneyFormatter) {
56
-            $money_formatter = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\currency\formatters\MoneyFormatter');
57
-        }
58
-        $this->money_formatter = $money_formatter;
59
-        parent::__construct($table_column, $nicename, $nullable, $default_value);
60
-        $this->setSchemaType('object');
61
-    }
32
+	/**
33
+	 * @param string       $table_column
34
+	 * @param string       $nicename
35
+	 * @param bool         $nullable
36
+	 * @param null         $default_value
37
+	 * @param MoneyFactory $factory
38
+	 * @param MoneyFormatter $money_formatter
39
+	 * @throws InvalidArgumentException
40
+	 * @throws InvalidInterfaceException
41
+	 * @throws InvalidDataTypeException
42
+	 */
43
+	public function __construct(
44
+		$table_column,
45
+		$nicename,
46
+		$nullable,
47
+		$default_value = null,
48
+		MoneyFactory $factory = null,
49
+		MoneyFormatter $money_formatter = null
50
+	) {
51
+		if (! $factory instanceof MoneyFactory) {
52
+			$factory = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\currency\MoneyFactory');
53
+		}
54
+		$this->money_factory = $factory;
55
+		if (! $money_formatter instanceof MoneyFormatter) {
56
+			$money_formatter = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\currency\formatters\MoneyFormatter');
57
+		}
58
+		$this->money_formatter = $money_formatter;
59
+		parent::__construct($table_column, $nicename, $nullable, $default_value);
60
+		$this->setSchemaType('object');
61
+	}
62 62
 
63 63
 
64
-    /**
65
-     * Formats the value for pretty output, according to $schema.
66
-     * If legacy filters are being used, uses EEH_Money::format_currency() to format it and currency data from the database
67
-     * (which admins can change), otherwise uses MoneyFormatter which takes currency information from a JSON file
68
-     * (which admins CANNOT change).
69
-     * Legacy Schemas (use the admin-editable currency data from the database):
70
-     *    'localized_float': "3,023.00"
71
-     *    'no_currency_code': "$3,023.00"
72
-     *    null: "$3,023.00<span>USD</span>"
73
-     * New Schemas (use the currency data from a JSON file that we control):
74
-     *    MoneyFormatter::RAW: "3023.0000"
75
-     *    MoneyFormatter::DECIMAL_ONLY: "3023.00"
76
-     *    MoneyFormatter::ADD THOUSANDS/: "3,023.00"
77
-     *    MoneyFormatter::ADD_CURRENCY_SIGN: "$3,023.00"
78
-     *    MoneyFormatter::ADD_CURRENCY_CODE: "$3,023.00<span>USD</span>"
79
-     *
80
-     * @param string|Money $value_on_field_to_be_outputted
81
-     * @param string       $schema
82
-     * @return string
83
-     * @throws InvalidIdentifierException
84
-     * @throws InvalidArgumentException
85
-     * @throws InvalidInterfaceException
86
-     * @throws InvalidDataTypeException
87
-     * @throws EE_Error
88
-     * @throws ReflectionException
89
-     */
90
-    public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
91
-    {
92
-        //using the default or old schemas? Use the legacy formatting (which uses the database's currency data,
93
-        //whereas the new code uses the JSON file's currency data
94
-        if (in_array(
95
-            $schema,
96
-            array(
97
-                'localized_float',
98
-                'no_currency_code',
99
-                null
100
-            ),
101
-            true
102
-        )) {
103
-            $value_on_field_to_be_outputted = $this->ensureNotMoney($value_on_field_to_be_outputted);
104
-            $pretty_float = parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted);
64
+	/**
65
+	 * Formats the value for pretty output, according to $schema.
66
+	 * If legacy filters are being used, uses EEH_Money::format_currency() to format it and currency data from the database
67
+	 * (which admins can change), otherwise uses MoneyFormatter which takes currency information from a JSON file
68
+	 * (which admins CANNOT change).
69
+	 * Legacy Schemas (use the admin-editable currency data from the database):
70
+	 *    'localized_float': "3,023.00"
71
+	 *    'no_currency_code': "$3,023.00"
72
+	 *    null: "$3,023.00<span>USD</span>"
73
+	 * New Schemas (use the currency data from a JSON file that we control):
74
+	 *    MoneyFormatter::RAW: "3023.0000"
75
+	 *    MoneyFormatter::DECIMAL_ONLY: "3023.00"
76
+	 *    MoneyFormatter::ADD THOUSANDS/: "3,023.00"
77
+	 *    MoneyFormatter::ADD_CURRENCY_SIGN: "$3,023.00"
78
+	 *    MoneyFormatter::ADD_CURRENCY_CODE: "$3,023.00<span>USD</span>"
79
+	 *
80
+	 * @param string|Money $value_on_field_to_be_outputted
81
+	 * @param string       $schema
82
+	 * @return string
83
+	 * @throws InvalidIdentifierException
84
+	 * @throws InvalidArgumentException
85
+	 * @throws InvalidInterfaceException
86
+	 * @throws InvalidDataTypeException
87
+	 * @throws EE_Error
88
+	 * @throws ReflectionException
89
+	 */
90
+	public function prepare_for_pretty_echoing($value_on_field_to_be_outputted, $schema = null)
91
+	{
92
+		//using the default or old schemas? Use the legacy formatting (which uses the database's currency data,
93
+		//whereas the new code uses the JSON file's currency data
94
+		if (in_array(
95
+			$schema,
96
+			array(
97
+				'localized_float',
98
+				'no_currency_code',
99
+				null
100
+			),
101
+			true
102
+		)) {
103
+			$value_on_field_to_be_outputted = $this->ensureNotMoney($value_on_field_to_be_outputted);
104
+			$pretty_float = parent::prepare_for_pretty_echoing($value_on_field_to_be_outputted);
105 105
 
106
-            if ($schema === 'localized_float') {
107
-                return $pretty_float;
108
-            }
109
-            $display_code = true;
110
-            if ($schema === 'no_currency_code') {
111
-                //          echo "schema no currency!";
112
-                $display_code = false;
113
-            }
106
+			if ($schema === 'localized_float') {
107
+				return $pretty_float;
108
+			}
109
+			$display_code = true;
110
+			if ($schema === 'no_currency_code') {
111
+				//          echo "schema no currency!";
112
+				$display_code = false;
113
+			}
114 114
 
115
-            //we don't use the $pretty_float because format_currency will take care of it.
116
-            return EEH_Money::format_currency($value_on_field_to_be_outputted, false, $display_code);
117
-        }
118
-        //ok let's just use the new formatting code then
119
-        $schema = (string)$schema;
120
-        switch ($schema) {
121
-            case (string)CurrencyAmountFormatterInterface::ADD_CURRENCY_CODE:
122
-                $formatting_level = CurrencyAmountFormatterInterface::ADD_CURRENCY_CODE;
123
-                break;
124
-            case (string)CurrencyAmountFormatterInterface::ADD_CURRENCY_SIGN:
125
-                $formatting_level = CurrencyAmountFormatterInterface::ADD_CURRENCY_SIGN;
126
-                break;
127
-            case (string)CurrencyAmountFormatterInterface::ADD_THOUSANDS:
128
-                $formatting_level = CurrencyAmountFormatterInterface::ADD_THOUSANDS;
129
-                break;
130
-            case (string)CurrencyAmountFormatterInterface::DECIMAL_ONLY:
131
-                $formatting_level = CurrencyAmountFormatterInterface::DECIMAL_ONLY;
132
-                break;
133
-            default:
134
-                $formatting_level = CurrencyAmountFormatterInterface::INTERNATIONAL;
135
-        }
136
-        $value_on_field_to_be_outputted = $this->ensureMoney($value_on_field_to_be_outputted);
137
-        return $this->money_formatter->format(
138
-            $value_on_field_to_be_outputted,
139
-            $formatting_level
140
-        );
141
-    }
115
+			//we don't use the $pretty_float because format_currency will take care of it.
116
+			return EEH_Money::format_currency($value_on_field_to_be_outputted, false, $display_code);
117
+		}
118
+		//ok let's just use the new formatting code then
119
+		$schema = (string)$schema;
120
+		switch ($schema) {
121
+			case (string)CurrencyAmountFormatterInterface::ADD_CURRENCY_CODE:
122
+				$formatting_level = CurrencyAmountFormatterInterface::ADD_CURRENCY_CODE;
123
+				break;
124
+			case (string)CurrencyAmountFormatterInterface::ADD_CURRENCY_SIGN:
125
+				$formatting_level = CurrencyAmountFormatterInterface::ADD_CURRENCY_SIGN;
126
+				break;
127
+			case (string)CurrencyAmountFormatterInterface::ADD_THOUSANDS:
128
+				$formatting_level = CurrencyAmountFormatterInterface::ADD_THOUSANDS;
129
+				break;
130
+			case (string)CurrencyAmountFormatterInterface::DECIMAL_ONLY:
131
+				$formatting_level = CurrencyAmountFormatterInterface::DECIMAL_ONLY;
132
+				break;
133
+			default:
134
+				$formatting_level = CurrencyAmountFormatterInterface::INTERNATIONAL;
135
+		}
136
+		$value_on_field_to_be_outputted = $this->ensureMoney($value_on_field_to_be_outputted);
137
+		return $this->money_formatter->format(
138
+			$value_on_field_to_be_outputted,
139
+			$formatting_level
140
+		);
141
+	}
142 142
 
143 143
 
144
-    /**
145
-     * Make sure this value is a money object
146
-     *
147
-     * @param string|float|int|Money $value
148
-     * @return Money
149
-     * @throws InvalidIdentifierException
150
-     * @throws InvalidArgumentException
151
-     * @throws InvalidInterfaceException
152
-     * @throws InvalidDataTypeException
153
-     * @throws EE_Error
154
-     */
155
-    private function ensureMoney($value)
156
-    {
157
-        if (! $value instanceof Money) {
158
-            return $this->money_factory->createForSite($value);
159
-        }
160
-        return $value;
161
-    }
144
+	/**
145
+	 * Make sure this value is a money object
146
+	 *
147
+	 * @param string|float|int|Money $value
148
+	 * @return Money
149
+	 * @throws InvalidIdentifierException
150
+	 * @throws InvalidArgumentException
151
+	 * @throws InvalidInterfaceException
152
+	 * @throws InvalidDataTypeException
153
+	 * @throws EE_Error
154
+	 */
155
+	private function ensureMoney($value)
156
+	{
157
+		if (! $value instanceof Money) {
158
+			return $this->money_factory->createForSite($value);
159
+		}
160
+		return $value;
161
+	}
162 162
 
163 163
 
164 164
 
165
-    /**
166
-     * Ensures we're dealing with something that isn't Money
167
-     * (for passing off to legacy systems or the parent field)
168
-     * @param  string|float|int|Money $value
169
-     * @return string|float|int
170
-     */
171
-    private function ensureNotMoney($value)
172
-    {
173
-        if( $value instanceof Money) {
174
-            return $value->amount();
175
-        }
176
-        return $value;
177
-    }
165
+	/**
166
+	 * Ensures we're dealing with something that isn't Money
167
+	 * (for passing off to legacy systems or the parent field)
168
+	 * @param  string|float|int|Money $value
169
+	 * @return string|float|int
170
+	 */
171
+	private function ensureNotMoney($value)
172
+	{
173
+		if( $value instanceof Money) {
174
+			return $value->amount();
175
+		}
176
+		return $value;
177
+	}
178 178
 
179 179
 
180
-    /**
181
-     * If provided with a string, strips out money-related formatting to turn it into a proper float.
182
-     * Rounds the float to the correct number of decimal places for this country's currency.
183
-     * Also, interprets periods and commas according to the country's currency settings.
184
-     * So if you want to pass in a string that NEEDS to interpret periods as decimal marks,
185
-     * type cast it to a float first.
186
-     *
187
-     * @param string|float|int|Money $value_inputted_for_field_on_model_object
188
-     * @return Money
189
-     * @throws InvalidInterfaceException
190
-     * @throws InvalidIdentifierException
191
-     * @throws InvalidDataTypeException
192
-     * @throws EE_Error
193
-     * @throws InvalidArgumentException
194
-     */
195
-    public function prepare_for_set($value_inputted_for_field_on_model_object)
196
-    {
197
-        if ($value_inputted_for_field_on_model_object instanceof Money) {
198
-            return $value_inputted_for_field_on_model_object;
199
-        }
200
-        //now it's a float-style string or number
201
-        return $this->ensureMoney(
202
-            parent::prepare_for_set($value_inputted_for_field_on_model_object)
203
-        );
204
-    }
180
+	/**
181
+	 * If provided with a string, strips out money-related formatting to turn it into a proper float.
182
+	 * Rounds the float to the correct number of decimal places for this country's currency.
183
+	 * Also, interprets periods and commas according to the country's currency settings.
184
+	 * So if you want to pass in a string that NEEDS to interpret periods as decimal marks,
185
+	 * type cast it to a float first.
186
+	 *
187
+	 * @param string|float|int|Money $value_inputted_for_field_on_model_object
188
+	 * @return Money
189
+	 * @throws InvalidInterfaceException
190
+	 * @throws InvalidIdentifierException
191
+	 * @throws InvalidDataTypeException
192
+	 * @throws EE_Error
193
+	 * @throws InvalidArgumentException
194
+	 */
195
+	public function prepare_for_set($value_inputted_for_field_on_model_object)
196
+	{
197
+		if ($value_inputted_for_field_on_model_object instanceof Money) {
198
+			return $value_inputted_for_field_on_model_object;
199
+		}
200
+		//now it's a float-style string or number
201
+		return $this->ensureMoney(
202
+			parent::prepare_for_set($value_inputted_for_field_on_model_object)
203
+		);
204
+	}
205 205
 
206 206
 
207 207
 
208
-    /**
209
-     * @param string|float|int|Money $value_of_field_on_model_object
210
-     * @return float
211
-     * @throws InvalidArgumentException
212
-     * @throws InvalidInterfaceException
213
-     * @throws InvalidDataTypeException
214
-     */
215
-    public function prepare_for_get($value_of_field_on_model_object)
216
-    {
217
-        $value_of_field_on_model_object = $this->ensureNotMoney($value_of_field_on_model_object);
218
-        $c = EE_Registry::instance()->CFG->currency;
219
-        return round(parent::prepare_for_get($value_of_field_on_model_object), $c->dec_plc);
220
-    }
208
+	/**
209
+	 * @param string|float|int|Money $value_of_field_on_model_object
210
+	 * @return float
211
+	 * @throws InvalidArgumentException
212
+	 * @throws InvalidInterfaceException
213
+	 * @throws InvalidDataTypeException
214
+	 */
215
+	public function prepare_for_get($value_of_field_on_model_object)
216
+	{
217
+		$value_of_field_on_model_object = $this->ensureNotMoney($value_of_field_on_model_object);
218
+		$c = EE_Registry::instance()->CFG->currency;
219
+		return round(parent::prepare_for_get($value_of_field_on_model_object), $c->dec_plc);
220
+	}
221 221
 
222 222
 
223
-    /**
224
-     * Takes the incoming float and create a money entity for the model object
225
-     *
226
-     * @param string|float|int $value_found_in_db_for_model_object
227
-     * @return Money
228
-     * @throws InvalidIdentifierException
229
-     * @throws InvalidArgumentException
230
-     * @throws InvalidInterfaceException
231
-     * @throws InvalidDataTypeException
232
-     * @throws EE_Error
233
-     */
234
-    public function prepare_for_set_from_db($value_found_in_db_for_model_object)
235
-    {
236
-        return $this->money_factory->createForSite($value_found_in_db_for_model_object);
237
-    }
223
+	/**
224
+	 * Takes the incoming float and create a money entity for the model object
225
+	 *
226
+	 * @param string|float|int $value_found_in_db_for_model_object
227
+	 * @return Money
228
+	 * @throws InvalidIdentifierException
229
+	 * @throws InvalidArgumentException
230
+	 * @throws InvalidInterfaceException
231
+	 * @throws InvalidDataTypeException
232
+	 * @throws EE_Error
233
+	 */
234
+	public function prepare_for_set_from_db($value_found_in_db_for_model_object)
235
+	{
236
+		return $this->money_factory->createForSite($value_found_in_db_for_model_object);
237
+	}
238 238
 
239 239
 
240 240
 
241
-    /**
242
-     * Prepares a value for use in the DB
243
-     * @param string|float|int|Money $value_of_field_on_model_object
244
-     * @return float
245
-     */
246
-    public function prepare_for_use_in_db($value_of_field_on_model_object)
247
-    {
248
-        $value_of_field_on_model_object = $this->ensureNotMoney($value_of_field_on_model_object);
249
-        return parent::prepare_for_use_in_db($value_of_field_on_model_object);
250
-    }
241
+	/**
242
+	 * Prepares a value for use in the DB
243
+	 * @param string|float|int|Money $value_of_field_on_model_object
244
+	 * @return float
245
+	 */
246
+	public function prepare_for_use_in_db($value_of_field_on_model_object)
247
+	{
248
+		$value_of_field_on_model_object = $this->ensureNotMoney($value_of_field_on_model_object);
249
+		return parent::prepare_for_use_in_db($value_of_field_on_model_object);
250
+	}
251 251
 
252 252
 
253 253
 
254
-    public function getSchemaProperties()
255
-    {
256
-        return array(
257
-            'raw' => array(
258
-                'description' =>  sprintf(
259
-                    __('%s - the raw value as it exists in the database as a simple float.', 'event_espresso'),
260
-                    $this->get_nicename()
261
-                ),
262
-                'type' => 'number'
263
-            ),
264
-            'pretty' => array(
265
-                'description' =>  sprintf(
266
-                    __('%s - formatted for display in the set currency and decimal places.', 'event_espresso'),
267
-                    $this->get_nicename()
268
-                ),
269
-                'type' => 'string'
270
-            )
271
-        );
272
-    }
254
+	public function getSchemaProperties()
255
+	{
256
+		return array(
257
+			'raw' => array(
258
+				'description' =>  sprintf(
259
+					__('%s - the raw value as it exists in the database as a simple float.', 'event_espresso'),
260
+					$this->get_nicename()
261
+				),
262
+				'type' => 'number'
263
+			),
264
+			'pretty' => array(
265
+				'description' =>  sprintf(
266
+					__('%s - formatted for display in the set currency and decimal places.', 'event_espresso'),
267
+					$this->get_nicename()
268
+				),
269
+				'type' => 'string'
270
+			)
271
+		);
272
+	}
273 273
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -48,11 +48,11 @@  discard block
 block discarded – undo
48 48
         MoneyFactory $factory = null,
49 49
         MoneyFormatter $money_formatter = null
50 50
     ) {
51
-        if (! $factory instanceof MoneyFactory) {
51
+        if ( ! $factory instanceof MoneyFactory) {
52 52
             $factory = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\currency\MoneyFactory');
53 53
         }
54 54
         $this->money_factory = $factory;
55
-        if (! $money_formatter instanceof MoneyFormatter) {
55
+        if ( ! $money_formatter instanceof MoneyFormatter) {
56 56
             $money_formatter = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\currency\formatters\MoneyFormatter');
57 57
         }
58 58
         $this->money_formatter = $money_formatter;
@@ -116,18 +116,18 @@  discard block
 block discarded – undo
116 116
             return EEH_Money::format_currency($value_on_field_to_be_outputted, false, $display_code);
117 117
         }
118 118
         //ok let's just use the new formatting code then
119
-        $schema = (string)$schema;
119
+        $schema = (string) $schema;
120 120
         switch ($schema) {
121
-            case (string)CurrencyAmountFormatterInterface::ADD_CURRENCY_CODE:
121
+            case (string) CurrencyAmountFormatterInterface::ADD_CURRENCY_CODE:
122 122
                 $formatting_level = CurrencyAmountFormatterInterface::ADD_CURRENCY_CODE;
123 123
                 break;
124
-            case (string)CurrencyAmountFormatterInterface::ADD_CURRENCY_SIGN:
124
+            case (string) CurrencyAmountFormatterInterface::ADD_CURRENCY_SIGN:
125 125
                 $formatting_level = CurrencyAmountFormatterInterface::ADD_CURRENCY_SIGN;
126 126
                 break;
127
-            case (string)CurrencyAmountFormatterInterface::ADD_THOUSANDS:
127
+            case (string) CurrencyAmountFormatterInterface::ADD_THOUSANDS:
128 128
                 $formatting_level = CurrencyAmountFormatterInterface::ADD_THOUSANDS;
129 129
                 break;
130
-            case (string)CurrencyAmountFormatterInterface::DECIMAL_ONLY:
130
+            case (string) CurrencyAmountFormatterInterface::DECIMAL_ONLY:
131 131
                 $formatting_level = CurrencyAmountFormatterInterface::DECIMAL_ONLY;
132 132
                 break;
133 133
             default:
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
      */
155 155
     private function ensureMoney($value)
156 156
     {
157
-        if (! $value instanceof Money) {
157
+        if ( ! $value instanceof Money) {
158 158
             return $this->money_factory->createForSite($value);
159 159
         }
160 160
         return $value;
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
      */
171 171
     private function ensureNotMoney($value)
172 172
     {
173
-        if( $value instanceof Money) {
173
+        if ($value instanceof Money) {
174 174
             return $value->amount();
175 175
         }
176 176
         return $value;
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 2 patches
Indentation   +2880 added lines, -2880 removed lines patch added patch discarded remove patch
@@ -11,7 +11,7 @@  discard block
 block discarded – undo
11 11
 use EventEspresso\core\services\loaders\LoaderFactory;
12 12
 
13 13
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
14
-    exit('No direct script access allowed');
14
+	exit('No direct script access allowed');
15 15
 }
16 16
 do_action('AHEE_log', __FILE__, ' FILE LOADED', '');
17 17
 
@@ -27,2885 +27,2885 @@  discard block
 block discarded – undo
27 27
 abstract class EE_Base_Class
28 28
 {
29 29
 
30
-    /**
31
-     * This is an array of the original properties and values provided during construction
32
-     * of this model object. (keys are model field names, values are their values).
33
-     * This list is important to remember so that when we are merging data from the db, we know
34
-     * which values to override and which to not override.
35
-     *
36
-     * @var array
37
-     */
38
-    protected $_props_n_values_provided_in_constructor;
39
-
40
-    /**
41
-     * Timezone
42
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
43
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
44
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
45
-     * access to it.
46
-     *
47
-     * @var string
48
-     */
49
-    protected $_timezone;
50
-
51
-
52
-
53
-    /**
54
-     * date format
55
-     * pattern or format for displaying dates
56
-     *
57
-     * @var string $_dt_frmt
58
-     */
59
-    protected $_dt_frmt;
60
-
61
-
62
-
63
-    /**
64
-     * time format
65
-     * pattern or format for displaying time
66
-     *
67
-     * @var string $_tm_frmt
68
-     */
69
-    protected $_tm_frmt;
70
-
71
-
72
-
73
-    /**
74
-     * This property is for holding a cached array of object properties indexed by property name as the key.
75
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
76
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
77
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
78
-     *
79
-     * @var array
80
-     */
81
-    protected $_cached_properties = array();
82
-
83
-    /**
84
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
85
-     * single
86
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
87
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
88
-     * all others have an array)
89
-     *
90
-     * @var array
91
-     */
92
-    protected $_model_relations = array();
93
-
94
-    /**
95
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
96
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
97
-     *
98
-     * @var array
99
-     */
100
-    protected $_fields = array();
101
-
102
-    /**
103
-     * @var boolean indicating whether or not this model object is intended to ever be saved
104
-     * For example, we might create model objects intended to only be used for the duration
105
-     * of this request and to be thrown away, and if they were accidentally saved
106
-     * it would be a bug.
107
-     */
108
-    protected $_allow_persist = true;
109
-
110
-    /**
111
-     * @var boolean indicating whether or not this model object's properties have changed since construction
112
-     */
113
-    protected $_has_changes = false;
114
-
115
-    /**
116
-     * @var EEM_Base
117
-     */
118
-    protected $_model;
119
-
120
-    /**
121
-     * @var MoneyFactory
122
-     */
123
-    protected $money_factory;
124
-
125
-
126
-    /**
127
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
128
-     * play nice
129
-     *
130
-     * @param array $fieldValues where each key is a field (ie, array key in the 2nd
131
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
132
-     *                                                         TXN_amount, QST_name, etc) and values are their values
133
-     * @param boolean $bydb a flag for setting if the class is instantiated by the
134
-     *                                                         corresponding db model or not.
135
-     * @param string $timezone indicate what timezone you want any datetime fields to
136
-     *                                                         be in when instantiating a EE_Base_Class object.
137
-     * @param array $date_formats An array of date formats to set on construct where first
138
-     *                                                         value is the date_format and second value is the time
139
-     *                                                         format.
140
-     * @throws InvalidArgumentException
141
-     * @throws InvalidInterfaceException
142
-     * @throws InvalidDataTypeException
143
-     * @throws EE_Error
144
-     */
145
-    protected function __construct(
146
-        $fieldValues = array(),
147
-        $bydb = false,
148
-        $timezone = '',
149
-        $date_formats = array()
150
-    ) {
151
-        $className = get_class($this);
152
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
153
-        $model = $this->get_model();
154
-        $model_fields = $model->field_settings(false);
155
-        // ensure $fieldValues is an array
156
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
157
-        // EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
158
-        // verify client code has not passed any invalid field names
159
-        foreach ($fieldValues as $field_name => $field_value) {
160
-            if ( ! isset($model_fields[$field_name])) {
161
-                throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
162
-                    "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
163
-            }
164
-        }
165
-        // EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
166
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
167
-        if ( ! empty($date_formats) && is_array($date_formats)) {
168
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
169
-        } else {
170
-            //set default formats for date and time
171
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
172
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
173
-        }
174
-        //if db model is instantiating
175
-        if ($bydb) {
176
-            //client code has indicated these field values are from the database
177
-            foreach ($model_fields as $fieldName => $field) {
178
-                $this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
179
-            }
180
-        } else {
181
-            //we're constructing a brand
182
-            //new instance of the model object. Generally, this means we'll need to do more field validation
183
-            foreach ($model_fields as $fieldName => $field) {
184
-                $this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
185
-            }
186
-        }
187
-        //remember what values were passed to this constructor
188
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
189
-        //remember in entity mapper
190
-        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
191
-            $model->add_to_entity_map($this);
192
-        }
193
-        //setup all the relations
194
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
195
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
196
-                $this->_model_relations[$relation_name] = null;
197
-            } else {
198
-                $this->_model_relations[$relation_name] = array();
199
-            }
200
-        }
201
-        /**
202
-         * Action done at the end of each model object construction
203
-         *
204
-         * @param EE_Base_Class $this the model object just created
205
-         */
206
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
207
-    }
208
-
209
-
210
-
211
-    /**
212
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
213
-     *
214
-     * @return boolean
215
-     */
216
-    public function allow_persist()
217
-    {
218
-        return $this->_allow_persist;
219
-    }
220
-
221
-
222
-
223
-    /**
224
-     * Sets whether or not this model object should be allowed to be saved to the DB.
225
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
226
-     * you got new information that somehow made you change your mind.
227
-     *
228
-     * @param boolean $allow_persist
229
-     * @return boolean
230
-     */
231
-    public function set_allow_persist($allow_persist)
232
-    {
233
-        return $this->_allow_persist = $allow_persist;
234
-    }
235
-
236
-
237
-
238
-    /**
239
-     * Gets the field's original value when this object was constructed during this request.
240
-     * This can be helpful when determining if a model object has changed or not
241
-     *
242
-     * @param string $field_name
243
-     * @return mixed|null
244
-     * @throws EE_Error
245
-     */
246
-    public function get_original($field_name)
247
-    {
248
-        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
249
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
250
-        ) {
251
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
252
-        } else {
253
-            return null;
254
-        }
255
-    }
256
-
257
-
258
-
259
-    /**
260
-     * @param EE_Base_Class $obj
261
-     * @return string
262
-     */
263
-    public function get_class($obj)
264
-    {
265
-        return get_class($obj);
266
-    }
267
-
268
-
269
-    /**
270
-     * Overrides parent because parent expects old models.
271
-     * This also doesn't do any validation, and won't work for serialized arrays
272
-     *
273
-     * @param    string $field_name
274
-     * @param    mixed $field_value
275
-     * @param bool $use_default
276
-     * @throws InvalidArgumentException
277
-     * @throws InvalidInterfaceException
278
-     * @throws InvalidDataTypeException
279
-     * @throws EE_Error
280
-     */
281
-    public function set($field_name, $field_value, $use_default = false)
282
-    {
283
-        // if not using default and nothing has changed, and object has already been setup (has ID),
284
-        // then don't do anything
285
-        if (
286
-            ! $use_default
287
-            && $this->_fields[$field_name] === $field_value
288
-            && $this->ID()
289
-        ) {
290
-            return;
291
-        }
292
-        $model = $this->get_model();
293
-        $this->_has_changes = true;
294
-        $field_obj = $model->field_settings_for($field_name);
295
-        if ($field_obj instanceof EE_Model_Field_Base) {
296
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
297
-            if ($field_obj instanceof EE_Datetime_Field) {
298
-                $field_obj->set_timezone($this->_timezone);
299
-                $field_obj->set_date_format($this->_dt_frmt);
300
-                $field_obj->set_time_format($this->_tm_frmt);
301
-            }
302
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
303
-            //should the value be null?
304
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
305
-                $this->_fields[$field_name] = $field_obj->get_default_value();
306
-                /**
307
-                 * To save having to refactor all the models, if a default value is used for a
308
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
309
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
310
-                 * object.
311
-                 *
312
-                 * @since 4.6.10+
313
-                 */
314
-                if (
315
-                    $field_obj instanceof EE_Datetime_Field
316
-                    && $this->_fields[$field_name] !== null
317
-                    && ! $this->_fields[$field_name] instanceof DateTime
318
-                ) {
319
-                    empty($this->_fields[$field_name])
320
-                        ? $this->set($field_name, time())
321
-                        : $this->set($field_name, $this->_fields[$field_name]);
322
-                }
323
-            } else {
324
-                $this->_fields[$field_name] = $holder_of_value;
325
-            }
326
-            //if we're not in the constructor...
327
-            //now check if what we set was a primary key
328
-            if (
329
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
330
-                $this->_props_n_values_provided_in_constructor
331
-                && $field_value
332
-                && $field_name === $model->primary_key_name()
333
-            ) {
334
-                //if so, we want all this object's fields to be filled either with
335
-                //what we've explicitly set on this model
336
-                //or what we have in the db
337
-                // echo "setting primary key!";
338
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
339
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
340
-                foreach ($fields_on_model as $field_obj) {
341
-                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
342
-                         && $field_obj->get_name() !== $field_name
343
-                    ) {
344
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
345
-                    }
346
-                }
347
-                //oh this model object has an ID? well make sure its in the entity mapper
348
-                $model->add_to_entity_map($this);
349
-            }
350
-            //let's unset any cache for this field_name from the $_cached_properties property.
351
-            $this->_clear_cached_property($field_name);
352
-        } else {
353
-            throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
354
-                "event_espresso"), $field_name));
355
-        }
356
-    }
357
-
358
-
359
-
360
-    /**
361
-     * This sets the field value on the db column if it exists for the given $column_name or
362
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
363
-     *
364
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
365
-     * @param string $field_name  Must be the exact column name.
366
-     * @param mixed  $field_value The value to set.
367
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
368
-     * @throws EE_Error
369
-     */
370
-    public function set_field_or_extra_meta($field_name, $field_value)
371
-    {
372
-        if ($this->get_model()->has_field($field_name)) {
373
-            $this->set($field_name, $field_value);
374
-            return true;
375
-        } else {
376
-            //ensure this object is saved first so that extra meta can be properly related.
377
-            $this->save();
378
-            return $this->update_extra_meta($field_name, $field_value);
379
-        }
380
-    }
381
-
382
-
383
-
384
-    /**
385
-     * This retrieves the value of the db column set on this class or if that's not present
386
-     * it will attempt to retrieve from extra_meta if found.
387
-     * Example Usage:
388
-     * Via EE_Message child class:
389
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
390
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
391
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
392
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
393
-     * value for those extra fields dynamically via the EE_message object.
394
-     *
395
-     * @param  string $field_name expecting the fully qualified field name.
396
-     * @return mixed|null  value for the field if found.  null if not found.
397
-     * @throws EE_Error
398
-     */
399
-    public function get_field_or_extra_meta($field_name)
400
-    {
401
-        if ($this->get_model()->has_field($field_name)) {
402
-            $column_value = $this->get($field_name);
403
-        } else {
404
-            //This isn't a column in the main table, let's see if it is in the extra meta.
405
-            $column_value = $this->get_extra_meta($field_name, true, null);
406
-        }
407
-        return $column_value;
408
-    }
409
-
410
-
411
-    /**
412
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
413
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
414
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
415
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
416
-     *
417
-     * @access public
418
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
419
-     * @return void
420
-     * @throws InvalidArgumentException
421
-     * @throws InvalidInterfaceException
422
-     * @throws InvalidDataTypeException
423
-     * @throws EE_Error
424
-     */
425
-    public function set_timezone($timezone = '')
426
-    {
427
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
428
-        //make sure we clear all cached properties because they won't be relevant now
429
-        $this->_clear_cached_properties();
430
-        //make sure we update field settings and the date for all EE_Datetime_Fields
431
-        $model_fields = $this->get_model()->field_settings(false);
432
-        foreach ($model_fields as $field_name => $field_obj) {
433
-            if ($field_obj instanceof EE_Datetime_Field) {
434
-                $field_obj->set_timezone($this->_timezone);
435
-                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
436
-                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
437
-                }
438
-            }
439
-        }
440
-    }
441
-
442
-
443
-
444
-    /**
445
-     * This just returns whatever is set for the current timezone.
446
-     *
447
-     * @access public
448
-     * @return string timezone string
449
-     */
450
-    public function get_timezone()
451
-    {
452
-        return $this->_timezone;
453
-    }
454
-
455
-
456
-
457
-    /**
458
-     * This sets the internal date format to what is sent in to be used as the new default for the class
459
-     * internally instead of wp set date format options
460
-     *
461
-     * @since 4.6
462
-     * @param string $format should be a format recognizable by PHP date() functions.
463
-     */
464
-    public function set_date_format($format)
465
-    {
466
-        $this->_dt_frmt = $format;
467
-        //clear cached_properties because they won't be relevant now.
468
-        $this->_clear_cached_properties();
469
-    }
470
-
471
-
472
-
473
-    /**
474
-     * This sets the internal time format string to what is sent in to be used as the new default for the
475
-     * class internally instead of wp set time format options.
476
-     *
477
-     * @since 4.6
478
-     * @param string $format should be a format recognizable by PHP date() functions.
479
-     */
480
-    public function set_time_format($format)
481
-    {
482
-        $this->_tm_frmt = $format;
483
-        //clear cached_properties because they won't be relevant now.
484
-        $this->_clear_cached_properties();
485
-    }
486
-
487
-
488
-
489
-    /**
490
-     * This returns the current internal set format for the date and time formats.
491
-     *
492
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
493
-     *                             where the first value is the date format and the second value is the time format.
494
-     * @return mixed string|array
495
-     */
496
-    public function get_format($full = true)
497
-    {
498
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
499
-    }
500
-
501
-
502
-
503
-    /**
504
-     * cache
505
-     * stores the passed model object on the current model object.
506
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
507
-     *
508
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
509
-     *                                       'Registration' associated with this model object
510
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
511
-     *                                       that could be a payment or a registration)
512
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
513
-     *                                       items which will be stored in an array on this object
514
-     * @throws EE_Error
515
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
516
-     *                  related thing, no array)
517
-     */
518
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
519
-    {
520
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
521
-        if ( ! $object_to_cache instanceof EE_Base_Class) {
522
-            return false;
523
-        }
524
-        // also get "how" the object is related, or throw an error
525
-        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
526
-            throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
527
-                $relationName, get_class($this)));
528
-        }
529
-        // how many things are related ?
530
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
531
-            // if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
532
-            // so for these model objects just set it to be cached
533
-            $this->_model_relations[$relationName] = $object_to_cache;
534
-            $return = true;
535
-        } else {
536
-            // otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
537
-            // eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
538
-            if ( ! is_array($this->_model_relations[$relationName])) {
539
-                // if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
540
-                $this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
541
-                    ? array($this->_model_relations[$relationName]) : array();
542
-            }
543
-            // first check for a cache_id which is normally empty
544
-            if ( ! empty($cache_id)) {
545
-                // if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
546
-                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
547
-                $return = $cache_id;
548
-            } elseif ($object_to_cache->ID()) {
549
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
550
-                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
551
-                $return = $object_to_cache->ID();
552
-            } else {
553
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
554
-                $this->_model_relations[$relationName][] = $object_to_cache;
555
-                // move the internal pointer to the end of the array
556
-                end($this->_model_relations[$relationName]);
557
-                // and grab the key so that we can return it
558
-                $return = key($this->_model_relations[$relationName]);
559
-            }
560
-        }
561
-        return $return;
562
-    }
563
-
564
-
565
-
566
-    /**
567
-     * For adding an item to the cached_properties property.
568
-     *
569
-     * @access protected
570
-     * @param string      $fieldname the property item the corresponding value is for.
571
-     * @param mixed       $value     The value we are caching.
572
-     * @param string|null $cache_type
573
-     * @return void
574
-     * @throws EE_Error
575
-     */
576
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
577
-    {
578
-        //first make sure this property exists
579
-        $this->get_model()->field_settings_for($fieldname);
580
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
581
-        $this->_cached_properties[$fieldname][$cache_type] = $value;
582
-    }
583
-
584
-
585
-
586
-    /**
587
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
588
-     * This also SETS the cache if we return the actual property!
589
-     *
590
-     * @param string $fieldname        the name of the property we're trying to retrieve
591
-     * @param bool   $pretty
592
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
593
-     *                                 (in cases where the same property may be used for different outputs
594
-     *                                 - i.e. datetime, money etc.)
595
-     *                                 It can also accept certain pre-defined "schema" strings
596
-     *                                 to define how to output the property.
597
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
598
-     * @return mixed                   whatever the value for the property is we're retrieving
599
-     * @throws EE_Error
600
-     */
601
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
602
-    {
603
-        //verify the field exists
604
-        $model = $this->get_model();
605
-        $model->field_settings_for($fieldname);
606
-        $cache_type = $pretty ? 'pretty' : 'standard';
607
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
608
-        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
609
-            return $this->_cached_properties[$fieldname][$cache_type];
610
-        }
611
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
612
-        $this->_set_cached_property($fieldname, $value, $cache_type);
613
-        return $value;
614
-    }
615
-
616
-
617
-    /**
618
-     * If the cache didn't fetch the needed item, this fetches it.
619
-     * @param string $fieldname
620
-     * @param bool $pretty
621
-     * @param string $extra_cache_ref
622
-     * @return mixed
623
-     * @throws EE_Error
624
-     */
625
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
626
-    {
627
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
628
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
629
-        if ($field_obj instanceof EE_Datetime_Field) {
630
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
631
-        }
632
-        if ( ! isset($this->_fields[$fieldname])) {
633
-            $this->_fields[$fieldname] = null;
634
-        }
635
-        $value = $pretty
636
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
637
-            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
638
-        return $value;
639
-    }
640
-
641
-
642
-    /**
643
-     * set timezone, formats, and output for EE_Datetime_Field objects
644
-     *
645
-     * @param \EE_Datetime_Field $datetime_field
646
-     * @param bool $pretty
647
-     * @param null $date_or_time
648
-     * @return void
649
-     * @throws InvalidArgumentException
650
-     * @throws InvalidInterfaceException
651
-     * @throws InvalidDataTypeException
652
-     * @throws EE_Error
653
-     */
654
-    protected function _prepare_datetime_field(
655
-        EE_Datetime_Field $datetime_field,
656
-        $pretty = false,
657
-        $date_or_time = null
658
-    ) {
659
-        $datetime_field->set_timezone($this->_timezone);
660
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
661
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
662
-        //set the output returned
663
-        switch ($date_or_time) {
664
-            case 'D' :
665
-                $datetime_field->set_date_time_output('date');
666
-                break;
667
-            case 'T' :
668
-                $datetime_field->set_date_time_output('time');
669
-                break;
670
-            default :
671
-                $datetime_field->set_date_time_output();
672
-        }
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     * This just takes care of clearing out the cached_properties
679
-     *
680
-     * @return void
681
-     */
682
-    protected function _clear_cached_properties()
683
-    {
684
-        $this->_cached_properties = array();
685
-    }
686
-
687
-
688
-
689
-    /**
690
-     * This just clears out ONE property if it exists in the cache
691
-     *
692
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
693
-     * @return void
694
-     */
695
-    protected function _clear_cached_property($property_name)
696
-    {
697
-        if (isset($this->_cached_properties[$property_name])) {
698
-            unset($this->_cached_properties[$property_name]);
699
-        }
700
-    }
701
-
702
-
703
-
704
-    /**
705
-     * Ensures that this related thing is a model object.
706
-     *
707
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
708
-     * @param string $model_name   name of the related thing, eg 'Attendee',
709
-     * @return EE_Base_Class
710
-     * @throws EE_Error
711
-     */
712
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
713
-    {
714
-        $other_model_instance = self::_get_model_instance_with_name(
715
-            self::_get_model_classname($model_name),
716
-            $this->_timezone
717
-        );
718
-        return $other_model_instance->ensure_is_obj($object_or_id);
719
-    }
720
-
721
-
722
-
723
-    /**
724
-     * Forgets the cached model of the given relation Name. So the next time we request it,
725
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
726
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
727
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
728
-     *
729
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
730
-     *                                                     Eg 'Registration'
731
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
732
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
733
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
734
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
735
-     *                                                     this is HasMany or HABTM.
736
-     * @throws EE_Error
737
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
738
-     *                       relation from all
739
-     */
740
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
741
-    {
742
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
743
-        $index_in_cache = '';
744
-        if ( ! $relationship_to_model) {
745
-            throw new EE_Error(
746
-                sprintf(
747
-                    __("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
748
-                    $relationName,
749
-                    get_class($this)
750
-                )
751
-            );
752
-        }
753
-        if ($clear_all) {
754
-            $obj_removed = true;
755
-            $this->_model_relations[$relationName] = null;
756
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
757
-            $obj_removed = $this->_model_relations[$relationName];
758
-            $this->_model_relations[$relationName] = null;
759
-        } else {
760
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
761
-                && $object_to_remove_or_index_into_array->ID()
762
-            ) {
763
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
764
-                if (is_array($this->_model_relations[$relationName])
765
-                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
766
-                ) {
767
-                    $index_found_at = null;
768
-                    //find this object in the array even though it has a different key
769
-                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
770
-                        if (
771
-                            $obj instanceof EE_Base_Class
772
-                            && (
773
-                                $obj == $object_to_remove_or_index_into_array
774
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
775
-                            )
776
-                        ) {
777
-                            $index_found_at = $index;
778
-                            break;
779
-                        }
780
-                    }
781
-                    if ($index_found_at) {
782
-                        $index_in_cache = $index_found_at;
783
-                    } else {
784
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
785
-                        //if it wasn't in it to begin with. So we're done
786
-                        return $object_to_remove_or_index_into_array;
787
-                    }
788
-                }
789
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
790
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
791
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
792
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
793
-                        $index_in_cache = $index;
794
-                    }
795
-                }
796
-            } else {
797
-                $index_in_cache = $object_to_remove_or_index_into_array;
798
-            }
799
-            //supposedly we've found it. But it could just be that the client code
800
-            //provided a bad index/object
801
-            if (
802
-            isset(
803
-                $this->_model_relations[$relationName],
804
-                $this->_model_relations[$relationName][$index_in_cache]
805
-            )
806
-            ) {
807
-                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
808
-                unset($this->_model_relations[$relationName][$index_in_cache]);
809
-            } else {
810
-                //that thing was never cached anyways.
811
-                $obj_removed = null;
812
-            }
813
-        }
814
-        return $obj_removed;
815
-    }
816
-
817
-
818
-
819
-    /**
820
-     * update_cache_after_object_save
821
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
822
-     * obtained after being saved to the db
823
-     *
824
-     * @param string         $relationName       - the type of object that is cached
825
-     * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
826
-     * @param string         $current_cache_id   - the ID that was used when originally caching the object
827
-     * @return boolean TRUE on success, FALSE on fail
828
-     * @throws EE_Error
829
-     */
830
-    public function update_cache_after_object_save(
831
-        $relationName,
832
-        EE_Base_Class $newly_saved_object,
833
-        $current_cache_id = ''
834
-    ) {
835
-        // verify that incoming object is of the correct type
836
-        $obj_class = 'EE_' . $relationName;
837
-        if ($newly_saved_object instanceof $obj_class) {
838
-            /* @type EE_Base_Class $newly_saved_object */
839
-            // now get the type of relation
840
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
841
-            // if this is a 1:1 relationship
842
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
843
-                // then just replace the cached object with the newly saved object
844
-                $this->_model_relations[$relationName] = $newly_saved_object;
845
-                return true;
846
-                // or if it's some kind of sordid feral polyamorous relationship...
847
-            } elseif (is_array($this->_model_relations[$relationName])
848
-                      && isset($this->_model_relations[$relationName][$current_cache_id])
849
-            ) {
850
-                // then remove the current cached item
851
-                unset($this->_model_relations[$relationName][$current_cache_id]);
852
-                // and cache the newly saved object using it's new ID
853
-                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
854
-                return true;
855
-            }
856
-        }
857
-        return false;
858
-    }
859
-
860
-
861
-
862
-    /**
863
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
864
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
865
-     *
866
-     * @param string $relationName
867
-     * @return EE_Base_Class
868
-     */
869
-    public function get_one_from_cache($relationName)
870
-    {
871
-        $cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
872
-            : null;
873
-        if (is_array($cached_array_or_object)) {
874
-            return array_shift($cached_array_or_object);
875
-        } else {
876
-            return $cached_array_or_object;
877
-        }
878
-    }
879
-
880
-
881
-    /**
882
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
883
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
884
-     *
885
-     * @param string $relationName
886
-     * @throws \ReflectionException
887
-     * @throws InvalidArgumentException
888
-     * @throws InvalidInterfaceException
889
-     * @throws InvalidDataTypeException
890
-     * @throws EE_Error
891
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
892
-     */
893
-    public function get_all_from_cache($relationName)
894
-    {
895
-        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
896
-        // if the result is not an array, but exists, make it an array
897
-        $objects = is_array($objects) ? $objects : array($objects);
898
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
899
-        //basically, if this model object was stored in the session, and these cached model objects
900
-        //already have IDs, let's make sure they're in their model's entity mapper
901
-        //otherwise we will have duplicates next time we call
902
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
903
-        $model = EE_Registry::instance()->load_model($relationName);
904
-        foreach ($objects as $model_object) {
905
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
906
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
907
-                if ($model_object->ID()) {
908
-                    $model->add_to_entity_map($model_object);
909
-                }
910
-            } else {
911
-                throw new EE_Error(
912
-                    sprintf(
913
-                        __(
914
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
915
-                            'event_espresso'
916
-                        ),
917
-                        $relationName,
918
-                        gettype($model_object)
919
-                    )
920
-                );
921
-            }
922
-        }
923
-        return $objects;
924
-    }
925
-
926
-
927
-
928
-    /**
929
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
930
-     * matching the given query conditions.
931
-     *
932
-     * @param null  $field_to_order_by  What field is being used as the reference point.
933
-     * @param int   $limit              How many objects to return.
934
-     * @param array $query_params       Any additional conditions on the query.
935
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
936
-     *                                  you can indicate just the columns you want returned
937
-     * @return array|EE_Base_Class[]
938
-     * @throws EE_Error
939
-     */
940
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
941
-    {
942
-        $model = $this->get_model();
943
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
944
-            ? $model->get_primary_key_field()->get_name()
945
-            : $field_to_order_by;
946
-        $current_value = ! empty($field) ? $this->get($field) : null;
947
-        if (empty($field) || empty($current_value)) {
948
-            return array();
949
-        }
950
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
951
-    }
952
-
953
-
954
-
955
-    /**
956
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
957
-     * matching the given query conditions.
958
-     *
959
-     * @param null  $field_to_order_by  What field is being used as the reference point.
960
-     * @param int   $limit              How many objects to return.
961
-     * @param array $query_params       Any additional conditions on the query.
962
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
963
-     *                                  you can indicate just the columns you want returned
964
-     * @return array|EE_Base_Class[]
965
-     * @throws EE_Error
966
-     */
967
-    public function previous_x(
968
-        $field_to_order_by = null,
969
-        $limit = 1,
970
-        $query_params = array(),
971
-        $columns_to_select = null
972
-    ) {
973
-        $model = $this->get_model();
974
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
975
-            ? $model->get_primary_key_field()->get_name()
976
-            : $field_to_order_by;
977
-        $current_value = ! empty($field) ? $this->get($field) : null;
978
-        if (empty($field) || empty($current_value)) {
979
-            return array();
980
-        }
981
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
982
-    }
983
-
984
-
985
-
986
-    /**
987
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
988
-     * matching the given query conditions.
989
-     *
990
-     * @param null  $field_to_order_by  What field is being used as the reference point.
991
-     * @param array $query_params       Any additional conditions on the query.
992
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
993
-     *                                  you can indicate just the columns you want returned
994
-     * @return array|EE_Base_Class
995
-     * @throws EE_Error
996
-     */
997
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
998
-    {
999
-        $model = $this->get_model();
1000
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1001
-            ? $model->get_primary_key_field()->get_name()
1002
-            : $field_to_order_by;
1003
-        $current_value = ! empty($field) ? $this->get($field) : null;
1004
-        if (empty($field) || empty($current_value)) {
1005
-            return array();
1006
-        }
1007
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1008
-    }
1009
-
1010
-
1011
-
1012
-    /**
1013
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1014
-     * matching the given query conditions.
1015
-     *
1016
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1017
-     * @param array $query_params       Any additional conditions on the query.
1018
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1019
-     *                                  you can indicate just the column you want returned
1020
-     * @return array|EE_Base_Class
1021
-     * @throws EE_Error
1022
-     */
1023
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1024
-    {
1025
-        $model = $this->get_model();
1026
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1027
-            ? $model->get_primary_key_field()->get_name()
1028
-            : $field_to_order_by;
1029
-        $current_value = ! empty($field) ? $this->get($field) : null;
1030
-        if (empty($field) || empty($current_value)) {
1031
-            return array();
1032
-        }
1033
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1034
-    }
1035
-
1036
-
1037
-
1038
-    /**
1039
-     * Overrides parent because parent expects old models.
1040
-     * This also doesn't do any validation, and won't work for serialized arrays
1041
-     *
1042
-     * @param string $field_name
1043
-     * @param mixed  $field_value_from_db
1044
-     * @throws EE_Error
1045
-     */
1046
-    public function set_from_db($field_name, $field_value_from_db)
1047
-    {
1048
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1049
-        if ($field_obj instanceof EE_Model_Field_Base) {
1050
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
1051
-            //eg, a CPT model object could have an entry in the posts table, but no
1052
-            //entry in the meta table. Meaning that all its columns in the meta table
1053
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
1054
-            if ($field_value_from_db === null) {
1055
-                if ($field_obj->is_nullable()) {
1056
-                    //if the field allows nulls, then let it be null
1057
-                    $field_value = null;
1058
-                } else {
1059
-                    $field_value = $field_obj->get_default_value();
1060
-                }
1061
-            } else {
1062
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1063
-            }
1064
-            $this->_fields[$field_name] = $field_value;
1065
-            $this->_clear_cached_property($field_name);
1066
-        }
1067
-    }
1068
-
1069
-
1070
-
1071
-    /**
1072
-     * verifies that the specified field is of the correct type
1073
-     *
1074
-     * @param string $field_name
1075
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1076
-     *                                (in cases where the same property may be used for different outputs
1077
-     *                                - i.e. datetime, money etc.)
1078
-     * @return mixed
1079
-     * @throws EE_Error
1080
-     */
1081
-    public function get($field_name, $extra_cache_ref = null)
1082
-    {
1083
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1084
-    }
1085
-
1086
-
1087
-
1088
-    /**
1089
-     * This method simply returns the RAW unprocessed value for the given property in this class
1090
-     *
1091
-     * @param  string $field_name A valid fieldname
1092
-     * @return mixed              Whatever the raw value stored on the property is.
1093
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1094
-     */
1095
-    public function get_raw($field_name)
1096
-    {
1097
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1098
-        switch(true){
1099
-            case $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime:
1100
-                $value = $this->_fields[$field_name]->format('U');
1101
-                break;
1102
-            case $field_settings instanceof EE_Money_Field && $this->_fields[$field_name] instanceof Money:
1103
-                $value = $this->_fields[$field_name]->floatAmount();
1104
-                break;
1105
-            default:
1106
-                $value = $this->_fields[$field_name];
1107
-        }
1108
-        return $value;
1109
-    }
1110
-
1111
-
1112
-
1113
-    /**
1114
-     * This is used to return the internal DateTime object used for a field that is a
1115
-     * EE_Datetime_Field.
1116
-     *
1117
-     * @param string $field_name               The field name retrieving the DateTime object.
1118
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1119
-     * @throws EE_Error
1120
-     *                                         an error is set and false returned.  If the field IS an
1121
-     *                                         EE_Datetime_Field and but the field value is null, then
1122
-     *                                         just null is returned (because that indicates that likely
1123
-     *                                         this field is nullable).
1124
-     */
1125
-    public function get_DateTime_object($field_name)
1126
-    {
1127
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1128
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1129
-            EE_Error::add_error(
1130
-                sprintf(
1131
-                    __(
1132
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1133
-                        'event_espresso'
1134
-                    ),
1135
-                    $field_name
1136
-                ),
1137
-                __FILE__,
1138
-                __FUNCTION__,
1139
-                __LINE__
1140
-            );
1141
-            return false;
1142
-        }
1143
-        return $this->_fields[$field_name];
1144
-    }
1145
-
1146
-
1147
-    /**
1148
-     * Gets a Money object for the specified field. Please note that this should only be
1149
-     * used for fields corresponding to EE_Money_Fields, and it will always return a money object,
1150
-     * or else it will throw an exception.
1151
-     *
1152
-     * @param $field_name
1153
-     * @return Money
1154
-     * @throws InvalidEntityException
1155
-     * @throws EE_Error
1156
-     * @throws DomainException
1157
-     */
1158
-    public function getMoneyObject($field_name)
1159
-    {
1160
-        $this->verifyUsesMoney(__FUNCTION__);
1161
-        $field = $this->get_model()->field_settings_for($field_name);
1162
-        $value = isset($this->_fields[$field_name]) ? $this->_fields[$field_name] : null;
1163
-        if (! $field instanceof EE_Money_Field
1164
-            || ! $value instanceof Money) {
1165
-            throw new InvalidEntityException(
1166
-                get_class($value),
1167
-                'Money',
1168
-                sprintf(
1169
-                    esc_html__(
1170
-                        // @codingStandardsIgnoreStart
1171
-                        'Tried to retrieve money value from %1$s with ID %2$s from field %3$s but no money object present.',
1172
-                        // @codingStandardsIgnoreEnd
1173
-                        'event_espresso'
1174
-                    ),
1175
-                    get_class($this),
1176
-                    $this->ID(),
1177
-                    $field_name
1178
-                )
1179
-            );
1180
-        }
1181
-        return $value;
1182
-    }
1183
-
1184
-
1185
-
1186
-    /**
1187
-     * To be used in template to immediately echo out the value, and format it for output.
1188
-     * Eg, should call stripslashes and whatnot before echoing
1189
-     *
1190
-     * @param string $field_name      the name of the field as it appears in the DB
1191
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1192
-     *                                (in cases where the same property may be used for different outputs
1193
-     *                                - i.e. datetime, money etc.)
1194
-     * @return void
1195
-     * @throws EE_Error
1196
-     */
1197
-    public function e($field_name, $extra_cache_ref = null)
1198
-    {
1199
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1206
-     * can be easily used as the value of form input.
1207
-     *
1208
-     * @param string $field_name
1209
-     * @return void
1210
-     * @throws EE_Error
1211
-     */
1212
-    public function f($field_name)
1213
-    {
1214
-        $this->e($field_name, 'form_input');
1215
-    }
1216
-
1217
-    /**
1218
-     * Same as `f()` but just returns the value instead of echoing it
1219
-     * @param string $field_name
1220
-     * @return string
1221
-     * @throws EE_Error
1222
-     */
1223
-    public function get_f($field_name)
1224
-    {
1225
-        return (string)$this->get_pretty($field_name,'form_input');
1226
-    }
1227
-
1228
-
1229
-
1230
-    /**
1231
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1232
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1233
-     * to see what options are available.
1234
-     * @param string $field_name
1235
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1236
-     *                                (in cases where the same property may be used for different outputs
1237
-     *                                - i.e. datetime, money etc.)
1238
-     * @return mixed
1239
-     * @throws EE_Error
1240
-     */
1241
-    public function get_pretty($field_name, $extra_cache_ref = null)
1242
-    {
1243
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1244
-    }
1245
-
1246
-
1247
-
1248
-    /**
1249
-     * This simply returns the datetime for the given field name
1250
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1251
-     * (and the equivalent e_date, e_time, e_datetime).
1252
-     *
1253
-     * @access   protected
1254
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1255
-     * @param string   $dt_frmt      valid datetime format used for date
1256
-     *                               (if '' then we just use the default on the field,
1257
-     *                               if NULL we use the last-used format)
1258
-     * @param string   $tm_frmt      Same as above except this is for time format
1259
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1260
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1261
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1262
-     *                               if field is not a valid dtt field, or void if echoing
1263
-     * @throws EE_Error
1264
-     */
1265
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1266
-    {
1267
-        // clear cached property
1268
-        $this->_clear_cached_property($field_name);
1269
-        //reset format properties because they are used in get()
1270
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1271
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1272
-        if ($echo) {
1273
-            $this->e($field_name, $date_or_time);
1274
-            return '';
1275
-        }
1276
-        return $this->get($field_name, $date_or_time);
1277
-    }
1278
-
1279
-
1280
-
1281
-    /**
1282
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1283
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1284
-     * other echoes the pretty value for dtt)
1285
-     *
1286
-     * @param  string $field_name name of model object datetime field holding the value
1287
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1288
-     * @return string            datetime value formatted
1289
-     * @throws EE_Error
1290
-     */
1291
-    public function get_date($field_name, $format = '')
1292
-    {
1293
-        return $this->_get_datetime($field_name, $format, null, 'D');
1294
-    }
1295
-
1296
-
1297
-
1298
-    /**
1299
-     * @param      $field_name
1300
-     * @param string $format
1301
-     * @throws EE_Error
1302
-     */
1303
-    public function e_date($field_name, $format = '')
1304
-    {
1305
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1306
-    }
1307
-
1308
-
1309
-
1310
-    /**
1311
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1312
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1313
-     * other echoes the pretty value for dtt)
1314
-     *
1315
-     * @param  string $field_name name of model object datetime field holding the value
1316
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1317
-     * @return string             datetime value formatted
1318
-     * @throws EE_Error
1319
-     */
1320
-    public function get_time($field_name, $format = '')
1321
-    {
1322
-        return $this->_get_datetime($field_name, null, $format, 'T');
1323
-    }
1324
-
1325
-
1326
-
1327
-    /**
1328
-     * @param      $field_name
1329
-     * @param string $format
1330
-     * @throws EE_Error
1331
-     */
1332
-    public function e_time($field_name, $format = '')
1333
-    {
1334
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1335
-    }
1336
-
1337
-
1338
-
1339
-    /**
1340
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1341
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1342
-     * other echoes the pretty value for dtt)
1343
-     *
1344
-     * @param  string $field_name name of model object datetime field holding the value
1345
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1346
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1347
-     * @return string             datetime value formatted
1348
-     * @throws EE_Error
1349
-     */
1350
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1351
-    {
1352
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1353
-    }
1354
-
1355
-
1356
-
1357
-    /**
1358
-     * @param string $field_name
1359
-     * @param string $dt_frmt
1360
-     * @param string $tm_frmt
1361
-     * @throws EE_Error
1362
-     */
1363
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1364
-    {
1365
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1366
-    }
1367
-
1368
-
1369
-    /**
1370
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1371
-     *
1372
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1373
-     * @param string $format PHP valid date/time string format.  If none is provided then the internal set format
1374
-     *                           on the object will be used.
1375
-     * @return string Date and time string in set locale or false if no field exists for the given
1376
-     * @throws InvalidArgumentException
1377
-     * @throws InvalidInterfaceException
1378
-     * @throws InvalidDataTypeException
1379
-     * @throws EE_Error
1380
-     *                           field name.
1381
-     */
1382
-    public function get_i18n_datetime($field_name, $format = '')
1383
-    {
1384
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1385
-        return date_i18n(
1386
-            $format,
1387
-            EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1388
-        );
1389
-    }
1390
-
1391
-
1392
-
1393
-    /**
1394
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1395
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1396
-     * thrown.
1397
-     *
1398
-     * @param  string $field_name The field name being checked
1399
-     * @throws EE_Error
1400
-     * @return EE_Datetime_Field
1401
-     */
1402
-    protected function _get_dtt_field_settings($field_name)
1403
-    {
1404
-        $field = $this->get_model()->field_settings_for($field_name);
1405
-        //check if field is dtt
1406
-        if ($field instanceof EE_Datetime_Field) {
1407
-            return $field;
1408
-        } else {
1409
-            throw new EE_Error(sprintf(__('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',
1410
-                'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1411
-        }
1412
-    }
1413
-
1414
-
1415
-
1416
-
1417
-    /**
1418
-     * NOTE ABOUT BELOW:
1419
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1420
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1421
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1422
-     * method and make sure you send the entire datetime value for setting.
1423
-     */
1424
-    /**
1425
-     * sets the time on a datetime property
1426
-     *
1427
-     * @access protected
1428
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1429
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1430
-     * @throws EE_Error
1431
-     */
1432
-    protected function _set_time_for($time, $fieldname)
1433
-    {
1434
-        $this->_set_date_time('T', $time, $fieldname);
1435
-    }
1436
-
1437
-
1438
-
1439
-    /**
1440
-     * sets the date on a datetime property
1441
-     *
1442
-     * @access protected
1443
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1444
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1445
-     * @throws EE_Error
1446
-     */
1447
-    protected function _set_date_for($date, $fieldname)
1448
-    {
1449
-        $this->_set_date_time('D', $date, $fieldname);
1450
-    }
1451
-
1452
-
1453
-    /**
1454
-     * This takes care of setting a date or time independently on a given model object property. This method also
1455
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1456
-     *
1457
-     * @access protected
1458
-     * @param string $what "T" for time, 'B' for both, 'D' for Date.
1459
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1460
-     * @param string $fieldname the name of the field the date OR time is being set on (must match a
1461
-     *                                        EE_Datetime_Field property)
1462
-     * @throws InvalidArgumentException
1463
-     * @throws InvalidInterfaceException
1464
-     * @throws InvalidDataTypeException
1465
-     * @throws EE_Error
1466
-     */
1467
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1468
-    {
1469
-        $field = $this->_get_dtt_field_settings($fieldname);
1470
-        $field->set_timezone($this->_timezone);
1471
-        $field->set_date_format($this->_dt_frmt);
1472
-        $field->set_time_format($this->_tm_frmt);
1473
-        switch ($what) {
1474
-            case 'T' :
1475
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1476
-                    $datetime_value,
1477
-                    $this->_fields[$fieldname]
1478
-                );
1479
-                break;
1480
-            case 'D' :
1481
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1482
-                    $datetime_value,
1483
-                    $this->_fields[$fieldname]
1484
-                );
1485
-                break;
1486
-            case 'B' :
1487
-                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1488
-                break;
1489
-        }
1490
-        $this->_clear_cached_property($fieldname);
1491
-    }
1492
-
1493
-
1494
-    /**
1495
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1496
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1497
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1498
-     * that could lead to some unexpected results!
1499
-     *
1500
-     * @access public
1501
-     * @param string $field_name This is the name of the field on the object that contains the date/time
1502
-     *                                         value being returned.
1503
-     * @param string $callback must match a valid method in this class (defaults to get_datetime)
1504
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1505
-     * @param string $prepend You can include something to prepend on the timestamp
1506
-     * @param string $append You can include something to append on the timestamp
1507
-     * @throws InvalidArgumentException
1508
-     * @throws InvalidInterfaceException
1509
-     * @throws InvalidDataTypeException
1510
-     * @throws EE_Error
1511
-     * @return string timestamp
1512
-     */
1513
-    public function display_in_my_timezone(
1514
-        $field_name,
1515
-        $callback = 'get_datetime',
1516
-        $args = null,
1517
-        $prepend = '',
1518
-        $append = ''
1519
-    ) {
1520
-        $timezone = EEH_DTT_Helper::get_timezone();
1521
-        if ($timezone === $this->_timezone) {
1522
-            return '';
1523
-        }
1524
-        $original_timezone = $this->_timezone;
1525
-        $this->set_timezone($timezone);
1526
-        $fn = (array)$field_name;
1527
-        $args = array_merge($fn, (array)$args);
1528
-        if ( ! method_exists($this, $callback)) {
1529
-            throw new EE_Error(
1530
-                sprintf(
1531
-                    __(
1532
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1533
-                        'event_espresso'
1534
-                    ),
1535
-                    $callback
1536
-                )
1537
-            );
1538
-        }
1539
-        $args = (array)$args;
1540
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1541
-        $this->set_timezone($original_timezone);
1542
-        return $return;
1543
-    }
1544
-
1545
-
1546
-
1547
-    /**
1548
-     * Deletes this model object.
1549
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1550
-     * override
1551
-     * `EE_Base_Class::_delete` NOT this class.
1552
-     *
1553
-     * @return boolean | int
1554
-     * @throws EE_Error
1555
-     */
1556
-    public function delete()
1557
-    {
1558
-        /**
1559
-         * Called just before the `EE_Base_Class::_delete` method call.
1560
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1561
-         * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1562
-         * soft deletes (trash) the object and does not permanently delete it.
1563
-         *
1564
-         * @param EE_Base_Class $model_object about to be 'deleted'
1565
-         */
1566
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1567
-        $result = $this->_delete();
1568
-        /**
1569
-         * Called just after the `EE_Base_Class::_delete` method call.
1570
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1571
-         * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1572
-         * soft deletes (trash) the object and does not permanently delete it.
1573
-         *
1574
-         * @param EE_Base_Class $model_object that was just 'deleted'
1575
-         * @param boolean       $result
1576
-         */
1577
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1578
-        return $result;
1579
-    }
1580
-
1581
-
1582
-
1583
-    /**
1584
-     * Calls the specific delete method for the instantiated class.
1585
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1586
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1587
-     * `EE_Base_Class::delete`
1588
-     *
1589
-     * @return bool|int
1590
-     * @throws EE_Error
1591
-     */
1592
-    protected function _delete()
1593
-    {
1594
-        return $this->delete_permanently();
1595
-    }
1596
-
1597
-
1598
-
1599
-    /**
1600
-     * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1601
-     * error)
1602
-     *
1603
-     * @return bool | int
1604
-     * @throws EE_Error
1605
-     */
1606
-    public function delete_permanently()
1607
-    {
1608
-        /**
1609
-         * Called just before HARD deleting a model object
1610
-         *
1611
-         * @param EE_Base_Class $model_object about to be 'deleted'
1612
-         */
1613
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1614
-        $model = $this->get_model();
1615
-        $result = $model->delete_permanently_by_ID($this->ID());
1616
-        $this->refresh_cache_of_related_objects();
1617
-        /**
1618
-         * Called just after HARD deleting a model object
1619
-         *
1620
-         * @param EE_Base_Class $model_object that was just 'deleted'
1621
-         * @param boolean       $result
1622
-         */
1623
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1624
-        return $result;
1625
-    }
1626
-
1627
-
1628
-
1629
-    /**
1630
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1631
-     * related model objects
1632
-     *
1633
-     * @throws EE_Error
1634
-     */
1635
-    public function refresh_cache_of_related_objects()
1636
-    {
1637
-        $model = $this->get_model();
1638
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1639
-            if ( ! empty($this->_model_relations[$relation_name])) {
1640
-                $related_objects = $this->_model_relations[$relation_name];
1641
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1642
-                    //this relation only stores a single model object, not an array
1643
-                    //but let's make it consistent
1644
-                    $related_objects = array($related_objects);
1645
-                }
1646
-                foreach ($related_objects as $related_object) {
1647
-                    //only refresh their cache if they're in memory
1648
-                    if ($related_object instanceof EE_Base_Class) {
1649
-                        $related_object->clear_cache($model->get_this_model_name(), $this);
1650
-                    }
1651
-                }
1652
-            }
1653
-        }
1654
-    }
1655
-
1656
-
1657
-
1658
-    /**
1659
-     *        Saves this object to the database. An array may be supplied to set some values on this
1660
-     * object just before saving.
1661
-     *
1662
-     * @access public
1663
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1664
-     *                                 if provided during the save() method (often client code will change the fields'
1665
-     *                                 values before calling save)
1666
-     * @throws EE_Error
1667
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1668
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1669
-     */
1670
-    public function save($set_cols_n_values = array())
1671
-    {
1672
-        $model = $this->get_model();
1673
-        /**
1674
-         * Filters the fields we're about to save on the model object
1675
-         *
1676
-         * @param array         $set_cols_n_values
1677
-         * @param EE_Base_Class $model_object
1678
-         */
1679
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1680
-            $this);
1681
-        //set attributes as provided in $set_cols_n_values
1682
-        foreach ($set_cols_n_values as $column => $value) {
1683
-            $this->set($column, $value);
1684
-        }
1685
-        // no changes ? then don't do anything
1686
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1687
-            return 0;
1688
-        }
1689
-        /**
1690
-         * Saving a model object.
1691
-         * Before we perform a save, this action is fired.
1692
-         *
1693
-         * @param EE_Base_Class $model_object the model object about to be saved.
1694
-         */
1695
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1696
-        if ( ! $this->allow_persist()) {
1697
-            return 0;
1698
-        }
1699
-        //now get current attribute values
1700
-        $save_cols_n_values = $this->_fields;
1701
-        //if the object already has an ID, update it. Otherwise, insert it
1702
-        //also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1703
-        $old_assumption_concerning_value_preparation = $model
1704
-                                                            ->get_assumption_concerning_values_already_prepared_by_model_object();
1705
-        $model->assume_values_already_prepared_by_model_object(true);
1706
-        //does this model have an autoincrement PK?
1707
-        if ($model->has_primary_key_field()) {
1708
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1709
-                //ok check if it's set, if so: update; if not, insert
1710
-                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1711
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1712
-                } else {
1713
-                    unset($save_cols_n_values[$model->primary_key_name()]);
1714
-                    $results = $model->insert($save_cols_n_values);
1715
-                    if ($results) {
1716
-                        //if successful, set the primary key
1717
-                        //but don't use the normal SET method, because it will check if
1718
-                        //an item with the same ID exists in the mapper & db, then
1719
-                        //will find it in the db (because we just added it) and THAT object
1720
-                        //will get added to the mapper before we can add this one!
1721
-                        //but if we just avoid using the SET method, all that headache can be avoided
1722
-                        $pk_field_name = $model->primary_key_name();
1723
-                        $this->_fields[$pk_field_name] = $results;
1724
-                        $this->_clear_cached_property($pk_field_name);
1725
-                        $model->add_to_entity_map($this);
1726
-                        $this->_update_cached_related_model_objs_fks();
1727
-                    }
1728
-                }
1729
-            } else {//PK is NOT auto-increment
1730
-                //so check if one like it already exists in the db
1731
-                if ($model->exists_by_ID($this->ID())) {
1732
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1733
-                        throw new EE_Error(
1734
-                            sprintf(
1735
-                                __('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',
1736
-                                    'event_espresso'),
1737
-                                get_class($this),
1738
-                                get_class($model) . '::instance()->add_to_entity_map()',
1739
-                                get_class($model) . '::instance()->get_one_by_ID()',
1740
-                                '<br />'
1741
-                            )
1742
-                        );
1743
-                    }
1744
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1745
-                } else {
1746
-                    $results = $model->insert($save_cols_n_values);
1747
-                    $this->_update_cached_related_model_objs_fks();
1748
-                }
1749
-            }
1750
-        } else {//there is NO primary key
1751
-            $already_in_db = false;
1752
-            foreach ($model->unique_indexes() as $index) {
1753
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1754
-                if ($model->exists(array($uniqueness_where_params))) {
1755
-                    $already_in_db = true;
1756
-                }
1757
-            }
1758
-            if ($already_in_db) {
1759
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1760
-                    $model->get_combined_primary_key_fields());
1761
-                $results = $model->update($save_cols_n_values, $combined_pk_fields_n_values);
1762
-            } else {
1763
-                $results = $model->insert($save_cols_n_values);
1764
-            }
1765
-        }
1766
-        //restore the old assumption about values being prepared by the model object
1767
-        $model
1768
-             ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1769
-        /**
1770
-         * After saving the model object this action is called
1771
-         *
1772
-         * @param EE_Base_Class $model_object which was just saved
1773
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1774
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1775
-         */
1776
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1777
-        $this->_has_changes = false;
1778
-        return $results;
1779
-    }
1780
-
1781
-
1782
-
1783
-    /**
1784
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1785
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1786
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1787
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1788
-     * 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
1789
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1790
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1791
-     *
1792
-     * @return void
1793
-     * @throws EE_Error
1794
-     */
1795
-    protected function _update_cached_related_model_objs_fks()
1796
-    {
1797
-        $model = $this->get_model();
1798
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1799
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1800
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1801
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1802
-                        $model->get_this_model_name()
1803
-                    );
1804
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1805
-                    if ($related_model_obj_in_cache->ID()) {
1806
-                        $related_model_obj_in_cache->save();
1807
-                    }
1808
-                }
1809
-            }
1810
-        }
1811
-    }
1812
-
1813
-
1814
-
1815
-    /**
1816
-     * Saves this model object and its NEW cached relations to the database.
1817
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1818
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1819
-     * because otherwise, there's a potential for infinite looping of saving
1820
-     * Saves the cached related model objects, and ensures the relation between them
1821
-     * and this object and properly setup
1822
-     *
1823
-     * @return int ID of new model object on save; 0 on failure+
1824
-     * @throws EE_Error
1825
-     */
1826
-    public function save_new_cached_related_model_objs()
1827
-    {
1828
-        //make sure this has been saved
1829
-        if ( ! $this->ID()) {
1830
-            $id = $this->save();
1831
-        } else {
1832
-            $id = $this->ID();
1833
-        }
1834
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1835
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1836
-            if ($this->_model_relations[$relationName]) {
1837
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1838
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1839
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1840
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1841
-                    //but ONLY if it DOES NOT exist in the DB
1842
-                    /* @var $related_model_obj EE_Base_Class */
1843
-                    $related_model_obj = $this->_model_relations[$relationName];
1844
-                    //					if( ! $related_model_obj->ID()){
1845
-                    $this->_add_relation_to($related_model_obj, $relationName);
1846
-                    $related_model_obj->save_new_cached_related_model_objs();
1847
-                    //					}
1848
-                } else {
1849
-                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1850
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
1851
-                        //but ONLY if it DOES NOT exist in the DB
1852
-                        //						if( ! $related_model_obj->ID()){
1853
-                        $this->_add_relation_to($related_model_obj, $relationName);
1854
-                        $related_model_obj->save_new_cached_related_model_objs();
1855
-                        //						}
1856
-                    }
1857
-                }
1858
-            }
1859
-        }
1860
-        return $id;
1861
-    }
1862
-
1863
-
1864
-
1865
-    /**
1866
-     * for getting a model while instantiated.
1867
-     *
1868
-     * @return EEM_Base | EEM_CPT_Base
1869
-     */
1870
-    public function get_model()
1871
-    {
1872
-        if( ! $this->_model){
1873
-            $modelName = self::_get_model_classname(get_class($this));
1874
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1875
-        } else {
1876
-            $this->_model->set_timezone($this->_timezone);
1877
-        }
1878
-
1879
-        return $this->_model;
1880
-    }
1881
-
1882
-
1883
-
1884
-    /**
1885
-     * @param $props_n_values
1886
-     * @param $classname
1887
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1888
-     * @throws EE_Error
1889
-     */
1890
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1891
-    {
1892
-        //TODO: will not work for Term_Relationships because they have no PK!
1893
-        $primary_id_ref = self::_get_primary_key_name($classname);
1894
-        if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1895
-            $id = $props_n_values[$primary_id_ref];
1896
-            return self::_get_model($classname)->get_from_entity_map($id);
1897
-        }
1898
-        return false;
1899
-    }
1900
-
1901
-
1902
-
1903
-    /**
1904
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1905
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1906
-     * 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
1907
-     * we return false.
1908
-     *
1909
-     * @param  array  $props_n_values   incoming array of properties and their values
1910
-     * @param  string $classname        the classname of the child class
1911
-     * @param null    $timezone
1912
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
1913
-     *                                  date_format and the second value is the time format
1914
-     * @return mixed (EE_Base_Class|bool)
1915
-     * @throws EE_Error
1916
-     */
1917
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1918
-    {
1919
-        $existing = null;
1920
-        $model = self::_get_model($classname, $timezone);
1921
-        if ($model->has_primary_key_field()) {
1922
-            $primary_id_ref = self::_get_primary_key_name($classname);
1923
-            if (array_key_exists($primary_id_ref, $props_n_values)
1924
-                && ! empty($props_n_values[$primary_id_ref])
1925
-            ) {
1926
-                $existing = $model->get_one_by_ID(
1927
-                    $props_n_values[$primary_id_ref]
1928
-                );
1929
-            }
1930
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
1931
-            //no primary key on this model, but there's still a matching item in the DB
1932
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1933
-                self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1934
-            );
1935
-        }
1936
-        if ($existing) {
1937
-            //set date formats if present before setting values
1938
-            if ( ! empty($date_formats) && is_array($date_formats)) {
1939
-                $existing->set_date_format($date_formats[0]);
1940
-                $existing->set_time_format($date_formats[1]);
1941
-            } else {
1942
-                //set default formats for date and time
1943
-                $existing->set_date_format(get_option('date_format'));
1944
-                $existing->set_time_format(get_option('time_format'));
1945
-            }
1946
-            foreach ($props_n_values as $property => $field_value) {
1947
-                $existing->set($property, $field_value);
1948
-            }
1949
-            return $existing;
1950
-        } else {
1951
-            return false;
1952
-        }
1953
-    }
1954
-
1955
-
1956
-
1957
-    /**
1958
-     * Gets the EEM_*_Model for this class
1959
-     *
1960
-     * @access public now, as this is more convenient
1961
-     * @param      $classname
1962
-     * @param null $timezone
1963
-     * @throws EE_Error
1964
-     * @return EEM_Base
1965
-     */
1966
-    protected static function _get_model($classname, $timezone = null)
1967
-    {
1968
-        //find model for this class
1969
-        if ( ! $classname) {
1970
-            throw new EE_Error(
1971
-                sprintf(
1972
-                    __(
1973
-                        "What were you thinking calling _get_model(%s)?? You need to specify the class name",
1974
-                        "event_espresso"
1975
-                    ),
1976
-                    $classname
1977
-                )
1978
-            );
1979
-        }
1980
-        $modelName = self::_get_model_classname($classname);
1981
-        return self::_get_model_instance_with_name($modelName, $timezone);
1982
-    }
1983
-
1984
-
1985
-    /**
1986
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1987
-     *
1988
-     * @param string $model_classname
1989
-     * @param null $timezone
1990
-     * @return EEM_Base
1991
-     * @throws \ReflectionException
1992
-     * @throws InvalidArgumentException
1993
-     * @throws InvalidInterfaceException
1994
-     * @throws InvalidDataTypeException
1995
-     * @throws EE_Error
1996
-     */
1997
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1998
-    {
1999
-        $model_classname = str_replace('EEM_', '', $model_classname);
2000
-        $model = EE_Registry::instance()->load_model($model_classname);
2001
-        $model->set_timezone($timezone);
2002
-        return $model;
2003
-    }
2004
-
2005
-
2006
-
2007
-    /**
2008
-     * If a model name is provided (eg Registration), gets the model classname for that model.
2009
-     * Also works if a model class's classname is provided (eg EE_Registration).
2010
-     *
2011
-     * @param null $model_name
2012
-     * @return string like EEM_Attendee
2013
-     */
2014
-    private static function _get_model_classname($model_name = null)
2015
-    {
2016
-        if (strpos($model_name, "EE_") === 0) {
2017
-            $model_classname = str_replace("EE_", "EEM_", $model_name);
2018
-        } else {
2019
-            $model_classname = "EEM_" . $model_name;
2020
-        }
2021
-        return $model_classname;
2022
-    }
2023
-
2024
-
2025
-
2026
-    /**
2027
-     * returns the name of the primary key attribute
2028
-     *
2029
-     * @param null $classname
2030
-     * @throws EE_Error
2031
-     * @return string
2032
-     */
2033
-    protected static function _get_primary_key_name($classname = null)
2034
-    {
2035
-        if ( ! $classname) {
2036
-            throw new EE_Error(
2037
-                sprintf(
2038
-                    __("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
2039
-                    $classname
2040
-                )
2041
-            );
2042
-        }
2043
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2044
-    }
2045
-
2046
-
2047
-
2048
-    /**
2049
-     * Gets the value of the primary key.
2050
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2051
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2052
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2053
-     *
2054
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2055
-     * @throws EE_Error
2056
-     */
2057
-    public function ID()
2058
-    {
2059
-        $model = $this->get_model();
2060
-        //now that we know the name of the variable, use a variable variable to get its value and return its
2061
-        if ($model->has_primary_key_field()) {
2062
-            return $this->_fields[$model->primary_key_name()];
2063
-        } else {
2064
-            return $model->get_index_primary_key_string($this->_fields);
2065
-        }
2066
-    }
2067
-
2068
-
2069
-
2070
-    /**
2071
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2072
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2073
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2074
-     *
2075
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2076
-     * @param string $relationName                     eg 'Events','Question',etc.
2077
-     *                                                 an attendee to a group, you also want to specify which role they
2078
-     *                                                 will have in that group. So you would use this parameter to
2079
-     *                                                 specify array('role-column-name'=>'role-id')
2080
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2081
-     *                                                 allow you to further constrict the relation to being added.
2082
-     *                                                 However, keep in mind that the columns (keys) given must match a
2083
-     *                                                 column on the JOIN table and currently only the HABTM models
2084
-     *                                                 accept these additional conditions.  Also remember that if an
2085
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2086
-     *                                                 NEW row is created in the join table.
2087
-     * @param null   $cache_id
2088
-     * @throws EE_Error
2089
-     * @return EE_Base_Class the object the relation was added to
2090
-     */
2091
-    public function _add_relation_to(
2092
-        $otherObjectModelObjectOrID,
2093
-        $relationName,
2094
-        $extra_join_model_fields_n_values = array(),
2095
-        $cache_id = null
2096
-    ) {
2097
-        $model = $this->get_model();
2098
-        //if this thing exists in the DB, save the relation to the DB
2099
-        if ($this->ID()) {
2100
-            $otherObject = $model
2101
-                                ->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2102
-                                    $extra_join_model_fields_n_values);
2103
-            //clear cache so future get_many_related and get_first_related() return new results.
2104
-            $this->clear_cache($relationName, $otherObject, true);
2105
-            if ($otherObject instanceof EE_Base_Class) {
2106
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2107
-            }
2108
-        } else {
2109
-            //this thing doesn't exist in the DB,  so just cache it
2110
-            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2111
-                throw new EE_Error(sprintf(
2112
-                    __('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',
2113
-                        'event_espresso'),
2114
-                    $otherObjectModelObjectOrID,
2115
-                    get_class($this)
2116
-                ));
2117
-            } else {
2118
-                $otherObject = $otherObjectModelObjectOrID;
2119
-            }
2120
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2121
-        }
2122
-        if ($otherObject instanceof EE_Base_Class) {
2123
-            //fix the reciprocal relation too
2124
-            if ($otherObject->ID()) {
2125
-                //its saved so assumed relations exist in the DB, so we can just
2126
-                //clear the cache so future queries use the updated info in the DB
2127
-                $otherObject->clear_cache($model->get_this_model_name(), null, true);
2128
-            } else {
2129
-                //it's not saved, so it caches relations like this
2130
-                $otherObject->cache($model->get_this_model_name(), $this);
2131
-            }
2132
-        }
2133
-        return $otherObject;
2134
-    }
2135
-
2136
-
2137
-
2138
-    /**
2139
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2140
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2141
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2142
-     * from the cache
2143
-     *
2144
-     * @param mixed  $otherObjectModelObjectOrID
2145
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2146
-     *                to the DB yet
2147
-     * @param string $relationName
2148
-     * @param array  $where_query
2149
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2150
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2151
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2152
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2153
-     *                created in the join table.
2154
-     * @return EE_Base_Class the relation was removed from
2155
-     * @throws EE_Error
2156
-     */
2157
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2158
-    {
2159
-        if ($this->ID()) {
2160
-            //if this exists in the DB, save the relation change to the DB too
2161
-            $otherObject = $this->get_model()
2162
-                                ->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2163
-                                    $where_query);
2164
-            $this->clear_cache($relationName, $otherObject);
2165
-        } else {
2166
-            //this doesn't exist in the DB, just remove it from the cache
2167
-            $otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2168
-        }
2169
-        if ($otherObject instanceof EE_Base_Class) {
2170
-            $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2171
-        }
2172
-        return $otherObject;
2173
-    }
2174
-
2175
-
2176
-
2177
-    /**
2178
-     * Removes ALL the related things for the $relationName.
2179
-     *
2180
-     * @param string $relationName
2181
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2182
-     * @return EE_Base_Class
2183
-     * @throws EE_Error
2184
-     */
2185
-    public function _remove_relations($relationName, $where_query_params = array())
2186
-    {
2187
-        if ($this->ID()) {
2188
-            //if this exists in the DB, save the relation change to the DB too
2189
-            $otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2190
-            $this->clear_cache($relationName, null, true);
2191
-        } else {
2192
-            //this doesn't exist in the DB, just remove it from the cache
2193
-            $otherObjects = $this->clear_cache($relationName, null, true);
2194
-        }
2195
-        if (is_array($otherObjects)) {
2196
-            foreach ($otherObjects as $otherObject) {
2197
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2198
-            }
2199
-        }
2200
-        return $otherObjects;
2201
-    }
2202
-
2203
-
2204
-
2205
-    /**
2206
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2207
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2208
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2209
-     * because we want to get even deleted items etc.
2210
-     *
2211
-     * @param string $relationName key in the model's _model_relations array
2212
-     * @param array  $query_params like EEM_Base::get_all
2213
-     * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2214
-     * @throws EE_Error
2215
-     *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2216
-     *                             you want IDs
2217
-     */
2218
-    public function get_many_related($relationName, $query_params = array())
2219
-    {
2220
-        if ($this->ID()) {
2221
-            //this exists in the DB, so get the related things from either the cache or the DB
2222
-            //if there are query parameters, forget about caching the related model objects.
2223
-            if ($query_params) {
2224
-                $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2225
-            } else {
2226
-                //did we already cache the result of this query?
2227
-                $cached_results = $this->get_all_from_cache($relationName);
2228
-                if ( ! $cached_results) {
2229
-                    $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2230
-                    //if no query parameters were passed, then we got all the related model objects
2231
-                    //for that relation. We can cache them then.
2232
-                    foreach ($related_model_objects as $related_model_object) {
2233
-                        $this->cache($relationName, $related_model_object);
2234
-                    }
2235
-                } else {
2236
-                    $related_model_objects = $cached_results;
2237
-                }
2238
-            }
2239
-        } else {
2240
-            //this doesn't exist in the DB, so just get the related things from the cache
2241
-            $related_model_objects = $this->get_all_from_cache($relationName);
2242
-        }
2243
-        return $related_model_objects;
2244
-    }
2245
-
2246
-
2247
-    /**
2248
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2249
-     * unless otherwise specified in the $query_params
2250
-     *
2251
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2252
-     * @param array $query_params like EEM_Base::get_all's
2253
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2254
-     * @param bool $distinct if we want to only count the distinct values for the column then you can trigger
2255
-     *                               that by the setting $distinct to TRUE;
2256
-     * @return int
2257
-     * @throws EE_Error
2258
-     */
2259
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2260
-    {
2261
-        return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2262
-    }
2263
-
2264
-
2265
-    /**
2266
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2267
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2268
-     *
2269
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2270
-     * @param array $query_params like EEM_Base::get_all's
2271
-     * @param string $field_to_sum name of field to count by.
2272
-     *                              By default, uses primary key (which doesn't make much sense, so you should probably
2273
-     *                              change it)
2274
-     * @return int
2275
-     * @throws EE_Error
2276
-     */
2277
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2278
-    {
2279
-        return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2280
-    }
2281
-
2282
-
2283
-
2284
-    /**
2285
-     * Gets the first (ie, one) related model object of the specified type.
2286
-     *
2287
-     * @param string $relationName key in the model's _model_relations array
2288
-     * @param array  $query_params like EEM_Base::get_all
2289
-     * @return EE_Base_Class (not an array, a single object)
2290
-     * @throws EE_Error
2291
-     */
2292
-    public function get_first_related($relationName, $query_params = array())
2293
-    {
2294
-        $model = $this->get_model();
2295
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2296
-            //if they've provided some query parameters, don't bother trying to cache the result
2297
-            //also make sure we're not caching the result of get_first_related
2298
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2299
-            if ($query_params
2300
-                || ! $model->related_settings_for($relationName)
2301
-                     instanceof
2302
-                     EE_Belongs_To_Relation
2303
-            ) {
2304
-                $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2305
-            } else {
2306
-                //first, check if we've already cached the result of this query
2307
-                $cached_result = $this->get_one_from_cache($relationName);
2308
-                if ( ! $cached_result) {
2309
-                    $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2310
-                    $this->cache($relationName, $related_model_object);
2311
-                } else {
2312
-                    $related_model_object = $cached_result;
2313
-                }
2314
-            }
2315
-        } else {
2316
-            $related_model_object = null;
2317
-            //this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2318
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2319
-                $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2320
-            }
2321
-            //this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2322
-            if ( ! $related_model_object) {
2323
-                $related_model_object = $this->get_one_from_cache($relationName);
2324
-            }
2325
-        }
2326
-        return $related_model_object;
2327
-    }
2328
-
2329
-
2330
-
2331
-    /**
2332
-     * Does a delete on all related objects of type $relationName and removes
2333
-     * the current model object's relation to them. If they can't be deleted (because
2334
-     * of blocking related model objects) does nothing. If the related model objects are
2335
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2336
-     * If this model object doesn't exist yet in the DB, just removes its related things
2337
-     *
2338
-     * @param string $relationName
2339
-     * @param array  $query_params like EEM_Base::get_all's
2340
-     * @return int how many deleted
2341
-     * @throws EE_Error
2342
-     */
2343
-    public function delete_related($relationName, $query_params = array())
2344
-    {
2345
-        if ($this->ID()) {
2346
-            $count = $this->get_model()->delete_related($this, $relationName, $query_params);
2347
-        } else {
2348
-            $count = count($this->get_all_from_cache($relationName));
2349
-            $this->clear_cache($relationName, null, true);
2350
-        }
2351
-        return $count;
2352
-    }
2353
-
2354
-
2355
-
2356
-    /**
2357
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2358
-     * the current model object's relation to them. If they can't be deleted (because
2359
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2360
-     * If the related thing isn't a soft-deletable model object, this function is identical
2361
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2362
-     *
2363
-     * @param string $relationName
2364
-     * @param array  $query_params like EEM_Base::get_all's
2365
-     * @return int how many deleted (including those soft deleted)
2366
-     * @throws EE_Error
2367
-     */
2368
-    public function delete_related_permanently($relationName, $query_params = array())
2369
-    {
2370
-        if ($this->ID()) {
2371
-            $count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2372
-        } else {
2373
-            $count = count($this->get_all_from_cache($relationName));
2374
-        }
2375
-        $this->clear_cache($relationName, null, true);
2376
-        return $count;
2377
-    }
2378
-
2379
-
2380
-
2381
-    /**
2382
-     * is_set
2383
-     * Just a simple utility function children can use for checking if property exists
2384
-     *
2385
-     * @access  public
2386
-     * @param  string $field_name property to check
2387
-     * @return bool                              TRUE if existing,FALSE if not.
2388
-     */
2389
-    public function is_set($field_name)
2390
-    {
2391
-        return isset($this->_fields[$field_name]);
2392
-    }
2393
-
2394
-
2395
-
2396
-    /**
2397
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2398
-     * EE_Error exception if they don't
2399
-     *
2400
-     * @param  mixed (string|array) $properties properties to check
2401
-     * @throws EE_Error
2402
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2403
-     */
2404
-    protected function _property_exists($properties)
2405
-    {
2406
-        foreach ((array)$properties as $property_name) {
2407
-            //first make sure this property exists
2408
-            if ( ! $this->_fields[$property_name]) {
2409
-                throw new EE_Error(
2410
-                    sprintf(
2411
-                        __(
2412
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2413
-                            'event_espresso'
2414
-                        ),
2415
-                        $property_name
2416
-                    )
2417
-                );
2418
-            }
2419
-        }
2420
-        return true;
2421
-    }
2422
-
2423
-
2424
-
2425
-    /**
2426
-     * This simply returns an array of model fields for this object
2427
-     *
2428
-     * @return array
2429
-     * @throws EE_Error
2430
-     */
2431
-    public function model_field_array()
2432
-    {
2433
-        $fields = $this->get_model()->field_settings(false);
2434
-        $properties = array();
2435
-        //remove prepended underscore
2436
-        foreach ($fields as $field_name => $settings) {
2437
-            $properties[$field_name] = $this->get($field_name);
2438
-        }
2439
-        return $properties;
2440
-    }
2441
-
2442
-
2443
-
2444
-    /**
2445
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2446
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2447
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2448
-     * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2449
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2450
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2451
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
2452
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
2453
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2454
-     * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2455
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2456
-     *        return $previousReturnValue.$returnString;
2457
-     * }
2458
-     * require('EE_Answer.class.php');
2459
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2460
-     * echo $answer->my_callback('monkeys',100);
2461
-     * //will output "you called my_callback! and passed args:monkeys,100"
2462
-     *
2463
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2464
-     * @param array  $args       array of original arguments passed to the function
2465
-     * @throws EE_Error
2466
-     * @return mixed whatever the plugin which calls add_filter decides
2467
-     */
2468
-    public function __call($methodName, $args)
2469
-    {
2470
-        $className = get_class($this);
2471
-        $tagName = "FHEE__{$className}__{$methodName}";
2472
-        if ( ! has_filter($tagName)) {
2473
-            throw new EE_Error(
2474
-                sprintf(
2475
-                    __(
2476
-                        "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;}",
2477
-                        "event_espresso"
2478
-                    ),
2479
-                    $methodName,
2480
-                    $className,
2481
-                    $tagName
2482
-                )
2483
-            );
2484
-        }
2485
-        return apply_filters($tagName, null, $this, $args);
2486
-    }
2487
-
2488
-
2489
-    /**
2490
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2491
-     * A $previous_value can be specified in case there are many meta rows with the same key
2492
-     *
2493
-     * @param string $meta_key
2494
-     * @param mixed $meta_value
2495
-     * @param mixed $previous_value
2496
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2497
-     * @throws InvalidArgumentException
2498
-     * @throws InvalidInterfaceException
2499
-     * @throws InvalidDataTypeException
2500
-     * @throws EE_Error
2501
-     * NOTE: if the values haven't changed, returns 0
2502
-     */
2503
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2504
-    {
2505
-        $query_params = array(
2506
-            array(
2507
-                'EXM_key'  => $meta_key,
2508
-                'OBJ_ID'   => $this->ID(),
2509
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2510
-            ),
2511
-        );
2512
-        if ($previous_value !== null) {
2513
-            $query_params[0]['EXM_value'] = $meta_value;
2514
-        }
2515
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2516
-        if ( ! $existing_rows_like_that) {
2517
-            return $this->add_extra_meta($meta_key, $meta_value);
2518
-        }
2519
-        foreach ($existing_rows_like_that as $existing_row) {
2520
-            $existing_row->save(array('EXM_value' => $meta_value));
2521
-        }
2522
-        return count($existing_rows_like_that);
2523
-    }
2524
-
2525
-
2526
-    /**
2527
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2528
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2529
-     * extra meta row was entered, false if not
2530
-     *
2531
-     * @param string $meta_key
2532
-     * @param mixed $meta_value
2533
-     * @param boolean $unique
2534
-     * @return boolean
2535
-     * @throws InvalidArgumentException
2536
-     * @throws InvalidInterfaceException
2537
-     * @throws InvalidDataTypeException
2538
-     * @throws EE_Error
2539
-     */
2540
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2541
-    {
2542
-        if ($unique) {
2543
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2544
-                array(
2545
-                    array(
2546
-                        'EXM_key'  => $meta_key,
2547
-                        'OBJ_ID'   => $this->ID(),
2548
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2549
-                    ),
2550
-                )
2551
-            );
2552
-            if ($existing_extra_meta) {
2553
-                return false;
2554
-            }
2555
-        }
2556
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2557
-            array(
2558
-                'EXM_key'   => $meta_key,
2559
-                'EXM_value' => $meta_value,
2560
-                'OBJ_ID'    => $this->ID(),
2561
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2562
-            )
2563
-        );
2564
-        $new_extra_meta->save();
2565
-        return true;
2566
-    }
2567
-
2568
-
2569
-    /**
2570
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2571
-     * is specified, only deletes extra meta records with that value.
2572
-     *
2573
-     * @param string $meta_key
2574
-     * @param mixed $meta_value
2575
-     * @return int number of extra meta rows deleted
2576
-     * @throws InvalidArgumentException
2577
-     * @throws InvalidInterfaceException
2578
-     * @throws InvalidDataTypeException
2579
-     * @throws EE_Error
2580
-     */
2581
-    public function delete_extra_meta($meta_key, $meta_value = null)
2582
-    {
2583
-        $query_params = array(
2584
-            array(
2585
-                'EXM_key'  => $meta_key,
2586
-                'OBJ_ID'   => $this->ID(),
2587
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2588
-            ),
2589
-        );
2590
-        if ($meta_value !== null) {
2591
-            $query_params[0]['EXM_value'] = $meta_value;
2592
-        }
2593
-        return EEM_Extra_Meta::instance()->delete($query_params);
2594
-    }
2595
-
2596
-
2597
-
2598
-    /**
2599
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2600
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2601
-     * You can specify $default is case you haven't found the extra meta
2602
-     *
2603
-     * @param string  $meta_key
2604
-     * @param boolean $single
2605
-     * @param mixed   $default if we don't find anything, what should we return?
2606
-     * @return mixed single value if $single; array if ! $single
2607
-     * @throws EE_Error
2608
-     */
2609
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2610
-    {
2611
-        if ($single) {
2612
-            $result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2613
-            if ($result instanceof EE_Extra_Meta) {
2614
-                return $result->value();
2615
-            }
2616
-        } else {
2617
-            $results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2618
-            if ($results) {
2619
-                $values = array();
2620
-                foreach ($results as $result) {
2621
-                    if ($result instanceof EE_Extra_Meta) {
2622
-                        $values[$result->ID()] = $result->value();
2623
-                    }
2624
-                }
2625
-                return $values;
2626
-            }
2627
-        }
2628
-        //if nothing discovered yet return default.
2629
-        return apply_filters(
2630
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2631
-            $default,
2632
-            $meta_key,
2633
-            $single,
2634
-            $this
2635
-            );
2636
-    }
2637
-
2638
-
2639
-
2640
-    /**
2641
-     * Returns a simple array of all the extra meta associated with this model object.
2642
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2643
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2644
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2645
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2646
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2647
-     * finally the extra meta's value as each sub-value. (eg
2648
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2649
-     *
2650
-     * @param boolean $one_of_each_key
2651
-     * @return array
2652
-     * @throws EE_Error
2653
-     */
2654
-    public function all_extra_meta_array($one_of_each_key = true)
2655
-    {
2656
-        $return_array = array();
2657
-        if ($one_of_each_key) {
2658
-            $extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2659
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2660
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2661
-                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2662
-                }
2663
-            }
2664
-        } else {
2665
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2666
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2667
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2668
-                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2669
-                        $return_array[$extra_meta_obj->key()] = array();
2670
-                    }
2671
-                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2672
-                }
2673
-            }
2674
-        }
2675
-        return $return_array;
2676
-    }
2677
-
2678
-
2679
-
2680
-    /**
2681
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2682
-     *
2683
-     * @return string
2684
-     * @throws EE_Error
2685
-     */
2686
-    public function name()
2687
-    {
2688
-        //find a field that's not a text field
2689
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2690
-        if ($field_we_can_use) {
2691
-            return $this->get($field_we_can_use->get_name());
2692
-        } else {
2693
-            $first_few_properties = $this->model_field_array();
2694
-            $first_few_properties = array_slice($first_few_properties, 0, 3);
2695
-            $name_parts = array();
2696
-            foreach ($first_few_properties as $name => $value) {
2697
-                $name_parts[] = "$name:$value";
2698
-            }
2699
-            return implode(",", $name_parts);
2700
-        }
2701
-    }
2702
-
2703
-
2704
-
2705
-    /**
2706
-     * in_entity_map
2707
-     * Checks if this model object has been proven to already be in the entity map
2708
-     *
2709
-     * @return boolean
2710
-     * @throws EE_Error
2711
-     */
2712
-    public function in_entity_map()
2713
-    {
2714
-        if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2715
-            //well, if we looked, did we find it in the entity map?
2716
-            return true;
2717
-        } else {
2718
-            return false;
2719
-        }
2720
-    }
2721
-
2722
-
2723
-
2724
-    /**
2725
-     * refresh_from_db
2726
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2727
-     *
2728
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2729
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2730
-     */
2731
-    public function refresh_from_db()
2732
-    {
2733
-        if ($this->ID() && $this->in_entity_map()) {
2734
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
2735
-        } else {
2736
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2737
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
2738
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2739
-            //absolutely nothing in it for this ID
2740
-            if (WP_DEBUG) {
2741
-                throw new EE_Error(
2742
-                    sprintf(
2743
-                        __('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.',
2744
-                            'event_espresso'),
2745
-                        $this->ID(),
2746
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2747
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2748
-                    )
2749
-                );
2750
-            }
2751
-        }
2752
-    }
2753
-
2754
-
2755
-    /**
2756
-     * Gets the money field's amount in subunits (and if the currency has no subunits, gets it in the main units).
2757
-     * If you want to use this method, the class must implement UsesMoneyInterface and injected a MoneyFactory in
2758
-     * its constructor
2759
-     * @param string $money_field_name
2760
-     * @return int
2761
-     * @throws InvalidEntityException
2762
-     * @throws EE_Error
2763
-     * @throws DomainException
2764
-     */
2765
-    public function moneyInSubunits($money_field_name)
2766
-    {
2767
-        $this->verifyUsesMoney(__FUNCTION__);
2768
-        return $this->getMoneyObject($money_field_name)->amountInSubunits();
2769
-    }
2770
-
2771
-
2772
-    /**
2773
-     * Sets the money field's amount based on the incoming monetary subunits (eg pennies). If the currency has no
2774
-     * subunits, the amount is actually assumed to be in the currency's main units.
2775
-     * If you want to use this method, the class must implement UsesMoneyInterface and injected a MoneyFactory in
2776
-     * its constructor
2777
-     *
2778
-     * @param string $money_field_name
2779
-     * @param int    $amount_in_subunits
2780
-     * @throws InvalidArgumentException
2781
-     * @throws InvalidInterfaceException
2782
-     * @throws InvalidIdentifierException
2783
-     * @throws InvalidDataTypeException
2784
-     * @throws EE_Error
2785
-     * @throws DomainException
2786
-     */
2787
-    public function setMoneySubunits($money_field_name,$amount_in_subunits)
2788
-    {
2789
-        $this->verifyUsesMoney(__FUNCTION__);
2790
-        $money = $this->money_factory->createFromSubUnits(
2791
-            $amount_in_subunits,
2792
-            EE_Config::instance()->currency->code
2793
-        );
2794
-        $this->set($money_field_name, $money);
2795
-    }
2796
-
2797
-
2798
-    /**
2799
-     * Checks this class has implemented UsesMoneyInterface
2800
-     * @param string $function
2801
-     * @throws DomainException
2802
-     * @throws EE_Error
2803
-     */
2804
-    private function verifyUsesMoney($function)
2805
-    {
2806
-        if (! $this instanceof UsesMoneyInterface) {
2807
-            throw new DomainException(
2808
-                sprintf(
2809
-                    esc_html__(
2810
-                        '%1$s does not use an %2$s object for representing money values, therefore the %3$s method can not be called.',
2811
-                        'event_espresso'
2812
-                    ),
2813
-                    $this->name(),
2814
-                    'EventEspresso\core\domain\values\currency\Money',
2815
-                    "{$function}()"
2816
-                )
2817
-            );
2818
-        }
2819
-    }
2820
-
2821
-
2822
-
2823
-    /**
2824
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2825
-     * (probably a bad assumption they have made, oh well)
2826
-     *
2827
-     * @return string
2828
-     */
2829
-    public function __toString()
2830
-    {
2831
-        try {
2832
-            return sprintf('%s (%s)', $this->name(), $this->ID());
2833
-        } catch (Exception $e) {
2834
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2835
-            return '';
2836
-        }
2837
-    }
2838
-
2839
-
2840
-
2841
-    /**
2842
-     * Clear related model objects if they're already in the DB, because otherwise when we
2843
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
2844
-     * This means if we have made changes to those related model objects, and want to unserialize
2845
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
2846
-     * Instead, those related model objects should be directly serialized and stored.
2847
-     * Eg, the following won't work:
2848
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2849
-     * $att = $reg->attendee();
2850
-     * $att->set( 'ATT_fname', 'Dirk' );
2851
-     * update_option( 'my_option', serialize( $reg ) );
2852
-     * //END REQUEST
2853
-     * //START NEXT REQUEST
2854
-     * $reg = get_option( 'my_option' );
2855
-     * $reg->attendee()->save();
2856
-     * And would need to be replace with:
2857
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2858
-     * $att = $reg->attendee();
2859
-     * $att->set( 'ATT_fname', 'Dirk' );
2860
-     * update_option( 'my_option', serialize( $reg ) );
2861
-     * //END REQUEST
2862
-     * //START NEXT REQUEST
2863
-     * $att = get_option( 'my_option' );
2864
-     * $att->save();
2865
-     *
2866
-     * @return array
2867
-     * @throws EE_Error
2868
-     */
2869
-    public function __sleep()
2870
-    {
2871
-        $model = $this->get_model();
2872
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2873
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
2874
-                $classname = 'EE_' . $model->get_this_model_name();
2875
-                if (
2876
-                    $this->get_one_from_cache($relation_name) instanceof $classname
2877
-                    && $this->get_one_from_cache($relation_name)->ID()
2878
-                ) {
2879
-                    $this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2880
-                }
2881
-            }
2882
-        }
2883
-        $this->_props_n_values_provided_in_constructor = array();
2884
-        $properties_to_serialize = get_object_vars($this);
2885
-        //don't serialize the model. It's big and that risks recursion
2886
-        unset(
2887
-            $properties_to_serialize['_model'],
2888
-            $properties_to_serialize['money_factory']
2889
-        );
2890
-        return array_keys($properties_to_serialize);
2891
-    }
2892
-
2893
-
2894
-    /**
2895
-     * restore _props_n_values_provided_in_constructor
2896
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2897
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
2898
-     * At best, you would only be able to detect if state change has occurred during THIS request.
2899
-     * @throws InvalidInterfaceException
2900
-     * @throws InvalidDataTypeException
2901
-     */
2902
-    public function __wakeup()
2903
-    {
2904
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
2905
-        if( $this instanceof UsesMoneyInterface) {
2906
-            $this->money_factory = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\currency\MoneyFactory');
2907
-        }
2908
-    }
30
+	/**
31
+	 * This is an array of the original properties and values provided during construction
32
+	 * of this model object. (keys are model field names, values are their values).
33
+	 * This list is important to remember so that when we are merging data from the db, we know
34
+	 * which values to override and which to not override.
35
+	 *
36
+	 * @var array
37
+	 */
38
+	protected $_props_n_values_provided_in_constructor;
39
+
40
+	/**
41
+	 * Timezone
42
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
43
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
44
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
45
+	 * access to it.
46
+	 *
47
+	 * @var string
48
+	 */
49
+	protected $_timezone;
50
+
51
+
52
+
53
+	/**
54
+	 * date format
55
+	 * pattern or format for displaying dates
56
+	 *
57
+	 * @var string $_dt_frmt
58
+	 */
59
+	protected $_dt_frmt;
60
+
61
+
62
+
63
+	/**
64
+	 * time format
65
+	 * pattern or format for displaying time
66
+	 *
67
+	 * @var string $_tm_frmt
68
+	 */
69
+	protected $_tm_frmt;
70
+
71
+
72
+
73
+	/**
74
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
75
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
76
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
77
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
78
+	 *
79
+	 * @var array
80
+	 */
81
+	protected $_cached_properties = array();
82
+
83
+	/**
84
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
85
+	 * single
86
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
87
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
88
+	 * all others have an array)
89
+	 *
90
+	 * @var array
91
+	 */
92
+	protected $_model_relations = array();
93
+
94
+	/**
95
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
96
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
97
+	 *
98
+	 * @var array
99
+	 */
100
+	protected $_fields = array();
101
+
102
+	/**
103
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
104
+	 * For example, we might create model objects intended to only be used for the duration
105
+	 * of this request and to be thrown away, and if they were accidentally saved
106
+	 * it would be a bug.
107
+	 */
108
+	protected $_allow_persist = true;
109
+
110
+	/**
111
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
112
+	 */
113
+	protected $_has_changes = false;
114
+
115
+	/**
116
+	 * @var EEM_Base
117
+	 */
118
+	protected $_model;
119
+
120
+	/**
121
+	 * @var MoneyFactory
122
+	 */
123
+	protected $money_factory;
124
+
125
+
126
+	/**
127
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
128
+	 * play nice
129
+	 *
130
+	 * @param array $fieldValues where each key is a field (ie, array key in the 2nd
131
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
132
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
133
+	 * @param boolean $bydb a flag for setting if the class is instantiated by the
134
+	 *                                                         corresponding db model or not.
135
+	 * @param string $timezone indicate what timezone you want any datetime fields to
136
+	 *                                                         be in when instantiating a EE_Base_Class object.
137
+	 * @param array $date_formats An array of date formats to set on construct where first
138
+	 *                                                         value is the date_format and second value is the time
139
+	 *                                                         format.
140
+	 * @throws InvalidArgumentException
141
+	 * @throws InvalidInterfaceException
142
+	 * @throws InvalidDataTypeException
143
+	 * @throws EE_Error
144
+	 */
145
+	protected function __construct(
146
+		$fieldValues = array(),
147
+		$bydb = false,
148
+		$timezone = '',
149
+		$date_formats = array()
150
+	) {
151
+		$className = get_class($this);
152
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
153
+		$model = $this->get_model();
154
+		$model_fields = $model->field_settings(false);
155
+		// ensure $fieldValues is an array
156
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
157
+		// EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
158
+		// verify client code has not passed any invalid field names
159
+		foreach ($fieldValues as $field_name => $field_value) {
160
+			if ( ! isset($model_fields[$field_name])) {
161
+				throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
162
+					"event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
163
+			}
164
+		}
165
+		// EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
166
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
167
+		if ( ! empty($date_formats) && is_array($date_formats)) {
168
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
169
+		} else {
170
+			//set default formats for date and time
171
+			$this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
172
+			$this->_tm_frmt = (string)get_option('time_format', 'g:i a');
173
+		}
174
+		//if db model is instantiating
175
+		if ($bydb) {
176
+			//client code has indicated these field values are from the database
177
+			foreach ($model_fields as $fieldName => $field) {
178
+				$this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
179
+			}
180
+		} else {
181
+			//we're constructing a brand
182
+			//new instance of the model object. Generally, this means we'll need to do more field validation
183
+			foreach ($model_fields as $fieldName => $field) {
184
+				$this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
185
+			}
186
+		}
187
+		//remember what values were passed to this constructor
188
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
189
+		//remember in entity mapper
190
+		if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
191
+			$model->add_to_entity_map($this);
192
+		}
193
+		//setup all the relations
194
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
195
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
196
+				$this->_model_relations[$relation_name] = null;
197
+			} else {
198
+				$this->_model_relations[$relation_name] = array();
199
+			}
200
+		}
201
+		/**
202
+		 * Action done at the end of each model object construction
203
+		 *
204
+		 * @param EE_Base_Class $this the model object just created
205
+		 */
206
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
207
+	}
208
+
209
+
210
+
211
+	/**
212
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
213
+	 *
214
+	 * @return boolean
215
+	 */
216
+	public function allow_persist()
217
+	{
218
+		return $this->_allow_persist;
219
+	}
220
+
221
+
222
+
223
+	/**
224
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
225
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
226
+	 * you got new information that somehow made you change your mind.
227
+	 *
228
+	 * @param boolean $allow_persist
229
+	 * @return boolean
230
+	 */
231
+	public function set_allow_persist($allow_persist)
232
+	{
233
+		return $this->_allow_persist = $allow_persist;
234
+	}
235
+
236
+
237
+
238
+	/**
239
+	 * Gets the field's original value when this object was constructed during this request.
240
+	 * This can be helpful when determining if a model object has changed or not
241
+	 *
242
+	 * @param string $field_name
243
+	 * @return mixed|null
244
+	 * @throws EE_Error
245
+	 */
246
+	public function get_original($field_name)
247
+	{
248
+		if (isset($this->_props_n_values_provided_in_constructor[$field_name])
249
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
250
+		) {
251
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
252
+		} else {
253
+			return null;
254
+		}
255
+	}
256
+
257
+
258
+
259
+	/**
260
+	 * @param EE_Base_Class $obj
261
+	 * @return string
262
+	 */
263
+	public function get_class($obj)
264
+	{
265
+		return get_class($obj);
266
+	}
267
+
268
+
269
+	/**
270
+	 * Overrides parent because parent expects old models.
271
+	 * This also doesn't do any validation, and won't work for serialized arrays
272
+	 *
273
+	 * @param    string $field_name
274
+	 * @param    mixed $field_value
275
+	 * @param bool $use_default
276
+	 * @throws InvalidArgumentException
277
+	 * @throws InvalidInterfaceException
278
+	 * @throws InvalidDataTypeException
279
+	 * @throws EE_Error
280
+	 */
281
+	public function set($field_name, $field_value, $use_default = false)
282
+	{
283
+		// if not using default and nothing has changed, and object has already been setup (has ID),
284
+		// then don't do anything
285
+		if (
286
+			! $use_default
287
+			&& $this->_fields[$field_name] === $field_value
288
+			&& $this->ID()
289
+		) {
290
+			return;
291
+		}
292
+		$model = $this->get_model();
293
+		$this->_has_changes = true;
294
+		$field_obj = $model->field_settings_for($field_name);
295
+		if ($field_obj instanceof EE_Model_Field_Base) {
296
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
297
+			if ($field_obj instanceof EE_Datetime_Field) {
298
+				$field_obj->set_timezone($this->_timezone);
299
+				$field_obj->set_date_format($this->_dt_frmt);
300
+				$field_obj->set_time_format($this->_tm_frmt);
301
+			}
302
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
303
+			//should the value be null?
304
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
305
+				$this->_fields[$field_name] = $field_obj->get_default_value();
306
+				/**
307
+				 * To save having to refactor all the models, if a default value is used for a
308
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
309
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
310
+				 * object.
311
+				 *
312
+				 * @since 4.6.10+
313
+				 */
314
+				if (
315
+					$field_obj instanceof EE_Datetime_Field
316
+					&& $this->_fields[$field_name] !== null
317
+					&& ! $this->_fields[$field_name] instanceof DateTime
318
+				) {
319
+					empty($this->_fields[$field_name])
320
+						? $this->set($field_name, time())
321
+						: $this->set($field_name, $this->_fields[$field_name]);
322
+				}
323
+			} else {
324
+				$this->_fields[$field_name] = $holder_of_value;
325
+			}
326
+			//if we're not in the constructor...
327
+			//now check if what we set was a primary key
328
+			if (
329
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
330
+				$this->_props_n_values_provided_in_constructor
331
+				&& $field_value
332
+				&& $field_name === $model->primary_key_name()
333
+			) {
334
+				//if so, we want all this object's fields to be filled either with
335
+				//what we've explicitly set on this model
336
+				//or what we have in the db
337
+				// echo "setting primary key!";
338
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
339
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
340
+				foreach ($fields_on_model as $field_obj) {
341
+					if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
342
+						 && $field_obj->get_name() !== $field_name
343
+					) {
344
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
345
+					}
346
+				}
347
+				//oh this model object has an ID? well make sure its in the entity mapper
348
+				$model->add_to_entity_map($this);
349
+			}
350
+			//let's unset any cache for this field_name from the $_cached_properties property.
351
+			$this->_clear_cached_property($field_name);
352
+		} else {
353
+			throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
354
+				"event_espresso"), $field_name));
355
+		}
356
+	}
357
+
358
+
359
+
360
+	/**
361
+	 * This sets the field value on the db column if it exists for the given $column_name or
362
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
363
+	 *
364
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
365
+	 * @param string $field_name  Must be the exact column name.
366
+	 * @param mixed  $field_value The value to set.
367
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
368
+	 * @throws EE_Error
369
+	 */
370
+	public function set_field_or_extra_meta($field_name, $field_value)
371
+	{
372
+		if ($this->get_model()->has_field($field_name)) {
373
+			$this->set($field_name, $field_value);
374
+			return true;
375
+		} else {
376
+			//ensure this object is saved first so that extra meta can be properly related.
377
+			$this->save();
378
+			return $this->update_extra_meta($field_name, $field_value);
379
+		}
380
+	}
381
+
382
+
383
+
384
+	/**
385
+	 * This retrieves the value of the db column set on this class or if that's not present
386
+	 * it will attempt to retrieve from extra_meta if found.
387
+	 * Example Usage:
388
+	 * Via EE_Message child class:
389
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
390
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
391
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
392
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
393
+	 * value for those extra fields dynamically via the EE_message object.
394
+	 *
395
+	 * @param  string $field_name expecting the fully qualified field name.
396
+	 * @return mixed|null  value for the field if found.  null if not found.
397
+	 * @throws EE_Error
398
+	 */
399
+	public function get_field_or_extra_meta($field_name)
400
+	{
401
+		if ($this->get_model()->has_field($field_name)) {
402
+			$column_value = $this->get($field_name);
403
+		} else {
404
+			//This isn't a column in the main table, let's see if it is in the extra meta.
405
+			$column_value = $this->get_extra_meta($field_name, true, null);
406
+		}
407
+		return $column_value;
408
+	}
409
+
410
+
411
+	/**
412
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
413
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
414
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
415
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
416
+	 *
417
+	 * @access public
418
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
419
+	 * @return void
420
+	 * @throws InvalidArgumentException
421
+	 * @throws InvalidInterfaceException
422
+	 * @throws InvalidDataTypeException
423
+	 * @throws EE_Error
424
+	 */
425
+	public function set_timezone($timezone = '')
426
+	{
427
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
428
+		//make sure we clear all cached properties because they won't be relevant now
429
+		$this->_clear_cached_properties();
430
+		//make sure we update field settings and the date for all EE_Datetime_Fields
431
+		$model_fields = $this->get_model()->field_settings(false);
432
+		foreach ($model_fields as $field_name => $field_obj) {
433
+			if ($field_obj instanceof EE_Datetime_Field) {
434
+				$field_obj->set_timezone($this->_timezone);
435
+				if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
436
+					$this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
437
+				}
438
+			}
439
+		}
440
+	}
441
+
442
+
443
+
444
+	/**
445
+	 * This just returns whatever is set for the current timezone.
446
+	 *
447
+	 * @access public
448
+	 * @return string timezone string
449
+	 */
450
+	public function get_timezone()
451
+	{
452
+		return $this->_timezone;
453
+	}
454
+
455
+
456
+
457
+	/**
458
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
459
+	 * internally instead of wp set date format options
460
+	 *
461
+	 * @since 4.6
462
+	 * @param string $format should be a format recognizable by PHP date() functions.
463
+	 */
464
+	public function set_date_format($format)
465
+	{
466
+		$this->_dt_frmt = $format;
467
+		//clear cached_properties because they won't be relevant now.
468
+		$this->_clear_cached_properties();
469
+	}
470
+
471
+
472
+
473
+	/**
474
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
475
+	 * class internally instead of wp set time format options.
476
+	 *
477
+	 * @since 4.6
478
+	 * @param string $format should be a format recognizable by PHP date() functions.
479
+	 */
480
+	public function set_time_format($format)
481
+	{
482
+		$this->_tm_frmt = $format;
483
+		//clear cached_properties because they won't be relevant now.
484
+		$this->_clear_cached_properties();
485
+	}
486
+
487
+
488
+
489
+	/**
490
+	 * This returns the current internal set format for the date and time formats.
491
+	 *
492
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
493
+	 *                             where the first value is the date format and the second value is the time format.
494
+	 * @return mixed string|array
495
+	 */
496
+	public function get_format($full = true)
497
+	{
498
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
499
+	}
500
+
501
+
502
+
503
+	/**
504
+	 * cache
505
+	 * stores the passed model object on the current model object.
506
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
507
+	 *
508
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
509
+	 *                                       'Registration' associated with this model object
510
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
511
+	 *                                       that could be a payment or a registration)
512
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
513
+	 *                                       items which will be stored in an array on this object
514
+	 * @throws EE_Error
515
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
516
+	 *                  related thing, no array)
517
+	 */
518
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
519
+	{
520
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
521
+		if ( ! $object_to_cache instanceof EE_Base_Class) {
522
+			return false;
523
+		}
524
+		// also get "how" the object is related, or throw an error
525
+		if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
526
+			throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
527
+				$relationName, get_class($this)));
528
+		}
529
+		// how many things are related ?
530
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
531
+			// if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
532
+			// so for these model objects just set it to be cached
533
+			$this->_model_relations[$relationName] = $object_to_cache;
534
+			$return = true;
535
+		} else {
536
+			// otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
537
+			// eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
538
+			if ( ! is_array($this->_model_relations[$relationName])) {
539
+				// if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
540
+				$this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
541
+					? array($this->_model_relations[$relationName]) : array();
542
+			}
543
+			// first check for a cache_id which is normally empty
544
+			if ( ! empty($cache_id)) {
545
+				// if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
546
+				$this->_model_relations[$relationName][$cache_id] = $object_to_cache;
547
+				$return = $cache_id;
548
+			} elseif ($object_to_cache->ID()) {
549
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
550
+				$this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
551
+				$return = $object_to_cache->ID();
552
+			} else {
553
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
554
+				$this->_model_relations[$relationName][] = $object_to_cache;
555
+				// move the internal pointer to the end of the array
556
+				end($this->_model_relations[$relationName]);
557
+				// and grab the key so that we can return it
558
+				$return = key($this->_model_relations[$relationName]);
559
+			}
560
+		}
561
+		return $return;
562
+	}
563
+
564
+
565
+
566
+	/**
567
+	 * For adding an item to the cached_properties property.
568
+	 *
569
+	 * @access protected
570
+	 * @param string      $fieldname the property item the corresponding value is for.
571
+	 * @param mixed       $value     The value we are caching.
572
+	 * @param string|null $cache_type
573
+	 * @return void
574
+	 * @throws EE_Error
575
+	 */
576
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
577
+	{
578
+		//first make sure this property exists
579
+		$this->get_model()->field_settings_for($fieldname);
580
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
581
+		$this->_cached_properties[$fieldname][$cache_type] = $value;
582
+	}
583
+
584
+
585
+
586
+	/**
587
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
588
+	 * This also SETS the cache if we return the actual property!
589
+	 *
590
+	 * @param string $fieldname        the name of the property we're trying to retrieve
591
+	 * @param bool   $pretty
592
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
593
+	 *                                 (in cases where the same property may be used for different outputs
594
+	 *                                 - i.e. datetime, money etc.)
595
+	 *                                 It can also accept certain pre-defined "schema" strings
596
+	 *                                 to define how to output the property.
597
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
598
+	 * @return mixed                   whatever the value for the property is we're retrieving
599
+	 * @throws EE_Error
600
+	 */
601
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
602
+	{
603
+		//verify the field exists
604
+		$model = $this->get_model();
605
+		$model->field_settings_for($fieldname);
606
+		$cache_type = $pretty ? 'pretty' : 'standard';
607
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
608
+		if (isset($this->_cached_properties[$fieldname][$cache_type])) {
609
+			return $this->_cached_properties[$fieldname][$cache_type];
610
+		}
611
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
612
+		$this->_set_cached_property($fieldname, $value, $cache_type);
613
+		return $value;
614
+	}
615
+
616
+
617
+	/**
618
+	 * If the cache didn't fetch the needed item, this fetches it.
619
+	 * @param string $fieldname
620
+	 * @param bool $pretty
621
+	 * @param string $extra_cache_ref
622
+	 * @return mixed
623
+	 * @throws EE_Error
624
+	 */
625
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
626
+	{
627
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
628
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
629
+		if ($field_obj instanceof EE_Datetime_Field) {
630
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
631
+		}
632
+		if ( ! isset($this->_fields[$fieldname])) {
633
+			$this->_fields[$fieldname] = null;
634
+		}
635
+		$value = $pretty
636
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
637
+			: $field_obj->prepare_for_get($this->_fields[$fieldname]);
638
+		return $value;
639
+	}
640
+
641
+
642
+	/**
643
+	 * set timezone, formats, and output for EE_Datetime_Field objects
644
+	 *
645
+	 * @param \EE_Datetime_Field $datetime_field
646
+	 * @param bool $pretty
647
+	 * @param null $date_or_time
648
+	 * @return void
649
+	 * @throws InvalidArgumentException
650
+	 * @throws InvalidInterfaceException
651
+	 * @throws InvalidDataTypeException
652
+	 * @throws EE_Error
653
+	 */
654
+	protected function _prepare_datetime_field(
655
+		EE_Datetime_Field $datetime_field,
656
+		$pretty = false,
657
+		$date_or_time = null
658
+	) {
659
+		$datetime_field->set_timezone($this->_timezone);
660
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
661
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
662
+		//set the output returned
663
+		switch ($date_or_time) {
664
+			case 'D' :
665
+				$datetime_field->set_date_time_output('date');
666
+				break;
667
+			case 'T' :
668
+				$datetime_field->set_date_time_output('time');
669
+				break;
670
+			default :
671
+				$datetime_field->set_date_time_output();
672
+		}
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 * This just takes care of clearing out the cached_properties
679
+	 *
680
+	 * @return void
681
+	 */
682
+	protected function _clear_cached_properties()
683
+	{
684
+		$this->_cached_properties = array();
685
+	}
686
+
687
+
688
+
689
+	/**
690
+	 * This just clears out ONE property if it exists in the cache
691
+	 *
692
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
693
+	 * @return void
694
+	 */
695
+	protected function _clear_cached_property($property_name)
696
+	{
697
+		if (isset($this->_cached_properties[$property_name])) {
698
+			unset($this->_cached_properties[$property_name]);
699
+		}
700
+	}
701
+
702
+
703
+
704
+	/**
705
+	 * Ensures that this related thing is a model object.
706
+	 *
707
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
708
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
709
+	 * @return EE_Base_Class
710
+	 * @throws EE_Error
711
+	 */
712
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
713
+	{
714
+		$other_model_instance = self::_get_model_instance_with_name(
715
+			self::_get_model_classname($model_name),
716
+			$this->_timezone
717
+		);
718
+		return $other_model_instance->ensure_is_obj($object_or_id);
719
+	}
720
+
721
+
722
+
723
+	/**
724
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
725
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
726
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
727
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
728
+	 *
729
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
730
+	 *                                                     Eg 'Registration'
731
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
732
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
733
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
734
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
735
+	 *                                                     this is HasMany or HABTM.
736
+	 * @throws EE_Error
737
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
738
+	 *                       relation from all
739
+	 */
740
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
741
+	{
742
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
743
+		$index_in_cache = '';
744
+		if ( ! $relationship_to_model) {
745
+			throw new EE_Error(
746
+				sprintf(
747
+					__("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
748
+					$relationName,
749
+					get_class($this)
750
+				)
751
+			);
752
+		}
753
+		if ($clear_all) {
754
+			$obj_removed = true;
755
+			$this->_model_relations[$relationName] = null;
756
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
757
+			$obj_removed = $this->_model_relations[$relationName];
758
+			$this->_model_relations[$relationName] = null;
759
+		} else {
760
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
761
+				&& $object_to_remove_or_index_into_array->ID()
762
+			) {
763
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
764
+				if (is_array($this->_model_relations[$relationName])
765
+					&& ! isset($this->_model_relations[$relationName][$index_in_cache])
766
+				) {
767
+					$index_found_at = null;
768
+					//find this object in the array even though it has a different key
769
+					foreach ($this->_model_relations[$relationName] as $index => $obj) {
770
+						if (
771
+							$obj instanceof EE_Base_Class
772
+							&& (
773
+								$obj == $object_to_remove_or_index_into_array
774
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
775
+							)
776
+						) {
777
+							$index_found_at = $index;
778
+							break;
779
+						}
780
+					}
781
+					if ($index_found_at) {
782
+						$index_in_cache = $index_found_at;
783
+					} else {
784
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
785
+						//if it wasn't in it to begin with. So we're done
786
+						return $object_to_remove_or_index_into_array;
787
+					}
788
+				}
789
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
790
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
791
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
792
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
793
+						$index_in_cache = $index;
794
+					}
795
+				}
796
+			} else {
797
+				$index_in_cache = $object_to_remove_or_index_into_array;
798
+			}
799
+			//supposedly we've found it. But it could just be that the client code
800
+			//provided a bad index/object
801
+			if (
802
+			isset(
803
+				$this->_model_relations[$relationName],
804
+				$this->_model_relations[$relationName][$index_in_cache]
805
+			)
806
+			) {
807
+				$obj_removed = $this->_model_relations[$relationName][$index_in_cache];
808
+				unset($this->_model_relations[$relationName][$index_in_cache]);
809
+			} else {
810
+				//that thing was never cached anyways.
811
+				$obj_removed = null;
812
+			}
813
+		}
814
+		return $obj_removed;
815
+	}
816
+
817
+
818
+
819
+	/**
820
+	 * update_cache_after_object_save
821
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
822
+	 * obtained after being saved to the db
823
+	 *
824
+	 * @param string         $relationName       - the type of object that is cached
825
+	 * @param EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
826
+	 * @param string         $current_cache_id   - the ID that was used when originally caching the object
827
+	 * @return boolean TRUE on success, FALSE on fail
828
+	 * @throws EE_Error
829
+	 */
830
+	public function update_cache_after_object_save(
831
+		$relationName,
832
+		EE_Base_Class $newly_saved_object,
833
+		$current_cache_id = ''
834
+	) {
835
+		// verify that incoming object is of the correct type
836
+		$obj_class = 'EE_' . $relationName;
837
+		if ($newly_saved_object instanceof $obj_class) {
838
+			/* @type EE_Base_Class $newly_saved_object */
839
+			// now get the type of relation
840
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
841
+			// if this is a 1:1 relationship
842
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
843
+				// then just replace the cached object with the newly saved object
844
+				$this->_model_relations[$relationName] = $newly_saved_object;
845
+				return true;
846
+				// or if it's some kind of sordid feral polyamorous relationship...
847
+			} elseif (is_array($this->_model_relations[$relationName])
848
+					  && isset($this->_model_relations[$relationName][$current_cache_id])
849
+			) {
850
+				// then remove the current cached item
851
+				unset($this->_model_relations[$relationName][$current_cache_id]);
852
+				// and cache the newly saved object using it's new ID
853
+				$this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
854
+				return true;
855
+			}
856
+		}
857
+		return false;
858
+	}
859
+
860
+
861
+
862
+	/**
863
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
864
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
865
+	 *
866
+	 * @param string $relationName
867
+	 * @return EE_Base_Class
868
+	 */
869
+	public function get_one_from_cache($relationName)
870
+	{
871
+		$cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
872
+			: null;
873
+		if (is_array($cached_array_or_object)) {
874
+			return array_shift($cached_array_or_object);
875
+		} else {
876
+			return $cached_array_or_object;
877
+		}
878
+	}
879
+
880
+
881
+	/**
882
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
883
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
884
+	 *
885
+	 * @param string $relationName
886
+	 * @throws \ReflectionException
887
+	 * @throws InvalidArgumentException
888
+	 * @throws InvalidInterfaceException
889
+	 * @throws InvalidDataTypeException
890
+	 * @throws EE_Error
891
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
892
+	 */
893
+	public function get_all_from_cache($relationName)
894
+	{
895
+		$objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
896
+		// if the result is not an array, but exists, make it an array
897
+		$objects = is_array($objects) ? $objects : array($objects);
898
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
899
+		//basically, if this model object was stored in the session, and these cached model objects
900
+		//already have IDs, let's make sure they're in their model's entity mapper
901
+		//otherwise we will have duplicates next time we call
902
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
903
+		$model = EE_Registry::instance()->load_model($relationName);
904
+		foreach ($objects as $model_object) {
905
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
906
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
907
+				if ($model_object->ID()) {
908
+					$model->add_to_entity_map($model_object);
909
+				}
910
+			} else {
911
+				throw new EE_Error(
912
+					sprintf(
913
+						__(
914
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
915
+							'event_espresso'
916
+						),
917
+						$relationName,
918
+						gettype($model_object)
919
+					)
920
+				);
921
+			}
922
+		}
923
+		return $objects;
924
+	}
925
+
926
+
927
+
928
+	/**
929
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
930
+	 * matching the given query conditions.
931
+	 *
932
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
933
+	 * @param int   $limit              How many objects to return.
934
+	 * @param array $query_params       Any additional conditions on the query.
935
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
936
+	 *                                  you can indicate just the columns you want returned
937
+	 * @return array|EE_Base_Class[]
938
+	 * @throws EE_Error
939
+	 */
940
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
941
+	{
942
+		$model = $this->get_model();
943
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
944
+			? $model->get_primary_key_field()->get_name()
945
+			: $field_to_order_by;
946
+		$current_value = ! empty($field) ? $this->get($field) : null;
947
+		if (empty($field) || empty($current_value)) {
948
+			return array();
949
+		}
950
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
951
+	}
952
+
953
+
954
+
955
+	/**
956
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
957
+	 * matching the given query conditions.
958
+	 *
959
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
960
+	 * @param int   $limit              How many objects to return.
961
+	 * @param array $query_params       Any additional conditions on the query.
962
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
963
+	 *                                  you can indicate just the columns you want returned
964
+	 * @return array|EE_Base_Class[]
965
+	 * @throws EE_Error
966
+	 */
967
+	public function previous_x(
968
+		$field_to_order_by = null,
969
+		$limit = 1,
970
+		$query_params = array(),
971
+		$columns_to_select = null
972
+	) {
973
+		$model = $this->get_model();
974
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
975
+			? $model->get_primary_key_field()->get_name()
976
+			: $field_to_order_by;
977
+		$current_value = ! empty($field) ? $this->get($field) : null;
978
+		if (empty($field) || empty($current_value)) {
979
+			return array();
980
+		}
981
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
982
+	}
983
+
984
+
985
+
986
+	/**
987
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
988
+	 * matching the given query conditions.
989
+	 *
990
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
991
+	 * @param array $query_params       Any additional conditions on the query.
992
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
993
+	 *                                  you can indicate just the columns you want returned
994
+	 * @return array|EE_Base_Class
995
+	 * @throws EE_Error
996
+	 */
997
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
998
+	{
999
+		$model = $this->get_model();
1000
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1001
+			? $model->get_primary_key_field()->get_name()
1002
+			: $field_to_order_by;
1003
+		$current_value = ! empty($field) ? $this->get($field) : null;
1004
+		if (empty($field) || empty($current_value)) {
1005
+			return array();
1006
+		}
1007
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1008
+	}
1009
+
1010
+
1011
+
1012
+	/**
1013
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1014
+	 * matching the given query conditions.
1015
+	 *
1016
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1017
+	 * @param array $query_params       Any additional conditions on the query.
1018
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1019
+	 *                                  you can indicate just the column you want returned
1020
+	 * @return array|EE_Base_Class
1021
+	 * @throws EE_Error
1022
+	 */
1023
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1024
+	{
1025
+		$model = $this->get_model();
1026
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1027
+			? $model->get_primary_key_field()->get_name()
1028
+			: $field_to_order_by;
1029
+		$current_value = ! empty($field) ? $this->get($field) : null;
1030
+		if (empty($field) || empty($current_value)) {
1031
+			return array();
1032
+		}
1033
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1034
+	}
1035
+
1036
+
1037
+
1038
+	/**
1039
+	 * Overrides parent because parent expects old models.
1040
+	 * This also doesn't do any validation, and won't work for serialized arrays
1041
+	 *
1042
+	 * @param string $field_name
1043
+	 * @param mixed  $field_value_from_db
1044
+	 * @throws EE_Error
1045
+	 */
1046
+	public function set_from_db($field_name, $field_value_from_db)
1047
+	{
1048
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1049
+		if ($field_obj instanceof EE_Model_Field_Base) {
1050
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
1051
+			//eg, a CPT model object could have an entry in the posts table, but no
1052
+			//entry in the meta table. Meaning that all its columns in the meta table
1053
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
1054
+			if ($field_value_from_db === null) {
1055
+				if ($field_obj->is_nullable()) {
1056
+					//if the field allows nulls, then let it be null
1057
+					$field_value = null;
1058
+				} else {
1059
+					$field_value = $field_obj->get_default_value();
1060
+				}
1061
+			} else {
1062
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1063
+			}
1064
+			$this->_fields[$field_name] = $field_value;
1065
+			$this->_clear_cached_property($field_name);
1066
+		}
1067
+	}
1068
+
1069
+
1070
+
1071
+	/**
1072
+	 * verifies that the specified field is of the correct type
1073
+	 *
1074
+	 * @param string $field_name
1075
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1076
+	 *                                (in cases where the same property may be used for different outputs
1077
+	 *                                - i.e. datetime, money etc.)
1078
+	 * @return mixed
1079
+	 * @throws EE_Error
1080
+	 */
1081
+	public function get($field_name, $extra_cache_ref = null)
1082
+	{
1083
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1084
+	}
1085
+
1086
+
1087
+
1088
+	/**
1089
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1090
+	 *
1091
+	 * @param  string $field_name A valid fieldname
1092
+	 * @return mixed              Whatever the raw value stored on the property is.
1093
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1094
+	 */
1095
+	public function get_raw($field_name)
1096
+	{
1097
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1098
+		switch(true){
1099
+			case $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime:
1100
+				$value = $this->_fields[$field_name]->format('U');
1101
+				break;
1102
+			case $field_settings instanceof EE_Money_Field && $this->_fields[$field_name] instanceof Money:
1103
+				$value = $this->_fields[$field_name]->floatAmount();
1104
+				break;
1105
+			default:
1106
+				$value = $this->_fields[$field_name];
1107
+		}
1108
+		return $value;
1109
+	}
1110
+
1111
+
1112
+
1113
+	/**
1114
+	 * This is used to return the internal DateTime object used for a field that is a
1115
+	 * EE_Datetime_Field.
1116
+	 *
1117
+	 * @param string $field_name               The field name retrieving the DateTime object.
1118
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1119
+	 * @throws EE_Error
1120
+	 *                                         an error is set and false returned.  If the field IS an
1121
+	 *                                         EE_Datetime_Field and but the field value is null, then
1122
+	 *                                         just null is returned (because that indicates that likely
1123
+	 *                                         this field is nullable).
1124
+	 */
1125
+	public function get_DateTime_object($field_name)
1126
+	{
1127
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1128
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1129
+			EE_Error::add_error(
1130
+				sprintf(
1131
+					__(
1132
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1133
+						'event_espresso'
1134
+					),
1135
+					$field_name
1136
+				),
1137
+				__FILE__,
1138
+				__FUNCTION__,
1139
+				__LINE__
1140
+			);
1141
+			return false;
1142
+		}
1143
+		return $this->_fields[$field_name];
1144
+	}
1145
+
1146
+
1147
+	/**
1148
+	 * Gets a Money object for the specified field. Please note that this should only be
1149
+	 * used for fields corresponding to EE_Money_Fields, and it will always return a money object,
1150
+	 * or else it will throw an exception.
1151
+	 *
1152
+	 * @param $field_name
1153
+	 * @return Money
1154
+	 * @throws InvalidEntityException
1155
+	 * @throws EE_Error
1156
+	 * @throws DomainException
1157
+	 */
1158
+	public function getMoneyObject($field_name)
1159
+	{
1160
+		$this->verifyUsesMoney(__FUNCTION__);
1161
+		$field = $this->get_model()->field_settings_for($field_name);
1162
+		$value = isset($this->_fields[$field_name]) ? $this->_fields[$field_name] : null;
1163
+		if (! $field instanceof EE_Money_Field
1164
+			|| ! $value instanceof Money) {
1165
+			throw new InvalidEntityException(
1166
+				get_class($value),
1167
+				'Money',
1168
+				sprintf(
1169
+					esc_html__(
1170
+						// @codingStandardsIgnoreStart
1171
+						'Tried to retrieve money value from %1$s with ID %2$s from field %3$s but no money object present.',
1172
+						// @codingStandardsIgnoreEnd
1173
+						'event_espresso'
1174
+					),
1175
+					get_class($this),
1176
+					$this->ID(),
1177
+					$field_name
1178
+				)
1179
+			);
1180
+		}
1181
+		return $value;
1182
+	}
1183
+
1184
+
1185
+
1186
+	/**
1187
+	 * To be used in template to immediately echo out the value, and format it for output.
1188
+	 * Eg, should call stripslashes and whatnot before echoing
1189
+	 *
1190
+	 * @param string $field_name      the name of the field as it appears in the DB
1191
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1192
+	 *                                (in cases where the same property may be used for different outputs
1193
+	 *                                - i.e. datetime, money etc.)
1194
+	 * @return void
1195
+	 * @throws EE_Error
1196
+	 */
1197
+	public function e($field_name, $extra_cache_ref = null)
1198
+	{
1199
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1206
+	 * can be easily used as the value of form input.
1207
+	 *
1208
+	 * @param string $field_name
1209
+	 * @return void
1210
+	 * @throws EE_Error
1211
+	 */
1212
+	public function f($field_name)
1213
+	{
1214
+		$this->e($field_name, 'form_input');
1215
+	}
1216
+
1217
+	/**
1218
+	 * Same as `f()` but just returns the value instead of echoing it
1219
+	 * @param string $field_name
1220
+	 * @return string
1221
+	 * @throws EE_Error
1222
+	 */
1223
+	public function get_f($field_name)
1224
+	{
1225
+		return (string)$this->get_pretty($field_name,'form_input');
1226
+	}
1227
+
1228
+
1229
+
1230
+	/**
1231
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1232
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1233
+	 * to see what options are available.
1234
+	 * @param string $field_name
1235
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1236
+	 *                                (in cases where the same property may be used for different outputs
1237
+	 *                                - i.e. datetime, money etc.)
1238
+	 * @return mixed
1239
+	 * @throws EE_Error
1240
+	 */
1241
+	public function get_pretty($field_name, $extra_cache_ref = null)
1242
+	{
1243
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1244
+	}
1245
+
1246
+
1247
+
1248
+	/**
1249
+	 * This simply returns the datetime for the given field name
1250
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1251
+	 * (and the equivalent e_date, e_time, e_datetime).
1252
+	 *
1253
+	 * @access   protected
1254
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1255
+	 * @param string   $dt_frmt      valid datetime format used for date
1256
+	 *                               (if '' then we just use the default on the field,
1257
+	 *                               if NULL we use the last-used format)
1258
+	 * @param string   $tm_frmt      Same as above except this is for time format
1259
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1260
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1261
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1262
+	 *                               if field is not a valid dtt field, or void if echoing
1263
+	 * @throws EE_Error
1264
+	 */
1265
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1266
+	{
1267
+		// clear cached property
1268
+		$this->_clear_cached_property($field_name);
1269
+		//reset format properties because they are used in get()
1270
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1271
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1272
+		if ($echo) {
1273
+			$this->e($field_name, $date_or_time);
1274
+			return '';
1275
+		}
1276
+		return $this->get($field_name, $date_or_time);
1277
+	}
1278
+
1279
+
1280
+
1281
+	/**
1282
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1283
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1284
+	 * other echoes the pretty value for dtt)
1285
+	 *
1286
+	 * @param  string $field_name name of model object datetime field holding the value
1287
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1288
+	 * @return string            datetime value formatted
1289
+	 * @throws EE_Error
1290
+	 */
1291
+	public function get_date($field_name, $format = '')
1292
+	{
1293
+		return $this->_get_datetime($field_name, $format, null, 'D');
1294
+	}
1295
+
1296
+
1297
+
1298
+	/**
1299
+	 * @param      $field_name
1300
+	 * @param string $format
1301
+	 * @throws EE_Error
1302
+	 */
1303
+	public function e_date($field_name, $format = '')
1304
+	{
1305
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1306
+	}
1307
+
1308
+
1309
+
1310
+	/**
1311
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1312
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1313
+	 * other echoes the pretty value for dtt)
1314
+	 *
1315
+	 * @param  string $field_name name of model object datetime field holding the value
1316
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1317
+	 * @return string             datetime value formatted
1318
+	 * @throws EE_Error
1319
+	 */
1320
+	public function get_time($field_name, $format = '')
1321
+	{
1322
+		return $this->_get_datetime($field_name, null, $format, 'T');
1323
+	}
1324
+
1325
+
1326
+
1327
+	/**
1328
+	 * @param      $field_name
1329
+	 * @param string $format
1330
+	 * @throws EE_Error
1331
+	 */
1332
+	public function e_time($field_name, $format = '')
1333
+	{
1334
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1335
+	}
1336
+
1337
+
1338
+
1339
+	/**
1340
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1341
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1342
+	 * other echoes the pretty value for dtt)
1343
+	 *
1344
+	 * @param  string $field_name name of model object datetime field holding the value
1345
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1346
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1347
+	 * @return string             datetime value formatted
1348
+	 * @throws EE_Error
1349
+	 */
1350
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1351
+	{
1352
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1353
+	}
1354
+
1355
+
1356
+
1357
+	/**
1358
+	 * @param string $field_name
1359
+	 * @param string $dt_frmt
1360
+	 * @param string $tm_frmt
1361
+	 * @throws EE_Error
1362
+	 */
1363
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1364
+	{
1365
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1366
+	}
1367
+
1368
+
1369
+	/**
1370
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1371
+	 *
1372
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1373
+	 * @param string $format PHP valid date/time string format.  If none is provided then the internal set format
1374
+	 *                           on the object will be used.
1375
+	 * @return string Date and time string in set locale or false if no field exists for the given
1376
+	 * @throws InvalidArgumentException
1377
+	 * @throws InvalidInterfaceException
1378
+	 * @throws InvalidDataTypeException
1379
+	 * @throws EE_Error
1380
+	 *                           field name.
1381
+	 */
1382
+	public function get_i18n_datetime($field_name, $format = '')
1383
+	{
1384
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1385
+		return date_i18n(
1386
+			$format,
1387
+			EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1388
+		);
1389
+	}
1390
+
1391
+
1392
+
1393
+	/**
1394
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1395
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1396
+	 * thrown.
1397
+	 *
1398
+	 * @param  string $field_name The field name being checked
1399
+	 * @throws EE_Error
1400
+	 * @return EE_Datetime_Field
1401
+	 */
1402
+	protected function _get_dtt_field_settings($field_name)
1403
+	{
1404
+		$field = $this->get_model()->field_settings_for($field_name);
1405
+		//check if field is dtt
1406
+		if ($field instanceof EE_Datetime_Field) {
1407
+			return $field;
1408
+		} else {
1409
+			throw new EE_Error(sprintf(__('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',
1410
+				'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1411
+		}
1412
+	}
1413
+
1414
+
1415
+
1416
+
1417
+	/**
1418
+	 * NOTE ABOUT BELOW:
1419
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1420
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1421
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1422
+	 * method and make sure you send the entire datetime value for setting.
1423
+	 */
1424
+	/**
1425
+	 * sets the time on a datetime property
1426
+	 *
1427
+	 * @access protected
1428
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1429
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1430
+	 * @throws EE_Error
1431
+	 */
1432
+	protected function _set_time_for($time, $fieldname)
1433
+	{
1434
+		$this->_set_date_time('T', $time, $fieldname);
1435
+	}
1436
+
1437
+
1438
+
1439
+	/**
1440
+	 * sets the date on a datetime property
1441
+	 *
1442
+	 * @access protected
1443
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1444
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1445
+	 * @throws EE_Error
1446
+	 */
1447
+	protected function _set_date_for($date, $fieldname)
1448
+	{
1449
+		$this->_set_date_time('D', $date, $fieldname);
1450
+	}
1451
+
1452
+
1453
+	/**
1454
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1455
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1456
+	 *
1457
+	 * @access protected
1458
+	 * @param string $what "T" for time, 'B' for both, 'D' for Date.
1459
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1460
+	 * @param string $fieldname the name of the field the date OR time is being set on (must match a
1461
+	 *                                        EE_Datetime_Field property)
1462
+	 * @throws InvalidArgumentException
1463
+	 * @throws InvalidInterfaceException
1464
+	 * @throws InvalidDataTypeException
1465
+	 * @throws EE_Error
1466
+	 */
1467
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1468
+	{
1469
+		$field = $this->_get_dtt_field_settings($fieldname);
1470
+		$field->set_timezone($this->_timezone);
1471
+		$field->set_date_format($this->_dt_frmt);
1472
+		$field->set_time_format($this->_tm_frmt);
1473
+		switch ($what) {
1474
+			case 'T' :
1475
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1476
+					$datetime_value,
1477
+					$this->_fields[$fieldname]
1478
+				);
1479
+				break;
1480
+			case 'D' :
1481
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1482
+					$datetime_value,
1483
+					$this->_fields[$fieldname]
1484
+				);
1485
+				break;
1486
+			case 'B' :
1487
+				$this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1488
+				break;
1489
+		}
1490
+		$this->_clear_cached_property($fieldname);
1491
+	}
1492
+
1493
+
1494
+	/**
1495
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1496
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1497
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1498
+	 * that could lead to some unexpected results!
1499
+	 *
1500
+	 * @access public
1501
+	 * @param string $field_name This is the name of the field on the object that contains the date/time
1502
+	 *                                         value being returned.
1503
+	 * @param string $callback must match a valid method in this class (defaults to get_datetime)
1504
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1505
+	 * @param string $prepend You can include something to prepend on the timestamp
1506
+	 * @param string $append You can include something to append on the timestamp
1507
+	 * @throws InvalidArgumentException
1508
+	 * @throws InvalidInterfaceException
1509
+	 * @throws InvalidDataTypeException
1510
+	 * @throws EE_Error
1511
+	 * @return string timestamp
1512
+	 */
1513
+	public function display_in_my_timezone(
1514
+		$field_name,
1515
+		$callback = 'get_datetime',
1516
+		$args = null,
1517
+		$prepend = '',
1518
+		$append = ''
1519
+	) {
1520
+		$timezone = EEH_DTT_Helper::get_timezone();
1521
+		if ($timezone === $this->_timezone) {
1522
+			return '';
1523
+		}
1524
+		$original_timezone = $this->_timezone;
1525
+		$this->set_timezone($timezone);
1526
+		$fn = (array)$field_name;
1527
+		$args = array_merge($fn, (array)$args);
1528
+		if ( ! method_exists($this, $callback)) {
1529
+			throw new EE_Error(
1530
+				sprintf(
1531
+					__(
1532
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1533
+						'event_espresso'
1534
+					),
1535
+					$callback
1536
+				)
1537
+			);
1538
+		}
1539
+		$args = (array)$args;
1540
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1541
+		$this->set_timezone($original_timezone);
1542
+		return $return;
1543
+	}
1544
+
1545
+
1546
+
1547
+	/**
1548
+	 * Deletes this model object.
1549
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1550
+	 * override
1551
+	 * `EE_Base_Class::_delete` NOT this class.
1552
+	 *
1553
+	 * @return boolean | int
1554
+	 * @throws EE_Error
1555
+	 */
1556
+	public function delete()
1557
+	{
1558
+		/**
1559
+		 * Called just before the `EE_Base_Class::_delete` method call.
1560
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1561
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1562
+		 * soft deletes (trash) the object and does not permanently delete it.
1563
+		 *
1564
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1565
+		 */
1566
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1567
+		$result = $this->_delete();
1568
+		/**
1569
+		 * Called just after the `EE_Base_Class::_delete` method call.
1570
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1571
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1572
+		 * soft deletes (trash) the object and does not permanently delete it.
1573
+		 *
1574
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1575
+		 * @param boolean       $result
1576
+		 */
1577
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1578
+		return $result;
1579
+	}
1580
+
1581
+
1582
+
1583
+	/**
1584
+	 * Calls the specific delete method for the instantiated class.
1585
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1586
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1587
+	 * `EE_Base_Class::delete`
1588
+	 *
1589
+	 * @return bool|int
1590
+	 * @throws EE_Error
1591
+	 */
1592
+	protected function _delete()
1593
+	{
1594
+		return $this->delete_permanently();
1595
+	}
1596
+
1597
+
1598
+
1599
+	/**
1600
+	 * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1601
+	 * error)
1602
+	 *
1603
+	 * @return bool | int
1604
+	 * @throws EE_Error
1605
+	 */
1606
+	public function delete_permanently()
1607
+	{
1608
+		/**
1609
+		 * Called just before HARD deleting a model object
1610
+		 *
1611
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1612
+		 */
1613
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1614
+		$model = $this->get_model();
1615
+		$result = $model->delete_permanently_by_ID($this->ID());
1616
+		$this->refresh_cache_of_related_objects();
1617
+		/**
1618
+		 * Called just after HARD deleting a model object
1619
+		 *
1620
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1621
+		 * @param boolean       $result
1622
+		 */
1623
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1624
+		return $result;
1625
+	}
1626
+
1627
+
1628
+
1629
+	/**
1630
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1631
+	 * related model objects
1632
+	 *
1633
+	 * @throws EE_Error
1634
+	 */
1635
+	public function refresh_cache_of_related_objects()
1636
+	{
1637
+		$model = $this->get_model();
1638
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1639
+			if ( ! empty($this->_model_relations[$relation_name])) {
1640
+				$related_objects = $this->_model_relations[$relation_name];
1641
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1642
+					//this relation only stores a single model object, not an array
1643
+					//but let's make it consistent
1644
+					$related_objects = array($related_objects);
1645
+				}
1646
+				foreach ($related_objects as $related_object) {
1647
+					//only refresh their cache if they're in memory
1648
+					if ($related_object instanceof EE_Base_Class) {
1649
+						$related_object->clear_cache($model->get_this_model_name(), $this);
1650
+					}
1651
+				}
1652
+			}
1653
+		}
1654
+	}
1655
+
1656
+
1657
+
1658
+	/**
1659
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1660
+	 * object just before saving.
1661
+	 *
1662
+	 * @access public
1663
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1664
+	 *                                 if provided during the save() method (often client code will change the fields'
1665
+	 *                                 values before calling save)
1666
+	 * @throws EE_Error
1667
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1668
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1669
+	 */
1670
+	public function save($set_cols_n_values = array())
1671
+	{
1672
+		$model = $this->get_model();
1673
+		/**
1674
+		 * Filters the fields we're about to save on the model object
1675
+		 *
1676
+		 * @param array         $set_cols_n_values
1677
+		 * @param EE_Base_Class $model_object
1678
+		 */
1679
+		$set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1680
+			$this);
1681
+		//set attributes as provided in $set_cols_n_values
1682
+		foreach ($set_cols_n_values as $column => $value) {
1683
+			$this->set($column, $value);
1684
+		}
1685
+		// no changes ? then don't do anything
1686
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1687
+			return 0;
1688
+		}
1689
+		/**
1690
+		 * Saving a model object.
1691
+		 * Before we perform a save, this action is fired.
1692
+		 *
1693
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1694
+		 */
1695
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1696
+		if ( ! $this->allow_persist()) {
1697
+			return 0;
1698
+		}
1699
+		//now get current attribute values
1700
+		$save_cols_n_values = $this->_fields;
1701
+		//if the object already has an ID, update it. Otherwise, insert it
1702
+		//also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1703
+		$old_assumption_concerning_value_preparation = $model
1704
+															->get_assumption_concerning_values_already_prepared_by_model_object();
1705
+		$model->assume_values_already_prepared_by_model_object(true);
1706
+		//does this model have an autoincrement PK?
1707
+		if ($model->has_primary_key_field()) {
1708
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1709
+				//ok check if it's set, if so: update; if not, insert
1710
+				if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1711
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1712
+				} else {
1713
+					unset($save_cols_n_values[$model->primary_key_name()]);
1714
+					$results = $model->insert($save_cols_n_values);
1715
+					if ($results) {
1716
+						//if successful, set the primary key
1717
+						//but don't use the normal SET method, because it will check if
1718
+						//an item with the same ID exists in the mapper & db, then
1719
+						//will find it in the db (because we just added it) and THAT object
1720
+						//will get added to the mapper before we can add this one!
1721
+						//but if we just avoid using the SET method, all that headache can be avoided
1722
+						$pk_field_name = $model->primary_key_name();
1723
+						$this->_fields[$pk_field_name] = $results;
1724
+						$this->_clear_cached_property($pk_field_name);
1725
+						$model->add_to_entity_map($this);
1726
+						$this->_update_cached_related_model_objs_fks();
1727
+					}
1728
+				}
1729
+			} else {//PK is NOT auto-increment
1730
+				//so check if one like it already exists in the db
1731
+				if ($model->exists_by_ID($this->ID())) {
1732
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1733
+						throw new EE_Error(
1734
+							sprintf(
1735
+								__('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',
1736
+									'event_espresso'),
1737
+								get_class($this),
1738
+								get_class($model) . '::instance()->add_to_entity_map()',
1739
+								get_class($model) . '::instance()->get_one_by_ID()',
1740
+								'<br />'
1741
+							)
1742
+						);
1743
+					}
1744
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1745
+				} else {
1746
+					$results = $model->insert($save_cols_n_values);
1747
+					$this->_update_cached_related_model_objs_fks();
1748
+				}
1749
+			}
1750
+		} else {//there is NO primary key
1751
+			$already_in_db = false;
1752
+			foreach ($model->unique_indexes() as $index) {
1753
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1754
+				if ($model->exists(array($uniqueness_where_params))) {
1755
+					$already_in_db = true;
1756
+				}
1757
+			}
1758
+			if ($already_in_db) {
1759
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1760
+					$model->get_combined_primary_key_fields());
1761
+				$results = $model->update($save_cols_n_values, $combined_pk_fields_n_values);
1762
+			} else {
1763
+				$results = $model->insert($save_cols_n_values);
1764
+			}
1765
+		}
1766
+		//restore the old assumption about values being prepared by the model object
1767
+		$model
1768
+			 ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1769
+		/**
1770
+		 * After saving the model object this action is called
1771
+		 *
1772
+		 * @param EE_Base_Class $model_object which was just saved
1773
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1774
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1775
+		 */
1776
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1777
+		$this->_has_changes = false;
1778
+		return $results;
1779
+	}
1780
+
1781
+
1782
+
1783
+	/**
1784
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1785
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1786
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1787
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1788
+	 * 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
1789
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1790
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1791
+	 *
1792
+	 * @return void
1793
+	 * @throws EE_Error
1794
+	 */
1795
+	protected function _update_cached_related_model_objs_fks()
1796
+	{
1797
+		$model = $this->get_model();
1798
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1799
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1800
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1801
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1802
+						$model->get_this_model_name()
1803
+					);
1804
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1805
+					if ($related_model_obj_in_cache->ID()) {
1806
+						$related_model_obj_in_cache->save();
1807
+					}
1808
+				}
1809
+			}
1810
+		}
1811
+	}
1812
+
1813
+
1814
+
1815
+	/**
1816
+	 * Saves this model object and its NEW cached relations to the database.
1817
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1818
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1819
+	 * because otherwise, there's a potential for infinite looping of saving
1820
+	 * Saves the cached related model objects, and ensures the relation between them
1821
+	 * and this object and properly setup
1822
+	 *
1823
+	 * @return int ID of new model object on save; 0 on failure+
1824
+	 * @throws EE_Error
1825
+	 */
1826
+	public function save_new_cached_related_model_objs()
1827
+	{
1828
+		//make sure this has been saved
1829
+		if ( ! $this->ID()) {
1830
+			$id = $this->save();
1831
+		} else {
1832
+			$id = $this->ID();
1833
+		}
1834
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1835
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1836
+			if ($this->_model_relations[$relationName]) {
1837
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1838
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1839
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1840
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1841
+					//but ONLY if it DOES NOT exist in the DB
1842
+					/* @var $related_model_obj EE_Base_Class */
1843
+					$related_model_obj = $this->_model_relations[$relationName];
1844
+					//					if( ! $related_model_obj->ID()){
1845
+					$this->_add_relation_to($related_model_obj, $relationName);
1846
+					$related_model_obj->save_new_cached_related_model_objs();
1847
+					//					}
1848
+				} else {
1849
+					foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1850
+						//add a relation to that relation type (which saves the appropriate thing in the process)
1851
+						//but ONLY if it DOES NOT exist in the DB
1852
+						//						if( ! $related_model_obj->ID()){
1853
+						$this->_add_relation_to($related_model_obj, $relationName);
1854
+						$related_model_obj->save_new_cached_related_model_objs();
1855
+						//						}
1856
+					}
1857
+				}
1858
+			}
1859
+		}
1860
+		return $id;
1861
+	}
1862
+
1863
+
1864
+
1865
+	/**
1866
+	 * for getting a model while instantiated.
1867
+	 *
1868
+	 * @return EEM_Base | EEM_CPT_Base
1869
+	 */
1870
+	public function get_model()
1871
+	{
1872
+		if( ! $this->_model){
1873
+			$modelName = self::_get_model_classname(get_class($this));
1874
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1875
+		} else {
1876
+			$this->_model->set_timezone($this->_timezone);
1877
+		}
1878
+
1879
+		return $this->_model;
1880
+	}
1881
+
1882
+
1883
+
1884
+	/**
1885
+	 * @param $props_n_values
1886
+	 * @param $classname
1887
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1888
+	 * @throws EE_Error
1889
+	 */
1890
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1891
+	{
1892
+		//TODO: will not work for Term_Relationships because they have no PK!
1893
+		$primary_id_ref = self::_get_primary_key_name($classname);
1894
+		if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1895
+			$id = $props_n_values[$primary_id_ref];
1896
+			return self::_get_model($classname)->get_from_entity_map($id);
1897
+		}
1898
+		return false;
1899
+	}
1900
+
1901
+
1902
+
1903
+	/**
1904
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1905
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1906
+	 * 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
1907
+	 * we return false.
1908
+	 *
1909
+	 * @param  array  $props_n_values   incoming array of properties and their values
1910
+	 * @param  string $classname        the classname of the child class
1911
+	 * @param null    $timezone
1912
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
1913
+	 *                                  date_format and the second value is the time format
1914
+	 * @return mixed (EE_Base_Class|bool)
1915
+	 * @throws EE_Error
1916
+	 */
1917
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1918
+	{
1919
+		$existing = null;
1920
+		$model = self::_get_model($classname, $timezone);
1921
+		if ($model->has_primary_key_field()) {
1922
+			$primary_id_ref = self::_get_primary_key_name($classname);
1923
+			if (array_key_exists($primary_id_ref, $props_n_values)
1924
+				&& ! empty($props_n_values[$primary_id_ref])
1925
+			) {
1926
+				$existing = $model->get_one_by_ID(
1927
+					$props_n_values[$primary_id_ref]
1928
+				);
1929
+			}
1930
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
1931
+			//no primary key on this model, but there's still a matching item in the DB
1932
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1933
+				self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1934
+			);
1935
+		}
1936
+		if ($existing) {
1937
+			//set date formats if present before setting values
1938
+			if ( ! empty($date_formats) && is_array($date_formats)) {
1939
+				$existing->set_date_format($date_formats[0]);
1940
+				$existing->set_time_format($date_formats[1]);
1941
+			} else {
1942
+				//set default formats for date and time
1943
+				$existing->set_date_format(get_option('date_format'));
1944
+				$existing->set_time_format(get_option('time_format'));
1945
+			}
1946
+			foreach ($props_n_values as $property => $field_value) {
1947
+				$existing->set($property, $field_value);
1948
+			}
1949
+			return $existing;
1950
+		} else {
1951
+			return false;
1952
+		}
1953
+	}
1954
+
1955
+
1956
+
1957
+	/**
1958
+	 * Gets the EEM_*_Model for this class
1959
+	 *
1960
+	 * @access public now, as this is more convenient
1961
+	 * @param      $classname
1962
+	 * @param null $timezone
1963
+	 * @throws EE_Error
1964
+	 * @return EEM_Base
1965
+	 */
1966
+	protected static function _get_model($classname, $timezone = null)
1967
+	{
1968
+		//find model for this class
1969
+		if ( ! $classname) {
1970
+			throw new EE_Error(
1971
+				sprintf(
1972
+					__(
1973
+						"What were you thinking calling _get_model(%s)?? You need to specify the class name",
1974
+						"event_espresso"
1975
+					),
1976
+					$classname
1977
+				)
1978
+			);
1979
+		}
1980
+		$modelName = self::_get_model_classname($classname);
1981
+		return self::_get_model_instance_with_name($modelName, $timezone);
1982
+	}
1983
+
1984
+
1985
+	/**
1986
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1987
+	 *
1988
+	 * @param string $model_classname
1989
+	 * @param null $timezone
1990
+	 * @return EEM_Base
1991
+	 * @throws \ReflectionException
1992
+	 * @throws InvalidArgumentException
1993
+	 * @throws InvalidInterfaceException
1994
+	 * @throws InvalidDataTypeException
1995
+	 * @throws EE_Error
1996
+	 */
1997
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1998
+	{
1999
+		$model_classname = str_replace('EEM_', '', $model_classname);
2000
+		$model = EE_Registry::instance()->load_model($model_classname);
2001
+		$model->set_timezone($timezone);
2002
+		return $model;
2003
+	}
2004
+
2005
+
2006
+
2007
+	/**
2008
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
2009
+	 * Also works if a model class's classname is provided (eg EE_Registration).
2010
+	 *
2011
+	 * @param null $model_name
2012
+	 * @return string like EEM_Attendee
2013
+	 */
2014
+	private static function _get_model_classname($model_name = null)
2015
+	{
2016
+		if (strpos($model_name, "EE_") === 0) {
2017
+			$model_classname = str_replace("EE_", "EEM_", $model_name);
2018
+		} else {
2019
+			$model_classname = "EEM_" . $model_name;
2020
+		}
2021
+		return $model_classname;
2022
+	}
2023
+
2024
+
2025
+
2026
+	/**
2027
+	 * returns the name of the primary key attribute
2028
+	 *
2029
+	 * @param null $classname
2030
+	 * @throws EE_Error
2031
+	 * @return string
2032
+	 */
2033
+	protected static function _get_primary_key_name($classname = null)
2034
+	{
2035
+		if ( ! $classname) {
2036
+			throw new EE_Error(
2037
+				sprintf(
2038
+					__("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
2039
+					$classname
2040
+				)
2041
+			);
2042
+		}
2043
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2044
+	}
2045
+
2046
+
2047
+
2048
+	/**
2049
+	 * Gets the value of the primary key.
2050
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2051
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2052
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2053
+	 *
2054
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2055
+	 * @throws EE_Error
2056
+	 */
2057
+	public function ID()
2058
+	{
2059
+		$model = $this->get_model();
2060
+		//now that we know the name of the variable, use a variable variable to get its value and return its
2061
+		if ($model->has_primary_key_field()) {
2062
+			return $this->_fields[$model->primary_key_name()];
2063
+		} else {
2064
+			return $model->get_index_primary_key_string($this->_fields);
2065
+		}
2066
+	}
2067
+
2068
+
2069
+
2070
+	/**
2071
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2072
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2073
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2074
+	 *
2075
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2076
+	 * @param string $relationName                     eg 'Events','Question',etc.
2077
+	 *                                                 an attendee to a group, you also want to specify which role they
2078
+	 *                                                 will have in that group. So you would use this parameter to
2079
+	 *                                                 specify array('role-column-name'=>'role-id')
2080
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2081
+	 *                                                 allow you to further constrict the relation to being added.
2082
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2083
+	 *                                                 column on the JOIN table and currently only the HABTM models
2084
+	 *                                                 accept these additional conditions.  Also remember that if an
2085
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2086
+	 *                                                 NEW row is created in the join table.
2087
+	 * @param null   $cache_id
2088
+	 * @throws EE_Error
2089
+	 * @return EE_Base_Class the object the relation was added to
2090
+	 */
2091
+	public function _add_relation_to(
2092
+		$otherObjectModelObjectOrID,
2093
+		$relationName,
2094
+		$extra_join_model_fields_n_values = array(),
2095
+		$cache_id = null
2096
+	) {
2097
+		$model = $this->get_model();
2098
+		//if this thing exists in the DB, save the relation to the DB
2099
+		if ($this->ID()) {
2100
+			$otherObject = $model
2101
+								->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2102
+									$extra_join_model_fields_n_values);
2103
+			//clear cache so future get_many_related and get_first_related() return new results.
2104
+			$this->clear_cache($relationName, $otherObject, true);
2105
+			if ($otherObject instanceof EE_Base_Class) {
2106
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2107
+			}
2108
+		} else {
2109
+			//this thing doesn't exist in the DB,  so just cache it
2110
+			if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2111
+				throw new EE_Error(sprintf(
2112
+					__('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',
2113
+						'event_espresso'),
2114
+					$otherObjectModelObjectOrID,
2115
+					get_class($this)
2116
+				));
2117
+			} else {
2118
+				$otherObject = $otherObjectModelObjectOrID;
2119
+			}
2120
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2121
+		}
2122
+		if ($otherObject instanceof EE_Base_Class) {
2123
+			//fix the reciprocal relation too
2124
+			if ($otherObject->ID()) {
2125
+				//its saved so assumed relations exist in the DB, so we can just
2126
+				//clear the cache so future queries use the updated info in the DB
2127
+				$otherObject->clear_cache($model->get_this_model_name(), null, true);
2128
+			} else {
2129
+				//it's not saved, so it caches relations like this
2130
+				$otherObject->cache($model->get_this_model_name(), $this);
2131
+			}
2132
+		}
2133
+		return $otherObject;
2134
+	}
2135
+
2136
+
2137
+
2138
+	/**
2139
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2140
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2141
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2142
+	 * from the cache
2143
+	 *
2144
+	 * @param mixed  $otherObjectModelObjectOrID
2145
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2146
+	 *                to the DB yet
2147
+	 * @param string $relationName
2148
+	 * @param array  $where_query
2149
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2150
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2151
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2152
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2153
+	 *                created in the join table.
2154
+	 * @return EE_Base_Class the relation was removed from
2155
+	 * @throws EE_Error
2156
+	 */
2157
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2158
+	{
2159
+		if ($this->ID()) {
2160
+			//if this exists in the DB, save the relation change to the DB too
2161
+			$otherObject = $this->get_model()
2162
+								->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2163
+									$where_query);
2164
+			$this->clear_cache($relationName, $otherObject);
2165
+		} else {
2166
+			//this doesn't exist in the DB, just remove it from the cache
2167
+			$otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2168
+		}
2169
+		if ($otherObject instanceof EE_Base_Class) {
2170
+			$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2171
+		}
2172
+		return $otherObject;
2173
+	}
2174
+
2175
+
2176
+
2177
+	/**
2178
+	 * Removes ALL the related things for the $relationName.
2179
+	 *
2180
+	 * @param string $relationName
2181
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2182
+	 * @return EE_Base_Class
2183
+	 * @throws EE_Error
2184
+	 */
2185
+	public function _remove_relations($relationName, $where_query_params = array())
2186
+	{
2187
+		if ($this->ID()) {
2188
+			//if this exists in the DB, save the relation change to the DB too
2189
+			$otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2190
+			$this->clear_cache($relationName, null, true);
2191
+		} else {
2192
+			//this doesn't exist in the DB, just remove it from the cache
2193
+			$otherObjects = $this->clear_cache($relationName, null, true);
2194
+		}
2195
+		if (is_array($otherObjects)) {
2196
+			foreach ($otherObjects as $otherObject) {
2197
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2198
+			}
2199
+		}
2200
+		return $otherObjects;
2201
+	}
2202
+
2203
+
2204
+
2205
+	/**
2206
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2207
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2208
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2209
+	 * because we want to get even deleted items etc.
2210
+	 *
2211
+	 * @param string $relationName key in the model's _model_relations array
2212
+	 * @param array  $query_params like EEM_Base::get_all
2213
+	 * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2214
+	 * @throws EE_Error
2215
+	 *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2216
+	 *                             you want IDs
2217
+	 */
2218
+	public function get_many_related($relationName, $query_params = array())
2219
+	{
2220
+		if ($this->ID()) {
2221
+			//this exists in the DB, so get the related things from either the cache or the DB
2222
+			//if there are query parameters, forget about caching the related model objects.
2223
+			if ($query_params) {
2224
+				$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2225
+			} else {
2226
+				//did we already cache the result of this query?
2227
+				$cached_results = $this->get_all_from_cache($relationName);
2228
+				if ( ! $cached_results) {
2229
+					$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2230
+					//if no query parameters were passed, then we got all the related model objects
2231
+					//for that relation. We can cache them then.
2232
+					foreach ($related_model_objects as $related_model_object) {
2233
+						$this->cache($relationName, $related_model_object);
2234
+					}
2235
+				} else {
2236
+					$related_model_objects = $cached_results;
2237
+				}
2238
+			}
2239
+		} else {
2240
+			//this doesn't exist in the DB, so just get the related things from the cache
2241
+			$related_model_objects = $this->get_all_from_cache($relationName);
2242
+		}
2243
+		return $related_model_objects;
2244
+	}
2245
+
2246
+
2247
+	/**
2248
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2249
+	 * unless otherwise specified in the $query_params
2250
+	 *
2251
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2252
+	 * @param array $query_params like EEM_Base::get_all's
2253
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2254
+	 * @param bool $distinct if we want to only count the distinct values for the column then you can trigger
2255
+	 *                               that by the setting $distinct to TRUE;
2256
+	 * @return int
2257
+	 * @throws EE_Error
2258
+	 */
2259
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2260
+	{
2261
+		return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2262
+	}
2263
+
2264
+
2265
+	/**
2266
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2267
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2268
+	 *
2269
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2270
+	 * @param array $query_params like EEM_Base::get_all's
2271
+	 * @param string $field_to_sum name of field to count by.
2272
+	 *                              By default, uses primary key (which doesn't make much sense, so you should probably
2273
+	 *                              change it)
2274
+	 * @return int
2275
+	 * @throws EE_Error
2276
+	 */
2277
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2278
+	{
2279
+		return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2280
+	}
2281
+
2282
+
2283
+
2284
+	/**
2285
+	 * Gets the first (ie, one) related model object of the specified type.
2286
+	 *
2287
+	 * @param string $relationName key in the model's _model_relations array
2288
+	 * @param array  $query_params like EEM_Base::get_all
2289
+	 * @return EE_Base_Class (not an array, a single object)
2290
+	 * @throws EE_Error
2291
+	 */
2292
+	public function get_first_related($relationName, $query_params = array())
2293
+	{
2294
+		$model = $this->get_model();
2295
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2296
+			//if they've provided some query parameters, don't bother trying to cache the result
2297
+			//also make sure we're not caching the result of get_first_related
2298
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2299
+			if ($query_params
2300
+				|| ! $model->related_settings_for($relationName)
2301
+					 instanceof
2302
+					 EE_Belongs_To_Relation
2303
+			) {
2304
+				$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2305
+			} else {
2306
+				//first, check if we've already cached the result of this query
2307
+				$cached_result = $this->get_one_from_cache($relationName);
2308
+				if ( ! $cached_result) {
2309
+					$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2310
+					$this->cache($relationName, $related_model_object);
2311
+				} else {
2312
+					$related_model_object = $cached_result;
2313
+				}
2314
+			}
2315
+		} else {
2316
+			$related_model_object = null;
2317
+			//this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2318
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2319
+				$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2320
+			}
2321
+			//this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2322
+			if ( ! $related_model_object) {
2323
+				$related_model_object = $this->get_one_from_cache($relationName);
2324
+			}
2325
+		}
2326
+		return $related_model_object;
2327
+	}
2328
+
2329
+
2330
+
2331
+	/**
2332
+	 * Does a delete on all related objects of type $relationName and removes
2333
+	 * the current model object's relation to them. If they can't be deleted (because
2334
+	 * of blocking related model objects) does nothing. If the related model objects are
2335
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2336
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2337
+	 *
2338
+	 * @param string $relationName
2339
+	 * @param array  $query_params like EEM_Base::get_all's
2340
+	 * @return int how many deleted
2341
+	 * @throws EE_Error
2342
+	 */
2343
+	public function delete_related($relationName, $query_params = array())
2344
+	{
2345
+		if ($this->ID()) {
2346
+			$count = $this->get_model()->delete_related($this, $relationName, $query_params);
2347
+		} else {
2348
+			$count = count($this->get_all_from_cache($relationName));
2349
+			$this->clear_cache($relationName, null, true);
2350
+		}
2351
+		return $count;
2352
+	}
2353
+
2354
+
2355
+
2356
+	/**
2357
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2358
+	 * the current model object's relation to them. If they can't be deleted (because
2359
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2360
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2361
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2362
+	 *
2363
+	 * @param string $relationName
2364
+	 * @param array  $query_params like EEM_Base::get_all's
2365
+	 * @return int how many deleted (including those soft deleted)
2366
+	 * @throws EE_Error
2367
+	 */
2368
+	public function delete_related_permanently($relationName, $query_params = array())
2369
+	{
2370
+		if ($this->ID()) {
2371
+			$count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2372
+		} else {
2373
+			$count = count($this->get_all_from_cache($relationName));
2374
+		}
2375
+		$this->clear_cache($relationName, null, true);
2376
+		return $count;
2377
+	}
2378
+
2379
+
2380
+
2381
+	/**
2382
+	 * is_set
2383
+	 * Just a simple utility function children can use for checking if property exists
2384
+	 *
2385
+	 * @access  public
2386
+	 * @param  string $field_name property to check
2387
+	 * @return bool                              TRUE if existing,FALSE if not.
2388
+	 */
2389
+	public function is_set($field_name)
2390
+	{
2391
+		return isset($this->_fields[$field_name]);
2392
+	}
2393
+
2394
+
2395
+
2396
+	/**
2397
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2398
+	 * EE_Error exception if they don't
2399
+	 *
2400
+	 * @param  mixed (string|array) $properties properties to check
2401
+	 * @throws EE_Error
2402
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2403
+	 */
2404
+	protected function _property_exists($properties)
2405
+	{
2406
+		foreach ((array)$properties as $property_name) {
2407
+			//first make sure this property exists
2408
+			if ( ! $this->_fields[$property_name]) {
2409
+				throw new EE_Error(
2410
+					sprintf(
2411
+						__(
2412
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2413
+							'event_espresso'
2414
+						),
2415
+						$property_name
2416
+					)
2417
+				);
2418
+			}
2419
+		}
2420
+		return true;
2421
+	}
2422
+
2423
+
2424
+
2425
+	/**
2426
+	 * This simply returns an array of model fields for this object
2427
+	 *
2428
+	 * @return array
2429
+	 * @throws EE_Error
2430
+	 */
2431
+	public function model_field_array()
2432
+	{
2433
+		$fields = $this->get_model()->field_settings(false);
2434
+		$properties = array();
2435
+		//remove prepended underscore
2436
+		foreach ($fields as $field_name => $settings) {
2437
+			$properties[$field_name] = $this->get($field_name);
2438
+		}
2439
+		return $properties;
2440
+	}
2441
+
2442
+
2443
+
2444
+	/**
2445
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2446
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2447
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2448
+	 * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2449
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2450
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2451
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
2452
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
2453
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2454
+	 * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2455
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2456
+	 *        return $previousReturnValue.$returnString;
2457
+	 * }
2458
+	 * require('EE_Answer.class.php');
2459
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2460
+	 * echo $answer->my_callback('monkeys',100);
2461
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2462
+	 *
2463
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2464
+	 * @param array  $args       array of original arguments passed to the function
2465
+	 * @throws EE_Error
2466
+	 * @return mixed whatever the plugin which calls add_filter decides
2467
+	 */
2468
+	public function __call($methodName, $args)
2469
+	{
2470
+		$className = get_class($this);
2471
+		$tagName = "FHEE__{$className}__{$methodName}";
2472
+		if ( ! has_filter($tagName)) {
2473
+			throw new EE_Error(
2474
+				sprintf(
2475
+					__(
2476
+						"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;}",
2477
+						"event_espresso"
2478
+					),
2479
+					$methodName,
2480
+					$className,
2481
+					$tagName
2482
+				)
2483
+			);
2484
+		}
2485
+		return apply_filters($tagName, null, $this, $args);
2486
+	}
2487
+
2488
+
2489
+	/**
2490
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2491
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2492
+	 *
2493
+	 * @param string $meta_key
2494
+	 * @param mixed $meta_value
2495
+	 * @param mixed $previous_value
2496
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2497
+	 * @throws InvalidArgumentException
2498
+	 * @throws InvalidInterfaceException
2499
+	 * @throws InvalidDataTypeException
2500
+	 * @throws EE_Error
2501
+	 * NOTE: if the values haven't changed, returns 0
2502
+	 */
2503
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2504
+	{
2505
+		$query_params = array(
2506
+			array(
2507
+				'EXM_key'  => $meta_key,
2508
+				'OBJ_ID'   => $this->ID(),
2509
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2510
+			),
2511
+		);
2512
+		if ($previous_value !== null) {
2513
+			$query_params[0]['EXM_value'] = $meta_value;
2514
+		}
2515
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2516
+		if ( ! $existing_rows_like_that) {
2517
+			return $this->add_extra_meta($meta_key, $meta_value);
2518
+		}
2519
+		foreach ($existing_rows_like_that as $existing_row) {
2520
+			$existing_row->save(array('EXM_value' => $meta_value));
2521
+		}
2522
+		return count($existing_rows_like_that);
2523
+	}
2524
+
2525
+
2526
+	/**
2527
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2528
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2529
+	 * extra meta row was entered, false if not
2530
+	 *
2531
+	 * @param string $meta_key
2532
+	 * @param mixed $meta_value
2533
+	 * @param boolean $unique
2534
+	 * @return boolean
2535
+	 * @throws InvalidArgumentException
2536
+	 * @throws InvalidInterfaceException
2537
+	 * @throws InvalidDataTypeException
2538
+	 * @throws EE_Error
2539
+	 */
2540
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2541
+	{
2542
+		if ($unique) {
2543
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2544
+				array(
2545
+					array(
2546
+						'EXM_key'  => $meta_key,
2547
+						'OBJ_ID'   => $this->ID(),
2548
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2549
+					),
2550
+				)
2551
+			);
2552
+			if ($existing_extra_meta) {
2553
+				return false;
2554
+			}
2555
+		}
2556
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2557
+			array(
2558
+				'EXM_key'   => $meta_key,
2559
+				'EXM_value' => $meta_value,
2560
+				'OBJ_ID'    => $this->ID(),
2561
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2562
+			)
2563
+		);
2564
+		$new_extra_meta->save();
2565
+		return true;
2566
+	}
2567
+
2568
+
2569
+	/**
2570
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2571
+	 * is specified, only deletes extra meta records with that value.
2572
+	 *
2573
+	 * @param string $meta_key
2574
+	 * @param mixed $meta_value
2575
+	 * @return int number of extra meta rows deleted
2576
+	 * @throws InvalidArgumentException
2577
+	 * @throws InvalidInterfaceException
2578
+	 * @throws InvalidDataTypeException
2579
+	 * @throws EE_Error
2580
+	 */
2581
+	public function delete_extra_meta($meta_key, $meta_value = null)
2582
+	{
2583
+		$query_params = array(
2584
+			array(
2585
+				'EXM_key'  => $meta_key,
2586
+				'OBJ_ID'   => $this->ID(),
2587
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2588
+			),
2589
+		);
2590
+		if ($meta_value !== null) {
2591
+			$query_params[0]['EXM_value'] = $meta_value;
2592
+		}
2593
+		return EEM_Extra_Meta::instance()->delete($query_params);
2594
+	}
2595
+
2596
+
2597
+
2598
+	/**
2599
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2600
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2601
+	 * You can specify $default is case you haven't found the extra meta
2602
+	 *
2603
+	 * @param string  $meta_key
2604
+	 * @param boolean $single
2605
+	 * @param mixed   $default if we don't find anything, what should we return?
2606
+	 * @return mixed single value if $single; array if ! $single
2607
+	 * @throws EE_Error
2608
+	 */
2609
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2610
+	{
2611
+		if ($single) {
2612
+			$result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2613
+			if ($result instanceof EE_Extra_Meta) {
2614
+				return $result->value();
2615
+			}
2616
+		} else {
2617
+			$results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2618
+			if ($results) {
2619
+				$values = array();
2620
+				foreach ($results as $result) {
2621
+					if ($result instanceof EE_Extra_Meta) {
2622
+						$values[$result->ID()] = $result->value();
2623
+					}
2624
+				}
2625
+				return $values;
2626
+			}
2627
+		}
2628
+		//if nothing discovered yet return default.
2629
+		return apply_filters(
2630
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2631
+			$default,
2632
+			$meta_key,
2633
+			$single,
2634
+			$this
2635
+			);
2636
+	}
2637
+
2638
+
2639
+
2640
+	/**
2641
+	 * Returns a simple array of all the extra meta associated with this model object.
2642
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2643
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2644
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2645
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2646
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2647
+	 * finally the extra meta's value as each sub-value. (eg
2648
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2649
+	 *
2650
+	 * @param boolean $one_of_each_key
2651
+	 * @return array
2652
+	 * @throws EE_Error
2653
+	 */
2654
+	public function all_extra_meta_array($one_of_each_key = true)
2655
+	{
2656
+		$return_array = array();
2657
+		if ($one_of_each_key) {
2658
+			$extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2659
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2660
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2661
+					$return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2662
+				}
2663
+			}
2664
+		} else {
2665
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2666
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2667
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2668
+					if ( ! isset($return_array[$extra_meta_obj->key()])) {
2669
+						$return_array[$extra_meta_obj->key()] = array();
2670
+					}
2671
+					$return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2672
+				}
2673
+			}
2674
+		}
2675
+		return $return_array;
2676
+	}
2677
+
2678
+
2679
+
2680
+	/**
2681
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2682
+	 *
2683
+	 * @return string
2684
+	 * @throws EE_Error
2685
+	 */
2686
+	public function name()
2687
+	{
2688
+		//find a field that's not a text field
2689
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2690
+		if ($field_we_can_use) {
2691
+			return $this->get($field_we_can_use->get_name());
2692
+		} else {
2693
+			$first_few_properties = $this->model_field_array();
2694
+			$first_few_properties = array_slice($first_few_properties, 0, 3);
2695
+			$name_parts = array();
2696
+			foreach ($first_few_properties as $name => $value) {
2697
+				$name_parts[] = "$name:$value";
2698
+			}
2699
+			return implode(",", $name_parts);
2700
+		}
2701
+	}
2702
+
2703
+
2704
+
2705
+	/**
2706
+	 * in_entity_map
2707
+	 * Checks if this model object has been proven to already be in the entity map
2708
+	 *
2709
+	 * @return boolean
2710
+	 * @throws EE_Error
2711
+	 */
2712
+	public function in_entity_map()
2713
+	{
2714
+		if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2715
+			//well, if we looked, did we find it in the entity map?
2716
+			return true;
2717
+		} else {
2718
+			return false;
2719
+		}
2720
+	}
2721
+
2722
+
2723
+
2724
+	/**
2725
+	 * refresh_from_db
2726
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2727
+	 *
2728
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2729
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2730
+	 */
2731
+	public function refresh_from_db()
2732
+	{
2733
+		if ($this->ID() && $this->in_entity_map()) {
2734
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
2735
+		} else {
2736
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2737
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
2738
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2739
+			//absolutely nothing in it for this ID
2740
+			if (WP_DEBUG) {
2741
+				throw new EE_Error(
2742
+					sprintf(
2743
+						__('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.',
2744
+							'event_espresso'),
2745
+						$this->ID(),
2746
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2747
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2748
+					)
2749
+				);
2750
+			}
2751
+		}
2752
+	}
2753
+
2754
+
2755
+	/**
2756
+	 * Gets the money field's amount in subunits (and if the currency has no subunits, gets it in the main units).
2757
+	 * If you want to use this method, the class must implement UsesMoneyInterface and injected a MoneyFactory in
2758
+	 * its constructor
2759
+	 * @param string $money_field_name
2760
+	 * @return int
2761
+	 * @throws InvalidEntityException
2762
+	 * @throws EE_Error
2763
+	 * @throws DomainException
2764
+	 */
2765
+	public function moneyInSubunits($money_field_name)
2766
+	{
2767
+		$this->verifyUsesMoney(__FUNCTION__);
2768
+		return $this->getMoneyObject($money_field_name)->amountInSubunits();
2769
+	}
2770
+
2771
+
2772
+	/**
2773
+	 * Sets the money field's amount based on the incoming monetary subunits (eg pennies). If the currency has no
2774
+	 * subunits, the amount is actually assumed to be in the currency's main units.
2775
+	 * If you want to use this method, the class must implement UsesMoneyInterface and injected a MoneyFactory in
2776
+	 * its constructor
2777
+	 *
2778
+	 * @param string $money_field_name
2779
+	 * @param int    $amount_in_subunits
2780
+	 * @throws InvalidArgumentException
2781
+	 * @throws InvalidInterfaceException
2782
+	 * @throws InvalidIdentifierException
2783
+	 * @throws InvalidDataTypeException
2784
+	 * @throws EE_Error
2785
+	 * @throws DomainException
2786
+	 */
2787
+	public function setMoneySubunits($money_field_name,$amount_in_subunits)
2788
+	{
2789
+		$this->verifyUsesMoney(__FUNCTION__);
2790
+		$money = $this->money_factory->createFromSubUnits(
2791
+			$amount_in_subunits,
2792
+			EE_Config::instance()->currency->code
2793
+		);
2794
+		$this->set($money_field_name, $money);
2795
+	}
2796
+
2797
+
2798
+	/**
2799
+	 * Checks this class has implemented UsesMoneyInterface
2800
+	 * @param string $function
2801
+	 * @throws DomainException
2802
+	 * @throws EE_Error
2803
+	 */
2804
+	private function verifyUsesMoney($function)
2805
+	{
2806
+		if (! $this instanceof UsesMoneyInterface) {
2807
+			throw new DomainException(
2808
+				sprintf(
2809
+					esc_html__(
2810
+						'%1$s does not use an %2$s object for representing money values, therefore the %3$s method can not be called.',
2811
+						'event_espresso'
2812
+					),
2813
+					$this->name(),
2814
+					'EventEspresso\core\domain\values\currency\Money',
2815
+					"{$function}()"
2816
+				)
2817
+			);
2818
+		}
2819
+	}
2820
+
2821
+
2822
+
2823
+	/**
2824
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2825
+	 * (probably a bad assumption they have made, oh well)
2826
+	 *
2827
+	 * @return string
2828
+	 */
2829
+	public function __toString()
2830
+	{
2831
+		try {
2832
+			return sprintf('%s (%s)', $this->name(), $this->ID());
2833
+		} catch (Exception $e) {
2834
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2835
+			return '';
2836
+		}
2837
+	}
2838
+
2839
+
2840
+
2841
+	/**
2842
+	 * Clear related model objects if they're already in the DB, because otherwise when we
2843
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
2844
+	 * This means if we have made changes to those related model objects, and want to unserialize
2845
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
2846
+	 * Instead, those related model objects should be directly serialized and stored.
2847
+	 * Eg, the following won't work:
2848
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2849
+	 * $att = $reg->attendee();
2850
+	 * $att->set( 'ATT_fname', 'Dirk' );
2851
+	 * update_option( 'my_option', serialize( $reg ) );
2852
+	 * //END REQUEST
2853
+	 * //START NEXT REQUEST
2854
+	 * $reg = get_option( 'my_option' );
2855
+	 * $reg->attendee()->save();
2856
+	 * And would need to be replace with:
2857
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2858
+	 * $att = $reg->attendee();
2859
+	 * $att->set( 'ATT_fname', 'Dirk' );
2860
+	 * update_option( 'my_option', serialize( $reg ) );
2861
+	 * //END REQUEST
2862
+	 * //START NEXT REQUEST
2863
+	 * $att = get_option( 'my_option' );
2864
+	 * $att->save();
2865
+	 *
2866
+	 * @return array
2867
+	 * @throws EE_Error
2868
+	 */
2869
+	public function __sleep()
2870
+	{
2871
+		$model = $this->get_model();
2872
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2873
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
2874
+				$classname = 'EE_' . $model->get_this_model_name();
2875
+				if (
2876
+					$this->get_one_from_cache($relation_name) instanceof $classname
2877
+					&& $this->get_one_from_cache($relation_name)->ID()
2878
+				) {
2879
+					$this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2880
+				}
2881
+			}
2882
+		}
2883
+		$this->_props_n_values_provided_in_constructor = array();
2884
+		$properties_to_serialize = get_object_vars($this);
2885
+		//don't serialize the model. It's big and that risks recursion
2886
+		unset(
2887
+			$properties_to_serialize['_model'],
2888
+			$properties_to_serialize['money_factory']
2889
+		);
2890
+		return array_keys($properties_to_serialize);
2891
+	}
2892
+
2893
+
2894
+	/**
2895
+	 * restore _props_n_values_provided_in_constructor
2896
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2897
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
2898
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
2899
+	 * @throws InvalidInterfaceException
2900
+	 * @throws InvalidDataTypeException
2901
+	 */
2902
+	public function __wakeup()
2903
+	{
2904
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
2905
+		if( $this instanceof UsesMoneyInterface) {
2906
+			$this->money_factory = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\currency\MoneyFactory');
2907
+		}
2908
+	}
2909 2909
 
2910 2910
 
2911 2911
 
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -168,8 +168,8 @@  discard block
 block discarded – undo
168 168
             list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
169 169
         } else {
170 170
             //set default formats for date and time
171
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
172
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
171
+            $this->_dt_frmt = (string) get_option('date_format', 'Y-m-d');
172
+            $this->_tm_frmt = (string) get_option('time_format', 'g:i a');
173 173
         }
174 174
         //if db model is instantiating
175 175
         if ($bydb) {
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
      */
496 496
     public function get_format($full = true)
497 497
     {
498
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
498
+        return $full ? $this->_dt_frmt.' '.$this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
499 499
     }
500 500
 
501 501
 
@@ -604,7 +604,7 @@  discard block
 block discarded – undo
604 604
         $model = $this->get_model();
605 605
         $model->field_settings_for($fieldname);
606 606
         $cache_type = $pretty ? 'pretty' : 'standard';
607
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
607
+        $cache_type .= ! empty($extra_cache_ref) ? '_'.$extra_cache_ref : '';
608 608
         if (isset($this->_cached_properties[$fieldname][$cache_type])) {
609 609
             return $this->_cached_properties[$fieldname][$cache_type];
610 610
         }
@@ -833,7 +833,7 @@  discard block
 block discarded – undo
833 833
         $current_cache_id = ''
834 834
     ) {
835 835
         // verify that incoming object is of the correct type
836
-        $obj_class = 'EE_' . $relationName;
836
+        $obj_class = 'EE_'.$relationName;
837 837
         if ($newly_saved_object instanceof $obj_class) {
838 838
             /* @type EE_Base_Class $newly_saved_object */
839 839
             // now get the type of relation
@@ -1095,7 +1095,7 @@  discard block
 block discarded – undo
1095 1095
     public function get_raw($field_name)
1096 1096
     {
1097 1097
         $field_settings = $this->get_model()->field_settings_for($field_name);
1098
-        switch(true){
1098
+        switch (true) {
1099 1099
             case $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime:
1100 1100
                 $value = $this->_fields[$field_name]->format('U');
1101 1101
                 break;
@@ -1160,7 +1160,7 @@  discard block
 block discarded – undo
1160 1160
         $this->verifyUsesMoney(__FUNCTION__);
1161 1161
         $field = $this->get_model()->field_settings_for($field_name);
1162 1162
         $value = isset($this->_fields[$field_name]) ? $this->_fields[$field_name] : null;
1163
-        if (! $field instanceof EE_Money_Field
1163
+        if ( ! $field instanceof EE_Money_Field
1164 1164
             || ! $value instanceof Money) {
1165 1165
             throw new InvalidEntityException(
1166 1166
                 get_class($value),
@@ -1222,7 +1222,7 @@  discard block
 block discarded – undo
1222 1222
      */
1223 1223
     public function get_f($field_name)
1224 1224
     {
1225
-        return (string)$this->get_pretty($field_name,'form_input');
1225
+        return (string) $this->get_pretty($field_name, 'form_input');
1226 1226
     }
1227 1227
 
1228 1228
 
@@ -1381,7 +1381,7 @@  discard block
 block discarded – undo
1381 1381
      */
1382 1382
     public function get_i18n_datetime($field_name, $format = '')
1383 1383
     {
1384
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1384
+        $format = empty($format) ? $this->_dt_frmt.' '.$this->_tm_frmt : $format;
1385 1385
         return date_i18n(
1386 1386
             $format,
1387 1387
             EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
@@ -1523,8 +1523,8 @@  discard block
 block discarded – undo
1523 1523
         }
1524 1524
         $original_timezone = $this->_timezone;
1525 1525
         $this->set_timezone($timezone);
1526
-        $fn = (array)$field_name;
1527
-        $args = array_merge($fn, (array)$args);
1526
+        $fn = (array) $field_name;
1527
+        $args = array_merge($fn, (array) $args);
1528 1528
         if ( ! method_exists($this, $callback)) {
1529 1529
             throw new EE_Error(
1530 1530
                 sprintf(
@@ -1536,8 +1536,8 @@  discard block
 block discarded – undo
1536 1536
                 )
1537 1537
             );
1538 1538
         }
1539
-        $args = (array)$args;
1540
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1539
+        $args = (array) $args;
1540
+        $return = $prepend.call_user_func_array(array($this, $callback), $args).$append;
1541 1541
         $this->set_timezone($original_timezone);
1542 1542
         return $return;
1543 1543
     }
@@ -1676,14 +1676,14 @@  discard block
 block discarded – undo
1676 1676
          * @param array         $set_cols_n_values
1677 1677
          * @param EE_Base_Class $model_object
1678 1678
          */
1679
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1679
+        $set_cols_n_values = (array) apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1680 1680
             $this);
1681 1681
         //set attributes as provided in $set_cols_n_values
1682 1682
         foreach ($set_cols_n_values as $column => $value) {
1683 1683
             $this->set($column, $value);
1684 1684
         }
1685 1685
         // no changes ? then don't do anything
1686
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1686
+        if ( ! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1687 1687
             return 0;
1688 1688
         }
1689 1689
         /**
@@ -1735,8 +1735,8 @@  discard block
 block discarded – undo
1735 1735
                                 __('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',
1736 1736
                                     'event_espresso'),
1737 1737
                                 get_class($this),
1738
-                                get_class($model) . '::instance()->add_to_entity_map()',
1739
-                                get_class($model) . '::instance()->get_one_by_ID()',
1738
+                                get_class($model).'::instance()->add_to_entity_map()',
1739
+                                get_class($model).'::instance()->get_one_by_ID()',
1740 1740
                                 '<br />'
1741 1741
                             )
1742 1742
                         );
@@ -1869,7 +1869,7 @@  discard block
 block discarded – undo
1869 1869
      */
1870 1870
     public function get_model()
1871 1871
     {
1872
-        if( ! $this->_model){
1872
+        if ( ! $this->_model) {
1873 1873
             $modelName = self::_get_model_classname(get_class($this));
1874 1874
             $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1875 1875
         } else {
@@ -2016,7 +2016,7 @@  discard block
 block discarded – undo
2016 2016
         if (strpos($model_name, "EE_") === 0) {
2017 2017
             $model_classname = str_replace("EE_", "EEM_", $model_name);
2018 2018
         } else {
2019
-            $model_classname = "EEM_" . $model_name;
2019
+            $model_classname = "EEM_".$model_name;
2020 2020
         }
2021 2021
         return $model_classname;
2022 2022
     }
@@ -2403,7 +2403,7 @@  discard block
 block discarded – undo
2403 2403
      */
2404 2404
     protected function _property_exists($properties)
2405 2405
     {
2406
-        foreach ((array)$properties as $property_name) {
2406
+        foreach ((array) $properties as $property_name) {
2407 2407
             //first make sure this property exists
2408 2408
             if ( ! $this->_fields[$property_name]) {
2409 2409
                 throw new EE_Error(
@@ -2743,8 +2743,8 @@  discard block
 block discarded – undo
2743 2743
                         __('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.',
2744 2744
                             'event_espresso'),
2745 2745
                         $this->ID(),
2746
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2747
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2746
+                        get_class($this->get_model()).'::instance()->add_to_entity_map()',
2747
+                        get_class($this->get_model()).'::instance()->refresh_entity_map()'
2748 2748
                     )
2749 2749
                 );
2750 2750
             }
@@ -2784,7 +2784,7 @@  discard block
 block discarded – undo
2784 2784
      * @throws EE_Error
2785 2785
      * @throws DomainException
2786 2786
      */
2787
-    public function setMoneySubunits($money_field_name,$amount_in_subunits)
2787
+    public function setMoneySubunits($money_field_name, $amount_in_subunits)
2788 2788
     {
2789 2789
         $this->verifyUsesMoney(__FUNCTION__);
2790 2790
         $money = $this->money_factory->createFromSubUnits(
@@ -2803,7 +2803,7 @@  discard block
 block discarded – undo
2803 2803
      */
2804 2804
     private function verifyUsesMoney($function)
2805 2805
     {
2806
-        if (! $this instanceof UsesMoneyInterface) {
2806
+        if ( ! $this instanceof UsesMoneyInterface) {
2807 2807
             throw new DomainException(
2808 2808
                 sprintf(
2809 2809
                     esc_html__(
@@ -2871,7 +2871,7 @@  discard block
 block discarded – undo
2871 2871
         $model = $this->get_model();
2872 2872
         foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2873 2873
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
2874
-                $classname = 'EE_' . $model->get_this_model_name();
2874
+                $classname = 'EE_'.$model->get_this_model_name();
2875 2875
                 if (
2876 2876
                     $this->get_one_from_cache($relation_name) instanceof $classname
2877 2877
                     && $this->get_one_from_cache($relation_name)->ID()
@@ -2902,7 +2902,7 @@  discard block
 block discarded – undo
2902 2902
     public function __wakeup()
2903 2903
     {
2904 2904
         $this->_props_n_values_provided_in_constructor = $this->_fields;
2905
-        if( $this instanceof UsesMoneyInterface) {
2905
+        if ($this instanceof UsesMoneyInterface) {
2906 2906
             $this->money_factory = LoaderFactory::getLoader()->getShared('EventEspresso\core\services\currency\MoneyFactory');
2907 2907
         }
2908 2908
     }
Please login to merge, or discard this patch.