Completed
Branch more-reg-csv-fixes (87a98f)
by
unknown
30:58 queued 28:58
created
core/services/collections/CollectionDetails.php 2 patches
Indentation   +349 added lines, -349 removed lines patch added patch discarded remove patch
@@ -43,353 +43,353 @@
 block discarded – undo
43 43
 class CollectionDetails implements CollectionDetailsInterface
44 44
 {
45 45
 
46
-    /**
47
-     * if $identifier_type is set to this,
48
-     * then the collection will use each object's spl_object_hash() as it's identifier
49
-     */
50
-    const ID_OBJECT_HASH = 'identifier-uses-spl-object-hash';
51
-
52
-    /**
53
-     * if $identifier_type is set to this,
54
-     * then the collection will use each object's class name as it's identifier
55
-     */
56
-    const ID_CLASS_NAME = 'identifier-uses-object-class-name';
57
-
58
-    /**
59
-     * if $identifier_type is set to this,
60
-     * then the collection will use the return value from a specified callback method on each object
61
-     */
62
-    const ID_CALLBACK_METHOD = 'identifier-uses-callback-method';
63
-
64
-    /**
65
-     * The interface used for controlling what gets added to the collection
66
-     *
67
-     * @var string $collection_interface
68
-     */
69
-    protected $collection_interface = '';
70
-
71
-    /**
72
-     * a unique name used to identify the collection in filter names
73
-     * supplied value is run through sanitize_title_with_dashes(),
74
-     * but then also converts dashes to underscores
75
-     *
76
-     * @var string $collection_name
77
-     */
78
-    protected $collection_name = '';
79
-
80
-    /**
81
-     * what the collection uses for the object identifier.
82
-     * corresponds to one of the class constants above.
83
-     * CollectionDetails::ID_OBJECT_HASH will use spl_object_hash( object ) for the identifier
84
-     * CollectionDetails::ID_CLASS_NAME will use get_class( object ) for the identifier
85
-     * CollectionDetails::ID_CALLBACK_METHOD will use a callback for the identifier
86
-     * defaults to using spl_object_hash() so that multiple objects of the same class can be added
87
-     *
88
-     * @var string $identifier_type
89
-     */
90
-    protected $identifier_type = CollectionDetails::ID_OBJECT_HASH;
91
-
92
-    /**
93
-     * the pattern applied to paths when searching for class files to add to the collection
94
-     * ie: "My_Awesome_*.class.php"
95
-     * defaults to "*.php"
96
-     *
97
-     * @var string $file_mask
98
-     */
99
-    protected $file_mask = '';
100
-
101
-    /**
102
-     * if the $identifier_type above is set to CollectionDetails::ID_CALLBACK_METHOD,
103
-     * then this specifies the method to use on each entity.
104
-     * If the callback method does not exist, then an exception will be thrown
105
-     *
106
-     * @var string $identifier_callback
107
-     */
108
-    protected $identifier_callback = '';
109
-
110
-    /**
111
-     * an array of Fully Qualified Class Names
112
-     *  for example:
113
-     *  $FQCNs = array(
114
-     *      '/Fully/Qualified/ClassNameA'
115
-     *      '/Fully/Qualified/Other/ClassNameB'
116
-     *  );
117
-     *
118
-     * @var array $collection_FQCNs
119
-     */
120
-    protected $collection_FQCNs = array();
121
-
122
-    /**
123
-     * an array of full server paths to folders containing files to be loaded into collection
124
-     *  for example:
125
-     *  $paths = array(
126
-     *      '/full/server/path/to/ClassNameA.ext.php' // for class ClassNameA
127
-     *      '/full/server/path/to/other/ClassNameB.php' // for class ClassNameB
128
-     *  );
129
-     *
130
-     * @var array $collection_paths
131
-     */
132
-    protected $collection_paths = array();
133
-
134
-    /**
135
-     * @var LocatorInterface $file_locator
136
-     */
137
-    protected $file_locator;
138
-
139
-
140
-    /**
141
-     * CollectionDetails constructor.
142
-     *
143
-     * @access public
144
-     * @param string           $collection_name
145
-     * @param string           $collection_interface
146
-     * @param array            $collection_FQCNs
147
-     * @param array            $collection_paths
148
-     * @param string           $file_mask
149
-     * @param string           $identifier_type
150
-     * @param string           $identifier_callback
151
-     * @param LocatorInterface $file_locator
152
-     * @throws CollectionDetailsException
153
-     */
154
-    public function __construct(
155
-        $collection_name,
156
-        $collection_interface,
157
-        array $collection_FQCNs = array(),
158
-        array $collection_paths = array(),
159
-        $file_mask = '',
160
-        $identifier_type = CollectionDetails::ID_OBJECT_HASH,
161
-        $identifier_callback = '',
162
-        LocatorInterface $file_locator = null
163
-    ) {
164
-        try {
165
-            $this->setCollectionName($collection_name);
166
-            $this->setCollectionInterface($collection_interface);
167
-            $this->setCollectionFQCNs($collection_FQCNs);
168
-            $this->setCollectionPaths($collection_paths);
169
-            $this->setFileMasks($file_mask);
170
-            $this->setIdentifierType($identifier_type);
171
-            $this->setIdentifierCallback($identifier_callback);
172
-            $this->file_locator = $file_locator;
173
-        } catch (Exception $exception) {
174
-            throw new CollectionDetailsException($exception);
175
-        }
176
-    }
177
-
178
-
179
-    /**
180
-     * @access public
181
-     * @return mixed
182
-     */
183
-    public function getCollectionInterface()
184
-    {
185
-        return $this->collection_interface;
186
-    }
187
-
188
-
189
-    /**
190
-     * @access protected
191
-     * @param string $collection_interface
192
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
193
-     */
194
-    protected function setCollectionInterface($collection_interface)
195
-    {
196
-        if (! (interface_exists($collection_interface) || class_exists($collection_interface))) {
197
-            throw new InvalidInterfaceException($collection_interface);
198
-        }
199
-        $this->collection_interface = $collection_interface;
200
-    }
201
-
202
-
203
-    /**
204
-     * the collection name will be used for creating dynamic filters
205
-     *
206
-     * @access public
207
-     * @return string
208
-     */
209
-    public function collectionName()
210
-    {
211
-        return $this->collection_name;
212
-    }
213
-
214
-
215
-    /**
216
-     * sanitizes collection name and converts spaces and dashes to underscores
217
-     *
218
-     * @access protected
219
-     * @param string $collection_name
220
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
221
-     */
222
-    protected function setCollectionName($collection_name)
223
-    {
224
-        if (! is_string($collection_name)) {
225
-            throw new InvalidDataTypeException('$collection_name', $collection_name, 'string');
226
-        }
227
-        $this->collection_name = str_replace(
228
-            '-',
229
-            '_',
230
-            sanitize_title_with_dashes($collection_name, '', 'save')
231
-        );
232
-    }
233
-
234
-
235
-    /**
236
-     * @access public
237
-     * @return string
238
-     */
239
-    public function identifierType()
240
-    {
241
-        return $this->identifier_type;
242
-    }
243
-
244
-
245
-    /**
246
-     * @access protected
247
-     * @param string $identifier_type
248
-     * @throws InvalidIdentifierException
249
-     */
250
-    protected function setIdentifierType($identifier_type)
251
-    {
252
-        if (
253
-            ! ($identifier_type === CollectionDetails::ID_CLASS_NAME
254
-               || $identifier_type === CollectionDetails::ID_OBJECT_HASH
255
-               || $identifier_type === CollectionDetails::ID_CALLBACK_METHOD
256
-            )
257
-        ) {
258
-            throw new InvalidIdentifierException(
259
-                $identifier_type,
260
-                'CollectionDetails::ID_CLASS_NAME or CollectionDetails::ID_OBJECT_HASH or CollectionDetails::ID_CALLBACK_METHOD'
261
-            );
262
-        }
263
-        $this->identifier_type = $identifier_type;
264
-    }
265
-
266
-
267
-    /**
268
-     * @access public
269
-     * @return string
270
-     */
271
-    public function identifierCallback()
272
-    {
273
-        return $this->identifier_callback;
274
-    }
275
-
276
-
277
-    /**
278
-     * @access protected
279
-     * @param string $identifier_callback
280
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
281
-     */
282
-    protected function setIdentifierCallback($identifier_callback = 'identifier')
283
-    {
284
-        if (! is_string($identifier_callback)) {
285
-            throw new InvalidDataTypeException('$identifier_callback', $identifier_callback, 'string');
286
-        }
287
-        $this->identifier_callback = $identifier_callback;
288
-    }
289
-
290
-
291
-    /**
292
-     * @access public
293
-     * @return string
294
-     */
295
-    public function getFileMask()
296
-    {
297
-        return $this->file_mask;
298
-    }
299
-
300
-
301
-    /**
302
-     * sets the file mask which is then used to filter what files get loaded
303
-     * when searching for classes to add to the collection. Defaults to '*.php'
304
-     *
305
-     * @access protected
306
-     * @param string $file_mask
307
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
308
-     */
309
-    protected function setFileMasks($file_mask)
310
-    {
311
-        $this->file_mask = ! empty($file_mask) ? $file_mask : '*.php';
312
-        // we know our default is a string, so if it's not a string now,
313
-        // then that means the incoming parameter was something else
314
-        if (! is_string($this->file_mask)) {
315
-            throw new InvalidDataTypeException('$file_mask', $this->file_mask, 'string');
316
-        }
317
-    }
318
-
319
-
320
-    /**
321
-     * @access public
322
-     * @return array
323
-     */
324
-    public function getCollectionFQCNs()
325
-    {
326
-        return $this->collection_FQCNs;
327
-    }
328
-
329
-
330
-    /**
331
-     * @access public
332
-     * @param string|array $collection_FQCNs
333
-     * @throws \EventEspresso\core\exceptions\InvalidClassException
334
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
335
-     */
336
-    public function setCollectionFQCNs($collection_FQCNs)
337
-    {
338
-        foreach ((array) $collection_FQCNs as $collection_FQCN) {
339
-            if (! empty($collection_FQCN)) {
340
-                if (class_exists($collection_FQCN)) {
341
-                    $this->collection_FQCNs[] = $collection_FQCN;
342
-                } else {
343
-                    foreach ($this->getFQCNsFromPartialNamespace($collection_FQCN) as $FQCN) {
344
-                        $this->collection_FQCNs[] = $FQCN;
345
-                    }
346
-                }
347
-            }
348
-        }
349
-    }
350
-
351
-
352
-    /**
353
-     * @access protected
354
-     * @param  string $partial_FQCN
355
-     * @return array
356
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
357
-     * @throws \EventEspresso\core\exceptions\InvalidClassException
358
-     */
359
-    protected function getFQCNsFromPartialNamespace($partial_FQCN)
360
-    {
361
-        if (! $this->file_locator instanceof FqcnLocator) {
362
-            $this->file_locator = new FqcnLocator();
363
-        }
364
-        $this->file_locator->locate($partial_FQCN);
365
-        return $this->file_locator->getFQCNs();
366
-    }
367
-
368
-
369
-    /**
370
-     * @access public
371
-     * @return array
372
-     */
373
-    public function getCollectionPaths()
374
-    {
375
-        return $this->collection_paths;
376
-    }
377
-
378
-
379
-    /**
380
-     * @access public
381
-     * @param string|array $collection_paths
382
-     * @throws \EventEspresso\core\exceptions\InvalidFilePathException
383
-     */
384
-    public function setCollectionPaths($collection_paths)
385
-    {
386
-        foreach ((array) $collection_paths as $collection_path) {
387
-            if (! empty($collection_path)) {
388
-                if (! is_readable($collection_path)) {
389
-                    throw new InvalidFilePathException($collection_path);
390
-                }
391
-                $this->collection_paths[] = $collection_path;
392
-            }
393
-        }
394
-    }
46
+	/**
47
+	 * if $identifier_type is set to this,
48
+	 * then the collection will use each object's spl_object_hash() as it's identifier
49
+	 */
50
+	const ID_OBJECT_HASH = 'identifier-uses-spl-object-hash';
51
+
52
+	/**
53
+	 * if $identifier_type is set to this,
54
+	 * then the collection will use each object's class name as it's identifier
55
+	 */
56
+	const ID_CLASS_NAME = 'identifier-uses-object-class-name';
57
+
58
+	/**
59
+	 * if $identifier_type is set to this,
60
+	 * then the collection will use the return value from a specified callback method on each object
61
+	 */
62
+	const ID_CALLBACK_METHOD = 'identifier-uses-callback-method';
63
+
64
+	/**
65
+	 * The interface used for controlling what gets added to the collection
66
+	 *
67
+	 * @var string $collection_interface
68
+	 */
69
+	protected $collection_interface = '';
70
+
71
+	/**
72
+	 * a unique name used to identify the collection in filter names
73
+	 * supplied value is run through sanitize_title_with_dashes(),
74
+	 * but then also converts dashes to underscores
75
+	 *
76
+	 * @var string $collection_name
77
+	 */
78
+	protected $collection_name = '';
79
+
80
+	/**
81
+	 * what the collection uses for the object identifier.
82
+	 * corresponds to one of the class constants above.
83
+	 * CollectionDetails::ID_OBJECT_HASH will use spl_object_hash( object ) for the identifier
84
+	 * CollectionDetails::ID_CLASS_NAME will use get_class( object ) for the identifier
85
+	 * CollectionDetails::ID_CALLBACK_METHOD will use a callback for the identifier
86
+	 * defaults to using spl_object_hash() so that multiple objects of the same class can be added
87
+	 *
88
+	 * @var string $identifier_type
89
+	 */
90
+	protected $identifier_type = CollectionDetails::ID_OBJECT_HASH;
91
+
92
+	/**
93
+	 * the pattern applied to paths when searching for class files to add to the collection
94
+	 * ie: "My_Awesome_*.class.php"
95
+	 * defaults to "*.php"
96
+	 *
97
+	 * @var string $file_mask
98
+	 */
99
+	protected $file_mask = '';
100
+
101
+	/**
102
+	 * if the $identifier_type above is set to CollectionDetails::ID_CALLBACK_METHOD,
103
+	 * then this specifies the method to use on each entity.
104
+	 * If the callback method does not exist, then an exception will be thrown
105
+	 *
106
+	 * @var string $identifier_callback
107
+	 */
108
+	protected $identifier_callback = '';
109
+
110
+	/**
111
+	 * an array of Fully Qualified Class Names
112
+	 *  for example:
113
+	 *  $FQCNs = array(
114
+	 *      '/Fully/Qualified/ClassNameA'
115
+	 *      '/Fully/Qualified/Other/ClassNameB'
116
+	 *  );
117
+	 *
118
+	 * @var array $collection_FQCNs
119
+	 */
120
+	protected $collection_FQCNs = array();
121
+
122
+	/**
123
+	 * an array of full server paths to folders containing files to be loaded into collection
124
+	 *  for example:
125
+	 *  $paths = array(
126
+	 *      '/full/server/path/to/ClassNameA.ext.php' // for class ClassNameA
127
+	 *      '/full/server/path/to/other/ClassNameB.php' // for class ClassNameB
128
+	 *  );
129
+	 *
130
+	 * @var array $collection_paths
131
+	 */
132
+	protected $collection_paths = array();
133
+
134
+	/**
135
+	 * @var LocatorInterface $file_locator
136
+	 */
137
+	protected $file_locator;
138
+
139
+
140
+	/**
141
+	 * CollectionDetails constructor.
142
+	 *
143
+	 * @access public
144
+	 * @param string           $collection_name
145
+	 * @param string           $collection_interface
146
+	 * @param array            $collection_FQCNs
147
+	 * @param array            $collection_paths
148
+	 * @param string           $file_mask
149
+	 * @param string           $identifier_type
150
+	 * @param string           $identifier_callback
151
+	 * @param LocatorInterface $file_locator
152
+	 * @throws CollectionDetailsException
153
+	 */
154
+	public function __construct(
155
+		$collection_name,
156
+		$collection_interface,
157
+		array $collection_FQCNs = array(),
158
+		array $collection_paths = array(),
159
+		$file_mask = '',
160
+		$identifier_type = CollectionDetails::ID_OBJECT_HASH,
161
+		$identifier_callback = '',
162
+		LocatorInterface $file_locator = null
163
+	) {
164
+		try {
165
+			$this->setCollectionName($collection_name);
166
+			$this->setCollectionInterface($collection_interface);
167
+			$this->setCollectionFQCNs($collection_FQCNs);
168
+			$this->setCollectionPaths($collection_paths);
169
+			$this->setFileMasks($file_mask);
170
+			$this->setIdentifierType($identifier_type);
171
+			$this->setIdentifierCallback($identifier_callback);
172
+			$this->file_locator = $file_locator;
173
+		} catch (Exception $exception) {
174
+			throw new CollectionDetailsException($exception);
175
+		}
176
+	}
177
+
178
+
179
+	/**
180
+	 * @access public
181
+	 * @return mixed
182
+	 */
183
+	public function getCollectionInterface()
184
+	{
185
+		return $this->collection_interface;
186
+	}
187
+
188
+
189
+	/**
190
+	 * @access protected
191
+	 * @param string $collection_interface
192
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
193
+	 */
194
+	protected function setCollectionInterface($collection_interface)
195
+	{
196
+		if (! (interface_exists($collection_interface) || class_exists($collection_interface))) {
197
+			throw new InvalidInterfaceException($collection_interface);
198
+		}
199
+		$this->collection_interface = $collection_interface;
200
+	}
201
+
202
+
203
+	/**
204
+	 * the collection name will be used for creating dynamic filters
205
+	 *
206
+	 * @access public
207
+	 * @return string
208
+	 */
209
+	public function collectionName()
210
+	{
211
+		return $this->collection_name;
212
+	}
213
+
214
+
215
+	/**
216
+	 * sanitizes collection name and converts spaces and dashes to underscores
217
+	 *
218
+	 * @access protected
219
+	 * @param string $collection_name
220
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
221
+	 */
222
+	protected function setCollectionName($collection_name)
223
+	{
224
+		if (! is_string($collection_name)) {
225
+			throw new InvalidDataTypeException('$collection_name', $collection_name, 'string');
226
+		}
227
+		$this->collection_name = str_replace(
228
+			'-',
229
+			'_',
230
+			sanitize_title_with_dashes($collection_name, '', 'save')
231
+		);
232
+	}
233
+
234
+
235
+	/**
236
+	 * @access public
237
+	 * @return string
238
+	 */
239
+	public function identifierType()
240
+	{
241
+		return $this->identifier_type;
242
+	}
243
+
244
+
245
+	/**
246
+	 * @access protected
247
+	 * @param string $identifier_type
248
+	 * @throws InvalidIdentifierException
249
+	 */
250
+	protected function setIdentifierType($identifier_type)
251
+	{
252
+		if (
253
+			! ($identifier_type === CollectionDetails::ID_CLASS_NAME
254
+			   || $identifier_type === CollectionDetails::ID_OBJECT_HASH
255
+			   || $identifier_type === CollectionDetails::ID_CALLBACK_METHOD
256
+			)
257
+		) {
258
+			throw new InvalidIdentifierException(
259
+				$identifier_type,
260
+				'CollectionDetails::ID_CLASS_NAME or CollectionDetails::ID_OBJECT_HASH or CollectionDetails::ID_CALLBACK_METHOD'
261
+			);
262
+		}
263
+		$this->identifier_type = $identifier_type;
264
+	}
265
+
266
+
267
+	/**
268
+	 * @access public
269
+	 * @return string
270
+	 */
271
+	public function identifierCallback()
272
+	{
273
+		return $this->identifier_callback;
274
+	}
275
+
276
+
277
+	/**
278
+	 * @access protected
279
+	 * @param string $identifier_callback
280
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
281
+	 */
282
+	protected function setIdentifierCallback($identifier_callback = 'identifier')
283
+	{
284
+		if (! is_string($identifier_callback)) {
285
+			throw new InvalidDataTypeException('$identifier_callback', $identifier_callback, 'string');
286
+		}
287
+		$this->identifier_callback = $identifier_callback;
288
+	}
289
+
290
+
291
+	/**
292
+	 * @access public
293
+	 * @return string
294
+	 */
295
+	public function getFileMask()
296
+	{
297
+		return $this->file_mask;
298
+	}
299
+
300
+
301
+	/**
302
+	 * sets the file mask which is then used to filter what files get loaded
303
+	 * when searching for classes to add to the collection. Defaults to '*.php'
304
+	 *
305
+	 * @access protected
306
+	 * @param string $file_mask
307
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
308
+	 */
309
+	protected function setFileMasks($file_mask)
310
+	{
311
+		$this->file_mask = ! empty($file_mask) ? $file_mask : '*.php';
312
+		// we know our default is a string, so if it's not a string now,
313
+		// then that means the incoming parameter was something else
314
+		if (! is_string($this->file_mask)) {
315
+			throw new InvalidDataTypeException('$file_mask', $this->file_mask, 'string');
316
+		}
317
+	}
318
+
319
+
320
+	/**
321
+	 * @access public
322
+	 * @return array
323
+	 */
324
+	public function getCollectionFQCNs()
325
+	{
326
+		return $this->collection_FQCNs;
327
+	}
328
+
329
+
330
+	/**
331
+	 * @access public
332
+	 * @param string|array $collection_FQCNs
333
+	 * @throws \EventEspresso\core\exceptions\InvalidClassException
334
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
335
+	 */
336
+	public function setCollectionFQCNs($collection_FQCNs)
337
+	{
338
+		foreach ((array) $collection_FQCNs as $collection_FQCN) {
339
+			if (! empty($collection_FQCN)) {
340
+				if (class_exists($collection_FQCN)) {
341
+					$this->collection_FQCNs[] = $collection_FQCN;
342
+				} else {
343
+					foreach ($this->getFQCNsFromPartialNamespace($collection_FQCN) as $FQCN) {
344
+						$this->collection_FQCNs[] = $FQCN;
345
+					}
346
+				}
347
+			}
348
+		}
349
+	}
350
+
351
+
352
+	/**
353
+	 * @access protected
354
+	 * @param  string $partial_FQCN
355
+	 * @return array
356
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
357
+	 * @throws \EventEspresso\core\exceptions\InvalidClassException
358
+	 */
359
+	protected function getFQCNsFromPartialNamespace($partial_FQCN)
360
+	{
361
+		if (! $this->file_locator instanceof FqcnLocator) {
362
+			$this->file_locator = new FqcnLocator();
363
+		}
364
+		$this->file_locator->locate($partial_FQCN);
365
+		return $this->file_locator->getFQCNs();
366
+	}
367
+
368
+
369
+	/**
370
+	 * @access public
371
+	 * @return array
372
+	 */
373
+	public function getCollectionPaths()
374
+	{
375
+		return $this->collection_paths;
376
+	}
377
+
378
+
379
+	/**
380
+	 * @access public
381
+	 * @param string|array $collection_paths
382
+	 * @throws \EventEspresso\core\exceptions\InvalidFilePathException
383
+	 */
384
+	public function setCollectionPaths($collection_paths)
385
+	{
386
+		foreach ((array) $collection_paths as $collection_path) {
387
+			if (! empty($collection_path)) {
388
+				if (! is_readable($collection_path)) {
389
+					throw new InvalidFilePathException($collection_path);
390
+				}
391
+				$this->collection_paths[] = $collection_path;
392
+			}
393
+		}
394
+	}
395 395
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
      */
194 194
     protected function setCollectionInterface($collection_interface)
195 195
     {
196
-        if (! (interface_exists($collection_interface) || class_exists($collection_interface))) {
196
+        if ( ! (interface_exists($collection_interface) || class_exists($collection_interface))) {
197 197
             throw new InvalidInterfaceException($collection_interface);
198 198
         }
199 199
         $this->collection_interface = $collection_interface;
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
      */
222 222
     protected function setCollectionName($collection_name)
223 223
     {
224
-        if (! is_string($collection_name)) {
224
+        if ( ! is_string($collection_name)) {
225 225
             throw new InvalidDataTypeException('$collection_name', $collection_name, 'string');
226 226
         }
227 227
         $this->collection_name = str_replace(
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
      */
282 282
     protected function setIdentifierCallback($identifier_callback = 'identifier')
283 283
     {
284
-        if (! is_string($identifier_callback)) {
284
+        if ( ! is_string($identifier_callback)) {
285 285
             throw new InvalidDataTypeException('$identifier_callback', $identifier_callback, 'string');
286 286
         }
287 287
         $this->identifier_callback = $identifier_callback;
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
         $this->file_mask = ! empty($file_mask) ? $file_mask : '*.php';
312 312
         // we know our default is a string, so if it's not a string now,
313 313
         // then that means the incoming parameter was something else
314
-        if (! is_string($this->file_mask)) {
314
+        if ( ! is_string($this->file_mask)) {
315 315
             throw new InvalidDataTypeException('$file_mask', $this->file_mask, 'string');
316 316
         }
317 317
     }
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
     public function setCollectionFQCNs($collection_FQCNs)
337 337
     {
338 338
         foreach ((array) $collection_FQCNs as $collection_FQCN) {
339
-            if (! empty($collection_FQCN)) {
339
+            if ( ! empty($collection_FQCN)) {
340 340
                 if (class_exists($collection_FQCN)) {
341 341
                     $this->collection_FQCNs[] = $collection_FQCN;
342 342
                 } else {
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
      */
359 359
     protected function getFQCNsFromPartialNamespace($partial_FQCN)
360 360
     {
361
-        if (! $this->file_locator instanceof FqcnLocator) {
361
+        if ( ! $this->file_locator instanceof FqcnLocator) {
362 362
             $this->file_locator = new FqcnLocator();
363 363
         }
364 364
         $this->file_locator->locate($partial_FQCN);
@@ -384,8 +384,8 @@  discard block
 block discarded – undo
384 384
     public function setCollectionPaths($collection_paths)
385 385
     {
386 386
         foreach ((array) $collection_paths as $collection_path) {
387
-            if (! empty($collection_path)) {
388
-                if (! is_readable($collection_path)) {
387
+            if ( ! empty($collection_path)) {
388
+                if ( ! is_readable($collection_path)) {
389 389
                     throw new InvalidFilePathException($collection_path);
390 390
                 }
391 391
                 $this->collection_paths[] = $collection_path;
Please login to merge, or discard this patch.
core/services/notifications/PersistentAdminNoticeManager.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
      */
86 86
     public function setReturnUrl($return_url)
87 87
     {
88
-        if (! is_string($return_url)) {
88
+        if ( ! is_string($return_url)) {
89 89
             throw new InvalidDataTypeException('$return_url', $return_url, 'string');
90 90
         }
91 91
         $this->return_url = $return_url;
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
      */
103 103
     protected function getPersistentAdminNoticeCollection()
104 104
     {
105
-        if (! $this->notice_collection instanceof Collection) {
105
+        if ( ! $this->notice_collection instanceof Collection) {
106 106
             $this->notice_collection = new Collection(
107 107
                 'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
108 108
             );
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
     protected function retrieveStoredNotices()
126 126
     {
127 127
         $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
128
-        if (! empty($persistent_admin_notices)) {
128
+        if ( ! empty($persistent_admin_notices)) {
129 129
             foreach ($persistent_admin_notices as $name => $details) {
130 130
                 if (is_array($details)) {
131 131
                     if (
@@ -247,14 +247,14 @@  discard block
 block discarded – undo
247 247
     {
248 248
         wp_register_script(
249 249
             'espresso_core',
250
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
250
+            EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
251 251
             array('jquery'),
252 252
             EVENT_ESPRESSO_VERSION,
253 253
             true
254 254
         );
255 255
         wp_register_script(
256 256
             'ee_error_js',
257
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
257
+            EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js',
258 258
             array('espresso_core'),
259 259
             EVENT_ESPRESSO_VERSION,
260 260
             true
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
         // used in template
286 286
         $persistent_admin_notice_name = $persistent_admin_notice->getName();
287 287
         $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
288
-        require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
288
+        require EE_TEMPLATES.'/notifications/persistent_admin_notice.template.php';
289 289
     }
290 290
 
291 291
 
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
     {
311 311
         $pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
312 312
         $this->notice_collection = $this->getPersistentAdminNoticeCollection();
313
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
313
+        if ( ! empty($pan_name) && $this->notice_collection->has($pan_name)) {
314 314
             /** @var PersistentAdminNotice $persistent_admin_notice */
315 315
             $persistent_admin_notice = $this->notice_collection->get($pan_name);
316 316
             $persistent_admin_notice->setDismissed(true);
@@ -360,10 +360,10 @@  discard block
 block discarded – undo
360 360
             foreach ($this->notice_collection as $persistent_admin_notice) {
361 361
                 // are we deleting this notice ?
362 362
                 if ($persistent_admin_notice->getPurge()) {
363
-                    unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
363
+                    unset($persistent_admin_notices[$persistent_admin_notice->getName()]);
364 364
                 } else {
365 365
                     /** @var PersistentAdminNotice $persistent_admin_notice */
366
-                    $persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
366
+                    $persistent_admin_notices[$persistent_admin_notice->getName()] = array(
367 367
                         'message'     => $persistent_admin_notice->getMessage(),
368 368
                         'capability'  => $persistent_admin_notice->getCapability(),
369 369
                         'cap_context' => $persistent_admin_notice->getCapContext(),
Please login to merge, or discard this patch.
Indentation   +388 added lines, -388 removed lines patch added patch discarded remove patch
@@ -31,392 +31,392 @@
 block discarded – undo
31 31
 class PersistentAdminNoticeManager
32 32
 {
33 33
 
34
-    const WP_OPTION_KEY = 'ee_pers_admin_notices';
35
-
36
-    /**
37
-     * @var Collection|PersistentAdminNotice[] $notice_collection
38
-     */
39
-    private $notice_collection;
40
-
41
-    /**
42
-     * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
43
-     * persistent admin notice was displayed, and ultimately dismissed from.
44
-     *
45
-     * @var string $return_url
46
-     */
47
-    private $return_url;
48
-
49
-    /**
50
-     * @var CapabilitiesChecker $capabilities_checker
51
-     */
52
-    private $capabilities_checker;
53
-
54
-    /**
55
-     * @var RequestInterface $request
56
-     */
57
-    private $request;
58
-
59
-
60
-    /**
61
-     * PersistentAdminNoticeManager constructor
62
-     *
63
-     * @param CapabilitiesChecker $capabilities_checker
64
-     * @param RequestInterface    $request
65
-     * @param string              $return_url where to  redirect to after dismissing notices
66
-     * @throws InvalidDataTypeException
67
-     */
68
-    public function __construct(
69
-        CapabilitiesChecker $capabilities_checker,
70
-        RequestInterface $request,
71
-        $return_url = ''
72
-    ) {
73
-        $this->setReturnUrl($return_url);
74
-        $this->capabilities_checker = $capabilities_checker;
75
-        $this->request = $request;
76
-        // setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
77
-        // and we want to retrieve and generate any nag notices at the last possible moment
78
-        add_action('admin_notices', array($this, 'displayNotices'), 9);
79
-        add_action('network_admin_notices', array($this, 'displayNotices'), 9);
80
-        add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
81
-        add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
82
-    }
83
-
84
-
85
-    /**
86
-     * @param string $return_url
87
-     * @throws InvalidDataTypeException
88
-     */
89
-    public function setReturnUrl($return_url)
90
-    {
91
-        if (! is_string($return_url)) {
92
-            throw new InvalidDataTypeException('$return_url', $return_url, 'string');
93
-        }
94
-        $this->return_url = $return_url;
95
-    }
96
-
97
-
98
-    /**
99
-     * @return Collection
100
-     * @throws InvalidEntityException
101
-     * @throws InvalidInterfaceException
102
-     * @throws InvalidDataTypeException
103
-     * @throws DomainException
104
-     * @throws DuplicateCollectionIdentifierException
105
-     */
106
-    protected function getPersistentAdminNoticeCollection()
107
-    {
108
-        if (! $this->notice_collection instanceof Collection) {
109
-            $this->notice_collection = new Collection(
110
-                'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
111
-            );
112
-            $this->retrieveStoredNotices();
113
-            $this->registerNotices();
114
-        }
115
-        return $this->notice_collection;
116
-    }
117
-
118
-
119
-    /**
120
-     * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
121
-     *
122
-     * @return void
123
-     * @throws InvalidEntityException
124
-     * @throws DomainException
125
-     * @throws InvalidDataTypeException
126
-     * @throws DuplicateCollectionIdentifierException
127
-     */
128
-    protected function retrieveStoredNotices()
129
-    {
130
-        $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
131
-        if (! empty($persistent_admin_notices)) {
132
-            foreach ($persistent_admin_notices as $name => $details) {
133
-                if (is_array($details)) {
134
-                    if (
135
-                        ! isset(
136
-                            $details['message'],
137
-                            $details['capability'],
138
-                            $details['cap_context'],
139
-                            $details['dismissed']
140
-                        )
141
-                    ) {
142
-                        throw new DomainException(
143
-                            sprintf(
144
-                                esc_html__(
145
-                                    'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
146
-                                    'event_espresso'
147
-                                ),
148
-                                $name
149
-                            )
150
-                        );
151
-                    }
152
-                    // new format for nag notices
153
-                    $this->notice_collection->add(
154
-                        new PersistentAdminNotice(
155
-                            $name,
156
-                            $details['message'],
157
-                            false,
158
-                            $details['capability'],
159
-                            $details['cap_context'],
160
-                            $details['dismissed']
161
-                        ),
162
-                        sanitize_key($name)
163
-                    );
164
-                } else {
165
-                    try {
166
-                        // old nag notices, that we want to convert to the new format
167
-                        $this->notice_collection->add(
168
-                            new PersistentAdminNotice(
169
-                                $name,
170
-                                (string) $details,
171
-                                false,
172
-                                '',
173
-                                '',
174
-                                empty($details)
175
-                            ),
176
-                            sanitize_key($name)
177
-                        );
178
-                    } catch (Exception $e) {
179
-                        EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
180
-                    }
181
-                }
182
-                // each notice will self register when the action hook in registerNotices is triggered
183
-            }
184
-        }
185
-    }
186
-
187
-
188
-    /**
189
-     * exposes the Persistent Admin Notice Collection via an action
190
-     * so that PersistentAdminNotice objects can be added and/or removed
191
-     * without compromising the actual collection like a filter would
192
-     */
193
-    protected function registerNotices()
194
-    {
195
-        do_action(
196
-            'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
197
-            $this->notice_collection
198
-        );
199
-    }
200
-
201
-
202
-    /**
203
-     * @throws DomainException
204
-     * @throws InvalidClassException
205
-     * @throws InvalidDataTypeException
206
-     * @throws InvalidInterfaceException
207
-     * @throws InvalidEntityException
208
-     * @throws DuplicateCollectionIdentifierException
209
-     */
210
-    public function displayNotices()
211
-    {
212
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
213
-        if ($this->notice_collection->hasObjects()) {
214
-            $enqueue_assets = false;
215
-            // and display notices
216
-            foreach ($this->notice_collection as $persistent_admin_notice) {
217
-                /** @var PersistentAdminNotice $persistent_admin_notice */
218
-                // don't display notices that have already been dismissed
219
-                if ($persistent_admin_notice->getDismissed()) {
220
-                    continue;
221
-                }
222
-                try {
223
-                    $this->capabilities_checker->processCapCheck(
224
-                        $persistent_admin_notice->getCapCheck()
225
-                    );
226
-                } catch (InsufficientPermissionsException $e) {
227
-                    // user does not have required cap, so skip to next notice
228
-                    // and just eat the exception - nom nom nom nom
229
-                    continue;
230
-                }
231
-                if ($persistent_admin_notice->getMessage() === '') {
232
-                    continue;
233
-                }
234
-                $this->displayPersistentAdminNotice($persistent_admin_notice);
235
-                $enqueue_assets = true;
236
-            }
237
-            if ($enqueue_assets) {
238
-                $this->enqueueAssets();
239
-            }
240
-        }
241
-    }
242
-
243
-
244
-    /**
245
-     * does what it's named
246
-     *
247
-     * @return void
248
-     */
249
-    public function enqueueAssets()
250
-    {
251
-        wp_register_script(
252
-            'espresso_core',
253
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
254
-            array('jquery'),
255
-            EVENT_ESPRESSO_VERSION,
256
-            true
257
-        );
258
-        wp_register_script(
259
-            'ee_error_js',
260
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
261
-            array('espresso_core'),
262
-            EVENT_ESPRESSO_VERSION,
263
-            true
264
-        );
265
-        wp_localize_script(
266
-            'ee_error_js',
267
-            'ee_dismiss',
268
-            array(
269
-                'return_url'    => urlencode($this->return_url),
270
-                'ajax_url'      => WP_AJAX_URL,
271
-                'unknown_error' => wp_strip_all_tags(
272
-                    __(
273
-                        'An unknown error has occurred on the server while attempting to dismiss this notice.',
274
-                        'event_espresso'
275
-                    )
276
-                ),
277
-            )
278
-        );
279
-        wp_enqueue_script('ee_error_js');
280
-    }
281
-
282
-
283
-    /**
284
-     * displayPersistentAdminNoticeHtml
285
-     *
286
-     * @param  PersistentAdminNotice $persistent_admin_notice
287
-     */
288
-    protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
289
-    {
290
-        // used in template
291
-        $persistent_admin_notice_name = $persistent_admin_notice->getName();
292
-        $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
293
-        require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
294
-    }
295
-
296
-
297
-    /**
298
-     * dismissNotice
299
-     *
300
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
301
-     * @param bool   $purge    if true, then delete it from the db
302
-     * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
303
-     * @return void
304
-     * @throws InvalidEntityException
305
-     * @throws InvalidInterfaceException
306
-     * @throws InvalidDataTypeException
307
-     * @throws DomainException
308
-     * @throws InvalidArgumentException
309
-     * @throws InvalidArgumentException
310
-     * @throws InvalidArgumentException
311
-     * @throws InvalidArgumentException
312
-     * @throws DuplicateCollectionIdentifierException
313
-     */
314
-    public function dismissNotice($pan_name = '', $purge = false, $return = false)
315
-    {
316
-        $pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
317
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
318
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
319
-            /** @var PersistentAdminNotice $persistent_admin_notice */
320
-            $persistent_admin_notice = $this->notice_collection->get($pan_name);
321
-            $persistent_admin_notice->setDismissed(true);
322
-            $persistent_admin_notice->setPurge($purge);
323
-            $this->saveNotices();
324
-        }
325
-        if ($return) {
326
-            return;
327
-        }
328
-        if ($this->request->isAjax()) {
329
-            // grab any notices and concatenate into string
330
-            echo wp_json_encode(
331
-                array(
332
-                    'errors' => implode('<br />', EE_Error::get_notices(false)),
333
-                )
334
-            );
335
-            exit();
336
-        }
337
-        // save errors to a transient to be displayed on next request (after redirect)
338
-        EE_Error::get_notices(false, true);
339
-        wp_safe_redirect(
340
-            urldecode(
341
-                $this->request->getRequestParam('return_url', '')
342
-            )
343
-        );
344
-    }
345
-
346
-
347
-    /**
348
-     * saveNotices
349
-     *
350
-     * @throws DomainException
351
-     * @throws InvalidDataTypeException
352
-     * @throws InvalidInterfaceException
353
-     * @throws InvalidEntityException
354
-     * @throws DuplicateCollectionIdentifierException
355
-     */
356
-    public function saveNotices()
357
-    {
358
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
359
-        if ($this->notice_collection->hasObjects()) {
360
-            $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
361
-            // maybe initialize persistent_admin_notices
362
-            if (empty($persistent_admin_notices)) {
363
-                add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
364
-            }
365
-            foreach ($this->notice_collection as $persistent_admin_notice) {
366
-                // are we deleting this notice ?
367
-                if ($persistent_admin_notice->getPurge()) {
368
-                    unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
369
-                } else {
370
-                    /** @var PersistentAdminNotice $persistent_admin_notice */
371
-                    $persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
372
-                        'message'     => $persistent_admin_notice->getMessage(),
373
-                        'capability'  => $persistent_admin_notice->getCapability(),
374
-                        'cap_context' => $persistent_admin_notice->getCapContext(),
375
-                        'dismissed'   => $persistent_admin_notice->getDismissed(),
376
-                    );
377
-                }
378
-            }
379
-            update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
380
-        }
381
-    }
382
-
383
-
384
-    /**
385
-     * @throws DomainException
386
-     * @throws InvalidDataTypeException
387
-     * @throws InvalidEntityException
388
-     * @throws InvalidInterfaceException
389
-     * @throws DuplicateCollectionIdentifierException
390
-     */
391
-    public function registerAndSaveNotices()
392
-    {
393
-        $this->getPersistentAdminNoticeCollection();
394
-        $this->registerNotices();
395
-        $this->saveNotices();
396
-        add_filter(
397
-            'PersistentAdminNoticeManager__registerAndSaveNotices__complete',
398
-            '__return_true'
399
-        );
400
-    }
401
-
402
-
403
-    /**
404
-     * @throws DomainException
405
-     * @throws InvalidDataTypeException
406
-     * @throws InvalidEntityException
407
-     * @throws InvalidInterfaceException
408
-     * @throws InvalidArgumentException
409
-     * @throws DuplicateCollectionIdentifierException
410
-     */
411
-    public static function loadRegisterAndSaveNotices()
412
-    {
413
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
414
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
415
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
416
-        );
417
-        // if shutdown has already run, then call registerAndSaveNotices() manually
418
-        if (did_action('shutdown')) {
419
-            $persistent_admin_notice_manager->registerAndSaveNotices();
420
-        }
421
-    }
34
+	const WP_OPTION_KEY = 'ee_pers_admin_notices';
35
+
36
+	/**
37
+	 * @var Collection|PersistentAdminNotice[] $notice_collection
38
+	 */
39
+	private $notice_collection;
40
+
41
+	/**
42
+	 * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
43
+	 * persistent admin notice was displayed, and ultimately dismissed from.
44
+	 *
45
+	 * @var string $return_url
46
+	 */
47
+	private $return_url;
48
+
49
+	/**
50
+	 * @var CapabilitiesChecker $capabilities_checker
51
+	 */
52
+	private $capabilities_checker;
53
+
54
+	/**
55
+	 * @var RequestInterface $request
56
+	 */
57
+	private $request;
58
+
59
+
60
+	/**
61
+	 * PersistentAdminNoticeManager constructor
62
+	 *
63
+	 * @param CapabilitiesChecker $capabilities_checker
64
+	 * @param RequestInterface    $request
65
+	 * @param string              $return_url where to  redirect to after dismissing notices
66
+	 * @throws InvalidDataTypeException
67
+	 */
68
+	public function __construct(
69
+		CapabilitiesChecker $capabilities_checker,
70
+		RequestInterface $request,
71
+		$return_url = ''
72
+	) {
73
+		$this->setReturnUrl($return_url);
74
+		$this->capabilities_checker = $capabilities_checker;
75
+		$this->request = $request;
76
+		// setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
77
+		// and we want to retrieve and generate any nag notices at the last possible moment
78
+		add_action('admin_notices', array($this, 'displayNotices'), 9);
79
+		add_action('network_admin_notices', array($this, 'displayNotices'), 9);
80
+		add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
81
+		add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
82
+	}
83
+
84
+
85
+	/**
86
+	 * @param string $return_url
87
+	 * @throws InvalidDataTypeException
88
+	 */
89
+	public function setReturnUrl($return_url)
90
+	{
91
+		if (! is_string($return_url)) {
92
+			throw new InvalidDataTypeException('$return_url', $return_url, 'string');
93
+		}
94
+		$this->return_url = $return_url;
95
+	}
96
+
97
+
98
+	/**
99
+	 * @return Collection
100
+	 * @throws InvalidEntityException
101
+	 * @throws InvalidInterfaceException
102
+	 * @throws InvalidDataTypeException
103
+	 * @throws DomainException
104
+	 * @throws DuplicateCollectionIdentifierException
105
+	 */
106
+	protected function getPersistentAdminNoticeCollection()
107
+	{
108
+		if (! $this->notice_collection instanceof Collection) {
109
+			$this->notice_collection = new Collection(
110
+				'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
111
+			);
112
+			$this->retrieveStoredNotices();
113
+			$this->registerNotices();
114
+		}
115
+		return $this->notice_collection;
116
+	}
117
+
118
+
119
+	/**
120
+	 * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
121
+	 *
122
+	 * @return void
123
+	 * @throws InvalidEntityException
124
+	 * @throws DomainException
125
+	 * @throws InvalidDataTypeException
126
+	 * @throws DuplicateCollectionIdentifierException
127
+	 */
128
+	protected function retrieveStoredNotices()
129
+	{
130
+		$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
131
+		if (! empty($persistent_admin_notices)) {
132
+			foreach ($persistent_admin_notices as $name => $details) {
133
+				if (is_array($details)) {
134
+					if (
135
+						! isset(
136
+							$details['message'],
137
+							$details['capability'],
138
+							$details['cap_context'],
139
+							$details['dismissed']
140
+						)
141
+					) {
142
+						throw new DomainException(
143
+							sprintf(
144
+								esc_html__(
145
+									'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
146
+									'event_espresso'
147
+								),
148
+								$name
149
+							)
150
+						);
151
+					}
152
+					// new format for nag notices
153
+					$this->notice_collection->add(
154
+						new PersistentAdminNotice(
155
+							$name,
156
+							$details['message'],
157
+							false,
158
+							$details['capability'],
159
+							$details['cap_context'],
160
+							$details['dismissed']
161
+						),
162
+						sanitize_key($name)
163
+					);
164
+				} else {
165
+					try {
166
+						// old nag notices, that we want to convert to the new format
167
+						$this->notice_collection->add(
168
+							new PersistentAdminNotice(
169
+								$name,
170
+								(string) $details,
171
+								false,
172
+								'',
173
+								'',
174
+								empty($details)
175
+							),
176
+							sanitize_key($name)
177
+						);
178
+					} catch (Exception $e) {
179
+						EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
180
+					}
181
+				}
182
+				// each notice will self register when the action hook in registerNotices is triggered
183
+			}
184
+		}
185
+	}
186
+
187
+
188
+	/**
189
+	 * exposes the Persistent Admin Notice Collection via an action
190
+	 * so that PersistentAdminNotice objects can be added and/or removed
191
+	 * without compromising the actual collection like a filter would
192
+	 */
193
+	protected function registerNotices()
194
+	{
195
+		do_action(
196
+			'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
197
+			$this->notice_collection
198
+		);
199
+	}
200
+
201
+
202
+	/**
203
+	 * @throws DomainException
204
+	 * @throws InvalidClassException
205
+	 * @throws InvalidDataTypeException
206
+	 * @throws InvalidInterfaceException
207
+	 * @throws InvalidEntityException
208
+	 * @throws DuplicateCollectionIdentifierException
209
+	 */
210
+	public function displayNotices()
211
+	{
212
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
213
+		if ($this->notice_collection->hasObjects()) {
214
+			$enqueue_assets = false;
215
+			// and display notices
216
+			foreach ($this->notice_collection as $persistent_admin_notice) {
217
+				/** @var PersistentAdminNotice $persistent_admin_notice */
218
+				// don't display notices that have already been dismissed
219
+				if ($persistent_admin_notice->getDismissed()) {
220
+					continue;
221
+				}
222
+				try {
223
+					$this->capabilities_checker->processCapCheck(
224
+						$persistent_admin_notice->getCapCheck()
225
+					);
226
+				} catch (InsufficientPermissionsException $e) {
227
+					// user does not have required cap, so skip to next notice
228
+					// and just eat the exception - nom nom nom nom
229
+					continue;
230
+				}
231
+				if ($persistent_admin_notice->getMessage() === '') {
232
+					continue;
233
+				}
234
+				$this->displayPersistentAdminNotice($persistent_admin_notice);
235
+				$enqueue_assets = true;
236
+			}
237
+			if ($enqueue_assets) {
238
+				$this->enqueueAssets();
239
+			}
240
+		}
241
+	}
242
+
243
+
244
+	/**
245
+	 * does what it's named
246
+	 *
247
+	 * @return void
248
+	 */
249
+	public function enqueueAssets()
250
+	{
251
+		wp_register_script(
252
+			'espresso_core',
253
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
254
+			array('jquery'),
255
+			EVENT_ESPRESSO_VERSION,
256
+			true
257
+		);
258
+		wp_register_script(
259
+			'ee_error_js',
260
+			EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
261
+			array('espresso_core'),
262
+			EVENT_ESPRESSO_VERSION,
263
+			true
264
+		);
265
+		wp_localize_script(
266
+			'ee_error_js',
267
+			'ee_dismiss',
268
+			array(
269
+				'return_url'    => urlencode($this->return_url),
270
+				'ajax_url'      => WP_AJAX_URL,
271
+				'unknown_error' => wp_strip_all_tags(
272
+					__(
273
+						'An unknown error has occurred on the server while attempting to dismiss this notice.',
274
+						'event_espresso'
275
+					)
276
+				),
277
+			)
278
+		);
279
+		wp_enqueue_script('ee_error_js');
280
+	}
281
+
282
+
283
+	/**
284
+	 * displayPersistentAdminNoticeHtml
285
+	 *
286
+	 * @param  PersistentAdminNotice $persistent_admin_notice
287
+	 */
288
+	protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
289
+	{
290
+		// used in template
291
+		$persistent_admin_notice_name = $persistent_admin_notice->getName();
292
+		$persistent_admin_notice_message = $persistent_admin_notice->getMessage();
293
+		require EE_TEMPLATES . '/notifications/persistent_admin_notice.template.php';
294
+	}
295
+
296
+
297
+	/**
298
+	 * dismissNotice
299
+	 *
300
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
301
+	 * @param bool   $purge    if true, then delete it from the db
302
+	 * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
303
+	 * @return void
304
+	 * @throws InvalidEntityException
305
+	 * @throws InvalidInterfaceException
306
+	 * @throws InvalidDataTypeException
307
+	 * @throws DomainException
308
+	 * @throws InvalidArgumentException
309
+	 * @throws InvalidArgumentException
310
+	 * @throws InvalidArgumentException
311
+	 * @throws InvalidArgumentException
312
+	 * @throws DuplicateCollectionIdentifierException
313
+	 */
314
+	public function dismissNotice($pan_name = '', $purge = false, $return = false)
315
+	{
316
+		$pan_name = $this->request->getRequestParam('ee_nag_notice', $pan_name);
317
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
318
+		if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
319
+			/** @var PersistentAdminNotice $persistent_admin_notice */
320
+			$persistent_admin_notice = $this->notice_collection->get($pan_name);
321
+			$persistent_admin_notice->setDismissed(true);
322
+			$persistent_admin_notice->setPurge($purge);
323
+			$this->saveNotices();
324
+		}
325
+		if ($return) {
326
+			return;
327
+		}
328
+		if ($this->request->isAjax()) {
329
+			// grab any notices and concatenate into string
330
+			echo wp_json_encode(
331
+				array(
332
+					'errors' => implode('<br />', EE_Error::get_notices(false)),
333
+				)
334
+			);
335
+			exit();
336
+		}
337
+		// save errors to a transient to be displayed on next request (after redirect)
338
+		EE_Error::get_notices(false, true);
339
+		wp_safe_redirect(
340
+			urldecode(
341
+				$this->request->getRequestParam('return_url', '')
342
+			)
343
+		);
344
+	}
345
+
346
+
347
+	/**
348
+	 * saveNotices
349
+	 *
350
+	 * @throws DomainException
351
+	 * @throws InvalidDataTypeException
352
+	 * @throws InvalidInterfaceException
353
+	 * @throws InvalidEntityException
354
+	 * @throws DuplicateCollectionIdentifierException
355
+	 */
356
+	public function saveNotices()
357
+	{
358
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
359
+		if ($this->notice_collection->hasObjects()) {
360
+			$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
361
+			// maybe initialize persistent_admin_notices
362
+			if (empty($persistent_admin_notices)) {
363
+				add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
364
+			}
365
+			foreach ($this->notice_collection as $persistent_admin_notice) {
366
+				// are we deleting this notice ?
367
+				if ($persistent_admin_notice->getPurge()) {
368
+					unset($persistent_admin_notices[ $persistent_admin_notice->getName() ]);
369
+				} else {
370
+					/** @var PersistentAdminNotice $persistent_admin_notice */
371
+					$persistent_admin_notices[ $persistent_admin_notice->getName() ] = array(
372
+						'message'     => $persistent_admin_notice->getMessage(),
373
+						'capability'  => $persistent_admin_notice->getCapability(),
374
+						'cap_context' => $persistent_admin_notice->getCapContext(),
375
+						'dismissed'   => $persistent_admin_notice->getDismissed(),
376
+					);
377
+				}
378
+			}
379
+			update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
380
+		}
381
+	}
382
+
383
+
384
+	/**
385
+	 * @throws DomainException
386
+	 * @throws InvalidDataTypeException
387
+	 * @throws InvalidEntityException
388
+	 * @throws InvalidInterfaceException
389
+	 * @throws DuplicateCollectionIdentifierException
390
+	 */
391
+	public function registerAndSaveNotices()
392
+	{
393
+		$this->getPersistentAdminNoticeCollection();
394
+		$this->registerNotices();
395
+		$this->saveNotices();
396
+		add_filter(
397
+			'PersistentAdminNoticeManager__registerAndSaveNotices__complete',
398
+			'__return_true'
399
+		);
400
+	}
401
+
402
+
403
+	/**
404
+	 * @throws DomainException
405
+	 * @throws InvalidDataTypeException
406
+	 * @throws InvalidEntityException
407
+	 * @throws InvalidInterfaceException
408
+	 * @throws InvalidArgumentException
409
+	 * @throws DuplicateCollectionIdentifierException
410
+	 */
411
+	public static function loadRegisterAndSaveNotices()
412
+	{
413
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
414
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
415
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
416
+		);
417
+		// if shutdown has already run, then call registerAndSaveNotices() manually
418
+		if (did_action('shutdown')) {
419
+			$persistent_admin_notice_manager->registerAndSaveNotices();
420
+		}
421
+	}
422 422
 }
Please login to merge, or discard this patch.
core/services/database/TableAnalysis.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
     public function ensureTableNameHasPrefix($table_name)
33 33
     {
34 34
         global $wpdb;
35
-        return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix . $table_name;
35
+        return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix.$table_name;
36 36
     }
37 37
 
38 38
 
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
         $wpdb->last_error = $old_error;
82 82
         $EZSQL_ERROR = $ezsql_error_cache;
83 83
         // if there was a table doesn't exist error
84
-        if (! empty($new_error)) {
84
+        if ( ! empty($new_error)) {
85 85
             if (
86 86
                 in_array(
87 87
                     \EEH_Activation::last_wpdb_error_code(),
Please login to merge, or discard this patch.
Indentation   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -14,132 +14,132 @@
 block discarded – undo
14 14
 class TableAnalysis extends \EE_Base
15 15
 {
16 16
 
17
-    /**
18
-     * The maximum number of characters that can be indexed on a column using utf8mb4 collation,
19
-     * see https://events.codebasehq.com/redirect?https://make.wordpress.org/core/2015/04/02/the-utf8mb4-upgrade/
20
-     */
21
-    const INDEX_COLUMN_SIZE = 191;
17
+	/**
18
+	 * The maximum number of characters that can be indexed on a column using utf8mb4 collation,
19
+	 * see https://events.codebasehq.com/redirect?https://make.wordpress.org/core/2015/04/02/the-utf8mb4-upgrade/
20
+	 */
21
+	const INDEX_COLUMN_SIZE = 191;
22 22
 
23
-    /**
24
-     * Returns the table name which will definitely have the wpdb prefix on the front,
25
-     * except if it currently has the wpdb->base_prefix on the front, in which case
26
-     * it will have the wpdb->base_prefix on it
27
-     *
28
-     * @global \wpdb $wpdb
29
-     * @param string $table_name
30
-     * @return string $tableName, having ensured it has the wpdb prefix on the front
31
-     */
32
-    public function ensureTableNameHasPrefix($table_name)
33
-    {
34
-        global $wpdb;
35
-        return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix . $table_name;
36
-    }
23
+	/**
24
+	 * Returns the table name which will definitely have the wpdb prefix on the front,
25
+	 * except if it currently has the wpdb->base_prefix on the front, in which case
26
+	 * it will have the wpdb->base_prefix on it
27
+	 *
28
+	 * @global \wpdb $wpdb
29
+	 * @param string $table_name
30
+	 * @return string $tableName, having ensured it has the wpdb prefix on the front
31
+	 */
32
+	public function ensureTableNameHasPrefix($table_name)
33
+	{
34
+		global $wpdb;
35
+		return strpos($table_name, $wpdb->base_prefix) === 0 ? $table_name : $wpdb->prefix . $table_name;
36
+	}
37 37
 
38 38
 
39
-    /**
40
-     * Indicates whether or not the table has any entries. $table_name can
41
-     * optionally start with $wpdb->prefix or not
42
-     *
43
-     * @global \wpdb $wpdb
44
-     * @param string $table_name
45
-     * @return bool
46
-     */
47
-    public function tableIsEmpty($table_name)
48
-    {
49
-        global $wpdb;
50
-        $table_name = $this->ensureTableNameHasPrefix($table_name);
51
-        if ($this->tableExists($table_name)) {
52
-            $count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
53
-            return absint($count) === 0 ? true : false;
54
-        }
55
-        return false;
56
-    }
39
+	/**
40
+	 * Indicates whether or not the table has any entries. $table_name can
41
+	 * optionally start with $wpdb->prefix or not
42
+	 *
43
+	 * @global \wpdb $wpdb
44
+	 * @param string $table_name
45
+	 * @return bool
46
+	 */
47
+	public function tableIsEmpty($table_name)
48
+	{
49
+		global $wpdb;
50
+		$table_name = $this->ensureTableNameHasPrefix($table_name);
51
+		if ($this->tableExists($table_name)) {
52
+			$count = $wpdb->get_var("SELECT COUNT(*) FROM $table_name");
53
+			return absint($count) === 0 ? true : false;
54
+		}
55
+		return false;
56
+	}
57 57
 
58 58
 
59
-    /**
60
-     * Indicates whether or not the table exists. $table_name can optionally
61
-     * have the $wpdb->prefix on the beginning, or not.
62
-     *
63
-     * @global \wpdb $wpdb
64
-     * @global array EZSQL_Error
65
-     * @param        $table_name
66
-     * @return bool
67
-     */
68
-    public function tableExists($table_name)
69
-    {
70
-        global $wpdb, $EZSQL_ERROR;
71
-        $table_name = $this->ensureTableNameHasPrefix($table_name);
72
-        // ignore if this causes an sql error
73
-        $old_error = $wpdb->last_error;
74
-        $old_suppress_errors = $wpdb->suppress_errors();
75
-        $old_show_errors_value = $wpdb->show_errors(false);
76
-        $ezsql_error_cache = $EZSQL_ERROR;
77
-        $wpdb->get_results("SELECT * from $table_name LIMIT 1");
78
-        $wpdb->show_errors($old_show_errors_value);
79
-        $wpdb->suppress_errors($old_suppress_errors);
80
-        $new_error = $wpdb->last_error;
81
-        $wpdb->last_error = $old_error;
82
-        $EZSQL_ERROR = $ezsql_error_cache;
83
-        // if there was a table doesn't exist error
84
-        if (! empty($new_error)) {
85
-            if (
86
-                in_array(
87
-                    \EEH_Activation::last_wpdb_error_code(),
88
-                    array(
89
-                    1051, // bad table
90
-                    1109, // unknown table
91
-                    117, // no such table
92
-                    )
93
-                )
94
-                ||
95
-                preg_match(
96
-                    '~^Table .* doesn\'t exist~',
97
-                    $new_error
98
-                ) // in case not using mysql and error codes aren't reliable, just check for this error string
99
-            ) {
100
-                return false;
101
-            } else {
102
-                // log this because that's weird. Just use the normal PHP error log
103
-                error_log(
104
-                    sprintf(
105
-                        esc_html__(
106
-                            'Event Espresso error detected when checking if table existed: %1$s (it wasn\'t just that the table didn\'t exist either)',
107
-                            'event_espresso'
108
-                        ),
109
-                        $new_error
110
-                    )
111
-                );
112
-            }
113
-        }
114
-        return true;
115
-    }
59
+	/**
60
+	 * Indicates whether or not the table exists. $table_name can optionally
61
+	 * have the $wpdb->prefix on the beginning, or not.
62
+	 *
63
+	 * @global \wpdb $wpdb
64
+	 * @global array EZSQL_Error
65
+	 * @param        $table_name
66
+	 * @return bool
67
+	 */
68
+	public function tableExists($table_name)
69
+	{
70
+		global $wpdb, $EZSQL_ERROR;
71
+		$table_name = $this->ensureTableNameHasPrefix($table_name);
72
+		// ignore if this causes an sql error
73
+		$old_error = $wpdb->last_error;
74
+		$old_suppress_errors = $wpdb->suppress_errors();
75
+		$old_show_errors_value = $wpdb->show_errors(false);
76
+		$ezsql_error_cache = $EZSQL_ERROR;
77
+		$wpdb->get_results("SELECT * from $table_name LIMIT 1");
78
+		$wpdb->show_errors($old_show_errors_value);
79
+		$wpdb->suppress_errors($old_suppress_errors);
80
+		$new_error = $wpdb->last_error;
81
+		$wpdb->last_error = $old_error;
82
+		$EZSQL_ERROR = $ezsql_error_cache;
83
+		// if there was a table doesn't exist error
84
+		if (! empty($new_error)) {
85
+			if (
86
+				in_array(
87
+					\EEH_Activation::last_wpdb_error_code(),
88
+					array(
89
+					1051, // bad table
90
+					1109, // unknown table
91
+					117, // no such table
92
+					)
93
+				)
94
+				||
95
+				preg_match(
96
+					'~^Table .* doesn\'t exist~',
97
+					$new_error
98
+				) // in case not using mysql and error codes aren't reliable, just check for this error string
99
+			) {
100
+				return false;
101
+			} else {
102
+				// log this because that's weird. Just use the normal PHP error log
103
+				error_log(
104
+					sprintf(
105
+						esc_html__(
106
+							'Event Espresso error detected when checking if table existed: %1$s (it wasn\'t just that the table didn\'t exist either)',
107
+							'event_espresso'
108
+						),
109
+						$new_error
110
+					)
111
+				);
112
+			}
113
+		}
114
+		return true;
115
+	}
116 116
 
117 117
 
118
-    /**
119
-     * @param $table_name
120
-     * @param $index_name
121
-     * @return array of columns used on that index, Each entry is an object with the following properties {
122
-     * @type string Table
123
-     * @type string Non_unique "0" or "1"
124
-     * @type string Key_name
125
-     * @type string Seq_in_index
126
-     * @type string Column_name
127
-     * @type string Collation
128
-     * @type string Cardinality
129
-     * @type string Sub_part on a column, usually this is just the number of characters from this column to use in
130
-     *       indexing
131
-     * @type string|null Packed
132
-     * @type string Null
133
-     * @type string Index_type
134
-     * @type string Comment
135
-     * @type string Index_comment
136
-     * }
137
-     */
138
-    public function showIndexes($table_name, $index_name)
139
-    {
140
-        global $wpdb;
141
-        $table_name = $this->ensureTableNameHasPrefix($table_name);
142
-        $index_exists_query = "SHOW INDEX FROM {$table_name} WHERE Key_name = '{$index_name}'";
143
-        return $wpdb->get_results($index_exists_query);
144
-    }
118
+	/**
119
+	 * @param $table_name
120
+	 * @param $index_name
121
+	 * @return array of columns used on that index, Each entry is an object with the following properties {
122
+	 * @type string Table
123
+	 * @type string Non_unique "0" or "1"
124
+	 * @type string Key_name
125
+	 * @type string Seq_in_index
126
+	 * @type string Column_name
127
+	 * @type string Collation
128
+	 * @type string Cardinality
129
+	 * @type string Sub_part on a column, usually this is just the number of characters from this column to use in
130
+	 *       indexing
131
+	 * @type string|null Packed
132
+	 * @type string Null
133
+	 * @type string Index_type
134
+	 * @type string Comment
135
+	 * @type string Index_comment
136
+	 * }
137
+	 */
138
+	public function showIndexes($table_name, $index_name)
139
+	{
140
+		global $wpdb;
141
+		$table_name = $this->ensureTableNameHasPrefix($table_name);
142
+		$index_exists_query = "SHOW INDEX FROM {$table_name} WHERE Key_name = '{$index_name}'";
143
+		return $wpdb->get_results($index_exists_query);
144
+	}
145 145
 }
Please login to merge, or discard this patch.
core/services/cache/TransientCacheStorage.php 2 patches
Indentation   +363 added lines, -363 removed lines patch added patch discarded remove patch
@@ -16,367 +16,367 @@
 block discarded – undo
16 16
 class TransientCacheStorage implements CacheStorageInterface
17 17
 {
18 18
 
19
-    /**
20
-     * wp-option option_name for tracking transients
21
-     *
22
-     * @type string
23
-     */
24
-    const TRANSIENT_SCHEDULE_OPTIONS_KEY = 'ee_transient_schedule';
25
-
26
-    /**
27
-     * @var int $current_time
28
-     */
29
-    private $current_time;
30
-
31
-    /**
32
-     * how often to perform transient cleanup
33
-     *
34
-     * @var string $transient_cleanup_frequency
35
-     */
36
-    private $transient_cleanup_frequency;
37
-
38
-    /**
39
-     * options for how often to perform transient cleanup
40
-     *
41
-     * @var array $transient_cleanup_frequency_options
42
-     */
43
-    private $transient_cleanup_frequency_options = array();
44
-
45
-    /**
46
-     * @var array $transients
47
-     */
48
-    private $transients;
49
-
50
-
51
-    /**
52
-     * TransientCacheStorage constructor.
53
-     */
54
-    public function __construct()
55
-    {
56
-        $this->transient_cleanup_frequency = $this->setTransientCleanupFrequency();
57
-        // round current time down to closest 5 minutes to simplify scheduling
58
-        $this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
59
-        $this->transients = (array) get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
60
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
61
-            add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
62
-        }
63
-    }
64
-
65
-
66
-    /**
67
-     * Sets how often transient cleanup occurs
68
-     *
69
-     * @return string
70
-     */
71
-    private function setTransientCleanupFrequency()
72
-    {
73
-        // sets how often transients are cleaned up
74
-        $this->transient_cleanup_frequency_options = apply_filters(
75
-            'FHEE__TransientCacheStorage__transient_cleanup_schedule_options',
76
-            array(
77
-                'off',
78
-                '15-minutes',
79
-                'hour',
80
-                '12-hours',
81
-                'day',
82
-            )
83
-        );
84
-        $transient_cleanup_frequency = apply_filters(
85
-            'FHEE__TransientCacheStorage__transient_cleanup_schedule',
86
-            'hour'
87
-        );
88
-        return in_array(
89
-            $transient_cleanup_frequency,
90
-            $this->transient_cleanup_frequency_options,
91
-            true
92
-        )
93
-            ? $transient_cleanup_frequency
94
-            : 'hour';
95
-    }
96
-
97
-
98
-    /**
99
-     * we need to be able to round timestamps off to match the set transient cleanup frequency
100
-     * so if a transient is set to expire at 1:17 pm for example, and our cleanup schedule is every hour,
101
-     * then that timestamp needs to be rounded up to 2:00 pm so that it is removed
102
-     * during the next scheduled cleanup after its expiration.
103
-     * We also round off the current time timestamp to the closest 5 minutes
104
-     * just to make the timestamps a little easier to round which helps with debugging.
105
-     *
106
-     * @param int    $timestamp [required]
107
-     * @param string $cleanup_frequency
108
-     * @param bool   $round_up
109
-     * @return int
110
-     */
111
-    private function roundTimestamp($timestamp, $cleanup_frequency = 'hour', $round_up = true)
112
-    {
113
-        $cleanup_frequency = $cleanup_frequency ? $cleanup_frequency : $this->transient_cleanup_frequency;
114
-        // in order to round the time to the closest xx minutes (or hours),
115
-        // we take the minutes (or hours) portion of the timestamp and divide it by xx,
116
-        // round down to a whole number, then multiply by xx to bring us almost back up to where we were
117
-        // why round down ? so the minutes (or hours) don't go over 60 (or 24)
118
-        // and bump the hour, which could bump the day, which could bump the month, etc,
119
-        // which would be bad because we don't always want to round up,
120
-        // but when we do we can easily achieve that by simply adding the desired offset,
121
-        $minutes = '00';
122
-        $hours = 'H';
123
-        switch ($cleanup_frequency) {
124
-            case '5-minutes':
125
-                $minutes = floor((int) date('i', $timestamp) / 5) * 5;
126
-                $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
127
-                $offset = MINUTE_IN_SECONDS * 5;
128
-                break;
129
-            case '15-minutes':
130
-                $minutes = floor((int) date('i', $timestamp) / 15) * 15;
131
-                $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
132
-                $offset = MINUTE_IN_SECONDS * 15;
133
-                break;
134
-            case '12-hours':
135
-                $hours = floor((int) date('H', $timestamp) / 12) * 12;
136
-                $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
137
-                $offset = HOUR_IN_SECONDS * 12;
138
-                break;
139
-            case 'day':
140
-                $hours = '03'; // run cleanup at 3:00 am (or first site hit after that)
141
-                $offset = DAY_IN_SECONDS;
142
-                break;
143
-            case 'hour':
144
-            default:
145
-                $offset = HOUR_IN_SECONDS;
146
-                break;
147
-        }
148
-        $rounded_timestamp = (int) strtotime(date("Y-m-d {$hours}:{$minutes}:00", $timestamp));
149
-        $rounded_timestamp += $round_up ? $offset : 0;
150
-        return apply_filters(
151
-            'FHEE__TransientCacheStorage__roundTimestamp__timestamp',
152
-            $rounded_timestamp,
153
-            $timestamp,
154
-            $cleanup_frequency,
155
-            $round_up
156
-        );
157
-    }
158
-
159
-
160
-    /**
161
-     * Saves supplied data to a transient
162
-     * if an expiration is set, then it automatically schedules the transient for cleanup
163
-     *
164
-     * @param string $transient_key [required]
165
-     * @param string $data          [required]
166
-     * @param int    $expiration    number of seconds until the cache expires
167
-     * @return bool
168
-     */
169
-    public function add($transient_key, $data, $expiration = 0)
170
-    {
171
-        $expiration = (int) abs($expiration);
172
-        $saved = set_transient($transient_key, $data, $expiration);
173
-        if ($saved && $expiration) {
174
-            $this->scheduleTransientCleanup($transient_key, $expiration);
175
-        }
176
-        return $saved;
177
-    }
178
-
179
-
180
-    /**
181
-     * retrieves transient data
182
-     * automatically triggers early cache refresh for standard cache items
183
-     * in order to avoid cache stampedes on busy sites.
184
-     * For non-standard cache items like PHP Session data where early refreshing is not wanted,
185
-     * the $standard_cache parameter should be set to false when retrieving data
186
-     *
187
-     * @param string $transient_key [required]
188
-     * @param bool   $standard_cache
189
-     * @return mixed|null
190
-     */
191
-    public function get($transient_key, $standard_cache = true)
192
-    {
193
-        if (isset($this->transients[ $transient_key ])) {
194
-            // to avoid cache stampedes (AKA:dogpiles) for standard cache items,
195
-            // check if known cache expires within the next minute,
196
-            // and if so, remove it from our tracking and and return nothing.
197
-            // this should trigger the cache content to be regenerated during this request,
198
-            // while allowing any following requests to still access the existing cache
199
-            // until it gets replaced with the refreshed content
200
-            if (
201
-                $standard_cache
202
-                && $this->transients[ $transient_key ] - time() <= MINUTE_IN_SECONDS
203
-            ) {
204
-                unset($this->transients[ $transient_key ]);
205
-                $this->updateTransients();
206
-                return null;
207
-            }
208
-
209
-            // for non standard cache items, remove the key from our tracking,
210
-            // but proceed to retrieve the transient so that it also gets removed from the db
211
-            if ($this->transients[ $transient_key ] <= time()) {
212
-                unset($this->transients[ $transient_key ]);
213
-                $this->updateTransients();
214
-            }
215
-        }
216
-
217
-        $content = get_transient($transient_key);
218
-        return $content !== false ? $content : null;
219
-    }
220
-
221
-
222
-    /**
223
-     * delete a single transient and remove tracking
224
-     *
225
-     * @param string $transient_key [required] full or partial transient key to be deleted
226
-     */
227
-    public function delete($transient_key)
228
-    {
229
-        $this->deleteMany(array($transient_key));
230
-    }
231
-
232
-
233
-    /**
234
-     * delete multiple transients and remove tracking
235
-     *
236
-     * @param array $transient_keys [required] array of full or partial transient keys to be deleted
237
-     * @param bool  $force_delete   [optional] if true, then will not check incoming keys against those being tracked
238
-     *                              and proceed directly to deleting those entries from the cache storage
239
-     */
240
-    public function deleteMany(array $transient_keys, $force_delete = false)
241
-    {
242
-        $full_transient_keys = $force_delete ? $transient_keys : array();
243
-        if (empty($full_transient_keys)) {
244
-            foreach ($this->transients as $transient_key => $expiration) {
245
-                foreach ($transient_keys as $transient_key_to_delete) {
246
-                    if (strpos($transient_key, $transient_key_to_delete) !== false) {
247
-                        $full_transient_keys[] = $transient_key;
248
-                    }
249
-                }
250
-            }
251
-        }
252
-        if ($this->deleteTransientKeys($full_transient_keys)) {
253
-            $this->updateTransients();
254
-        }
255
-    }
256
-
257
-
258
-    /**
259
-     * sorts transients numerically by timestamp
260
-     * then saves the transient schedule to a WP option
261
-     */
262
-    private function updateTransients()
263
-    {
264
-        asort($this->transients, SORT_NUMERIC);
265
-        update_option(
266
-            TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY,
267
-            $this->transients
268
-        );
269
-    }
270
-
271
-
272
-    /**
273
-     * schedules a transient for cleanup by adding it to the transient tracking
274
-     *
275
-     * @param string $transient_key [required]
276
-     * @param int    $expiration    [required]
277
-     */
278
-    private function scheduleTransientCleanup($transient_key, $expiration)
279
-    {
280
-        // make sure a valid future timestamp is set
281
-        $expiration += $expiration < time() ? time() : 0;
282
-        // and round to the closest 15 minutes
283
-        $expiration = $this->roundTimestamp($expiration);
284
-        // save transients to clear using their ID as the key to avoid duplicates
285
-        $this->transients[ $transient_key ] = $expiration;
286
-        $this->updateTransients();
287
-    }
288
-
289
-
290
-    /**
291
-     * Since our tracked transients are sorted by their timestamps
292
-     * we can grab the first transient and see when it is scheduled for cleanup.
293
-     * If that timestamp is less than or equal to the current time,
294
-     * then cleanup is triggered
295
-     */
296
-    public function checkTransientCleanupSchedule()
297
-    {
298
-        if (empty($this->transients)) {
299
-            return;
300
-        }
301
-        // when do we run the next cleanup job?
302
-        reset($this->transients);
303
-        $next_scheduled_cleanup = current($this->transients);
304
-        // if the next cleanup job is scheduled for the current hour
305
-        if ($next_scheduled_cleanup <= $this->current_time) {
306
-            if ($this->cleanupExpiredTransients()) {
307
-                $this->updateTransients();
308
-            }
309
-        }
310
-    }
311
-
312
-
313
-    /**
314
-     * loops through the array of tracked transients,
315
-     * compiles a list of those that have expired, and sends that list off for deletion.
316
-     * Also removes any bad records from the transients array
317
-     *
318
-     * @return bool
319
-     */
320
-    private function cleanupExpiredTransients()
321
-    {
322
-        $update = false;
323
-        // filter the query limit. Set to 0 to turn off garbage collection
324
-        $limit = (int) abs(
325
-            apply_filters(
326
-                'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
327
-                50
328
-            )
329
-        );
330
-        // non-zero LIMIT means take out the trash
331
-        if ($limit) {
332
-            $transient_keys = array();
333
-            foreach ($this->transients as $transient_key => $expiration) {
334
-                if ($expiration > $this->current_time) {
335
-                    continue;
336
-                }
337
-                if (! $expiration || ! $transient_key) {
338
-                    unset($this->transients[ $transient_key ]);
339
-                    $update = true;
340
-                    continue;
341
-                }
342
-                $transient_keys[] = $transient_key;
343
-            }
344
-            // delete expired keys, but maintain value of $update if nothing is deleted
345
-            $update = $this->deleteTransientKeys($transient_keys, $limit) ? true : $update;
346
-            do_action('FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
347
-        }
348
-        return $update;
349
-    }
350
-
351
-
352
-    /**
353
-     * calls delete_transient() on each transient key provided, up to the specified limit
354
-     *
355
-     * @param array $transient_keys [required]
356
-     * @param int   $limit
357
-     * @return bool
358
-     */
359
-    private function deleteTransientKeys(array $transient_keys, $limit = 50)
360
-    {
361
-        if (empty($transient_keys)) {
362
-            return false;
363
-        }
364
-        $counter = 0;
365
-        foreach ($transient_keys as $transient_key) {
366
-            if ($counter === $limit) {
367
-                break;
368
-            }
369
-            // remove any transient prefixes
370
-            $transient_key = strpos($transient_key, '_transient_timeout_') === 0
371
-                ? str_replace('_transient_timeout_', '', $transient_key)
372
-                : $transient_key;
373
-            $transient_key = strpos($transient_key, '_transient_') === 0
374
-                ? str_replace('_transient_', '', $transient_key)
375
-                : $transient_key;
376
-            delete_transient($transient_key);
377
-            unset($this->transients[ $transient_key ]);
378
-            $counter++;
379
-        }
380
-        return $counter > 0;
381
-    }
19
+	/**
20
+	 * wp-option option_name for tracking transients
21
+	 *
22
+	 * @type string
23
+	 */
24
+	const TRANSIENT_SCHEDULE_OPTIONS_KEY = 'ee_transient_schedule';
25
+
26
+	/**
27
+	 * @var int $current_time
28
+	 */
29
+	private $current_time;
30
+
31
+	/**
32
+	 * how often to perform transient cleanup
33
+	 *
34
+	 * @var string $transient_cleanup_frequency
35
+	 */
36
+	private $transient_cleanup_frequency;
37
+
38
+	/**
39
+	 * options for how often to perform transient cleanup
40
+	 *
41
+	 * @var array $transient_cleanup_frequency_options
42
+	 */
43
+	private $transient_cleanup_frequency_options = array();
44
+
45
+	/**
46
+	 * @var array $transients
47
+	 */
48
+	private $transients;
49
+
50
+
51
+	/**
52
+	 * TransientCacheStorage constructor.
53
+	 */
54
+	public function __construct()
55
+	{
56
+		$this->transient_cleanup_frequency = $this->setTransientCleanupFrequency();
57
+		// round current time down to closest 5 minutes to simplify scheduling
58
+		$this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
59
+		$this->transients = (array) get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
60
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
61
+			add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
62
+		}
63
+	}
64
+
65
+
66
+	/**
67
+	 * Sets how often transient cleanup occurs
68
+	 *
69
+	 * @return string
70
+	 */
71
+	private function setTransientCleanupFrequency()
72
+	{
73
+		// sets how often transients are cleaned up
74
+		$this->transient_cleanup_frequency_options = apply_filters(
75
+			'FHEE__TransientCacheStorage__transient_cleanup_schedule_options',
76
+			array(
77
+				'off',
78
+				'15-minutes',
79
+				'hour',
80
+				'12-hours',
81
+				'day',
82
+			)
83
+		);
84
+		$transient_cleanup_frequency = apply_filters(
85
+			'FHEE__TransientCacheStorage__transient_cleanup_schedule',
86
+			'hour'
87
+		);
88
+		return in_array(
89
+			$transient_cleanup_frequency,
90
+			$this->transient_cleanup_frequency_options,
91
+			true
92
+		)
93
+			? $transient_cleanup_frequency
94
+			: 'hour';
95
+	}
96
+
97
+
98
+	/**
99
+	 * we need to be able to round timestamps off to match the set transient cleanup frequency
100
+	 * so if a transient is set to expire at 1:17 pm for example, and our cleanup schedule is every hour,
101
+	 * then that timestamp needs to be rounded up to 2:00 pm so that it is removed
102
+	 * during the next scheduled cleanup after its expiration.
103
+	 * We also round off the current time timestamp to the closest 5 minutes
104
+	 * just to make the timestamps a little easier to round which helps with debugging.
105
+	 *
106
+	 * @param int    $timestamp [required]
107
+	 * @param string $cleanup_frequency
108
+	 * @param bool   $round_up
109
+	 * @return int
110
+	 */
111
+	private function roundTimestamp($timestamp, $cleanup_frequency = 'hour', $round_up = true)
112
+	{
113
+		$cleanup_frequency = $cleanup_frequency ? $cleanup_frequency : $this->transient_cleanup_frequency;
114
+		// in order to round the time to the closest xx minutes (or hours),
115
+		// we take the minutes (or hours) portion of the timestamp and divide it by xx,
116
+		// round down to a whole number, then multiply by xx to bring us almost back up to where we were
117
+		// why round down ? so the minutes (or hours) don't go over 60 (or 24)
118
+		// and bump the hour, which could bump the day, which could bump the month, etc,
119
+		// which would be bad because we don't always want to round up,
120
+		// but when we do we can easily achieve that by simply adding the desired offset,
121
+		$minutes = '00';
122
+		$hours = 'H';
123
+		switch ($cleanup_frequency) {
124
+			case '5-minutes':
125
+				$minutes = floor((int) date('i', $timestamp) / 5) * 5;
126
+				$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
127
+				$offset = MINUTE_IN_SECONDS * 5;
128
+				break;
129
+			case '15-minutes':
130
+				$minutes = floor((int) date('i', $timestamp) / 15) * 15;
131
+				$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
132
+				$offset = MINUTE_IN_SECONDS * 15;
133
+				break;
134
+			case '12-hours':
135
+				$hours = floor((int) date('H', $timestamp) / 12) * 12;
136
+				$hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
137
+				$offset = HOUR_IN_SECONDS * 12;
138
+				break;
139
+			case 'day':
140
+				$hours = '03'; // run cleanup at 3:00 am (or first site hit after that)
141
+				$offset = DAY_IN_SECONDS;
142
+				break;
143
+			case 'hour':
144
+			default:
145
+				$offset = HOUR_IN_SECONDS;
146
+				break;
147
+		}
148
+		$rounded_timestamp = (int) strtotime(date("Y-m-d {$hours}:{$minutes}:00", $timestamp));
149
+		$rounded_timestamp += $round_up ? $offset : 0;
150
+		return apply_filters(
151
+			'FHEE__TransientCacheStorage__roundTimestamp__timestamp',
152
+			$rounded_timestamp,
153
+			$timestamp,
154
+			$cleanup_frequency,
155
+			$round_up
156
+		);
157
+	}
158
+
159
+
160
+	/**
161
+	 * Saves supplied data to a transient
162
+	 * if an expiration is set, then it automatically schedules the transient for cleanup
163
+	 *
164
+	 * @param string $transient_key [required]
165
+	 * @param string $data          [required]
166
+	 * @param int    $expiration    number of seconds until the cache expires
167
+	 * @return bool
168
+	 */
169
+	public function add($transient_key, $data, $expiration = 0)
170
+	{
171
+		$expiration = (int) abs($expiration);
172
+		$saved = set_transient($transient_key, $data, $expiration);
173
+		if ($saved && $expiration) {
174
+			$this->scheduleTransientCleanup($transient_key, $expiration);
175
+		}
176
+		return $saved;
177
+	}
178
+
179
+
180
+	/**
181
+	 * retrieves transient data
182
+	 * automatically triggers early cache refresh for standard cache items
183
+	 * in order to avoid cache stampedes on busy sites.
184
+	 * For non-standard cache items like PHP Session data where early refreshing is not wanted,
185
+	 * the $standard_cache parameter should be set to false when retrieving data
186
+	 *
187
+	 * @param string $transient_key [required]
188
+	 * @param bool   $standard_cache
189
+	 * @return mixed|null
190
+	 */
191
+	public function get($transient_key, $standard_cache = true)
192
+	{
193
+		if (isset($this->transients[ $transient_key ])) {
194
+			// to avoid cache stampedes (AKA:dogpiles) for standard cache items,
195
+			// check if known cache expires within the next minute,
196
+			// and if so, remove it from our tracking and and return nothing.
197
+			// this should trigger the cache content to be regenerated during this request,
198
+			// while allowing any following requests to still access the existing cache
199
+			// until it gets replaced with the refreshed content
200
+			if (
201
+				$standard_cache
202
+				&& $this->transients[ $transient_key ] - time() <= MINUTE_IN_SECONDS
203
+			) {
204
+				unset($this->transients[ $transient_key ]);
205
+				$this->updateTransients();
206
+				return null;
207
+			}
208
+
209
+			// for non standard cache items, remove the key from our tracking,
210
+			// but proceed to retrieve the transient so that it also gets removed from the db
211
+			if ($this->transients[ $transient_key ] <= time()) {
212
+				unset($this->transients[ $transient_key ]);
213
+				$this->updateTransients();
214
+			}
215
+		}
216
+
217
+		$content = get_transient($transient_key);
218
+		return $content !== false ? $content : null;
219
+	}
220
+
221
+
222
+	/**
223
+	 * delete a single transient and remove tracking
224
+	 *
225
+	 * @param string $transient_key [required] full or partial transient key to be deleted
226
+	 */
227
+	public function delete($transient_key)
228
+	{
229
+		$this->deleteMany(array($transient_key));
230
+	}
231
+
232
+
233
+	/**
234
+	 * delete multiple transients and remove tracking
235
+	 *
236
+	 * @param array $transient_keys [required] array of full or partial transient keys to be deleted
237
+	 * @param bool  $force_delete   [optional] if true, then will not check incoming keys against those being tracked
238
+	 *                              and proceed directly to deleting those entries from the cache storage
239
+	 */
240
+	public function deleteMany(array $transient_keys, $force_delete = false)
241
+	{
242
+		$full_transient_keys = $force_delete ? $transient_keys : array();
243
+		if (empty($full_transient_keys)) {
244
+			foreach ($this->transients as $transient_key => $expiration) {
245
+				foreach ($transient_keys as $transient_key_to_delete) {
246
+					if (strpos($transient_key, $transient_key_to_delete) !== false) {
247
+						$full_transient_keys[] = $transient_key;
248
+					}
249
+				}
250
+			}
251
+		}
252
+		if ($this->deleteTransientKeys($full_transient_keys)) {
253
+			$this->updateTransients();
254
+		}
255
+	}
256
+
257
+
258
+	/**
259
+	 * sorts transients numerically by timestamp
260
+	 * then saves the transient schedule to a WP option
261
+	 */
262
+	private function updateTransients()
263
+	{
264
+		asort($this->transients, SORT_NUMERIC);
265
+		update_option(
266
+			TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY,
267
+			$this->transients
268
+		);
269
+	}
270
+
271
+
272
+	/**
273
+	 * schedules a transient for cleanup by adding it to the transient tracking
274
+	 *
275
+	 * @param string $transient_key [required]
276
+	 * @param int    $expiration    [required]
277
+	 */
278
+	private function scheduleTransientCleanup($transient_key, $expiration)
279
+	{
280
+		// make sure a valid future timestamp is set
281
+		$expiration += $expiration < time() ? time() : 0;
282
+		// and round to the closest 15 minutes
283
+		$expiration = $this->roundTimestamp($expiration);
284
+		// save transients to clear using their ID as the key to avoid duplicates
285
+		$this->transients[ $transient_key ] = $expiration;
286
+		$this->updateTransients();
287
+	}
288
+
289
+
290
+	/**
291
+	 * Since our tracked transients are sorted by their timestamps
292
+	 * we can grab the first transient and see when it is scheduled for cleanup.
293
+	 * If that timestamp is less than or equal to the current time,
294
+	 * then cleanup is triggered
295
+	 */
296
+	public function checkTransientCleanupSchedule()
297
+	{
298
+		if (empty($this->transients)) {
299
+			return;
300
+		}
301
+		// when do we run the next cleanup job?
302
+		reset($this->transients);
303
+		$next_scheduled_cleanup = current($this->transients);
304
+		// if the next cleanup job is scheduled for the current hour
305
+		if ($next_scheduled_cleanup <= $this->current_time) {
306
+			if ($this->cleanupExpiredTransients()) {
307
+				$this->updateTransients();
308
+			}
309
+		}
310
+	}
311
+
312
+
313
+	/**
314
+	 * loops through the array of tracked transients,
315
+	 * compiles a list of those that have expired, and sends that list off for deletion.
316
+	 * Also removes any bad records from the transients array
317
+	 *
318
+	 * @return bool
319
+	 */
320
+	private function cleanupExpiredTransients()
321
+	{
322
+		$update = false;
323
+		// filter the query limit. Set to 0 to turn off garbage collection
324
+		$limit = (int) abs(
325
+			apply_filters(
326
+				'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
327
+				50
328
+			)
329
+		);
330
+		// non-zero LIMIT means take out the trash
331
+		if ($limit) {
332
+			$transient_keys = array();
333
+			foreach ($this->transients as $transient_key => $expiration) {
334
+				if ($expiration > $this->current_time) {
335
+					continue;
336
+				}
337
+				if (! $expiration || ! $transient_key) {
338
+					unset($this->transients[ $transient_key ]);
339
+					$update = true;
340
+					continue;
341
+				}
342
+				$transient_keys[] = $transient_key;
343
+			}
344
+			// delete expired keys, but maintain value of $update if nothing is deleted
345
+			$update = $this->deleteTransientKeys($transient_keys, $limit) ? true : $update;
346
+			do_action('FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
347
+		}
348
+		return $update;
349
+	}
350
+
351
+
352
+	/**
353
+	 * calls delete_transient() on each transient key provided, up to the specified limit
354
+	 *
355
+	 * @param array $transient_keys [required]
356
+	 * @param int   $limit
357
+	 * @return bool
358
+	 */
359
+	private function deleteTransientKeys(array $transient_keys, $limit = 50)
360
+	{
361
+		if (empty($transient_keys)) {
362
+			return false;
363
+		}
364
+		$counter = 0;
365
+		foreach ($transient_keys as $transient_key) {
366
+			if ($counter === $limit) {
367
+				break;
368
+			}
369
+			// remove any transient prefixes
370
+			$transient_key = strpos($transient_key, '_transient_timeout_') === 0
371
+				? str_replace('_transient_timeout_', '', $transient_key)
372
+				: $transient_key;
373
+			$transient_key = strpos($transient_key, '_transient_') === 0
374
+				? str_replace('_transient_', '', $transient_key)
375
+				: $transient_key;
376
+			delete_transient($transient_key);
377
+			unset($this->transients[ $transient_key ]);
378
+			$counter++;
379
+		}
380
+		return $counter > 0;
381
+	}
382 382
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
         // round current time down to closest 5 minutes to simplify scheduling
58 58
         $this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
59 59
         $this->transients = (array) get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
60
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
60
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
61 61
             add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
62 62
         }
63 63
     }
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
      */
191 191
     public function get($transient_key, $standard_cache = true)
192 192
     {
193
-        if (isset($this->transients[ $transient_key ])) {
193
+        if (isset($this->transients[$transient_key])) {
194 194
             // to avoid cache stampedes (AKA:dogpiles) for standard cache items,
195 195
             // check if known cache expires within the next minute,
196 196
             // and if so, remove it from our tracking and and return nothing.
@@ -199,17 +199,17 @@  discard block
 block discarded – undo
199 199
             // until it gets replaced with the refreshed content
200 200
             if (
201 201
                 $standard_cache
202
-                && $this->transients[ $transient_key ] - time() <= MINUTE_IN_SECONDS
202
+                && $this->transients[$transient_key] - time() <= MINUTE_IN_SECONDS
203 203
             ) {
204
-                unset($this->transients[ $transient_key ]);
204
+                unset($this->transients[$transient_key]);
205 205
                 $this->updateTransients();
206 206
                 return null;
207 207
             }
208 208
 
209 209
             // for non standard cache items, remove the key from our tracking,
210 210
             // but proceed to retrieve the transient so that it also gets removed from the db
211
-            if ($this->transients[ $transient_key ] <= time()) {
212
-                unset($this->transients[ $transient_key ]);
211
+            if ($this->transients[$transient_key] <= time()) {
212
+                unset($this->transients[$transient_key]);
213 213
                 $this->updateTransients();
214 214
             }
215 215
         }
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
         // and round to the closest 15 minutes
283 283
         $expiration = $this->roundTimestamp($expiration);
284 284
         // save transients to clear using their ID as the key to avoid duplicates
285
-        $this->transients[ $transient_key ] = $expiration;
285
+        $this->transients[$transient_key] = $expiration;
286 286
         $this->updateTransients();
287 287
     }
288 288
 
@@ -334,8 +334,8 @@  discard block
 block discarded – undo
334 334
                 if ($expiration > $this->current_time) {
335 335
                     continue;
336 336
                 }
337
-                if (! $expiration || ! $transient_key) {
338
-                    unset($this->transients[ $transient_key ]);
337
+                if ( ! $expiration || ! $transient_key) {
338
+                    unset($this->transients[$transient_key]);
339 339
                     $update = true;
340 340
                     continue;
341 341
                 }
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
                 ? str_replace('_transient_', '', $transient_key)
375 375
                 : $transient_key;
376 376
             delete_transient($transient_key);
377
-            unset($this->transients[ $transient_key ]);
377
+            unset($this->transients[$transient_key]);
378 378
             $counter++;
379 379
         }
380 380
         return $counter > 0;
Please login to merge, or discard this patch.
core/services/request/middleware/DetectLogin.php 1 patch
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -16,29 +16,29 @@
 block discarded – undo
16 16
 class DetectLogin extends Middleware
17 17
 {
18 18
 
19
-    /**
20
-     * converts a Request to a Response
21
-     *
22
-     * @param RequestInterface  $request
23
-     * @param ResponseInterface $response
24
-     * @return ResponseInterface
25
-     */
26
-    public function handleRequest(RequestInterface $request, ResponseInterface $response)
27
-    {
28
-        $this->request = $request;
29
-        $this->response = $response;
30
-        global $pagenow;
31
-        if (
32
-            in_array(
33
-                $pagenow,
34
-                array('wp-login.php', 'wp-register.php'),
35
-                true
36
-            )
37
-            && ! filter_var($request->getRequestParam('ee_load_on_login'), FILTER_VALIDATE_BOOLEAN)
38
-        ) {
39
-            $this->response->terminateRequest();
40
-        }
41
-        $this->response = $this->processRequestStack($this->request, $this->response);
42
-        return $this->response;
43
-    }
19
+	/**
20
+	 * converts a Request to a Response
21
+	 *
22
+	 * @param RequestInterface  $request
23
+	 * @param ResponseInterface $response
24
+	 * @return ResponseInterface
25
+	 */
26
+	public function handleRequest(RequestInterface $request, ResponseInterface $response)
27
+	{
28
+		$this->request = $request;
29
+		$this->response = $response;
30
+		global $pagenow;
31
+		if (
32
+			in_array(
33
+				$pagenow,
34
+				array('wp-login.php', 'wp-register.php'),
35
+				true
36
+			)
37
+			&& ! filter_var($request->getRequestParam('ee_load_on_login'), FILTER_VALIDATE_BOOLEAN)
38
+		) {
39
+			$this->response->terminateRequest();
40
+		}
41
+		$this->response = $this->processRequestStack($this->request, $this->response);
42
+		return $this->response;
43
+	}
44 44
 }
Please login to merge, or discard this patch.
core/services/container/DependencyInjector.php 2 patches
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -21,216 +21,216 @@
 block discarded – undo
21 21
 class DependencyInjector implements InjectorInterface
22 22
 {
23 23
 
24
-    /**
25
-     * @var CoffeePotInterface $coffee_pot
26
-     */
27
-    private $coffee_pot;
28
-
29
-    /**
30
-     * @var EEH_Array $array_helper
31
-     */
32
-    private $array_helper;
33
-
34
-    /**
35
-     * @var ReflectionClass[] $reflectors
36
-     */
37
-    private $reflectors;
38
-
39
-    /**
40
-     * @var ReflectionMethod[] $constructors
41
-     */
42
-    private $constructors;
43
-
44
-    /**
45
-     * @var ReflectionParameter[] $parameters
46
-     */
47
-    private $parameters;
48
-
49
-
50
-    /**
51
-     * DependencyInjector constructor
52
-     *
53
-     * @param CoffeePotInterface $coffee_pot
54
-     * @param EEH_Array          $array_helper
55
-     */
56
-    public function __construct(CoffeePotInterface $coffee_pot, EEH_Array $array_helper)
57
-    {
58
-        $this->coffee_pot = $coffee_pot;
59
-        $this->array_helper = $array_helper;
60
-    }
61
-
62
-
63
-    /**
64
-     * getReflectionClass
65
-     * checks if a ReflectionClass object has already been generated for a class
66
-     * and returns that instead of creating a new one
67
-     *
68
-     * @param string $class_name
69
-     * @return ReflectionClass
70
-     */
71
-    public function getReflectionClass($class_name)
72
-    {
73
-        if (
74
-            ! isset($this->reflectors[ $class_name ])
75
-            || ! $this->reflectors[ $class_name ] instanceof ReflectionClass
76
-        ) {
77
-            $this->reflectors[ $class_name ] = new ReflectionClass($class_name);
78
-        }
79
-        return $this->reflectors[ $class_name ];
80
-    }
81
-
82
-
83
-    /**
84
-     * getConstructor
85
-     * checks if a ReflectionMethod object has already been generated for the class constructor
86
-     * and returns that instead of creating a new one
87
-     *
88
-     * @param ReflectionClass $reflector
89
-     * @return ReflectionMethod
90
-     */
91
-    protected function getConstructor(ReflectionClass $reflector)
92
-    {
93
-        if (
94
-            ! isset($this->constructors[ $reflector->getName() ])
95
-            || ! $this->constructors[ $reflector->getName() ] instanceof ReflectionMethod
96
-        ) {
97
-            $this->constructors[ $reflector->getName() ] = $reflector->getConstructor();
98
-        }
99
-        return $this->constructors[ $reflector->getName() ];
100
-    }
101
-
102
-
103
-    /**
104
-     * getParameters
105
-     * checks if an array of ReflectionParameter objects has already been generated for the class constructor
106
-     * and returns that instead of creating a new one
107
-     *
108
-     * @param ReflectionMethod $constructor
109
-     * @return ReflectionParameter[]
110
-     */
111
-    protected function getParameters(ReflectionMethod $constructor)
112
-    {
113
-        if (! isset($this->parameters[ $constructor->class ])) {
114
-            $this->parameters[ $constructor->class ] = $constructor->getParameters();
115
-        }
116
-        return $this->parameters[ $constructor->class ];
117
-    }
118
-
119
-
120
-    /**
121
-     * resolveDependencies
122
-     * examines the constructor for the requested class to determine
123
-     * if any dependencies exist, and if they can be injected.
124
-     * If so, then those classes will be added to the array of arguments passed to the constructor
125
-     * PLZ NOTE: this is achieved by type hinting the constructor params
126
-     * For example:
127
-     *        if attempting to load a class "Foo" with the following constructor:
128
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
129
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
130
-     *        but only IF they are NOT already present in the incoming arguments array,
131
-     *        and the correct classes can be loaded
132
-     *
133
-     * @param RecipeInterface $recipe
134
-     * @param ReflectionClass $reflector
135
-     * @param array           $arguments
136
-     * @return array
137
-     * @throws UnexpectedValueException
138
-     */
139
-    public function resolveDependencies(RecipeInterface $recipe, ReflectionClass $reflector, $arguments = array())
140
-    {
141
-        // if arguments array is numerically and sequentially indexed, then we want it to remain as is,
142
-        // else wrap it in an additional array so that it doesn't get split into multiple parameters
143
-        $arguments = $this->array_helper->is_array_numerically_and_sequentially_indexed($arguments)
144
-            ? $arguments
145
-            : array($arguments);
146
-        $resolved_parameters = array();
147
-        // let's examine the constructor
148
-        // let's examine the constructor
149
-        $constructor = $this->getConstructor($reflector);
150
-        // whu? huh? nothing?
151
-        if (! $constructor) {
152
-            return $arguments;
153
-        }
154
-        // get constructor parameters
155
-        $params = $this->getParameters($constructor);
156
-        if (empty($params)) {
157
-            return $resolved_parameters;
158
-        }
159
-        $ingredients = $recipe->ingredients();
160
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
161
-        $argument_keys = array_keys($arguments);
162
-        // now loop thru all of the constructors expected parameters
163
-        foreach ($params as $index => $param) {
164
-            if (! $param instanceof ReflectionParameter) {
165
-                continue;
166
-            }
167
-            // is this a dependency for a specific class ?
168
-            $param_class = $param->getClass() ? $param->getClass()->name : '';
169
-            $param_name = $param->getName() ? $param->getName() : '';
170
-            if (
24
+	/**
25
+	 * @var CoffeePotInterface $coffee_pot
26
+	 */
27
+	private $coffee_pot;
28
+
29
+	/**
30
+	 * @var EEH_Array $array_helper
31
+	 */
32
+	private $array_helper;
33
+
34
+	/**
35
+	 * @var ReflectionClass[] $reflectors
36
+	 */
37
+	private $reflectors;
38
+
39
+	/**
40
+	 * @var ReflectionMethod[] $constructors
41
+	 */
42
+	private $constructors;
43
+
44
+	/**
45
+	 * @var ReflectionParameter[] $parameters
46
+	 */
47
+	private $parameters;
48
+
49
+
50
+	/**
51
+	 * DependencyInjector constructor
52
+	 *
53
+	 * @param CoffeePotInterface $coffee_pot
54
+	 * @param EEH_Array          $array_helper
55
+	 */
56
+	public function __construct(CoffeePotInterface $coffee_pot, EEH_Array $array_helper)
57
+	{
58
+		$this->coffee_pot = $coffee_pot;
59
+		$this->array_helper = $array_helper;
60
+	}
61
+
62
+
63
+	/**
64
+	 * getReflectionClass
65
+	 * checks if a ReflectionClass object has already been generated for a class
66
+	 * and returns that instead of creating a new one
67
+	 *
68
+	 * @param string $class_name
69
+	 * @return ReflectionClass
70
+	 */
71
+	public function getReflectionClass($class_name)
72
+	{
73
+		if (
74
+			! isset($this->reflectors[ $class_name ])
75
+			|| ! $this->reflectors[ $class_name ] instanceof ReflectionClass
76
+		) {
77
+			$this->reflectors[ $class_name ] = new ReflectionClass($class_name);
78
+		}
79
+		return $this->reflectors[ $class_name ];
80
+	}
81
+
82
+
83
+	/**
84
+	 * getConstructor
85
+	 * checks if a ReflectionMethod object has already been generated for the class constructor
86
+	 * and returns that instead of creating a new one
87
+	 *
88
+	 * @param ReflectionClass $reflector
89
+	 * @return ReflectionMethod
90
+	 */
91
+	protected function getConstructor(ReflectionClass $reflector)
92
+	{
93
+		if (
94
+			! isset($this->constructors[ $reflector->getName() ])
95
+			|| ! $this->constructors[ $reflector->getName() ] instanceof ReflectionMethod
96
+		) {
97
+			$this->constructors[ $reflector->getName() ] = $reflector->getConstructor();
98
+		}
99
+		return $this->constructors[ $reflector->getName() ];
100
+	}
101
+
102
+
103
+	/**
104
+	 * getParameters
105
+	 * checks if an array of ReflectionParameter objects has already been generated for the class constructor
106
+	 * and returns that instead of creating a new one
107
+	 *
108
+	 * @param ReflectionMethod $constructor
109
+	 * @return ReflectionParameter[]
110
+	 */
111
+	protected function getParameters(ReflectionMethod $constructor)
112
+	{
113
+		if (! isset($this->parameters[ $constructor->class ])) {
114
+			$this->parameters[ $constructor->class ] = $constructor->getParameters();
115
+		}
116
+		return $this->parameters[ $constructor->class ];
117
+	}
118
+
119
+
120
+	/**
121
+	 * resolveDependencies
122
+	 * examines the constructor for the requested class to determine
123
+	 * if any dependencies exist, and if they can be injected.
124
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
125
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
126
+	 * For example:
127
+	 *        if attempting to load a class "Foo" with the following constructor:
128
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
129
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
130
+	 *        but only IF they are NOT already present in the incoming arguments array,
131
+	 *        and the correct classes can be loaded
132
+	 *
133
+	 * @param RecipeInterface $recipe
134
+	 * @param ReflectionClass $reflector
135
+	 * @param array           $arguments
136
+	 * @return array
137
+	 * @throws UnexpectedValueException
138
+	 */
139
+	public function resolveDependencies(RecipeInterface $recipe, ReflectionClass $reflector, $arguments = array())
140
+	{
141
+		// if arguments array is numerically and sequentially indexed, then we want it to remain as is,
142
+		// else wrap it in an additional array so that it doesn't get split into multiple parameters
143
+		$arguments = $this->array_helper->is_array_numerically_and_sequentially_indexed($arguments)
144
+			? $arguments
145
+			: array($arguments);
146
+		$resolved_parameters = array();
147
+		// let's examine the constructor
148
+		// let's examine the constructor
149
+		$constructor = $this->getConstructor($reflector);
150
+		// whu? huh? nothing?
151
+		if (! $constructor) {
152
+			return $arguments;
153
+		}
154
+		// get constructor parameters
155
+		$params = $this->getParameters($constructor);
156
+		if (empty($params)) {
157
+			return $resolved_parameters;
158
+		}
159
+		$ingredients = $recipe->ingredients();
160
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
161
+		$argument_keys = array_keys($arguments);
162
+		// now loop thru all of the constructors expected parameters
163
+		foreach ($params as $index => $param) {
164
+			if (! $param instanceof ReflectionParameter) {
165
+				continue;
166
+			}
167
+			// is this a dependency for a specific class ?
168
+			$param_class = $param->getClass() ? $param->getClass()->name : '';
169
+			$param_name = $param->getName() ? $param->getName() : '';
170
+			if (
171 171
 // param is not a class but is specified in the list of ingredients for this Recipe
172
-                is_string($param_name) && isset($ingredients[ $param_name ])
173
-            ) {
174
-                // attempt to inject the dependency
175
-                $resolved_parameters[ $index ] = $ingredients[ $param_name ];
176
-            } elseif (
172
+				is_string($param_name) && isset($ingredients[ $param_name ])
173
+			) {
174
+				// attempt to inject the dependency
175
+				$resolved_parameters[ $index ] = $ingredients[ $param_name ];
176
+			} elseif (
177 177
 // param is specified in the list of ingredients for this Recipe
178
-                isset($ingredients[ $param_class ])
179
-            ) { // attempt to inject the dependency
180
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $ingredients[ $param_class ]);
181
-            } elseif (
178
+				isset($ingredients[ $param_class ])
179
+			) { // attempt to inject the dependency
180
+				$resolved_parameters[ $index ] = $this->injectDependency($reflector, $ingredients[ $param_class ]);
181
+			} elseif (
182 182
 // param is not even a class
183
-                empty($param_class)
184
-                // and something already exists in the incoming arguments for this param
185
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
186
-            ) {
187
-                // add parameter from incoming arguments
188
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
189
-            } elseif (
183
+				empty($param_class)
184
+				// and something already exists in the incoming arguments for this param
185
+				&& isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
186
+			) {
187
+				// add parameter from incoming arguments
188
+				$resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
189
+			} elseif (
190 190
 // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
191
-                ! empty($param_class)
192
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
193
-                && $arguments[ $argument_keys[ $index ] ] instanceof $param_class
194
-            ) {
195
-                // add parameter from incoming arguments
196
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
197
-            } elseif (
191
+				! empty($param_class)
192
+				&& isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
193
+				&& $arguments[ $argument_keys[ $index ] ] instanceof $param_class
194
+			) {
195
+				// add parameter from incoming arguments
196
+				$resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
197
+			} elseif (
198 198
 // parameter is type hinted as a class, and should be injected
199
-                ! empty($param_class)
200
-            ) {
201
-                // attempt to inject the dependency
202
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $param_class);
203
-            } elseif ($param->isOptional()) {
204
-                $resolved_parameters[ $index ] = $param->getDefaultValue();
205
-            } else {
206
-                $resolved_parameters[ $index ] = null;
207
-            }
208
-        }
209
-        return $resolved_parameters;
210
-    }
211
-
212
-
213
-    /**
214
-     * @param ReflectionClass $reflector
215
-     * @param string          $param_class
216
-     * @return mixed
217
-     * @throws UnexpectedValueException
218
-     */
219
-    private function injectDependency(ReflectionClass $reflector, $param_class)
220
-    {
221
-        $dependency = $this->coffee_pot->brew($param_class);
222
-        if (! $dependency instanceof $param_class) {
223
-            throw new UnexpectedValueException(
224
-                sprintf(
225
-                    esc_html__(
226
-                        'Could not resolve dependency for "%1$s" for the "%2$s" class constructor.',
227
-                        'event_espresso'
228
-                    ),
229
-                    $param_class,
230
-                    $reflector->getName()
231
-                )
232
-            );
233
-        }
234
-        return $dependency;
235
-    }
199
+				! empty($param_class)
200
+			) {
201
+				// attempt to inject the dependency
202
+				$resolved_parameters[ $index ] = $this->injectDependency($reflector, $param_class);
203
+			} elseif ($param->isOptional()) {
204
+				$resolved_parameters[ $index ] = $param->getDefaultValue();
205
+			} else {
206
+				$resolved_parameters[ $index ] = null;
207
+			}
208
+		}
209
+		return $resolved_parameters;
210
+	}
211
+
212
+
213
+	/**
214
+	 * @param ReflectionClass $reflector
215
+	 * @param string          $param_class
216
+	 * @return mixed
217
+	 * @throws UnexpectedValueException
218
+	 */
219
+	private function injectDependency(ReflectionClass $reflector, $param_class)
220
+	{
221
+		$dependency = $this->coffee_pot->brew($param_class);
222
+		if (! $dependency instanceof $param_class) {
223
+			throw new UnexpectedValueException(
224
+				sprintf(
225
+					esc_html__(
226
+						'Could not resolve dependency for "%1$s" for the "%2$s" class constructor.',
227
+						'event_espresso'
228
+					),
229
+					$param_class,
230
+					$reflector->getName()
231
+				)
232
+			);
233
+		}
234
+		return $dependency;
235
+	}
236 236
 }
Please login to merge, or discard this patch.
Spacing   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -71,12 +71,12 @@  discard block
 block discarded – undo
71 71
     public function getReflectionClass($class_name)
72 72
     {
73 73
         if (
74
-            ! isset($this->reflectors[ $class_name ])
75
-            || ! $this->reflectors[ $class_name ] instanceof ReflectionClass
74
+            ! isset($this->reflectors[$class_name])
75
+            || ! $this->reflectors[$class_name] instanceof ReflectionClass
76 76
         ) {
77
-            $this->reflectors[ $class_name ] = new ReflectionClass($class_name);
77
+            $this->reflectors[$class_name] = new ReflectionClass($class_name);
78 78
         }
79
-        return $this->reflectors[ $class_name ];
79
+        return $this->reflectors[$class_name];
80 80
     }
81 81
 
82 82
 
@@ -91,12 +91,12 @@  discard block
 block discarded – undo
91 91
     protected function getConstructor(ReflectionClass $reflector)
92 92
     {
93 93
         if (
94
-            ! isset($this->constructors[ $reflector->getName() ])
95
-            || ! $this->constructors[ $reflector->getName() ] instanceof ReflectionMethod
94
+            ! isset($this->constructors[$reflector->getName()])
95
+            || ! $this->constructors[$reflector->getName()] instanceof ReflectionMethod
96 96
         ) {
97
-            $this->constructors[ $reflector->getName() ] = $reflector->getConstructor();
97
+            $this->constructors[$reflector->getName()] = $reflector->getConstructor();
98 98
         }
99
-        return $this->constructors[ $reflector->getName() ];
99
+        return $this->constructors[$reflector->getName()];
100 100
     }
101 101
 
102 102
 
@@ -110,10 +110,10 @@  discard block
 block discarded – undo
110 110
      */
111 111
     protected function getParameters(ReflectionMethod $constructor)
112 112
     {
113
-        if (! isset($this->parameters[ $constructor->class ])) {
114
-            $this->parameters[ $constructor->class ] = $constructor->getParameters();
113
+        if ( ! isset($this->parameters[$constructor->class])) {
114
+            $this->parameters[$constructor->class] = $constructor->getParameters();
115 115
         }
116
-        return $this->parameters[ $constructor->class ];
116
+        return $this->parameters[$constructor->class];
117 117
     }
118 118
 
119 119
 
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
         // let's examine the constructor
149 149
         $constructor = $this->getConstructor($reflector);
150 150
         // whu? huh? nothing?
151
-        if (! $constructor) {
151
+        if ( ! $constructor) {
152 152
             return $arguments;
153 153
         }
154 154
         // get constructor parameters
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
         $argument_keys = array_keys($arguments);
162 162
         // now loop thru all of the constructors expected parameters
163 163
         foreach ($params as $index => $param) {
164
-            if (! $param instanceof ReflectionParameter) {
164
+            if ( ! $param instanceof ReflectionParameter) {
165 165
                 continue;
166 166
             }
167 167
             // is this a dependency for a specific class ?
@@ -169,41 +169,41 @@  discard block
 block discarded – undo
169 169
             $param_name = $param->getName() ? $param->getName() : '';
170 170
             if (
171 171
 // param is not a class but is specified in the list of ingredients for this Recipe
172
-                is_string($param_name) && isset($ingredients[ $param_name ])
172
+                is_string($param_name) && isset($ingredients[$param_name])
173 173
             ) {
174 174
                 // attempt to inject the dependency
175
-                $resolved_parameters[ $index ] = $ingredients[ $param_name ];
175
+                $resolved_parameters[$index] = $ingredients[$param_name];
176 176
             } elseif (
177 177
 // param is specified in the list of ingredients for this Recipe
178
-                isset($ingredients[ $param_class ])
178
+                isset($ingredients[$param_class])
179 179
             ) { // attempt to inject the dependency
180
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $ingredients[ $param_class ]);
180
+                $resolved_parameters[$index] = $this->injectDependency($reflector, $ingredients[$param_class]);
181 181
             } elseif (
182 182
 // param is not even a class
183 183
                 empty($param_class)
184 184
                 // and something already exists in the incoming arguments for this param
185
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
185
+                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
186 186
             ) {
187 187
                 // add parameter from incoming arguments
188
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
188
+                $resolved_parameters[$index] = $arguments[$argument_keys[$index]];
189 189
             } elseif (
190 190
 // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
191 191
                 ! empty($param_class)
192
-                && isset($argument_keys[ $index ], $arguments[ $argument_keys[ $index ] ])
193
-                && $arguments[ $argument_keys[ $index ] ] instanceof $param_class
192
+                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
193
+                && $arguments[$argument_keys[$index]] instanceof $param_class
194 194
             ) {
195 195
                 // add parameter from incoming arguments
196
-                $resolved_parameters[ $index ] = $arguments[ $argument_keys[ $index ] ];
196
+                $resolved_parameters[$index] = $arguments[$argument_keys[$index]];
197 197
             } elseif (
198 198
 // parameter is type hinted as a class, and should be injected
199 199
                 ! empty($param_class)
200 200
             ) {
201 201
                 // attempt to inject the dependency
202
-                $resolved_parameters[ $index ] = $this->injectDependency($reflector, $param_class);
202
+                $resolved_parameters[$index] = $this->injectDependency($reflector, $param_class);
203 203
             } elseif ($param->isOptional()) {
204
-                $resolved_parameters[ $index ] = $param->getDefaultValue();
204
+                $resolved_parameters[$index] = $param->getDefaultValue();
205 205
             } else {
206
-                $resolved_parameters[ $index ] = null;
206
+                $resolved_parameters[$index] = null;
207 207
             }
208 208
         }
209 209
         return $resolved_parameters;
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
     private function injectDependency(ReflectionClass $reflector, $param_class)
220 220
     {
221 221
         $dependency = $this->coffee_pot->brew($param_class);
222
-        if (! $dependency instanceof $param_class) {
222
+        if ( ! $dependency instanceof $param_class) {
223 223
             throw new UnexpectedValueException(
224 224
                 sprintf(
225 225
                     esc_html__(
Please login to merge, or discard this patch.
core/db_classes/EE_Question_Option.class.php 1 patch
Indentation   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -10,222 +10,222 @@
 block discarded – undo
10 10
 class EE_Question_Option extends EE_Soft_Delete_Base_Class implements EEI_Duplicatable
11 11
 {
12 12
 
13
-    /**
14
-     * Question Option Opt Group Name
15
-     *
16
-     * @access protected
17
-     * @var string
18
-     */
19
-    protected $_QSO_opt_group = null;
20
-
21
-
22
-    /**
23
-     *
24
-     * @param array  $props_n_values          incoming values
25
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
26
-     *                                        used.)
27
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
28
-     *                                        date_format and the second value is the time format
29
-     * @return EE_Attendee
30
-     */
31
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
32
-    {
33
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
34
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
35
-    }
36
-
37
-
38
-    /**
39
-     * @param array  $props_n_values  incoming values from the database
40
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
41
-     *                                the website will be used.
42
-     * @return EE_Attendee
43
-     */
44
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
45
-    {
46
-        return new self($props_n_values, true, $timezone);
47
-    }
48
-
49
-
50
-    /**
51
-     * Sets the option's key value
52
-     *
53
-     * @param string $value
54
-     * @return bool success
55
-     */
56
-    public function set_value($value)
57
-    {
58
-        $this->set('QSO_value', $value);
59
-    }
60
-
61
-
62
-    /**
63
-     * Sets the option's Display Text
64
-     *
65
-     * @param string $text
66
-     * @return bool success
67
-     */
68
-    public function set_desc($text)
69
-    {
70
-        $this->set('QSO_desc', $text);
71
-    }
72
-
73
-
74
-    /**
75
-     * Sets the order for this option
76
-     *
77
-     * @access public
78
-     * @param integer $order
79
-     * @return bool      $success
80
-     */
81
-    public function set_order($order)
82
-    {
83
-        $this->set('QSO_order', $order);
84
-    }
85
-
86
-
87
-    /**
88
-     * Sets the ID of the related question
89
-     *
90
-     * @param int $question_ID
91
-     * @return bool success
92
-     */
93
-    public function set_question_ID($question_ID)
94
-    {
95
-        $this->set('QST_ID', $question_ID);
96
-    }
97
-
98
-
99
-    /**
100
-     * Sets the option's opt_group
101
-     *
102
-     * @param string $text
103
-     * @return bool success
104
-     */
105
-    public function set_opt_group($text)
106
-    {
107
-        return $this->_QSO_opt_group = $text;
108
-    }
109
-
110
-
111
-    /**
112
-     * Gets the option's key value
113
-     *
114
-     * @return string
115
-     */
116
-    public function value()
117
-    {
118
-        return $this->get('QSO_value');
119
-    }
120
-
121
-
122
-    /**
123
-     * Gets the option's display text
124
-     *
125
-     * @return string
126
-     */
127
-    public function desc()
128
-    {
129
-        return $this->get('QSO_desc');
130
-    }
131
-
132
-
133
-    /**
134
-     * Returns whether this option has been deleted or not
135
-     *
136
-     * @return boolean
137
-     */
138
-    public function deleted()
139
-    {
140
-        return $this->get('QSO_deleted');
141
-    }
142
-
143
-
144
-    /**
145
-     * Returns the order or the Question Option
146
-     *
147
-     * @access public
148
-     * @return integer
149
-     */
150
-    public function order()
151
-    {
152
-        return $this->get('QSO_option');
153
-    }
154
-
155
-
156
-    /**
157
-     * Gets the related question's ID
158
-     *
159
-     * @return int
160
-     */
161
-    public function question_ID()
162
-    {
163
-        return $this->get('QST_ID');
164
-    }
165
-
166
-
167
-    /**
168
-     * Returns the question related to this question option
169
-     *
170
-     * @return EE_Question
171
-     */
172
-    public function question()
173
-    {
174
-        return $this->get_first_related('Question');
175
-    }
176
-
177
-
178
-    /**
179
-     * Gets the option's opt_group
180
-     *
181
-     * @return string
182
-     */
183
-    public function opt_group()
184
-    {
185
-        return $this->_QSO_opt_group;
186
-    }
187
-
188
-    /**
189
-     * Duplicates this question option. By default the new question option will be for the same question,
190
-     * but that can be overriden by setting the 'QST_ID' option
191
-     *
192
-     * @param array $options {
193
-     * @type int    $QST_ID  the QST_ID attribute of this question option, otherwise it will be for the same question
194
-     *                       as the original
195
-     */
196
-    public function duplicate($options = array())
197
-    {
198
-        $new_question_option = clone $this;
199
-        $new_question_option->set('QSO_ID', null);
200
-        if (
201
-            array_key_exists(
202
-                'QST_ID',
203
-                $options
204
-            )
205
-        ) {// use array_key_exists instead of isset because NULL might be a valid value
206
-            $new_question_option->set_question_ID($options['QST_ID']);
207
-        }
208
-        $new_question_option->save();
209
-    }
210
-
211
-    /**
212
-     * Gets the QSO_system value
213
-     *
214
-     * @return string|null
215
-     */
216
-    public function system()
217
-    {
218
-        return $this->get('QSO_system');
219
-    }
220
-
221
-    /**
222
-     * Sets QSO_system
223
-     *
224
-     * @param string $QSO_system
225
-     * @return bool
226
-     */
227
-    public function set_system($QSO_system)
228
-    {
229
-        return $this->set('QSO_system', $QSO_system);
230
-    }
13
+	/**
14
+	 * Question Option Opt Group Name
15
+	 *
16
+	 * @access protected
17
+	 * @var string
18
+	 */
19
+	protected $_QSO_opt_group = null;
20
+
21
+
22
+	/**
23
+	 *
24
+	 * @param array  $props_n_values          incoming values
25
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
26
+	 *                                        used.)
27
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
28
+	 *                                        date_format and the second value is the time format
29
+	 * @return EE_Attendee
30
+	 */
31
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
32
+	{
33
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
34
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
35
+	}
36
+
37
+
38
+	/**
39
+	 * @param array  $props_n_values  incoming values from the database
40
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
41
+	 *                                the website will be used.
42
+	 * @return EE_Attendee
43
+	 */
44
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
45
+	{
46
+		return new self($props_n_values, true, $timezone);
47
+	}
48
+
49
+
50
+	/**
51
+	 * Sets the option's key value
52
+	 *
53
+	 * @param string $value
54
+	 * @return bool success
55
+	 */
56
+	public function set_value($value)
57
+	{
58
+		$this->set('QSO_value', $value);
59
+	}
60
+
61
+
62
+	/**
63
+	 * Sets the option's Display Text
64
+	 *
65
+	 * @param string $text
66
+	 * @return bool success
67
+	 */
68
+	public function set_desc($text)
69
+	{
70
+		$this->set('QSO_desc', $text);
71
+	}
72
+
73
+
74
+	/**
75
+	 * Sets the order for this option
76
+	 *
77
+	 * @access public
78
+	 * @param integer $order
79
+	 * @return bool      $success
80
+	 */
81
+	public function set_order($order)
82
+	{
83
+		$this->set('QSO_order', $order);
84
+	}
85
+
86
+
87
+	/**
88
+	 * Sets the ID of the related question
89
+	 *
90
+	 * @param int $question_ID
91
+	 * @return bool success
92
+	 */
93
+	public function set_question_ID($question_ID)
94
+	{
95
+		$this->set('QST_ID', $question_ID);
96
+	}
97
+
98
+
99
+	/**
100
+	 * Sets the option's opt_group
101
+	 *
102
+	 * @param string $text
103
+	 * @return bool success
104
+	 */
105
+	public function set_opt_group($text)
106
+	{
107
+		return $this->_QSO_opt_group = $text;
108
+	}
109
+
110
+
111
+	/**
112
+	 * Gets the option's key value
113
+	 *
114
+	 * @return string
115
+	 */
116
+	public function value()
117
+	{
118
+		return $this->get('QSO_value');
119
+	}
120
+
121
+
122
+	/**
123
+	 * Gets the option's display text
124
+	 *
125
+	 * @return string
126
+	 */
127
+	public function desc()
128
+	{
129
+		return $this->get('QSO_desc');
130
+	}
131
+
132
+
133
+	/**
134
+	 * Returns whether this option has been deleted or not
135
+	 *
136
+	 * @return boolean
137
+	 */
138
+	public function deleted()
139
+	{
140
+		return $this->get('QSO_deleted');
141
+	}
142
+
143
+
144
+	/**
145
+	 * Returns the order or the Question Option
146
+	 *
147
+	 * @access public
148
+	 * @return integer
149
+	 */
150
+	public function order()
151
+	{
152
+		return $this->get('QSO_option');
153
+	}
154
+
155
+
156
+	/**
157
+	 * Gets the related question's ID
158
+	 *
159
+	 * @return int
160
+	 */
161
+	public function question_ID()
162
+	{
163
+		return $this->get('QST_ID');
164
+	}
165
+
166
+
167
+	/**
168
+	 * Returns the question related to this question option
169
+	 *
170
+	 * @return EE_Question
171
+	 */
172
+	public function question()
173
+	{
174
+		return $this->get_first_related('Question');
175
+	}
176
+
177
+
178
+	/**
179
+	 * Gets the option's opt_group
180
+	 *
181
+	 * @return string
182
+	 */
183
+	public function opt_group()
184
+	{
185
+		return $this->_QSO_opt_group;
186
+	}
187
+
188
+	/**
189
+	 * Duplicates this question option. By default the new question option will be for the same question,
190
+	 * but that can be overriden by setting the 'QST_ID' option
191
+	 *
192
+	 * @param array $options {
193
+	 * @type int    $QST_ID  the QST_ID attribute of this question option, otherwise it will be for the same question
194
+	 *                       as the original
195
+	 */
196
+	public function duplicate($options = array())
197
+	{
198
+		$new_question_option = clone $this;
199
+		$new_question_option->set('QSO_ID', null);
200
+		if (
201
+			array_key_exists(
202
+				'QST_ID',
203
+				$options
204
+			)
205
+		) {// use array_key_exists instead of isset because NULL might be a valid value
206
+			$new_question_option->set_question_ID($options['QST_ID']);
207
+		}
208
+		$new_question_option->save();
209
+	}
210
+
211
+	/**
212
+	 * Gets the QSO_system value
213
+	 *
214
+	 * @return string|null
215
+	 */
216
+	public function system()
217
+	{
218
+		return $this->get('QSO_system');
219
+	}
220
+
221
+	/**
222
+	 * Sets QSO_system
223
+	 *
224
+	 * @param string $QSO_system
225
+	 * @return bool
226
+	 */
227
+	public function set_system($QSO_system)
228
+	{
229
+		return $this->set('QSO_system', $QSO_system);
230
+	}
231 231
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Datetime.class.php 2 patches
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
             $date_or_time,
534 534
             $echo
535 535
         );
536
-        if (! $echo) {
536
+        if ( ! $echo) {
537 537
             return $dtt;
538 538
         }
539 539
         return '';
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
             '&nbsp;',
636 636
             $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
637 637
         );
638
-        return $start !== $end ? $start . $conjunction . $end : $start;
638
+        return $start !== $end ? $start.$conjunction.$end : $start;
639 639
     }
640 640
 
641 641
 
@@ -743,7 +743,7 @@  discard block
 block discarded – undo
743 743
             '&nbsp;',
744 744
             $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
745 745
         );
746
-        return $start !== $end ? $start . $conjunction . $end : $start;
746
+        return $start !== $end ? $start.$conjunction.$end : $start;
747 747
     }
748 748
 
749 749
 
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
     ) {
789 789
         $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
790 790
         $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
791
-        $full_format = $dt_format . $separator . $tm_format;
791
+        $full_format = $dt_format.$separator.$tm_format;
792 792
         // the range output depends on various conditions
793 793
         switch (true) {
794 794
             // start date timestamp and end date timestamp are the same.
@@ -1029,7 +1029,7 @@  discard block
 block discarded – undo
1029 1029
         // tickets remaining available for purchase
1030 1030
         // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1031 1031
         $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1032
-        if (! $consider_tickets) {
1032
+        if ( ! $consider_tickets) {
1033 1033
             return $dtt_remaining;
1034 1034
         }
1035 1035
         $tickets_remaining = $this->tickets_remaining();
@@ -1053,7 +1053,7 @@  discard block
 block discarded – undo
1053 1053
     {
1054 1054
         $sum = 0;
1055 1055
         $tickets = $this->tickets($query_params);
1056
-        if (! empty($tickets)) {
1056
+        if ( ! empty($tickets)) {
1057 1057
             foreach ($tickets as $ticket) {
1058 1058
                 if ($ticket instanceof EE_Ticket) {
1059 1059
                     // get the actual amount of tickets that can be sold
@@ -1204,7 +1204,7 @@  discard block
 block discarded – undo
1204 1204
     {
1205 1205
         if ($use_dtt_name) {
1206 1206
             $dtt_name = $this->name();
1207
-            if (! empty($dtt_name)) {
1207
+            if ( ! empty($dtt_name)) {
1208 1208
                 return $dtt_name;
1209 1209
             }
1210 1210
         }
@@ -1212,14 +1212,14 @@  discard block
 block discarded – undo
1212 1212
         if (
1213 1213
             date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1214 1214
         ) {
1215
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1215
+            $display_date = $this->start_date('M j\, Y g:i a').' - '.$this->end_date('M j\, Y g:i a');
1216 1216
             // next condition is if its the same month but different day
1217 1217
         } else {
1218 1218
             if (
1219 1219
                 date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1220 1220
                 && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1221 1221
             ) {
1222
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1222
+                $display_date = $this->start_date('M j\, g:i a').' - '.$this->end_date('M j\, g:i a Y');
1223 1223
             } else {
1224 1224
                 $display_date = $this->start_date('F j\, Y')
1225 1225
                                 . ' @ '
Please login to merge, or discard this patch.
Indentation   +1404 added lines, -1404 removed lines patch added patch discarded remove patch
@@ -13,1412 +13,1412 @@
 block discarded – undo
13 13
 class EE_Datetime extends EE_Soft_Delete_Base_Class
14 14
 {
15 15
 
16
-    /**
17
-     * constant used by get_active_status, indicates datetime has no more available spaces
18
-     */
19
-    const sold_out = 'DTS';
20
-
21
-    /**
22
-     * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
23
-     */
24
-    const active = 'DTA';
25
-
26
-    /**
27
-     * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
28
-     * expired
29
-     */
30
-    const upcoming = 'DTU';
31
-
32
-    /**
33
-     * Datetime is postponed
34
-     */
35
-    const postponed = 'DTP';
36
-
37
-    /**
38
-     * Datetime is cancelled
39
-     */
40
-    const cancelled = 'DTC';
41
-
42
-    /**
43
-     * constant used by get_active_status, indicates datetime has expired (event is over)
44
-     */
45
-    const expired = 'DTE';
46
-
47
-    /**
48
-     * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
49
-     */
50
-    const inactive = 'DTI';
51
-
52
-
53
-    /**
54
-     * @param array  $props_n_values    incoming values
55
-     * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
56
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
57
-     *                                  and the second value is the time format
58
-     * @return EE_Datetime
59
-     * @throws ReflectionException
60
-     * @throws InvalidArgumentException
61
-     * @throws InvalidInterfaceException
62
-     * @throws InvalidDataTypeException
63
-     * @throws EE_Error
64
-     */
65
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
66
-    {
67
-        $has_object = parent::_check_for_object(
68
-            $props_n_values,
69
-            __CLASS__,
70
-            $timezone,
71
-            $date_formats
72
-        );
73
-        return $has_object
74
-            ? $has_object
75
-            : new self($props_n_values, false, $timezone, $date_formats);
76
-    }
77
-
78
-
79
-    /**
80
-     * @param array  $props_n_values  incoming values from the database
81
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
-     *                                the website will be used.
83
-     * @return EE_Datetime
84
-     * @throws ReflectionException
85
-     * @throws InvalidArgumentException
86
-     * @throws InvalidInterfaceException
87
-     * @throws InvalidDataTypeException
88
-     * @throws EE_Error
89
-     */
90
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
91
-    {
92
-        return new self($props_n_values, true, $timezone);
93
-    }
94
-
95
-
96
-    /**
97
-     * @param $name
98
-     * @throws ReflectionException
99
-     * @throws InvalidArgumentException
100
-     * @throws InvalidInterfaceException
101
-     * @throws InvalidDataTypeException
102
-     * @throws EE_Error
103
-     */
104
-    public function set_name($name)
105
-    {
106
-        $this->set('DTT_name', $name);
107
-    }
108
-
109
-
110
-    /**
111
-     * @param $description
112
-     * @throws ReflectionException
113
-     * @throws InvalidArgumentException
114
-     * @throws InvalidInterfaceException
115
-     * @throws InvalidDataTypeException
116
-     * @throws EE_Error
117
-     */
118
-    public function set_description($description)
119
-    {
120
-        $this->set('DTT_description', $description);
121
-    }
122
-
123
-
124
-    /**
125
-     * Set event start date
126
-     * set the start date for an event
127
-     *
128
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
129
-     * @throws ReflectionException
130
-     * @throws InvalidArgumentException
131
-     * @throws InvalidInterfaceException
132
-     * @throws InvalidDataTypeException
133
-     * @throws EE_Error
134
-     */
135
-    public function set_start_date($date)
136
-    {
137
-        $this->_set_date_for($date, 'DTT_EVT_start');
138
-    }
139
-
140
-
141
-    /**
142
-     * Set event start time
143
-     * set the start time for an event
144
-     *
145
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
146
-     * @throws ReflectionException
147
-     * @throws InvalidArgumentException
148
-     * @throws InvalidInterfaceException
149
-     * @throws InvalidDataTypeException
150
-     * @throws EE_Error
151
-     */
152
-    public function set_start_time($time)
153
-    {
154
-        $this->_set_time_for($time, 'DTT_EVT_start');
155
-    }
156
-
157
-
158
-    /**
159
-     * Set event end date
160
-     * set the end date for an event
161
-     *
162
-     * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
163
-     * @throws ReflectionException
164
-     * @throws InvalidArgumentException
165
-     * @throws InvalidInterfaceException
166
-     * @throws InvalidDataTypeException
167
-     * @throws EE_Error
168
-     */
169
-    public function set_end_date($date)
170
-    {
171
-        $this->_set_date_for($date, 'DTT_EVT_end');
172
-    }
173
-
174
-
175
-    /**
176
-     * Set event end time
177
-     * set the end time for an event
178
-     *
179
-     * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
180
-     * @throws ReflectionException
181
-     * @throws InvalidArgumentException
182
-     * @throws InvalidInterfaceException
183
-     * @throws InvalidDataTypeException
184
-     * @throws EE_Error
185
-     */
186
-    public function set_end_time($time)
187
-    {
188
-        $this->_set_time_for($time, 'DTT_EVT_end');
189
-    }
190
-
191
-
192
-    /**
193
-     * Set registration limit
194
-     * set the maximum number of attendees that can be registered for this datetime slot
195
-     *
196
-     * @param int $reg_limit
197
-     * @throws ReflectionException
198
-     * @throws InvalidArgumentException
199
-     * @throws InvalidInterfaceException
200
-     * @throws InvalidDataTypeException
201
-     * @throws EE_Error
202
-     */
203
-    public function set_reg_limit($reg_limit)
204
-    {
205
-        $this->set('DTT_reg_limit', $reg_limit);
206
-    }
207
-
208
-
209
-    /**
210
-     * get the number of tickets sold for this datetime slot
211
-     *
212
-     * @return mixed int on success, FALSE on fail
213
-     * @throws ReflectionException
214
-     * @throws InvalidArgumentException
215
-     * @throws InvalidInterfaceException
216
-     * @throws InvalidDataTypeException
217
-     * @throws EE_Error
218
-     */
219
-    public function sold()
220
-    {
221
-        return $this->get_raw('DTT_sold');
222
-    }
223
-
224
-
225
-    /**
226
-     * @param int $sold
227
-     * @throws ReflectionException
228
-     * @throws InvalidArgumentException
229
-     * @throws InvalidInterfaceException
230
-     * @throws InvalidDataTypeException
231
-     * @throws EE_Error
232
-     */
233
-    public function set_sold($sold)
234
-    {
235
-        // sold can not go below zero
236
-        $sold = max(0, $sold);
237
-        $this->set('DTT_sold', $sold);
238
-    }
239
-
240
-
241
-    /**
242
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
243
-     * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
244
-     *
245
-     * @param int $qty
246
-     * @param boolean $also_decrease_reserved
247
-     * @return boolean indicating success
248
-     * @throws ReflectionException
249
-     * @throws InvalidArgumentException
250
-     * @throws InvalidInterfaceException
251
-     * @throws InvalidDataTypeException
252
-     * @throws EE_Error
253
-     */
254
-    public function increaseSold($qty = 1, $also_decrease_reserved = true)
255
-    {
256
-        $qty = absint($qty);
257
-        if ($also_decrease_reserved) {
258
-            $success = $this->adjustNumericFieldsInDb(
259
-                [
260
-                    'DTT_reserved' => $qty * -1,
261
-                    'DTT_sold' => $qty
262
-                ]
263
-            );
264
-        } else {
265
-            $success = $this->adjustNumericFieldsInDb(
266
-                [
267
-                    'DTT_sold' => $qty
268
-                ]
269
-            );
270
-        }
271
-
272
-        do_action(
273
-            'AHEE__EE_Datetime__increase_sold',
274
-            $this,
275
-            $qty,
276
-            $this->sold(),
277
-            $success
278
-        );
279
-        return $success;
280
-    }
281
-
282
-
283
-    /**
284
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
285
-     * to save afterwards.)
286
-     *
287
-     * @param int $qty
288
-     * @return boolean indicating success
289
-     * @throws ReflectionException
290
-     * @throws InvalidArgumentException
291
-     * @throws InvalidInterfaceException
292
-     * @throws InvalidDataTypeException
293
-     * @throws EE_Error
294
-     */
295
-    public function decreaseSold($qty = 1)
296
-    {
297
-        $qty = absint($qty);
298
-        $success = $this->adjustNumericFieldsInDb(
299
-            [
300
-                'DTT_sold' => $qty * -1
301
-            ]
302
-        );
303
-        do_action(
304
-            'AHEE__EE_Datetime__decrease_sold',
305
-            $this,
306
-            $qty,
307
-            $this->sold(),
308
-            $success
309
-        );
310
-        return $success;
311
-    }
312
-
313
-
314
-    /**
315
-     * Gets qty of reserved tickets for this datetime
316
-     *
317
-     * @return int
318
-     * @throws ReflectionException
319
-     * @throws InvalidArgumentException
320
-     * @throws InvalidInterfaceException
321
-     * @throws InvalidDataTypeException
322
-     * @throws EE_Error
323
-     */
324
-    public function reserved()
325
-    {
326
-        return $this->get_raw('DTT_reserved');
327
-    }
328
-
329
-
330
-    /**
331
-     * Sets qty of reserved tickets for this datetime
332
-     *
333
-     * @param int $reserved
334
-     * @throws ReflectionException
335
-     * @throws InvalidArgumentException
336
-     * @throws InvalidInterfaceException
337
-     * @throws InvalidDataTypeException
338
-     * @throws EE_Error
339
-     */
340
-    public function set_reserved($reserved)
341
-    {
342
-        // reserved can not go below zero
343
-        $reserved = max(0, (int) $reserved);
344
-        $this->set('DTT_reserved', $reserved);
345
-    }
346
-
347
-
348
-    /**
349
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
350
-     *
351
-     * @param int $qty
352
-     * @return boolean indicating success
353
-     * @throws ReflectionException
354
-     * @throws InvalidArgumentException
355
-     * @throws InvalidInterfaceException
356
-     * @throws InvalidDataTypeException
357
-     * @throws EE_Error
358
-     */
359
-    public function increaseReserved($qty = 1)
360
-    {
361
-        $qty = absint($qty);
362
-        $success = $this->incrementFieldConditionallyInDb(
363
-            'DTT_reserved',
364
-            'DTT_sold',
365
-            'DTT_reg_limit',
366
-            $qty
367
-        );
368
-        do_action(
369
-            'AHEE__EE_Datetime__increase_reserved',
370
-            $this,
371
-            $qty,
372
-            $this->reserved(),
373
-            $success
374
-        );
375
-        return $success;
376
-    }
377
-
378
-
379
-    /**
380
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
381
-     *
382
-     * @param int $qty
383
-     * @return boolean indicating success
384
-     * @throws ReflectionException
385
-     * @throws InvalidArgumentException
386
-     * @throws InvalidInterfaceException
387
-     * @throws InvalidDataTypeException
388
-     * @throws EE_Error
389
-     */
390
-    public function decreaseReserved($qty = 1)
391
-    {
392
-        $qty = absint($qty);
393
-        $success = $this->adjustNumericFieldsInDb(
394
-            [
395
-                'DTT_reserved' => $qty * -1
396
-            ]
397
-        );
398
-        do_action(
399
-            'AHEE__EE_Datetime__decrease_reserved',
400
-            $this,
401
-            $qty,
402
-            $this->reserved(),
403
-            $success
404
-        );
405
-        return $success;
406
-    }
407
-
408
-
409
-    /**
410
-     * total sold and reserved tickets
411
-     *
412
-     * @return int
413
-     * @throws ReflectionException
414
-     * @throws InvalidArgumentException
415
-     * @throws InvalidInterfaceException
416
-     * @throws InvalidDataTypeException
417
-     * @throws EE_Error
418
-     */
419
-    public function sold_and_reserved()
420
-    {
421
-        return $this->sold() + $this->reserved();
422
-    }
423
-
424
-
425
-    /**
426
-     * returns the datetime name
427
-     *
428
-     * @return string
429
-     * @throws ReflectionException
430
-     * @throws InvalidArgumentException
431
-     * @throws InvalidInterfaceException
432
-     * @throws InvalidDataTypeException
433
-     * @throws EE_Error
434
-     */
435
-    public function name()
436
-    {
437
-        return $this->get('DTT_name');
438
-    }
439
-
440
-
441
-    /**
442
-     * returns the datetime description
443
-     *
444
-     * @return string
445
-     * @throws ReflectionException
446
-     * @throws InvalidArgumentException
447
-     * @throws InvalidInterfaceException
448
-     * @throws InvalidDataTypeException
449
-     * @throws EE_Error
450
-     */
451
-    public function description()
452
-    {
453
-        return $this->get('DTT_description');
454
-    }
455
-
456
-
457
-    /**
458
-     * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
459
-     *
460
-     * @return boolean  TRUE if is primary, FALSE if not.
461
-     * @throws ReflectionException
462
-     * @throws InvalidArgumentException
463
-     * @throws InvalidInterfaceException
464
-     * @throws InvalidDataTypeException
465
-     * @throws EE_Error
466
-     */
467
-    public function is_primary()
468
-    {
469
-        return $this->get('DTT_is_primary');
470
-    }
471
-
472
-
473
-    /**
474
-     * This helper simply returns the order for the datetime
475
-     *
476
-     * @return int  The order of the datetime for this event.
477
-     * @throws ReflectionException
478
-     * @throws InvalidArgumentException
479
-     * @throws InvalidInterfaceException
480
-     * @throws InvalidDataTypeException
481
-     * @throws EE_Error
482
-     */
483
-    public function order()
484
-    {
485
-        return $this->get('DTT_order');
486
-    }
487
-
488
-
489
-    /**
490
-     * This helper simply returns the parent id for the datetime
491
-     *
492
-     * @return int
493
-     * @throws ReflectionException
494
-     * @throws InvalidArgumentException
495
-     * @throws InvalidInterfaceException
496
-     * @throws InvalidDataTypeException
497
-     * @throws EE_Error
498
-     */
499
-    public function parent()
500
-    {
501
-        return $this->get('DTT_parent');
502
-    }
503
-
504
-
505
-    /**
506
-     * show date and/or time
507
-     *
508
-     * @param string $date_or_time    whether to display a date or time or both
509
-     * @param string $start_or_end    whether to display start or end datetimes
510
-     * @param string $dt_frmt
511
-     * @param string $tm_frmt
512
-     * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
513
-     *                                otherwise we use the standard formats)
514
-     * @return string|bool  string on success, FALSE on fail
515
-     * @throws ReflectionException
516
-     * @throws InvalidArgumentException
517
-     * @throws InvalidInterfaceException
518
-     * @throws InvalidDataTypeException
519
-     * @throws EE_Error
520
-     */
521
-    private function _show_datetime(
522
-        $date_or_time = null,
523
-        $start_or_end = 'start',
524
-        $dt_frmt = '',
525
-        $tm_frmt = '',
526
-        $echo = false
527
-    ) {
528
-        $field_name = "DTT_EVT_{$start_or_end}";
529
-        $dtt = $this->_get_datetime(
530
-            $field_name,
531
-            $dt_frmt,
532
-            $tm_frmt,
533
-            $date_or_time,
534
-            $echo
535
-        );
536
-        if (! $echo) {
537
-            return $dtt;
538
-        }
539
-        return '';
540
-    }
541
-
542
-
543
-    /**
544
-     * get event start date.  Provide either the date format, or NULL to re-use the
545
-     * last-used format, or '' to use the default date format
546
-     *
547
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
548
-     * @return mixed            string on success, FALSE on fail
549
-     * @throws ReflectionException
550
-     * @throws InvalidArgumentException
551
-     * @throws InvalidInterfaceException
552
-     * @throws InvalidDataTypeException
553
-     * @throws EE_Error
554
-     */
555
-    public function start_date($dt_frmt = '')
556
-    {
557
-        return $this->_show_datetime('D', 'start', $dt_frmt);
558
-    }
559
-
560
-
561
-    /**
562
-     * Echoes start_date()
563
-     *
564
-     * @param string $dt_frmt
565
-     * @throws ReflectionException
566
-     * @throws InvalidArgumentException
567
-     * @throws InvalidInterfaceException
568
-     * @throws InvalidDataTypeException
569
-     * @throws EE_Error
570
-     */
571
-    public function e_start_date($dt_frmt = '')
572
-    {
573
-        $this->_show_datetime('D', 'start', $dt_frmt, null, true);
574
-    }
575
-
576
-
577
-    /**
578
-     * get end date. Provide either the date format, or NULL to re-use the
579
-     * last-used format, or '' to use the default date format
580
-     *
581
-     * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
582
-     * @return mixed            string on success, FALSE on fail
583
-     * @throws ReflectionException
584
-     * @throws InvalidArgumentException
585
-     * @throws InvalidInterfaceException
586
-     * @throws InvalidDataTypeException
587
-     * @throws EE_Error
588
-     */
589
-    public function end_date($dt_frmt = '')
590
-    {
591
-        return $this->_show_datetime('D', 'end', $dt_frmt);
592
-    }
593
-
594
-
595
-    /**
596
-     * Echoes the end date. See end_date()
597
-     *
598
-     * @param string $dt_frmt
599
-     * @throws ReflectionException
600
-     * @throws InvalidArgumentException
601
-     * @throws InvalidInterfaceException
602
-     * @throws InvalidDataTypeException
603
-     * @throws EE_Error
604
-     */
605
-    public function e_end_date($dt_frmt = '')
606
-    {
607
-        $this->_show_datetime('D', 'end', $dt_frmt, null, true);
608
-    }
609
-
610
-
611
-    /**
612
-     * get date_range - meaning the start AND end date
613
-     *
614
-     * @access public
615
-     * @param string $dt_frmt     string representation of date format defaults to WP settings
616
-     * @param string $conjunction conjunction junction what's your function ?
617
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
618
-     * @return mixed              string on success, FALSE on fail
619
-     * @throws ReflectionException
620
-     * @throws InvalidArgumentException
621
-     * @throws InvalidInterfaceException
622
-     * @throws InvalidDataTypeException
623
-     * @throws EE_Error
624
-     */
625
-    public function date_range($dt_frmt = '', $conjunction = ' - ')
626
-    {
627
-        $dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
628
-        $start = str_replace(
629
-            ' ',
630
-            '&nbsp;',
631
-            $this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
632
-        );
633
-        $end = str_replace(
634
-            ' ',
635
-            '&nbsp;',
636
-            $this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
637
-        );
638
-        return $start !== $end ? $start . $conjunction . $end : $start;
639
-    }
640
-
641
-
642
-    /**
643
-     * @param string $dt_frmt
644
-     * @param string $conjunction
645
-     * @throws ReflectionException
646
-     * @throws InvalidArgumentException
647
-     * @throws InvalidInterfaceException
648
-     * @throws InvalidDataTypeException
649
-     * @throws EE_Error
650
-     */
651
-    public function e_date_range($dt_frmt = '', $conjunction = ' - ')
652
-    {
653
-        echo esc_html($this->date_range($dt_frmt, $conjunction));
654
-    }
655
-
656
-
657
-    /**
658
-     * get start time
659
-     *
660
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
661
-     * @return mixed        string on success, FALSE on fail
662
-     * @throws ReflectionException
663
-     * @throws InvalidArgumentException
664
-     * @throws InvalidInterfaceException
665
-     * @throws InvalidDataTypeException
666
-     * @throws EE_Error
667
-     */
668
-    public function start_time($tm_format = '')
669
-    {
670
-        return $this->_show_datetime('T', 'start', null, $tm_format);
671
-    }
672
-
673
-
674
-    /**
675
-     * @param string $tm_format
676
-     * @throws ReflectionException
677
-     * @throws InvalidArgumentException
678
-     * @throws InvalidInterfaceException
679
-     * @throws InvalidDataTypeException
680
-     * @throws EE_Error
681
-     */
682
-    public function e_start_time($tm_format = '')
683
-    {
684
-        $this->_show_datetime('T', 'start', null, $tm_format, true);
685
-    }
686
-
687
-
688
-    /**
689
-     * get end time
690
-     *
691
-     * @param string $tm_format string representation of time format defaults to 'g:i a'
692
-     * @return mixed                string on success, FALSE on fail
693
-     * @throws ReflectionException
694
-     * @throws InvalidArgumentException
695
-     * @throws InvalidInterfaceException
696
-     * @throws InvalidDataTypeException
697
-     * @throws EE_Error
698
-     */
699
-    public function end_time($tm_format = '')
700
-    {
701
-        return $this->_show_datetime('T', 'end', null, $tm_format);
702
-    }
703
-
704
-
705
-    /**
706
-     * @param string $tm_format
707
-     * @throws ReflectionException
708
-     * @throws InvalidArgumentException
709
-     * @throws InvalidInterfaceException
710
-     * @throws InvalidDataTypeException
711
-     * @throws EE_Error
712
-     */
713
-    public function e_end_time($tm_format = '')
714
-    {
715
-        $this->_show_datetime('T', 'end', null, $tm_format, true);
716
-    }
717
-
718
-
719
-    /**
720
-     * get time_range
721
-     *
722
-     * @access public
723
-     * @param string $tm_format   string representation of time format defaults to 'g:i a'
724
-     * @param string $conjunction conjunction junction what's your function ?
725
-     *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
726
-     * @return mixed              string on success, FALSE on fail
727
-     * @throws ReflectionException
728
-     * @throws InvalidArgumentException
729
-     * @throws InvalidInterfaceException
730
-     * @throws InvalidDataTypeException
731
-     * @throws EE_Error
732
-     */
733
-    public function time_range($tm_format = '', $conjunction = ' - ')
734
-    {
735
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
736
-        $start = str_replace(
737
-            ' ',
738
-            '&nbsp;',
739
-            $this->get_i18n_datetime('DTT_EVT_start', $tm_format)
740
-        );
741
-        $end = str_replace(
742
-            ' ',
743
-            '&nbsp;',
744
-            $this->get_i18n_datetime('DTT_EVT_end', $tm_format)
745
-        );
746
-        return $start !== $end ? $start . $conjunction . $end : $start;
747
-    }
748
-
749
-
750
-    /**
751
-     * @param string $tm_format
752
-     * @param string $conjunction
753
-     * @throws ReflectionException
754
-     * @throws InvalidArgumentException
755
-     * @throws InvalidInterfaceException
756
-     * @throws InvalidDataTypeException
757
-     * @throws EE_Error
758
-     */
759
-    public function e_time_range($tm_format = '', $conjunction = ' - ')
760
-    {
761
-        echo esc_html($this->time_range($tm_format, $conjunction));
762
-    }
763
-
764
-
765
-    /**
766
-     * This returns a range representation of the date and times.
767
-     * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
768
-     * Also, the return value is localized.
769
-     *
770
-     * @param string $dt_format
771
-     * @param string $tm_format
772
-     * @param string $conjunction used between two different dates or times.
773
-     *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
774
-     * @param string $separator   used between the date and time formats.
775
-     *                            ex: Dec 1, 2016{$separator}2pm
776
-     * @return string
777
-     * @throws ReflectionException
778
-     * @throws InvalidArgumentException
779
-     * @throws InvalidInterfaceException
780
-     * @throws InvalidDataTypeException
781
-     * @throws EE_Error
782
-     */
783
-    public function date_and_time_range(
784
-        $dt_format = '',
785
-        $tm_format = '',
786
-        $conjunction = ' - ',
787
-        $separator = ' '
788
-    ) {
789
-        $dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
790
-        $tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
791
-        $full_format = $dt_format . $separator . $tm_format;
792
-        // the range output depends on various conditions
793
-        switch (true) {
794
-            // start date timestamp and end date timestamp are the same.
795
-            case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
796
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
797
-                break;
798
-            // start and end date are the same but times are different
799
-            case ($this->start_date() === $this->end_date()):
800
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
801
-                          . $conjunction
802
-                          . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
803
-                break;
804
-            // all other conditions
805
-            default:
806
-                $output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
807
-                          . $conjunction
808
-                          . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
809
-                break;
810
-        }
811
-        return $output;
812
-    }
813
-
814
-
815
-    /**
816
-     * This echos the results of date and time range.
817
-     *
818
-     * @see date_and_time_range() for more details on purpose.
819
-     * @param string $dt_format
820
-     * @param string $tm_format
821
-     * @param string $conjunction
822
-     * @return void
823
-     * @throws ReflectionException
824
-     * @throws InvalidArgumentException
825
-     * @throws InvalidInterfaceException
826
-     * @throws InvalidDataTypeException
827
-     * @throws EE_Error
828
-     */
829
-    public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
830
-    {
831
-        echo esc_html($this->date_and_time_range($dt_format, $tm_format, $conjunction));
832
-    }
833
-
834
-
835
-    /**
836
-     * get start date and start time
837
-     *
838
-     * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
839
-     * @param    string $tm_format - string representation of time format defaults to 'g:i a'
840
-     * @return    mixed    string on success, FALSE on fail
841
-     * @throws ReflectionException
842
-     * @throws InvalidArgumentException
843
-     * @throws InvalidInterfaceException
844
-     * @throws InvalidDataTypeException
845
-     * @throws EE_Error
846
-     */
847
-    public function start_date_and_time($dt_format = '', $tm_format = '')
848
-    {
849
-        return $this->_show_datetime('', 'start', $dt_format, $tm_format);
850
-    }
851
-
852
-
853
-    /**
854
-     * @param string $dt_frmt
855
-     * @param string $tm_format
856
-     * @throws ReflectionException
857
-     * @throws InvalidArgumentException
858
-     * @throws InvalidInterfaceException
859
-     * @throws InvalidDataTypeException
860
-     * @throws EE_Error
861
-     */
862
-    public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
863
-    {
864
-        $this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
865
-    }
866
-
867
-
868
-    /**
869
-     * Shows the length of the event (start to end time).
870
-     * Can be shown in 'seconds','minutes','hours', or 'days'.
871
-     * By default, rounds up. (So if you use 'days', and then event
872
-     * only occurs for 1 hour, it will return 1 day).
873
-     *
874
-     * @param string $units 'seconds','minutes','hours','days'
875
-     * @param bool   $round_up
876
-     * @return float|int|mixed
877
-     * @throws ReflectionException
878
-     * @throws InvalidArgumentException
879
-     * @throws InvalidInterfaceException
880
-     * @throws InvalidDataTypeException
881
-     * @throws EE_Error
882
-     */
883
-    public function length($units = 'seconds', $round_up = false)
884
-    {
885
-        $start = $this->get_raw('DTT_EVT_start');
886
-        $end = $this->get_raw('DTT_EVT_end');
887
-        $length_in_units = $end - $start;
888
-        switch ($units) {
889
-            // NOTE: We purposefully don't use "break;" in order to chain the divisions
890
-            /** @noinspection PhpMissingBreakStatementInspection */
891
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
892
-            case 'days':
893
-                $length_in_units /= 24;
894
-            /** @noinspection PhpMissingBreakStatementInspection */
895
-            case 'hours':
896
-                // fall through is intentional
897
-                $length_in_units /= 60;
898
-            /** @noinspection PhpMissingBreakStatementInspection */
899
-            case 'minutes':
900
-                // fall through is intentional
901
-                $length_in_units /= 60;
902
-            case 'seconds':
903
-            default:
904
-                $length_in_units = ceil($length_in_units);
905
-        }
906
-        // phpcs:enable
907
-        if ($round_up) {
908
-            $length_in_units = max($length_in_units, 1);
909
-        }
910
-        return $length_in_units;
911
-    }
912
-
913
-
914
-    /**
915
-     *        get end date and time
916
-     *
917
-     * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
918
-     * @param string $tm_format - string representation of time format defaults to 'g:i a'
919
-     * @return    mixed                string on success, FALSE on fail
920
-     * @throws ReflectionException
921
-     * @throws InvalidArgumentException
922
-     * @throws InvalidInterfaceException
923
-     * @throws InvalidDataTypeException
924
-     * @throws EE_Error
925
-     */
926
-    public function end_date_and_time($dt_frmt = '', $tm_format = '')
927
-    {
928
-        return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
929
-    }
930
-
931
-
932
-    /**
933
-     * @param string $dt_frmt
934
-     * @param string $tm_format
935
-     * @throws ReflectionException
936
-     * @throws InvalidArgumentException
937
-     * @throws InvalidInterfaceException
938
-     * @throws InvalidDataTypeException
939
-     * @throws EE_Error
940
-     */
941
-    public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
942
-    {
943
-        $this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
944
-    }
945
-
946
-
947
-    /**
948
-     *        get start timestamp
949
-     *
950
-     * @return        int
951
-     * @throws ReflectionException
952
-     * @throws InvalidArgumentException
953
-     * @throws InvalidInterfaceException
954
-     * @throws InvalidDataTypeException
955
-     * @throws EE_Error
956
-     */
957
-    public function start()
958
-    {
959
-        return $this->get_raw('DTT_EVT_start');
960
-    }
961
-
962
-
963
-    /**
964
-     *        get end timestamp
965
-     *
966
-     * @return        int
967
-     * @throws ReflectionException
968
-     * @throws InvalidArgumentException
969
-     * @throws InvalidInterfaceException
970
-     * @throws InvalidDataTypeException
971
-     * @throws EE_Error
972
-     */
973
-    public function end()
974
-    {
975
-        return $this->get_raw('DTT_EVT_end');
976
-    }
977
-
978
-
979
-    /**
980
-     *    get the registration limit for this datetime slot
981
-     *
982
-     * @return        mixed        int on success, FALSE on fail
983
-     * @throws ReflectionException
984
-     * @throws InvalidArgumentException
985
-     * @throws InvalidInterfaceException
986
-     * @throws InvalidDataTypeException
987
-     * @throws EE_Error
988
-     */
989
-    public function reg_limit()
990
-    {
991
-        return $this->get_raw('DTT_reg_limit');
992
-    }
993
-
994
-
995
-    /**
996
-     *    have the tickets sold for this datetime, met or exceed the registration limit ?
997
-     *
998
-     * @return        boolean
999
-     * @throws ReflectionException
1000
-     * @throws InvalidArgumentException
1001
-     * @throws InvalidInterfaceException
1002
-     * @throws InvalidDataTypeException
1003
-     * @throws EE_Error
1004
-     */
1005
-    public function sold_out()
1006
-    {
1007
-        return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1008
-    }
1009
-
1010
-
1011
-    /**
1012
-     * return the total number of spaces remaining at this venue.
1013
-     * This only takes the venue's capacity into account, NOT the tickets available for sale
1014
-     *
1015
-     * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1016
-     *                               Because if all tickets attached to this datetime have no spaces left,
1017
-     *                               then this datetime IS effectively sold out.
1018
-     *                               However, there are cases where we just want to know the spaces
1019
-     *                               remaining for this particular datetime, hence the flag.
1020
-     * @return int
1021
-     * @throws ReflectionException
1022
-     * @throws InvalidArgumentException
1023
-     * @throws InvalidInterfaceException
1024
-     * @throws InvalidDataTypeException
1025
-     * @throws EE_Error
1026
-     */
1027
-    public function spaces_remaining($consider_tickets = false)
1028
-    {
1029
-        // tickets remaining available for purchase
1030
-        // no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1031
-        $dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1032
-        if (! $consider_tickets) {
1033
-            return $dtt_remaining;
1034
-        }
1035
-        $tickets_remaining = $this->tickets_remaining();
1036
-        return min($dtt_remaining, $tickets_remaining);
1037
-    }
1038
-
1039
-
1040
-    /**
1041
-     * Counts the total tickets available
1042
-     * (from all the different types of tickets which are available for this datetime).
1043
-     *
1044
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1045
-     * @return int
1046
-     * @throws ReflectionException
1047
-     * @throws InvalidArgumentException
1048
-     * @throws InvalidInterfaceException
1049
-     * @throws InvalidDataTypeException
1050
-     * @throws EE_Error
1051
-     */
1052
-    public function tickets_remaining($query_params = array())
1053
-    {
1054
-        $sum = 0;
1055
-        $tickets = $this->tickets($query_params);
1056
-        if (! empty($tickets)) {
1057
-            foreach ($tickets as $ticket) {
1058
-                if ($ticket instanceof EE_Ticket) {
1059
-                    // get the actual amount of tickets that can be sold
1060
-                    $qty = $ticket->qty('saleable');
1061
-                    if ($qty === EE_INF) {
1062
-                        return EE_INF;
1063
-                    }
1064
-                    // no negative ticket quantities plz
1065
-                    if ($qty > 0) {
1066
-                        $sum += $qty;
1067
-                    }
1068
-                }
1069
-            }
1070
-        }
1071
-        return $sum;
1072
-    }
1073
-
1074
-
1075
-    /**
1076
-     * Gets the count of all the tickets available at this datetime (not ticket types)
1077
-     * before any were sold
1078
-     *
1079
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1080
-     * @return int
1081
-     * @throws ReflectionException
1082
-     * @throws InvalidArgumentException
1083
-     * @throws InvalidInterfaceException
1084
-     * @throws InvalidDataTypeException
1085
-     * @throws EE_Error
1086
-     */
1087
-    public function sum_tickets_initially_available($query_params = array())
1088
-    {
1089
-        return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1090
-    }
1091
-
1092
-
1093
-    /**
1094
-     * Returns the lesser-of-the two: spaces remaining at this datetime, or
1095
-     * the total tickets remaining (a sum of the tickets remaining for each ticket type
1096
-     * that is available for this datetime).
1097
-     *
1098
-     * @return int
1099
-     * @throws ReflectionException
1100
-     * @throws InvalidArgumentException
1101
-     * @throws InvalidInterfaceException
1102
-     * @throws InvalidDataTypeException
1103
-     * @throws EE_Error
1104
-     */
1105
-    public function total_tickets_available_at_this_datetime()
1106
-    {
1107
-        return $this->spaces_remaining(true);
1108
-    }
1109
-
1110
-
1111
-    /**
1112
-     * This simply compares the internal dtt for the given string with NOW
1113
-     * and determines if the date is upcoming or not.
1114
-     *
1115
-     * @access public
1116
-     * @return boolean
1117
-     * @throws ReflectionException
1118
-     * @throws InvalidArgumentException
1119
-     * @throws InvalidInterfaceException
1120
-     * @throws InvalidDataTypeException
1121
-     * @throws EE_Error
1122
-     */
1123
-    public function is_upcoming()
1124
-    {
1125
-        return ($this->get_raw('DTT_EVT_start') > time());
1126
-    }
1127
-
1128
-
1129
-    /**
1130
-     * This simply compares the internal datetime for the given string with NOW
1131
-     * and returns if the date is active (i.e. start and end time)
1132
-     *
1133
-     * @return boolean
1134
-     * @throws ReflectionException
1135
-     * @throws InvalidArgumentException
1136
-     * @throws InvalidInterfaceException
1137
-     * @throws InvalidDataTypeException
1138
-     * @throws EE_Error
1139
-     */
1140
-    public function is_active()
1141
-    {
1142
-        return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1143
-    }
1144
-
1145
-
1146
-    /**
1147
-     * This simply compares the internal dtt for the given string with NOW
1148
-     * and determines if the date is expired or not.
1149
-     *
1150
-     * @return boolean
1151
-     * @throws ReflectionException
1152
-     * @throws InvalidArgumentException
1153
-     * @throws InvalidInterfaceException
1154
-     * @throws InvalidDataTypeException
1155
-     * @throws EE_Error
1156
-     */
1157
-    public function is_expired()
1158
-    {
1159
-        return ($this->get_raw('DTT_EVT_end') < time());
1160
-    }
1161
-
1162
-
1163
-    /**
1164
-     * This returns the active status for whether an event is active, upcoming, or expired
1165
-     *
1166
-     * @return int return value will be one of the EE_Datetime status constants.
1167
-     * @throws ReflectionException
1168
-     * @throws InvalidArgumentException
1169
-     * @throws InvalidInterfaceException
1170
-     * @throws InvalidDataTypeException
1171
-     * @throws EE_Error
1172
-     */
1173
-    public function get_active_status()
1174
-    {
1175
-        $total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1176
-        if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1177
-            return EE_Datetime::sold_out;
1178
-        }
1179
-        if ($this->is_expired()) {
1180
-            return EE_Datetime::expired;
1181
-        }
1182
-        if ($this->is_upcoming()) {
1183
-            return EE_Datetime::upcoming;
1184
-        }
1185
-        if ($this->is_active()) {
1186
-            return EE_Datetime::active;
1187
-        }
1188
-        return null;
1189
-    }
1190
-
1191
-
1192
-    /**
1193
-     * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1194
-     *
1195
-     * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1196
-     * @return string
1197
-     * @throws ReflectionException
1198
-     * @throws InvalidArgumentException
1199
-     * @throws InvalidInterfaceException
1200
-     * @throws InvalidDataTypeException
1201
-     * @throws EE_Error
1202
-     */
1203
-    public function get_dtt_display_name($use_dtt_name = false)
1204
-    {
1205
-        if ($use_dtt_name) {
1206
-            $dtt_name = $this->name();
1207
-            if (! empty($dtt_name)) {
1208
-                return $dtt_name;
1209
-            }
1210
-        }
1211
-        // first condition is to see if the months are different
1212
-        if (
1213
-            date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1214
-        ) {
1215
-            $display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1216
-            // next condition is if its the same month but different day
1217
-        } else {
1218
-            if (
1219
-                date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1220
-                && date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1221
-            ) {
1222
-                $display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1223
-            } else {
1224
-                $display_date = $this->start_date('F j\, Y')
1225
-                                . ' @ '
1226
-                                . $this->start_date('g:i a')
1227
-                                . ' - '
1228
-                                . $this->end_date('g:i a');
1229
-            }
1230
-        }
1231
-        return $display_date;
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     * Gets all the tickets for this datetime
1237
-     *
1238
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1239
-     * @return EE_Base_Class[]|EE_Ticket[]
1240
-     * @throws ReflectionException
1241
-     * @throws InvalidArgumentException
1242
-     * @throws InvalidInterfaceException
1243
-     * @throws InvalidDataTypeException
1244
-     * @throws EE_Error
1245
-     */
1246
-    public function tickets($query_params = array())
1247
-    {
1248
-        return $this->get_many_related('Ticket', $query_params);
1249
-    }
1250
-
1251
-
1252
-    /**
1253
-     * Gets all the ticket types currently available for purchase
1254
-     *
1255
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1256
-     * @return EE_Ticket[]
1257
-     * @throws ReflectionException
1258
-     * @throws InvalidArgumentException
1259
-     * @throws InvalidInterfaceException
1260
-     * @throws InvalidDataTypeException
1261
-     * @throws EE_Error
1262
-     */
1263
-    public function ticket_types_available_for_purchase($query_params = array())
1264
-    {
1265
-        // first check if datetime is valid
1266
-        if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1267
-            return array();
1268
-        }
1269
-        if (empty($query_params)) {
1270
-            $query_params = array(
1271
-                array(
1272
-                    'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1273
-                    'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1274
-                    'TKT_deleted'    => false,
1275
-                ),
1276
-            );
1277
-        }
1278
-        return $this->tickets($query_params);
1279
-    }
1280
-
1281
-
1282
-    /**
1283
-     * @return EE_Base_Class|EE_Event
1284
-     * @throws ReflectionException
1285
-     * @throws InvalidArgumentException
1286
-     * @throws InvalidInterfaceException
1287
-     * @throws InvalidDataTypeException
1288
-     * @throws EE_Error
1289
-     */
1290
-    public function event()
1291
-    {
1292
-        return $this->get_first_related('Event');
1293
-    }
1294
-
1295
-
1296
-    /**
1297
-     * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1298
-     * (via the tickets).
1299
-     *
1300
-     * @return int
1301
-     * @throws ReflectionException
1302
-     * @throws InvalidArgumentException
1303
-     * @throws InvalidInterfaceException
1304
-     * @throws InvalidDataTypeException
1305
-     * @throws EE_Error
1306
-     */
1307
-    public function update_sold()
1308
-    {
1309
-        $count_regs_for_this_datetime = EEM_Registration::instance()->count(
1310
-            array(
1311
-                array(
1312
-                    'STS_ID'                 => EEM_Registration::status_id_approved,
1313
-                    'REG_deleted'            => 0,
1314
-                    'Ticket.Datetime.DTT_ID' => $this->ID(),
1315
-                ),
1316
-            )
1317
-        );
1318
-        $this->set_sold($count_regs_for_this_datetime);
1319
-        $this->save();
1320
-        return $count_regs_for_this_datetime;
1321
-    }
1322
-
1323
-
1324
-    /*******************************************************************
16
+	/**
17
+	 * constant used by get_active_status, indicates datetime has no more available spaces
18
+	 */
19
+	const sold_out = 'DTS';
20
+
21
+	/**
22
+	 * constant used by get_active_status, indicating datetime is still active (even is not over, can be registered-for)
23
+	 */
24
+	const active = 'DTA';
25
+
26
+	/**
27
+	 * constant used by get_active_status, indicating the datetime cannot be used for registrations yet, but has not
28
+	 * expired
29
+	 */
30
+	const upcoming = 'DTU';
31
+
32
+	/**
33
+	 * Datetime is postponed
34
+	 */
35
+	const postponed = 'DTP';
36
+
37
+	/**
38
+	 * Datetime is cancelled
39
+	 */
40
+	const cancelled = 'DTC';
41
+
42
+	/**
43
+	 * constant used by get_active_status, indicates datetime has expired (event is over)
44
+	 */
45
+	const expired = 'DTE';
46
+
47
+	/**
48
+	 * constant used in various places indicating that an event is INACTIVE (not yet ready to be published)
49
+	 */
50
+	const inactive = 'DTI';
51
+
52
+
53
+	/**
54
+	 * @param array  $props_n_values    incoming values
55
+	 * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
56
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the date_format
57
+	 *                                  and the second value is the time format
58
+	 * @return EE_Datetime
59
+	 * @throws ReflectionException
60
+	 * @throws InvalidArgumentException
61
+	 * @throws InvalidInterfaceException
62
+	 * @throws InvalidDataTypeException
63
+	 * @throws EE_Error
64
+	 */
65
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
66
+	{
67
+		$has_object = parent::_check_for_object(
68
+			$props_n_values,
69
+			__CLASS__,
70
+			$timezone,
71
+			$date_formats
72
+		);
73
+		return $has_object
74
+			? $has_object
75
+			: new self($props_n_values, false, $timezone, $date_formats);
76
+	}
77
+
78
+
79
+	/**
80
+	 * @param array  $props_n_values  incoming values from the database
81
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
+	 *                                the website will be used.
83
+	 * @return EE_Datetime
84
+	 * @throws ReflectionException
85
+	 * @throws InvalidArgumentException
86
+	 * @throws InvalidInterfaceException
87
+	 * @throws InvalidDataTypeException
88
+	 * @throws EE_Error
89
+	 */
90
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
91
+	{
92
+		return new self($props_n_values, true, $timezone);
93
+	}
94
+
95
+
96
+	/**
97
+	 * @param $name
98
+	 * @throws ReflectionException
99
+	 * @throws InvalidArgumentException
100
+	 * @throws InvalidInterfaceException
101
+	 * @throws InvalidDataTypeException
102
+	 * @throws EE_Error
103
+	 */
104
+	public function set_name($name)
105
+	{
106
+		$this->set('DTT_name', $name);
107
+	}
108
+
109
+
110
+	/**
111
+	 * @param $description
112
+	 * @throws ReflectionException
113
+	 * @throws InvalidArgumentException
114
+	 * @throws InvalidInterfaceException
115
+	 * @throws InvalidDataTypeException
116
+	 * @throws EE_Error
117
+	 */
118
+	public function set_description($description)
119
+	{
120
+		$this->set('DTT_description', $description);
121
+	}
122
+
123
+
124
+	/**
125
+	 * Set event start date
126
+	 * set the start date for an event
127
+	 *
128
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
129
+	 * @throws ReflectionException
130
+	 * @throws InvalidArgumentException
131
+	 * @throws InvalidInterfaceException
132
+	 * @throws InvalidDataTypeException
133
+	 * @throws EE_Error
134
+	 */
135
+	public function set_start_date($date)
136
+	{
137
+		$this->_set_date_for($date, 'DTT_EVT_start');
138
+	}
139
+
140
+
141
+	/**
142
+	 * Set event start time
143
+	 * set the start time for an event
144
+	 *
145
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
146
+	 * @throws ReflectionException
147
+	 * @throws InvalidArgumentException
148
+	 * @throws InvalidInterfaceException
149
+	 * @throws InvalidDataTypeException
150
+	 * @throws EE_Error
151
+	 */
152
+	public function set_start_time($time)
153
+	{
154
+		$this->_set_time_for($time, 'DTT_EVT_start');
155
+	}
156
+
157
+
158
+	/**
159
+	 * Set event end date
160
+	 * set the end date for an event
161
+	 *
162
+	 * @param string $date a string representation of the event's date ex:  Dec. 25, 2025 or 12-25-2025
163
+	 * @throws ReflectionException
164
+	 * @throws InvalidArgumentException
165
+	 * @throws InvalidInterfaceException
166
+	 * @throws InvalidDataTypeException
167
+	 * @throws EE_Error
168
+	 */
169
+	public function set_end_date($date)
170
+	{
171
+		$this->_set_date_for($date, 'DTT_EVT_end');
172
+	}
173
+
174
+
175
+	/**
176
+	 * Set event end time
177
+	 * set the end time for an event
178
+	 *
179
+	 * @param string $time a string representation of the event time ex:  9am  or  7:30 PM
180
+	 * @throws ReflectionException
181
+	 * @throws InvalidArgumentException
182
+	 * @throws InvalidInterfaceException
183
+	 * @throws InvalidDataTypeException
184
+	 * @throws EE_Error
185
+	 */
186
+	public function set_end_time($time)
187
+	{
188
+		$this->_set_time_for($time, 'DTT_EVT_end');
189
+	}
190
+
191
+
192
+	/**
193
+	 * Set registration limit
194
+	 * set the maximum number of attendees that can be registered for this datetime slot
195
+	 *
196
+	 * @param int $reg_limit
197
+	 * @throws ReflectionException
198
+	 * @throws InvalidArgumentException
199
+	 * @throws InvalidInterfaceException
200
+	 * @throws InvalidDataTypeException
201
+	 * @throws EE_Error
202
+	 */
203
+	public function set_reg_limit($reg_limit)
204
+	{
205
+		$this->set('DTT_reg_limit', $reg_limit);
206
+	}
207
+
208
+
209
+	/**
210
+	 * get the number of tickets sold for this datetime slot
211
+	 *
212
+	 * @return mixed int on success, FALSE on fail
213
+	 * @throws ReflectionException
214
+	 * @throws InvalidArgumentException
215
+	 * @throws InvalidInterfaceException
216
+	 * @throws InvalidDataTypeException
217
+	 * @throws EE_Error
218
+	 */
219
+	public function sold()
220
+	{
221
+		return $this->get_raw('DTT_sold');
222
+	}
223
+
224
+
225
+	/**
226
+	 * @param int $sold
227
+	 * @throws ReflectionException
228
+	 * @throws InvalidArgumentException
229
+	 * @throws InvalidInterfaceException
230
+	 * @throws InvalidDataTypeException
231
+	 * @throws EE_Error
232
+	 */
233
+	public function set_sold($sold)
234
+	{
235
+		// sold can not go below zero
236
+		$sold = max(0, $sold);
237
+		$this->set('DTT_sold', $sold);
238
+	}
239
+
240
+
241
+	/**
242
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
243
+	 * Simultaneously decreases the reserved count, unless $also_decrease_reserved is false.
244
+	 *
245
+	 * @param int $qty
246
+	 * @param boolean $also_decrease_reserved
247
+	 * @return boolean indicating success
248
+	 * @throws ReflectionException
249
+	 * @throws InvalidArgumentException
250
+	 * @throws InvalidInterfaceException
251
+	 * @throws InvalidDataTypeException
252
+	 * @throws EE_Error
253
+	 */
254
+	public function increaseSold($qty = 1, $also_decrease_reserved = true)
255
+	{
256
+		$qty = absint($qty);
257
+		if ($also_decrease_reserved) {
258
+			$success = $this->adjustNumericFieldsInDb(
259
+				[
260
+					'DTT_reserved' => $qty * -1,
261
+					'DTT_sold' => $qty
262
+				]
263
+			);
264
+		} else {
265
+			$success = $this->adjustNumericFieldsInDb(
266
+				[
267
+					'DTT_sold' => $qty
268
+				]
269
+			);
270
+		}
271
+
272
+		do_action(
273
+			'AHEE__EE_Datetime__increase_sold',
274
+			$this,
275
+			$qty,
276
+			$this->sold(),
277
+			$success
278
+		);
279
+		return $success;
280
+	}
281
+
282
+
283
+	/**
284
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
285
+	 * to save afterwards.)
286
+	 *
287
+	 * @param int $qty
288
+	 * @return boolean indicating success
289
+	 * @throws ReflectionException
290
+	 * @throws InvalidArgumentException
291
+	 * @throws InvalidInterfaceException
292
+	 * @throws InvalidDataTypeException
293
+	 * @throws EE_Error
294
+	 */
295
+	public function decreaseSold($qty = 1)
296
+	{
297
+		$qty = absint($qty);
298
+		$success = $this->adjustNumericFieldsInDb(
299
+			[
300
+				'DTT_sold' => $qty * -1
301
+			]
302
+		);
303
+		do_action(
304
+			'AHEE__EE_Datetime__decrease_sold',
305
+			$this,
306
+			$qty,
307
+			$this->sold(),
308
+			$success
309
+		);
310
+		return $success;
311
+	}
312
+
313
+
314
+	/**
315
+	 * Gets qty of reserved tickets for this datetime
316
+	 *
317
+	 * @return int
318
+	 * @throws ReflectionException
319
+	 * @throws InvalidArgumentException
320
+	 * @throws InvalidInterfaceException
321
+	 * @throws InvalidDataTypeException
322
+	 * @throws EE_Error
323
+	 */
324
+	public function reserved()
325
+	{
326
+		return $this->get_raw('DTT_reserved');
327
+	}
328
+
329
+
330
+	/**
331
+	 * Sets qty of reserved tickets for this datetime
332
+	 *
333
+	 * @param int $reserved
334
+	 * @throws ReflectionException
335
+	 * @throws InvalidArgumentException
336
+	 * @throws InvalidInterfaceException
337
+	 * @throws InvalidDataTypeException
338
+	 * @throws EE_Error
339
+	 */
340
+	public function set_reserved($reserved)
341
+	{
342
+		// reserved can not go below zero
343
+		$reserved = max(0, (int) $reserved);
344
+		$this->set('DTT_reserved', $reserved);
345
+	}
346
+
347
+
348
+	/**
349
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
350
+	 *
351
+	 * @param int $qty
352
+	 * @return boolean indicating success
353
+	 * @throws ReflectionException
354
+	 * @throws InvalidArgumentException
355
+	 * @throws InvalidInterfaceException
356
+	 * @throws InvalidDataTypeException
357
+	 * @throws EE_Error
358
+	 */
359
+	public function increaseReserved($qty = 1)
360
+	{
361
+		$qty = absint($qty);
362
+		$success = $this->incrementFieldConditionallyInDb(
363
+			'DTT_reserved',
364
+			'DTT_sold',
365
+			'DTT_reg_limit',
366
+			$qty
367
+		);
368
+		do_action(
369
+			'AHEE__EE_Datetime__increase_reserved',
370
+			$this,
371
+			$qty,
372
+			$this->reserved(),
373
+			$success
374
+		);
375
+		return $success;
376
+	}
377
+
378
+
379
+	/**
380
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
381
+	 *
382
+	 * @param int $qty
383
+	 * @return boolean indicating success
384
+	 * @throws ReflectionException
385
+	 * @throws InvalidArgumentException
386
+	 * @throws InvalidInterfaceException
387
+	 * @throws InvalidDataTypeException
388
+	 * @throws EE_Error
389
+	 */
390
+	public function decreaseReserved($qty = 1)
391
+	{
392
+		$qty = absint($qty);
393
+		$success = $this->adjustNumericFieldsInDb(
394
+			[
395
+				'DTT_reserved' => $qty * -1
396
+			]
397
+		);
398
+		do_action(
399
+			'AHEE__EE_Datetime__decrease_reserved',
400
+			$this,
401
+			$qty,
402
+			$this->reserved(),
403
+			$success
404
+		);
405
+		return $success;
406
+	}
407
+
408
+
409
+	/**
410
+	 * total sold and reserved tickets
411
+	 *
412
+	 * @return int
413
+	 * @throws ReflectionException
414
+	 * @throws InvalidArgumentException
415
+	 * @throws InvalidInterfaceException
416
+	 * @throws InvalidDataTypeException
417
+	 * @throws EE_Error
418
+	 */
419
+	public function sold_and_reserved()
420
+	{
421
+		return $this->sold() + $this->reserved();
422
+	}
423
+
424
+
425
+	/**
426
+	 * returns the datetime name
427
+	 *
428
+	 * @return string
429
+	 * @throws ReflectionException
430
+	 * @throws InvalidArgumentException
431
+	 * @throws InvalidInterfaceException
432
+	 * @throws InvalidDataTypeException
433
+	 * @throws EE_Error
434
+	 */
435
+	public function name()
436
+	{
437
+		return $this->get('DTT_name');
438
+	}
439
+
440
+
441
+	/**
442
+	 * returns the datetime description
443
+	 *
444
+	 * @return string
445
+	 * @throws ReflectionException
446
+	 * @throws InvalidArgumentException
447
+	 * @throws InvalidInterfaceException
448
+	 * @throws InvalidDataTypeException
449
+	 * @throws EE_Error
450
+	 */
451
+	public function description()
452
+	{
453
+		return $this->get('DTT_description');
454
+	}
455
+
456
+
457
+	/**
458
+	 * This helper simply returns whether the event_datetime for the current datetime is a primary datetime
459
+	 *
460
+	 * @return boolean  TRUE if is primary, FALSE if not.
461
+	 * @throws ReflectionException
462
+	 * @throws InvalidArgumentException
463
+	 * @throws InvalidInterfaceException
464
+	 * @throws InvalidDataTypeException
465
+	 * @throws EE_Error
466
+	 */
467
+	public function is_primary()
468
+	{
469
+		return $this->get('DTT_is_primary');
470
+	}
471
+
472
+
473
+	/**
474
+	 * This helper simply returns the order for the datetime
475
+	 *
476
+	 * @return int  The order of the datetime for this event.
477
+	 * @throws ReflectionException
478
+	 * @throws InvalidArgumentException
479
+	 * @throws InvalidInterfaceException
480
+	 * @throws InvalidDataTypeException
481
+	 * @throws EE_Error
482
+	 */
483
+	public function order()
484
+	{
485
+		return $this->get('DTT_order');
486
+	}
487
+
488
+
489
+	/**
490
+	 * This helper simply returns the parent id for the datetime
491
+	 *
492
+	 * @return int
493
+	 * @throws ReflectionException
494
+	 * @throws InvalidArgumentException
495
+	 * @throws InvalidInterfaceException
496
+	 * @throws InvalidDataTypeException
497
+	 * @throws EE_Error
498
+	 */
499
+	public function parent()
500
+	{
501
+		return $this->get('DTT_parent');
502
+	}
503
+
504
+
505
+	/**
506
+	 * show date and/or time
507
+	 *
508
+	 * @param string $date_or_time    whether to display a date or time or both
509
+	 * @param string $start_or_end    whether to display start or end datetimes
510
+	 * @param string $dt_frmt
511
+	 * @param string $tm_frmt
512
+	 * @param bool   $echo            whether we echo or return (note echoing uses "pretty" formats,
513
+	 *                                otherwise we use the standard formats)
514
+	 * @return string|bool  string on success, FALSE on fail
515
+	 * @throws ReflectionException
516
+	 * @throws InvalidArgumentException
517
+	 * @throws InvalidInterfaceException
518
+	 * @throws InvalidDataTypeException
519
+	 * @throws EE_Error
520
+	 */
521
+	private function _show_datetime(
522
+		$date_or_time = null,
523
+		$start_or_end = 'start',
524
+		$dt_frmt = '',
525
+		$tm_frmt = '',
526
+		$echo = false
527
+	) {
528
+		$field_name = "DTT_EVT_{$start_or_end}";
529
+		$dtt = $this->_get_datetime(
530
+			$field_name,
531
+			$dt_frmt,
532
+			$tm_frmt,
533
+			$date_or_time,
534
+			$echo
535
+		);
536
+		if (! $echo) {
537
+			return $dtt;
538
+		}
539
+		return '';
540
+	}
541
+
542
+
543
+	/**
544
+	 * get event start date.  Provide either the date format, or NULL to re-use the
545
+	 * last-used format, or '' to use the default date format
546
+	 *
547
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
548
+	 * @return mixed            string on success, FALSE on fail
549
+	 * @throws ReflectionException
550
+	 * @throws InvalidArgumentException
551
+	 * @throws InvalidInterfaceException
552
+	 * @throws InvalidDataTypeException
553
+	 * @throws EE_Error
554
+	 */
555
+	public function start_date($dt_frmt = '')
556
+	{
557
+		return $this->_show_datetime('D', 'start', $dt_frmt);
558
+	}
559
+
560
+
561
+	/**
562
+	 * Echoes start_date()
563
+	 *
564
+	 * @param string $dt_frmt
565
+	 * @throws ReflectionException
566
+	 * @throws InvalidArgumentException
567
+	 * @throws InvalidInterfaceException
568
+	 * @throws InvalidDataTypeException
569
+	 * @throws EE_Error
570
+	 */
571
+	public function e_start_date($dt_frmt = '')
572
+	{
573
+		$this->_show_datetime('D', 'start', $dt_frmt, null, true);
574
+	}
575
+
576
+
577
+	/**
578
+	 * get end date. Provide either the date format, or NULL to re-use the
579
+	 * last-used format, or '' to use the default date format
580
+	 *
581
+	 * @param string $dt_frmt string representation of date format defaults to 'F j, Y'
582
+	 * @return mixed            string on success, FALSE on fail
583
+	 * @throws ReflectionException
584
+	 * @throws InvalidArgumentException
585
+	 * @throws InvalidInterfaceException
586
+	 * @throws InvalidDataTypeException
587
+	 * @throws EE_Error
588
+	 */
589
+	public function end_date($dt_frmt = '')
590
+	{
591
+		return $this->_show_datetime('D', 'end', $dt_frmt);
592
+	}
593
+
594
+
595
+	/**
596
+	 * Echoes the end date. See end_date()
597
+	 *
598
+	 * @param string $dt_frmt
599
+	 * @throws ReflectionException
600
+	 * @throws InvalidArgumentException
601
+	 * @throws InvalidInterfaceException
602
+	 * @throws InvalidDataTypeException
603
+	 * @throws EE_Error
604
+	 */
605
+	public function e_end_date($dt_frmt = '')
606
+	{
607
+		$this->_show_datetime('D', 'end', $dt_frmt, null, true);
608
+	}
609
+
610
+
611
+	/**
612
+	 * get date_range - meaning the start AND end date
613
+	 *
614
+	 * @access public
615
+	 * @param string $dt_frmt     string representation of date format defaults to WP settings
616
+	 * @param string $conjunction conjunction junction what's your function ?
617
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
618
+	 * @return mixed              string on success, FALSE on fail
619
+	 * @throws ReflectionException
620
+	 * @throws InvalidArgumentException
621
+	 * @throws InvalidInterfaceException
622
+	 * @throws InvalidDataTypeException
623
+	 * @throws EE_Error
624
+	 */
625
+	public function date_range($dt_frmt = '', $conjunction = ' - ')
626
+	{
627
+		$dt_frmt = ! empty($dt_frmt) ? $dt_frmt : $this->_dt_frmt;
628
+		$start = str_replace(
629
+			' ',
630
+			'&nbsp;',
631
+			$this->get_i18n_datetime('DTT_EVT_start', $dt_frmt)
632
+		);
633
+		$end = str_replace(
634
+			' ',
635
+			'&nbsp;',
636
+			$this->get_i18n_datetime('DTT_EVT_end', $dt_frmt)
637
+		);
638
+		return $start !== $end ? $start . $conjunction . $end : $start;
639
+	}
640
+
641
+
642
+	/**
643
+	 * @param string $dt_frmt
644
+	 * @param string $conjunction
645
+	 * @throws ReflectionException
646
+	 * @throws InvalidArgumentException
647
+	 * @throws InvalidInterfaceException
648
+	 * @throws InvalidDataTypeException
649
+	 * @throws EE_Error
650
+	 */
651
+	public function e_date_range($dt_frmt = '', $conjunction = ' - ')
652
+	{
653
+		echo esc_html($this->date_range($dt_frmt, $conjunction));
654
+	}
655
+
656
+
657
+	/**
658
+	 * get start time
659
+	 *
660
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
661
+	 * @return mixed        string on success, FALSE on fail
662
+	 * @throws ReflectionException
663
+	 * @throws InvalidArgumentException
664
+	 * @throws InvalidInterfaceException
665
+	 * @throws InvalidDataTypeException
666
+	 * @throws EE_Error
667
+	 */
668
+	public function start_time($tm_format = '')
669
+	{
670
+		return $this->_show_datetime('T', 'start', null, $tm_format);
671
+	}
672
+
673
+
674
+	/**
675
+	 * @param string $tm_format
676
+	 * @throws ReflectionException
677
+	 * @throws InvalidArgumentException
678
+	 * @throws InvalidInterfaceException
679
+	 * @throws InvalidDataTypeException
680
+	 * @throws EE_Error
681
+	 */
682
+	public function e_start_time($tm_format = '')
683
+	{
684
+		$this->_show_datetime('T', 'start', null, $tm_format, true);
685
+	}
686
+
687
+
688
+	/**
689
+	 * get end time
690
+	 *
691
+	 * @param string $tm_format string representation of time format defaults to 'g:i a'
692
+	 * @return mixed                string on success, FALSE on fail
693
+	 * @throws ReflectionException
694
+	 * @throws InvalidArgumentException
695
+	 * @throws InvalidInterfaceException
696
+	 * @throws InvalidDataTypeException
697
+	 * @throws EE_Error
698
+	 */
699
+	public function end_time($tm_format = '')
700
+	{
701
+		return $this->_show_datetime('T', 'end', null, $tm_format);
702
+	}
703
+
704
+
705
+	/**
706
+	 * @param string $tm_format
707
+	 * @throws ReflectionException
708
+	 * @throws InvalidArgumentException
709
+	 * @throws InvalidInterfaceException
710
+	 * @throws InvalidDataTypeException
711
+	 * @throws EE_Error
712
+	 */
713
+	public function e_end_time($tm_format = '')
714
+	{
715
+		$this->_show_datetime('T', 'end', null, $tm_format, true);
716
+	}
717
+
718
+
719
+	/**
720
+	 * get time_range
721
+	 *
722
+	 * @access public
723
+	 * @param string $tm_format   string representation of time format defaults to 'g:i a'
724
+	 * @param string $conjunction conjunction junction what's your function ?
725
+	 *                            this string joins the start date with the end date ie: Jan 01 "to" Dec 31
726
+	 * @return mixed              string on success, FALSE on fail
727
+	 * @throws ReflectionException
728
+	 * @throws InvalidArgumentException
729
+	 * @throws InvalidInterfaceException
730
+	 * @throws InvalidDataTypeException
731
+	 * @throws EE_Error
732
+	 */
733
+	public function time_range($tm_format = '', $conjunction = ' - ')
734
+	{
735
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
736
+		$start = str_replace(
737
+			' ',
738
+			'&nbsp;',
739
+			$this->get_i18n_datetime('DTT_EVT_start', $tm_format)
740
+		);
741
+		$end = str_replace(
742
+			' ',
743
+			'&nbsp;',
744
+			$this->get_i18n_datetime('DTT_EVT_end', $tm_format)
745
+		);
746
+		return $start !== $end ? $start . $conjunction . $end : $start;
747
+	}
748
+
749
+
750
+	/**
751
+	 * @param string $tm_format
752
+	 * @param string $conjunction
753
+	 * @throws ReflectionException
754
+	 * @throws InvalidArgumentException
755
+	 * @throws InvalidInterfaceException
756
+	 * @throws InvalidDataTypeException
757
+	 * @throws EE_Error
758
+	 */
759
+	public function e_time_range($tm_format = '', $conjunction = ' - ')
760
+	{
761
+		echo esc_html($this->time_range($tm_format, $conjunction));
762
+	}
763
+
764
+
765
+	/**
766
+	 * This returns a range representation of the date and times.
767
+	 * Output is dependent on the difference (or similarity) between DTT_EVT_start and DTT_EVT_end.
768
+	 * Also, the return value is localized.
769
+	 *
770
+	 * @param string $dt_format
771
+	 * @param string $tm_format
772
+	 * @param string $conjunction used between two different dates or times.
773
+	 *                            ex: Dec 1{$conjunction}}Dec 6, or 2pm{$conjunction}3pm
774
+	 * @param string $separator   used between the date and time formats.
775
+	 *                            ex: Dec 1, 2016{$separator}2pm
776
+	 * @return string
777
+	 * @throws ReflectionException
778
+	 * @throws InvalidArgumentException
779
+	 * @throws InvalidInterfaceException
780
+	 * @throws InvalidDataTypeException
781
+	 * @throws EE_Error
782
+	 */
783
+	public function date_and_time_range(
784
+		$dt_format = '',
785
+		$tm_format = '',
786
+		$conjunction = ' - ',
787
+		$separator = ' '
788
+	) {
789
+		$dt_format = ! empty($dt_format) ? $dt_format : $this->_dt_frmt;
790
+		$tm_format = ! empty($tm_format) ? $tm_format : $this->_tm_frmt;
791
+		$full_format = $dt_format . $separator . $tm_format;
792
+		// the range output depends on various conditions
793
+		switch (true) {
794
+			// start date timestamp and end date timestamp are the same.
795
+			case ($this->get_raw('DTT_EVT_start') === $this->get_raw('DTT_EVT_end')):
796
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format);
797
+				break;
798
+			// start and end date are the same but times are different
799
+			case ($this->start_date() === $this->end_date()):
800
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
801
+						  . $conjunction
802
+						  . $this->get_i18n_datetime('DTT_EVT_end', $tm_format);
803
+				break;
804
+			// all other conditions
805
+			default:
806
+				$output = $this->get_i18n_datetime('DTT_EVT_start', $full_format)
807
+						  . $conjunction
808
+						  . $this->get_i18n_datetime('DTT_EVT_end', $full_format);
809
+				break;
810
+		}
811
+		return $output;
812
+	}
813
+
814
+
815
+	/**
816
+	 * This echos the results of date and time range.
817
+	 *
818
+	 * @see date_and_time_range() for more details on purpose.
819
+	 * @param string $dt_format
820
+	 * @param string $tm_format
821
+	 * @param string $conjunction
822
+	 * @return void
823
+	 * @throws ReflectionException
824
+	 * @throws InvalidArgumentException
825
+	 * @throws InvalidInterfaceException
826
+	 * @throws InvalidDataTypeException
827
+	 * @throws EE_Error
828
+	 */
829
+	public function e_date_and_time_range($dt_format = '', $tm_format = '', $conjunction = ' - ')
830
+	{
831
+		echo esc_html($this->date_and_time_range($dt_format, $tm_format, $conjunction));
832
+	}
833
+
834
+
835
+	/**
836
+	 * get start date and start time
837
+	 *
838
+	 * @param    string $dt_format - string representation of date format defaults to 'F j, Y'
839
+	 * @param    string $tm_format - string representation of time format defaults to 'g:i a'
840
+	 * @return    mixed    string on success, FALSE on fail
841
+	 * @throws ReflectionException
842
+	 * @throws InvalidArgumentException
843
+	 * @throws InvalidInterfaceException
844
+	 * @throws InvalidDataTypeException
845
+	 * @throws EE_Error
846
+	 */
847
+	public function start_date_and_time($dt_format = '', $tm_format = '')
848
+	{
849
+		return $this->_show_datetime('', 'start', $dt_format, $tm_format);
850
+	}
851
+
852
+
853
+	/**
854
+	 * @param string $dt_frmt
855
+	 * @param string $tm_format
856
+	 * @throws ReflectionException
857
+	 * @throws InvalidArgumentException
858
+	 * @throws InvalidInterfaceException
859
+	 * @throws InvalidDataTypeException
860
+	 * @throws EE_Error
861
+	 */
862
+	public function e_start_date_and_time($dt_frmt = '', $tm_format = '')
863
+	{
864
+		$this->_show_datetime('', 'start', $dt_frmt, $tm_format, true);
865
+	}
866
+
867
+
868
+	/**
869
+	 * Shows the length of the event (start to end time).
870
+	 * Can be shown in 'seconds','minutes','hours', or 'days'.
871
+	 * By default, rounds up. (So if you use 'days', and then event
872
+	 * only occurs for 1 hour, it will return 1 day).
873
+	 *
874
+	 * @param string $units 'seconds','minutes','hours','days'
875
+	 * @param bool   $round_up
876
+	 * @return float|int|mixed
877
+	 * @throws ReflectionException
878
+	 * @throws InvalidArgumentException
879
+	 * @throws InvalidInterfaceException
880
+	 * @throws InvalidDataTypeException
881
+	 * @throws EE_Error
882
+	 */
883
+	public function length($units = 'seconds', $round_up = false)
884
+	{
885
+		$start = $this->get_raw('DTT_EVT_start');
886
+		$end = $this->get_raw('DTT_EVT_end');
887
+		$length_in_units = $end - $start;
888
+		switch ($units) {
889
+			// NOTE: We purposefully don't use "break;" in order to chain the divisions
890
+			/** @noinspection PhpMissingBreakStatementInspection */
891
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
892
+			case 'days':
893
+				$length_in_units /= 24;
894
+			/** @noinspection PhpMissingBreakStatementInspection */
895
+			case 'hours':
896
+				// fall through is intentional
897
+				$length_in_units /= 60;
898
+			/** @noinspection PhpMissingBreakStatementInspection */
899
+			case 'minutes':
900
+				// fall through is intentional
901
+				$length_in_units /= 60;
902
+			case 'seconds':
903
+			default:
904
+				$length_in_units = ceil($length_in_units);
905
+		}
906
+		// phpcs:enable
907
+		if ($round_up) {
908
+			$length_in_units = max($length_in_units, 1);
909
+		}
910
+		return $length_in_units;
911
+	}
912
+
913
+
914
+	/**
915
+	 *        get end date and time
916
+	 *
917
+	 * @param string $dt_frmt   - string representation of date format defaults to 'F j, Y'
918
+	 * @param string $tm_format - string representation of time format defaults to 'g:i a'
919
+	 * @return    mixed                string on success, FALSE on fail
920
+	 * @throws ReflectionException
921
+	 * @throws InvalidArgumentException
922
+	 * @throws InvalidInterfaceException
923
+	 * @throws InvalidDataTypeException
924
+	 * @throws EE_Error
925
+	 */
926
+	public function end_date_and_time($dt_frmt = '', $tm_format = '')
927
+	{
928
+		return $this->_show_datetime('', 'end', $dt_frmt, $tm_format);
929
+	}
930
+
931
+
932
+	/**
933
+	 * @param string $dt_frmt
934
+	 * @param string $tm_format
935
+	 * @throws ReflectionException
936
+	 * @throws InvalidArgumentException
937
+	 * @throws InvalidInterfaceException
938
+	 * @throws InvalidDataTypeException
939
+	 * @throws EE_Error
940
+	 */
941
+	public function e_end_date_and_time($dt_frmt = '', $tm_format = '')
942
+	{
943
+		$this->_show_datetime('', 'end', $dt_frmt, $tm_format, true);
944
+	}
945
+
946
+
947
+	/**
948
+	 *        get start timestamp
949
+	 *
950
+	 * @return        int
951
+	 * @throws ReflectionException
952
+	 * @throws InvalidArgumentException
953
+	 * @throws InvalidInterfaceException
954
+	 * @throws InvalidDataTypeException
955
+	 * @throws EE_Error
956
+	 */
957
+	public function start()
958
+	{
959
+		return $this->get_raw('DTT_EVT_start');
960
+	}
961
+
962
+
963
+	/**
964
+	 *        get end timestamp
965
+	 *
966
+	 * @return        int
967
+	 * @throws ReflectionException
968
+	 * @throws InvalidArgumentException
969
+	 * @throws InvalidInterfaceException
970
+	 * @throws InvalidDataTypeException
971
+	 * @throws EE_Error
972
+	 */
973
+	public function end()
974
+	{
975
+		return $this->get_raw('DTT_EVT_end');
976
+	}
977
+
978
+
979
+	/**
980
+	 *    get the registration limit for this datetime slot
981
+	 *
982
+	 * @return        mixed        int on success, FALSE on fail
983
+	 * @throws ReflectionException
984
+	 * @throws InvalidArgumentException
985
+	 * @throws InvalidInterfaceException
986
+	 * @throws InvalidDataTypeException
987
+	 * @throws EE_Error
988
+	 */
989
+	public function reg_limit()
990
+	{
991
+		return $this->get_raw('DTT_reg_limit');
992
+	}
993
+
994
+
995
+	/**
996
+	 *    have the tickets sold for this datetime, met or exceed the registration limit ?
997
+	 *
998
+	 * @return        boolean
999
+	 * @throws ReflectionException
1000
+	 * @throws InvalidArgumentException
1001
+	 * @throws InvalidInterfaceException
1002
+	 * @throws InvalidDataTypeException
1003
+	 * @throws EE_Error
1004
+	 */
1005
+	public function sold_out()
1006
+	{
1007
+		return $this->reg_limit() > 0 && $this->sold() >= $this->reg_limit();
1008
+	}
1009
+
1010
+
1011
+	/**
1012
+	 * return the total number of spaces remaining at this venue.
1013
+	 * This only takes the venue's capacity into account, NOT the tickets available for sale
1014
+	 *
1015
+	 * @param bool $consider_tickets Whether to consider tickets remaining when determining if there are any spaces left
1016
+	 *                               Because if all tickets attached to this datetime have no spaces left,
1017
+	 *                               then this datetime IS effectively sold out.
1018
+	 *                               However, there are cases where we just want to know the spaces
1019
+	 *                               remaining for this particular datetime, hence the flag.
1020
+	 * @return int
1021
+	 * @throws ReflectionException
1022
+	 * @throws InvalidArgumentException
1023
+	 * @throws InvalidInterfaceException
1024
+	 * @throws InvalidDataTypeException
1025
+	 * @throws EE_Error
1026
+	 */
1027
+	public function spaces_remaining($consider_tickets = false)
1028
+	{
1029
+		// tickets remaining available for purchase
1030
+		// no need for special checks for infinite, because if DTT_reg_limit == EE_INF, then EE_INF - x = EE_INF
1031
+		$dtt_remaining = $this->reg_limit() - $this->sold_and_reserved();
1032
+		if (! $consider_tickets) {
1033
+			return $dtt_remaining;
1034
+		}
1035
+		$tickets_remaining = $this->tickets_remaining();
1036
+		return min($dtt_remaining, $tickets_remaining);
1037
+	}
1038
+
1039
+
1040
+	/**
1041
+	 * Counts the total tickets available
1042
+	 * (from all the different types of tickets which are available for this datetime).
1043
+	 *
1044
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1045
+	 * @return int
1046
+	 * @throws ReflectionException
1047
+	 * @throws InvalidArgumentException
1048
+	 * @throws InvalidInterfaceException
1049
+	 * @throws InvalidDataTypeException
1050
+	 * @throws EE_Error
1051
+	 */
1052
+	public function tickets_remaining($query_params = array())
1053
+	{
1054
+		$sum = 0;
1055
+		$tickets = $this->tickets($query_params);
1056
+		if (! empty($tickets)) {
1057
+			foreach ($tickets as $ticket) {
1058
+				if ($ticket instanceof EE_Ticket) {
1059
+					// get the actual amount of tickets that can be sold
1060
+					$qty = $ticket->qty('saleable');
1061
+					if ($qty === EE_INF) {
1062
+						return EE_INF;
1063
+					}
1064
+					// no negative ticket quantities plz
1065
+					if ($qty > 0) {
1066
+						$sum += $qty;
1067
+					}
1068
+				}
1069
+			}
1070
+		}
1071
+		return $sum;
1072
+	}
1073
+
1074
+
1075
+	/**
1076
+	 * Gets the count of all the tickets available at this datetime (not ticket types)
1077
+	 * before any were sold
1078
+	 *
1079
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1080
+	 * @return int
1081
+	 * @throws ReflectionException
1082
+	 * @throws InvalidArgumentException
1083
+	 * @throws InvalidInterfaceException
1084
+	 * @throws InvalidDataTypeException
1085
+	 * @throws EE_Error
1086
+	 */
1087
+	public function sum_tickets_initially_available($query_params = array())
1088
+	{
1089
+		return $this->sum_related('Ticket', $query_params, 'TKT_qty');
1090
+	}
1091
+
1092
+
1093
+	/**
1094
+	 * Returns the lesser-of-the two: spaces remaining at this datetime, or
1095
+	 * the total tickets remaining (a sum of the tickets remaining for each ticket type
1096
+	 * that is available for this datetime).
1097
+	 *
1098
+	 * @return int
1099
+	 * @throws ReflectionException
1100
+	 * @throws InvalidArgumentException
1101
+	 * @throws InvalidInterfaceException
1102
+	 * @throws InvalidDataTypeException
1103
+	 * @throws EE_Error
1104
+	 */
1105
+	public function total_tickets_available_at_this_datetime()
1106
+	{
1107
+		return $this->spaces_remaining(true);
1108
+	}
1109
+
1110
+
1111
+	/**
1112
+	 * This simply compares the internal dtt for the given string with NOW
1113
+	 * and determines if the date is upcoming or not.
1114
+	 *
1115
+	 * @access public
1116
+	 * @return boolean
1117
+	 * @throws ReflectionException
1118
+	 * @throws InvalidArgumentException
1119
+	 * @throws InvalidInterfaceException
1120
+	 * @throws InvalidDataTypeException
1121
+	 * @throws EE_Error
1122
+	 */
1123
+	public function is_upcoming()
1124
+	{
1125
+		return ($this->get_raw('DTT_EVT_start') > time());
1126
+	}
1127
+
1128
+
1129
+	/**
1130
+	 * This simply compares the internal datetime for the given string with NOW
1131
+	 * and returns if the date is active (i.e. start and end time)
1132
+	 *
1133
+	 * @return boolean
1134
+	 * @throws ReflectionException
1135
+	 * @throws InvalidArgumentException
1136
+	 * @throws InvalidInterfaceException
1137
+	 * @throws InvalidDataTypeException
1138
+	 * @throws EE_Error
1139
+	 */
1140
+	public function is_active()
1141
+	{
1142
+		return ($this->get_raw('DTT_EVT_start') < time() && $this->get_raw('DTT_EVT_end') > time());
1143
+	}
1144
+
1145
+
1146
+	/**
1147
+	 * This simply compares the internal dtt for the given string with NOW
1148
+	 * and determines if the date is expired or not.
1149
+	 *
1150
+	 * @return boolean
1151
+	 * @throws ReflectionException
1152
+	 * @throws InvalidArgumentException
1153
+	 * @throws InvalidInterfaceException
1154
+	 * @throws InvalidDataTypeException
1155
+	 * @throws EE_Error
1156
+	 */
1157
+	public function is_expired()
1158
+	{
1159
+		return ($this->get_raw('DTT_EVT_end') < time());
1160
+	}
1161
+
1162
+
1163
+	/**
1164
+	 * This returns the active status for whether an event is active, upcoming, or expired
1165
+	 *
1166
+	 * @return int return value will be one of the EE_Datetime status constants.
1167
+	 * @throws ReflectionException
1168
+	 * @throws InvalidArgumentException
1169
+	 * @throws InvalidInterfaceException
1170
+	 * @throws InvalidDataTypeException
1171
+	 * @throws EE_Error
1172
+	 */
1173
+	public function get_active_status()
1174
+	{
1175
+		$total_tickets_for_this_dtt = $this->total_tickets_available_at_this_datetime();
1176
+		if ($total_tickets_for_this_dtt !== false && $total_tickets_for_this_dtt < 1) {
1177
+			return EE_Datetime::sold_out;
1178
+		}
1179
+		if ($this->is_expired()) {
1180
+			return EE_Datetime::expired;
1181
+		}
1182
+		if ($this->is_upcoming()) {
1183
+			return EE_Datetime::upcoming;
1184
+		}
1185
+		if ($this->is_active()) {
1186
+			return EE_Datetime::active;
1187
+		}
1188
+		return null;
1189
+	}
1190
+
1191
+
1192
+	/**
1193
+	 * This returns a nice display name for the datetime that is contingent on the span between the dates and times.
1194
+	 *
1195
+	 * @param  boolean $use_dtt_name if TRUE then we'll use DTT->name() if its not empty.
1196
+	 * @return string
1197
+	 * @throws ReflectionException
1198
+	 * @throws InvalidArgumentException
1199
+	 * @throws InvalidInterfaceException
1200
+	 * @throws InvalidDataTypeException
1201
+	 * @throws EE_Error
1202
+	 */
1203
+	public function get_dtt_display_name($use_dtt_name = false)
1204
+	{
1205
+		if ($use_dtt_name) {
1206
+			$dtt_name = $this->name();
1207
+			if (! empty($dtt_name)) {
1208
+				return $dtt_name;
1209
+			}
1210
+		}
1211
+		// first condition is to see if the months are different
1212
+		if (
1213
+			date('m', $this->get_raw('DTT_EVT_start')) !== date('m', $this->get_raw('DTT_EVT_end'))
1214
+		) {
1215
+			$display_date = $this->start_date('M j\, Y g:i a') . ' - ' . $this->end_date('M j\, Y g:i a');
1216
+			// next condition is if its the same month but different day
1217
+		} else {
1218
+			if (
1219
+				date('m', $this->get_raw('DTT_EVT_start')) === date('m', $this->get_raw('DTT_EVT_end'))
1220
+				&& date('d', $this->get_raw('DTT_EVT_start')) !== date('d', $this->get_raw('DTT_EVT_end'))
1221
+			) {
1222
+				$display_date = $this->start_date('M j\, g:i a') . ' - ' . $this->end_date('M j\, g:i a Y');
1223
+			} else {
1224
+				$display_date = $this->start_date('F j\, Y')
1225
+								. ' @ '
1226
+								. $this->start_date('g:i a')
1227
+								. ' - '
1228
+								. $this->end_date('g:i a');
1229
+			}
1230
+		}
1231
+		return $display_date;
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 * Gets all the tickets for this datetime
1237
+	 *
1238
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1239
+	 * @return EE_Base_Class[]|EE_Ticket[]
1240
+	 * @throws ReflectionException
1241
+	 * @throws InvalidArgumentException
1242
+	 * @throws InvalidInterfaceException
1243
+	 * @throws InvalidDataTypeException
1244
+	 * @throws EE_Error
1245
+	 */
1246
+	public function tickets($query_params = array())
1247
+	{
1248
+		return $this->get_many_related('Ticket', $query_params);
1249
+	}
1250
+
1251
+
1252
+	/**
1253
+	 * Gets all the ticket types currently available for purchase
1254
+	 *
1255
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1256
+	 * @return EE_Ticket[]
1257
+	 * @throws ReflectionException
1258
+	 * @throws InvalidArgumentException
1259
+	 * @throws InvalidInterfaceException
1260
+	 * @throws InvalidDataTypeException
1261
+	 * @throws EE_Error
1262
+	 */
1263
+	public function ticket_types_available_for_purchase($query_params = array())
1264
+	{
1265
+		// first check if datetime is valid
1266
+		if ($this->sold_out() || ! ($this->is_upcoming() || $this->is_active())) {
1267
+			return array();
1268
+		}
1269
+		if (empty($query_params)) {
1270
+			$query_params = array(
1271
+				array(
1272
+					'TKT_start_date' => array('<=', EEM_Ticket::instance()->current_time_for_query('TKT_start_date')),
1273
+					'TKT_end_date'   => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
1274
+					'TKT_deleted'    => false,
1275
+				),
1276
+			);
1277
+		}
1278
+		return $this->tickets($query_params);
1279
+	}
1280
+
1281
+
1282
+	/**
1283
+	 * @return EE_Base_Class|EE_Event
1284
+	 * @throws ReflectionException
1285
+	 * @throws InvalidArgumentException
1286
+	 * @throws InvalidInterfaceException
1287
+	 * @throws InvalidDataTypeException
1288
+	 * @throws EE_Error
1289
+	 */
1290
+	public function event()
1291
+	{
1292
+		return $this->get_first_related('Event');
1293
+	}
1294
+
1295
+
1296
+	/**
1297
+	 * Updates the DTT_sold attribute (and saves) based on the number of registrations for this datetime
1298
+	 * (via the tickets).
1299
+	 *
1300
+	 * @return int
1301
+	 * @throws ReflectionException
1302
+	 * @throws InvalidArgumentException
1303
+	 * @throws InvalidInterfaceException
1304
+	 * @throws InvalidDataTypeException
1305
+	 * @throws EE_Error
1306
+	 */
1307
+	public function update_sold()
1308
+	{
1309
+		$count_regs_for_this_datetime = EEM_Registration::instance()->count(
1310
+			array(
1311
+				array(
1312
+					'STS_ID'                 => EEM_Registration::status_id_approved,
1313
+					'REG_deleted'            => 0,
1314
+					'Ticket.Datetime.DTT_ID' => $this->ID(),
1315
+				),
1316
+			)
1317
+		);
1318
+		$this->set_sold($count_regs_for_this_datetime);
1319
+		$this->save();
1320
+		return $count_regs_for_this_datetime;
1321
+	}
1322
+
1323
+
1324
+	/*******************************************************************
1325 1325
      ***********************  DEPRECATED METHODS  **********************
1326 1326
      *******************************************************************/
1327 1327
 
1328 1328
 
1329
-    /**
1330
-     * Increments sold by amount passed by $qty, and persists it immediately to the database.
1331
-     *
1332
-     * @deprecated 4.9.80.p
1333
-     * @param int $qty
1334
-     * @return boolean
1335
-     * @throws ReflectionException
1336
-     * @throws InvalidArgumentException
1337
-     * @throws InvalidInterfaceException
1338
-     * @throws InvalidDataTypeException
1339
-     * @throws EE_Error
1340
-     */
1341
-    public function increase_sold($qty = 1)
1342
-    {
1343
-        EE_Error::doing_it_wrong(
1344
-            __FUNCTION__,
1345
-            esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1346
-            '4.9.80.p',
1347
-            '5.0.0.p'
1348
-        );
1349
-        return $this->increaseSold($qty);
1350
-    }
1351
-
1352
-
1353
-    /**
1354
-     * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1355
-     * to save afterwards.)
1356
-     *
1357
-     * @deprecated 4.9.80.p
1358
-     * @param int $qty
1359
-     * @return boolean
1360
-     * @throws ReflectionException
1361
-     * @throws InvalidArgumentException
1362
-     * @throws InvalidInterfaceException
1363
-     * @throws InvalidDataTypeException
1364
-     * @throws EE_Error
1365
-     */
1366
-    public function decrease_sold($qty = 1)
1367
-    {
1368
-        EE_Error::doing_it_wrong(
1369
-            __FUNCTION__,
1370
-            esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1371
-            '4.9.80.p',
1372
-            '5.0.0.p'
1373
-        );
1374
-        return $this->decreaseSold($qty);
1375
-    }
1376
-
1377
-
1378
-    /**
1379
-     * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1380
-     *
1381
-     * @deprecated 4.9.80.p
1382
-     * @param int $qty
1383
-     * @return boolean indicating success
1384
-     * @throws ReflectionException
1385
-     * @throws InvalidArgumentException
1386
-     * @throws InvalidInterfaceException
1387
-     * @throws InvalidDataTypeException
1388
-     * @throws EE_Error
1389
-     */
1390
-    public function increase_reserved($qty = 1)
1391
-    {
1392
-        EE_Error::doing_it_wrong(
1393
-            __FUNCTION__,
1394
-            esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1395
-            '4.9.80.p',
1396
-            '5.0.0.p'
1397
-        );
1398
-        return $this->increaseReserved($qty);
1399
-    }
1400
-
1401
-
1402
-    /**
1403
-     * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1404
-     *
1405
-     * @deprecated 4.9.80.p
1406
-     * @param int $qty
1407
-     * @return boolean
1408
-     * @throws ReflectionException
1409
-     * @throws InvalidArgumentException
1410
-     * @throws InvalidInterfaceException
1411
-     * @throws InvalidDataTypeException
1412
-     * @throws EE_Error
1413
-     */
1414
-    public function decrease_reserved($qty = 1)
1415
-    {
1416
-        EE_Error::doing_it_wrong(
1417
-            __FUNCTION__,
1418
-            esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1419
-            '4.9.80.p',
1420
-            '5.0.0.p'
1421
-        );
1422
-        return $this->decreaseReserved($qty);
1423
-    }
1329
+	/**
1330
+	 * Increments sold by amount passed by $qty, and persists it immediately to the database.
1331
+	 *
1332
+	 * @deprecated 4.9.80.p
1333
+	 * @param int $qty
1334
+	 * @return boolean
1335
+	 * @throws ReflectionException
1336
+	 * @throws InvalidArgumentException
1337
+	 * @throws InvalidInterfaceException
1338
+	 * @throws InvalidDataTypeException
1339
+	 * @throws EE_Error
1340
+	 */
1341
+	public function increase_sold($qty = 1)
1342
+	{
1343
+		EE_Error::doing_it_wrong(
1344
+			__FUNCTION__,
1345
+			esc_html__('Please use EE_Datetime::increaseSold() instead', 'event_espresso'),
1346
+			'4.9.80.p',
1347
+			'5.0.0.p'
1348
+		);
1349
+		return $this->increaseSold($qty);
1350
+	}
1351
+
1352
+
1353
+	/**
1354
+	 * Decrements (subtracts) sold amount passed by $qty directly in the DB and on the model object. (Ie, no need
1355
+	 * to save afterwards.)
1356
+	 *
1357
+	 * @deprecated 4.9.80.p
1358
+	 * @param int $qty
1359
+	 * @return boolean
1360
+	 * @throws ReflectionException
1361
+	 * @throws InvalidArgumentException
1362
+	 * @throws InvalidInterfaceException
1363
+	 * @throws InvalidDataTypeException
1364
+	 * @throws EE_Error
1365
+	 */
1366
+	public function decrease_sold($qty = 1)
1367
+	{
1368
+		EE_Error::doing_it_wrong(
1369
+			__FUNCTION__,
1370
+			esc_html__('Please use EE_Datetime::decreaseSold() instead', 'event_espresso'),
1371
+			'4.9.80.p',
1372
+			'5.0.0.p'
1373
+		);
1374
+		return $this->decreaseSold($qty);
1375
+	}
1376
+
1377
+
1378
+	/**
1379
+	 * Increments reserved by amount passed by $qty, and persists it immediately to the database.
1380
+	 *
1381
+	 * @deprecated 4.9.80.p
1382
+	 * @param int $qty
1383
+	 * @return boolean indicating success
1384
+	 * @throws ReflectionException
1385
+	 * @throws InvalidArgumentException
1386
+	 * @throws InvalidInterfaceException
1387
+	 * @throws InvalidDataTypeException
1388
+	 * @throws EE_Error
1389
+	 */
1390
+	public function increase_reserved($qty = 1)
1391
+	{
1392
+		EE_Error::doing_it_wrong(
1393
+			__FUNCTION__,
1394
+			esc_html__('Please use EE_Datetime::increaseReserved() instead', 'event_espresso'),
1395
+			'4.9.80.p',
1396
+			'5.0.0.p'
1397
+		);
1398
+		return $this->increaseReserved($qty);
1399
+	}
1400
+
1401
+
1402
+	/**
1403
+	 * Decrements (subtracts) reserved by amount passed by $qty, and persists it immediately to the database.
1404
+	 *
1405
+	 * @deprecated 4.9.80.p
1406
+	 * @param int $qty
1407
+	 * @return boolean
1408
+	 * @throws ReflectionException
1409
+	 * @throws InvalidArgumentException
1410
+	 * @throws InvalidInterfaceException
1411
+	 * @throws InvalidDataTypeException
1412
+	 * @throws EE_Error
1413
+	 */
1414
+	public function decrease_reserved($qty = 1)
1415
+	{
1416
+		EE_Error::doing_it_wrong(
1417
+			__FUNCTION__,
1418
+			esc_html__('Please use EE_Datetime::decreaseReserved() instead', 'event_espresso'),
1419
+			'4.9.80.p',
1420
+			'5.0.0.p'
1421
+		);
1422
+		return $this->decreaseReserved($qty);
1423
+	}
1424 1424
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Registration.class.php 2 patches
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
     {
120 120
         switch ($field_name) {
121 121
             case 'REG_code':
122
-                if (! empty($field_value) && $this->reg_code() === null) {
122
+                if ( ! empty($field_value) && $this->reg_code() === null) {
123 123
                     $this->set_reg_code($field_value, $use_default);
124 124
                 }
125 125
                 break;
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
     public function event()
407 407
     {
408 408
         $event = $this->get_first_related('Event');
409
-        if (! $event instanceof \EE_Event) {
409
+        if ( ! $event instanceof \EE_Event) {
410 410
             throw new EntityNotFoundException('Event ID', $this->event_ID());
411 411
         }
412 412
         return $event;
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
     {
450 450
         // reserved ticket and datetime counts will be decremented as sold counts are incremented
451 451
         // so stop tracking that this reg has a ticket reserved
452
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
452
+        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:".__LINE__.')');
453 453
         $ticket = $this->ticket();
454 454
         $ticket->increaseSold();
455 455
         // possibly set event status to sold out
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
                 && $update_ticket
505 505
             ) {
506 506
                 $ticket = $this->ticket();
507
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
507
+                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:".__LINE__.')');
508 508
                 $ticket->save();
509 509
             }
510 510
         }
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
                 && $update_ticket
537 537
             ) {
538 538
                 $ticket = $this->ticket();
539
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
539
+                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:".__LINE__.')');
540 540
             }
541 541
         }
542 542
     }
@@ -1211,7 +1211,7 @@  discard block
 block discarded – undo
1211 1211
                     : '';
1212 1212
                 break;
1213 1213
         }
1214
-        return $icon . $status[ $this->status_ID() ];
1214
+        return $icon.$status[$this->status_ID()];
1215 1215
     }
1216 1216
 
1217 1217
 
@@ -1455,7 +1455,7 @@  discard block
 block discarded – undo
1455 1455
     {
1456 1456
         $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1457 1457
 
1458
-        if (! $DTT_ID) {
1458
+        if ( ! $DTT_ID) {
1459 1459
             return false;
1460 1460
         }
1461 1461
 
@@ -1463,7 +1463,7 @@  discard block
 block discarded – undo
1463 1463
 
1464 1464
         // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1465 1465
         // check-in or not.
1466
-        if (! $max_uses || $max_uses === EE_INF) {
1466
+        if ( ! $max_uses || $max_uses === EE_INF) {
1467 1467
             return true;
1468 1468
         }
1469 1469
 
@@ -1523,7 +1523,7 @@  discard block
 block discarded – undo
1523 1523
             $datetime = $this->get_latest_related_datetime();
1524 1524
             $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1525 1525
             // verify the registration can checkin for the given DTT_ID
1526
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1526
+        } elseif ( ! $this->can_checkin($DTT_ID, $verify)) {
1527 1527
             EE_Error::add_error(
1528 1528
                 sprintf(
1529 1529
                     esc_html__(
@@ -1546,7 +1546,7 @@  discard block
 block discarded – undo
1546 1546
         );
1547 1547
         // start by getting the current status so we know what status we'll be changing to.
1548 1548
         $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1549
-        $status_to = $status_paths[ $cur_status ];
1549
+        $status_to = $status_paths[$cur_status];
1550 1550
         // database only records true for checked IN or false for checked OUT
1551 1551
         // no record ( null ) means checked in NEVER, but we obviously don't save that
1552 1552
         $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
@@ -1714,7 +1714,7 @@  discard block
 block discarded – undo
1714 1714
     public function transaction()
1715 1715
     {
1716 1716
         $transaction = $this->get_first_related('Transaction');
1717
-        if (! $transaction instanceof \EE_Transaction) {
1717
+        if ( ! $transaction instanceof \EE_Transaction) {
1718 1718
             throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1719 1719
         }
1720 1720
         return $transaction;
@@ -1768,11 +1768,11 @@  discard block
 block discarded – undo
1768 1768
             );
1769 1769
             return;
1770 1770
         }
1771
-        if (! $this->reg_code()) {
1771
+        if ( ! $this->reg_code()) {
1772 1772
             parent::set('REG_code', $REG_code, $use_default);
1773 1773
         } else {
1774 1774
             EE_Error::doing_it_wrong(
1775
-                __CLASS__ . '::' . __FUNCTION__,
1775
+                __CLASS__.'::'.__FUNCTION__,
1776 1776
                 esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1777 1777
                 '4.6.0'
1778 1778
             );
@@ -1924,7 +1924,7 @@  discard block
 block discarded – undo
1924 1924
                 break;
1925 1925
             }
1926 1926
         }
1927
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1927
+        if ( ! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1928 1928
             throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1929 1929
         }
1930 1930
         return $line_item;
Please login to merge, or discard this patch.
Indentation   +2113 added lines, -2113 removed lines patch added patch discarded remove patch
@@ -18,2117 +18,2117 @@
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * Used to reference when a registration has never been checked in.
23
-     *
24
-     * @deprecated use \EE_Checkin::status_checked_never instead
25
-     * @type int
26
-     */
27
-    const checkin_status_never = 2;
28
-
29
-    /**
30
-     * Used to reference when a registration has been checked in.
31
-     *
32
-     * @deprecated use \EE_Checkin::status_checked_in instead
33
-     * @type int
34
-     */
35
-    const checkin_status_in = 1;
36
-
37
-
38
-    /**
39
-     * Used to reference when a registration has been checked out.
40
-     *
41
-     * @deprecated use \EE_Checkin::status_checked_out instead
42
-     * @type int
43
-     */
44
-    const checkin_status_out = 0;
45
-
46
-
47
-    /**
48
-     * extra meta key for tracking reg status os trashed registrations
49
-     *
50
-     * @type string
51
-     */
52
-    const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
53
-
54
-
55
-    /**
56
-     * extra meta key for tracking if registration has reserved ticket
57
-     *
58
-     * @type string
59
-     */
60
-    const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
61
-
62
-
63
-    /**
64
-     * @param array  $props_n_values          incoming values
65
-     * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
66
-     *                                        used.)
67
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
68
-     *                                        date_format and the second value is the time format
69
-     * @return EE_Registration
70
-     * @throws EE_Error
71
-     */
72
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
73
-    {
74
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
75
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
76
-    }
77
-
78
-
79
-    /**
80
-     * @param array  $props_n_values  incoming values from the database
81
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
-     *                                the website will be used.
83
-     * @return EE_Registration
84
-     */
85
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
86
-    {
87
-        return new self($props_n_values, true, $timezone);
88
-    }
89
-
90
-
91
-    /**
92
-     *        Set Event ID
93
-     *
94
-     * @param        int $EVT_ID Event ID
95
-     * @throws EE_Error
96
-     * @throws RuntimeException
97
-     */
98
-    public function set_event($EVT_ID = 0)
99
-    {
100
-        $this->set('EVT_ID', $EVT_ID);
101
-    }
102
-
103
-
104
-    /**
105
-     * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
106
-     * be routed to internal methods
107
-     *
108
-     * @param string $field_name
109
-     * @param mixed  $field_value
110
-     * @param bool   $use_default
111
-     * @throws EE_Error
112
-     * @throws EntityNotFoundException
113
-     * @throws InvalidArgumentException
114
-     * @throws InvalidDataTypeException
115
-     * @throws InvalidInterfaceException
116
-     * @throws ReflectionException
117
-     * @throws RuntimeException
118
-     */
119
-    public function set($field_name, $field_value, $use_default = false)
120
-    {
121
-        switch ($field_name) {
122
-            case 'REG_code':
123
-                if (! empty($field_value) && $this->reg_code() === null) {
124
-                    $this->set_reg_code($field_value, $use_default);
125
-                }
126
-                break;
127
-            case 'STS_ID':
128
-                $this->set_status($field_value, $use_default);
129
-                break;
130
-            default:
131
-                parent::set($field_name, $field_value, $use_default);
132
-        }
133
-    }
134
-
135
-
136
-    /**
137
-     * Set Status ID
138
-     * updates the registration status and ALSO...
139
-     * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
140
-     * calls release_registration_space() if the reg status changes FROM approved to any other reg status
141
-     *
142
-     * @param string                $new_STS_ID
143
-     * @param boolean               $use_default
144
-     * @param ContextInterface|null $context
145
-     * @return bool
146
-     * @throws DomainException
147
-     * @throws EE_Error
148
-     * @throws EntityNotFoundException
149
-     * @throws InvalidArgumentException
150
-     * @throws InvalidDataTypeException
151
-     * @throws InvalidInterfaceException
152
-     * @throws ReflectionException
153
-     * @throws RuntimeException
154
-     * @throws UnexpectedEntityException
155
-     */
156
-    public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
157
-    {
158
-        // get current REG_Status
159
-        $old_STS_ID = $this->status_ID();
160
-        // if status has changed
161
-        if (
162
-            $old_STS_ID !== $new_STS_ID // and that status has actually changed
163
-            && ! empty($old_STS_ID) // and that old status is actually set
164
-            && ! empty($new_STS_ID) // as well as the new status
165
-            && $this->ID() // ensure registration is in the db
166
-        ) {
167
-            // update internal status first
168
-            parent::set('STS_ID', $new_STS_ID, $use_default);
169
-            // THEN handle other changes that occur when reg status changes
170
-            // TO approved
171
-            if ($new_STS_ID === EEM_Registration::status_id_approved) {
172
-                // reserve a space by incrementing ticket and datetime sold values
173
-                $this->reserveRegistrationSpace();
174
-                do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
175
-                // OR FROM  approved
176
-            } elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
177
-                // release a space by decrementing ticket and datetime sold values
178
-                $this->releaseRegistrationSpace();
179
-                do_action(
180
-                    'AHEE__EE_Registration__set_status__from_approved',
181
-                    $this,
182
-                    $old_STS_ID,
183
-                    $new_STS_ID,
184
-                    $context
185
-                );
186
-            }
187
-            // update status
188
-            parent::set('STS_ID', $new_STS_ID, $use_default);
189
-            $this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
190
-            if ($this->statusChangeUpdatesTransaction($context)) {
191
-                $this->updateTransactionAfterStatusChange();
192
-            }
193
-            do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
194
-            return true;
195
-        }
196
-        // even though the old value matches the new value, it's still good to
197
-        // allow the parent set method to have a say
198
-        parent::set('STS_ID', $new_STS_ID, $use_default);
199
-        return true;
200
-    }
201
-
202
-
203
-    /**
204
-     * update REGs and TXN when cancelled or declined registrations involved
205
-     *
206
-     * @param string                $new_STS_ID
207
-     * @param string                $old_STS_ID
208
-     * @param ContextInterface|null $context
209
-     * @throws EE_Error
210
-     * @throws InvalidArgumentException
211
-     * @throws InvalidDataTypeException
212
-     * @throws InvalidInterfaceException
213
-     * @throws ReflectionException
214
-     * @throws RuntimeException
215
-     */
216
-    private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
217
-    {
218
-        // these reg statuses should not be considered in any calculations involving monies owing
219
-        $closed_reg_statuses = EEM_Registration::closed_reg_statuses();
220
-        // true if registration has been cancelled or declined
221
-        $this->updateIfCanceled(
222
-            $closed_reg_statuses,
223
-            $new_STS_ID,
224
-            $old_STS_ID,
225
-            $context
226
-        );
227
-        $this->updateIfReinstated(
228
-            $closed_reg_statuses,
229
-            $new_STS_ID,
230
-            $old_STS_ID,
231
-            $context
232
-        );
233
-    }
234
-
235
-
236
-    /**
237
-     * update REGs and TXN when cancelled or declined registrations involved
238
-     *
239
-     * @param array                 $closed_reg_statuses
240
-     * @param string                $new_STS_ID
241
-     * @param string                $old_STS_ID
242
-     * @param ContextInterface|null $context
243
-     * @throws EE_Error
244
-     * @throws InvalidArgumentException
245
-     * @throws InvalidDataTypeException
246
-     * @throws InvalidInterfaceException
247
-     * @throws ReflectionException
248
-     * @throws RuntimeException
249
-     */
250
-    private function updateIfCanceled(
251
-        array $closed_reg_statuses,
252
-        $new_STS_ID,
253
-        $old_STS_ID,
254
-        ContextInterface $context = null
255
-    ) {
256
-        // true if registration has been cancelled or declined
257
-        if (
258
-            in_array($new_STS_ID, $closed_reg_statuses, true)
259
-            && ! in_array($old_STS_ID, $closed_reg_statuses, true)
260
-        ) {
261
-            /** @type EE_Registration_Processor $registration_processor */
262
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
263
-            /** @type EE_Transaction_Processor $transaction_processor */
264
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
265
-            // cancelled or declined registration
266
-            $registration_processor->update_registration_after_being_canceled_or_declined(
267
-                $this,
268
-                $closed_reg_statuses
269
-            );
270
-            $transaction_processor->update_transaction_after_canceled_or_declined_registration(
271
-                $this,
272
-                $closed_reg_statuses,
273
-                false
274
-            );
275
-            do_action(
276
-                'AHEE__EE_Registration__set_status__canceled_or_declined',
277
-                $this,
278
-                $old_STS_ID,
279
-                $new_STS_ID,
280
-                $context
281
-            );
282
-            return;
283
-        }
284
-    }
285
-
286
-
287
-    /**
288
-     * update REGs and TXN when cancelled or declined registrations involved
289
-     *
290
-     * @param array                 $closed_reg_statuses
291
-     * @param string                $new_STS_ID
292
-     * @param string                $old_STS_ID
293
-     * @param ContextInterface|null $context
294
-     * @throws EE_Error
295
-     * @throws InvalidArgumentException
296
-     * @throws InvalidDataTypeException
297
-     * @throws InvalidInterfaceException
298
-     * @throws ReflectionException
299
-     */
300
-    private function updateIfReinstated(
301
-        array $closed_reg_statuses,
302
-        $new_STS_ID,
303
-        $old_STS_ID,
304
-        ContextInterface $context = null
305
-    ) {
306
-        // true if reinstating cancelled or declined registration
307
-        if (
308
-            in_array($old_STS_ID, $closed_reg_statuses, true)
309
-            && ! in_array($new_STS_ID, $closed_reg_statuses, true)
310
-        ) {
311
-            /** @type EE_Registration_Processor $registration_processor */
312
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
313
-            /** @type EE_Transaction_Processor $transaction_processor */
314
-            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
315
-            // reinstating cancelled or declined registration
316
-            $registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
317
-                $this,
318
-                $closed_reg_statuses
319
-            );
320
-            $transaction_processor->update_transaction_after_reinstating_canceled_registration(
321
-                $this,
322
-                $closed_reg_statuses,
323
-                false
324
-            );
325
-            do_action(
326
-                'AHEE__EE_Registration__set_status__after_reinstated',
327
-                $this,
328
-                $old_STS_ID,
329
-                $new_STS_ID,
330
-                $context
331
-            );
332
-        }
333
-    }
334
-
335
-
336
-    /**
337
-     * @param ContextInterface|null $context
338
-     * @return bool
339
-     */
340
-    private function statusChangeUpdatesTransaction(ContextInterface $context = null)
341
-    {
342
-        $contexts_that_do_not_update_transaction = (array) apply_filters(
343
-            'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
344
-            array('spco_reg_step_attendee_information_process_registrations'),
345
-            $context,
346
-            $this
347
-        );
348
-        return ! (
349
-            $context instanceof ContextInterface
350
-            && in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
351
-        );
352
-    }
353
-
354
-
355
-    /**
356
-     * @throws EE_Error
357
-     * @throws EntityNotFoundException
358
-     * @throws InvalidArgumentException
359
-     * @throws InvalidDataTypeException
360
-     * @throws InvalidInterfaceException
361
-     * @throws ReflectionException
362
-     * @throws RuntimeException
363
-     */
364
-    private function updateTransactionAfterStatusChange()
365
-    {
366
-        /** @type EE_Transaction_Payments $transaction_payments */
367
-        $transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
368
-        $transaction_payments->recalculate_transaction_total($this->transaction(), false);
369
-        $this->transaction()->update_status_based_on_total_paid(true);
370
-    }
371
-
372
-
373
-    /**
374
-     *        get Status ID
375
-     */
376
-    public function status_ID()
377
-    {
378
-        return $this->get('STS_ID');
379
-    }
380
-
381
-
382
-    /**
383
-     * Gets the ticket this registration is for
384
-     *
385
-     * @param boolean $include_archived whether to include archived tickets or not.
386
-     *
387
-     * @return EE_Ticket|EE_Base_Class
388
-     * @throws EE_Error
389
-     */
390
-    public function ticket($include_archived = true)
391
-    {
392
-        $query_params = array();
393
-        if ($include_archived) {
394
-            $query_params['default_where_conditions'] = 'none';
395
-        }
396
-        return $this->get_first_related('Ticket', $query_params);
397
-    }
398
-
399
-
400
-    /**
401
-     * Gets the event this registration is for
402
-     *
403
-     * @return EE_Event
404
-     * @throws EE_Error
405
-     * @throws EntityNotFoundException
406
-     */
407
-    public function event()
408
-    {
409
-        $event = $this->get_first_related('Event');
410
-        if (! $event instanceof \EE_Event) {
411
-            throw new EntityNotFoundException('Event ID', $this->event_ID());
412
-        }
413
-        return $event;
414
-    }
415
-
416
-
417
-    /**
418
-     * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
419
-     * with the author of the event this registration is for.
420
-     *
421
-     * @since 4.5.0
422
-     * @return int
423
-     * @throws EE_Error
424
-     * @throws EntityNotFoundException
425
-     */
426
-    public function wp_user()
427
-    {
428
-        $event = $this->event();
429
-        if ($event instanceof EE_Event) {
430
-            return $event->wp_user();
431
-        }
432
-        return 0;
433
-    }
434
-
435
-
436
-    /**
437
-     * increments this registration's related ticket sold and corresponding datetime sold values
438
-     *
439
-     * @return void
440
-     * @throws DomainException
441
-     * @throws EE_Error
442
-     * @throws EntityNotFoundException
443
-     * @throws InvalidArgumentException
444
-     * @throws InvalidDataTypeException
445
-     * @throws InvalidInterfaceException
446
-     * @throws ReflectionException
447
-     * @throws UnexpectedEntityException
448
-     */
449
-    private function reserveRegistrationSpace()
450
-    {
451
-        // reserved ticket and datetime counts will be decremented as sold counts are incremented
452
-        // so stop tracking that this reg has a ticket reserved
453
-        $this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
454
-        $ticket = $this->ticket();
455
-        $ticket->increaseSold();
456
-        // possibly set event status to sold out
457
-        $this->event()->perform_sold_out_status_check();
458
-    }
459
-
460
-
461
-    /**
462
-     * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
463
-     *
464
-     * @return void
465
-     * @throws DomainException
466
-     * @throws EE_Error
467
-     * @throws EntityNotFoundException
468
-     * @throws InvalidArgumentException
469
-     * @throws InvalidDataTypeException
470
-     * @throws InvalidInterfaceException
471
-     * @throws ReflectionException
472
-     * @throws UnexpectedEntityException
473
-     */
474
-    private function releaseRegistrationSpace()
475
-    {
476
-        $ticket = $this->ticket();
477
-        $ticket->decreaseSold();
478
-        // possibly change event status from sold out back to previous status
479
-        $this->event()->perform_sold_out_status_check();
480
-    }
481
-
482
-
483
-    /**
484
-     * tracks this registration's ticket reservation in extra meta
485
-     * and can increment related ticket reserved and corresponding datetime reserved values
486
-     *
487
-     * @param bool $update_ticket if true, will increment ticket and datetime reserved count
488
-     * @return void
489
-     * @throws EE_Error
490
-     * @throws InvalidArgumentException
491
-     * @throws InvalidDataTypeException
492
-     * @throws InvalidInterfaceException
493
-     * @throws ReflectionException
494
-     */
495
-    public function reserve_ticket($update_ticket = false, $source = 'unknown')
496
-    {
497
-        // only reserve ticket if space is not currently reserved
498
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
499
-            $this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
500
-            // IMPORTANT !!!
501
-            // although checking $update_ticket first would be more efficient,
502
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
503
-            if (
504
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
505
-                && $update_ticket
506
-            ) {
507
-                $ticket = $this->ticket();
508
-                $ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
509
-                $ticket->save();
510
-            }
511
-        }
512
-    }
513
-
514
-
515
-    /**
516
-     * stops tracking this registration's ticket reservation in extra meta
517
-     * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
518
-     *
519
-     * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
520
-     * @return void
521
-     * @throws EE_Error
522
-     * @throws InvalidArgumentException
523
-     * @throws InvalidDataTypeException
524
-     * @throws InvalidInterfaceException
525
-     * @throws ReflectionException
526
-     */
527
-    public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
528
-    {
529
-        // only release ticket if space is currently reserved
530
-        if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
531
-            $this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
532
-            // IMPORTANT !!!
533
-            // although checking $update_ticket first would be more efficient,
534
-            // we NEED to ALWAYS call update_extra_meta(), which is why that is done first
535
-            if (
536
-                $this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
537
-                && $update_ticket
538
-            ) {
539
-                $ticket = $this->ticket();
540
-                $ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
541
-            }
542
-        }
543
-    }
544
-
545
-
546
-    /**
547
-     * Set Attendee ID
548
-     *
549
-     * @param        int $ATT_ID Attendee ID
550
-     * @throws EE_Error
551
-     * @throws RuntimeException
552
-     */
553
-    public function set_attendee_id($ATT_ID = 0)
554
-    {
555
-        $this->set('ATT_ID', $ATT_ID);
556
-    }
557
-
558
-
559
-    /**
560
-     *        Set Transaction ID
561
-     *
562
-     * @param        int $TXN_ID Transaction ID
563
-     * @throws EE_Error
564
-     * @throws RuntimeException
565
-     */
566
-    public function set_transaction_id($TXN_ID = 0)
567
-    {
568
-        $this->set('TXN_ID', $TXN_ID);
569
-    }
570
-
571
-
572
-    /**
573
-     *        Set Session
574
-     *
575
-     * @param    string $REG_session PHP Session ID
576
-     * @throws EE_Error
577
-     * @throws RuntimeException
578
-     */
579
-    public function set_session($REG_session = '')
580
-    {
581
-        $this->set('REG_session', $REG_session);
582
-    }
583
-
584
-
585
-    /**
586
-     *        Set Registration URL Link
587
-     *
588
-     * @param    string $REG_url_link Registration URL Link
589
-     * @throws EE_Error
590
-     * @throws RuntimeException
591
-     */
592
-    public function set_reg_url_link($REG_url_link = '')
593
-    {
594
-        $this->set('REG_url_link', $REG_url_link);
595
-    }
596
-
597
-
598
-    /**
599
-     *        Set Attendee Counter
600
-     *
601
-     * @param        int $REG_count Primary Attendee
602
-     * @throws EE_Error
603
-     * @throws RuntimeException
604
-     */
605
-    public function set_count($REG_count = 1)
606
-    {
607
-        $this->set('REG_count', $REG_count);
608
-    }
609
-
610
-
611
-    /**
612
-     *        Set Group Size
613
-     *
614
-     * @param        boolean $REG_group_size Group Registration
615
-     * @throws EE_Error
616
-     * @throws RuntimeException
617
-     */
618
-    public function set_group_size($REG_group_size = false)
619
-    {
620
-        $this->set('REG_group_size', $REG_group_size);
621
-    }
622
-
623
-
624
-    /**
625
-     *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
626
-     *    EEM_Registration::status_id_not_approved
627
-     *
628
-     * @return        boolean
629
-     */
630
-    public function is_not_approved()
631
-    {
632
-        return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
633
-    }
634
-
635
-
636
-    /**
637
-     *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
638
-     *    EEM_Registration::status_id_pending_payment
639
-     *
640
-     * @return        boolean
641
-     */
642
-    public function is_pending_payment()
643
-    {
644
-        return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
645
-    }
646
-
647
-
648
-    /**
649
-     *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
650
-     *
651
-     * @return        boolean
652
-     */
653
-    public function is_approved()
654
-    {
655
-        return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
656
-    }
657
-
658
-
659
-    /**
660
-     *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
661
-     *
662
-     * @return        boolean
663
-     */
664
-    public function is_cancelled()
665
-    {
666
-        return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
667
-    }
668
-
669
-
670
-    /**
671
-     *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
672
-     *
673
-     * @return        boolean
674
-     */
675
-    public function is_declined()
676
-    {
677
-        return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
678
-    }
679
-
680
-
681
-    /**
682
-     *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
683
-     *    EEM_Registration::status_id_incomplete
684
-     *
685
-     * @return        boolean
686
-     */
687
-    public function is_incomplete()
688
-    {
689
-        return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
690
-    }
691
-
692
-
693
-    /**
694
-     *        Set Registration Date
695
-     *
696
-     * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
697
-     *                                                 Date
698
-     * @throws EE_Error
699
-     * @throws RuntimeException
700
-     */
701
-    public function set_reg_date($REG_date = false)
702
-    {
703
-        $this->set('REG_date', $REG_date);
704
-    }
705
-
706
-
707
-    /**
708
-     *    Set final price owing for this registration after all ticket/price modifications
709
-     *
710
-     * @access    public
711
-     * @param    float $REG_final_price
712
-     * @throws EE_Error
713
-     * @throws RuntimeException
714
-     */
715
-    public function set_final_price($REG_final_price = 0.00)
716
-    {
717
-        $this->set('REG_final_price', $REG_final_price);
718
-    }
719
-
720
-
721
-    /**
722
-     *    Set amount paid towards this registration's final price
723
-     *
724
-     * @access    public
725
-     * @param    float $REG_paid
726
-     * @throws EE_Error
727
-     * @throws RuntimeException
728
-     */
729
-    public function set_paid($REG_paid = 0.00)
730
-    {
731
-        $this->set('REG_paid', $REG_paid);
732
-    }
733
-
734
-
735
-    /**
736
-     *        Attendee Is Going
737
-     *
738
-     * @param        boolean $REG_att_is_going Attendee Is Going
739
-     * @throws EE_Error
740
-     * @throws RuntimeException
741
-     */
742
-    public function set_att_is_going($REG_att_is_going = false)
743
-    {
744
-        $this->set('REG_att_is_going', $REG_att_is_going);
745
-    }
746
-
747
-
748
-    /**
749
-     * Gets the related attendee
750
-     *
751
-     * @return EE_Attendee
752
-     * @throws EE_Error
753
-     */
754
-    public function attendee()
755
-    {
756
-        return $this->get_first_related('Attendee');
757
-    }
758
-
759
-    /**
760
-     * Gets the name of the attendee.
761
-     * @since 4.10.12.p
762
-     * @param bool $apply_html_entities set to true if you want to use HTML entities.
763
-     * @return string
764
-     * @throws EE_Error
765
-     * @throws InvalidArgumentException
766
-     * @throws InvalidDataTypeException
767
-     * @throws InvalidInterfaceException
768
-     * @throws ReflectionException
769
-     */
770
-    public function attendeeName($apply_html_entities = false)
771
-    {
772
-        $attendee = $this->get_first_related('Attendee');
773
-        if ($attendee instanceof EE_Attendee) {
774
-            $attendee_name = $attendee->full_name($apply_html_entities);
775
-        } else {
776
-            $attendee_name = esc_html__('Unknown', 'event_espresso');
777
-        }
778
-        return $attendee_name;
779
-    }
780
-
781
-
782
-    /**
783
-     *        get Event ID
784
-     */
785
-    public function event_ID()
786
-    {
787
-        return $this->get('EVT_ID');
788
-    }
789
-
790
-
791
-    /**
792
-     *        get Event ID
793
-     */
794
-    public function event_name()
795
-    {
796
-        $event = $this->event_obj();
797
-        if ($event) {
798
-            return $event->name();
799
-        } else {
800
-            return null;
801
-        }
802
-    }
803
-
804
-
805
-    /**
806
-     * Fetches the event this registration is for
807
-     *
808
-     * @return EE_Event
809
-     * @throws EE_Error
810
-     */
811
-    public function event_obj()
812
-    {
813
-        return $this->get_first_related('Event');
814
-    }
815
-
816
-
817
-    /**
818
-     *        get Attendee ID
819
-     */
820
-    public function attendee_ID()
821
-    {
822
-        return $this->get('ATT_ID');
823
-    }
824
-
825
-
826
-    /**
827
-     *        get PHP Session ID
828
-     */
829
-    public function session_ID()
830
-    {
831
-        return $this->get('REG_session');
832
-    }
833
-
834
-
835
-    /**
836
-     * Gets the string which represents the URL trigger for the receipt template in the message template system.
837
-     *
838
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
839
-     * @return string
840
-     */
841
-    public function receipt_url($messenger = 'html')
842
-    {
843
-
844
-        /**
845
-         * The below will be deprecated one version after this.  We check first if there is a custom receipt template
846
-         * already in use on old system.  If there is then we just return the standard url for it.
847
-         *
848
-         * @since 4.5.0
849
-         */
850
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
851
-        $has_custom = EEH_Template::locate_template(
852
-            $template_relative_path,
853
-            array(),
854
-            true,
855
-            true,
856
-            true
857
-        );
858
-
859
-        if ($has_custom) {
860
-            return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
861
-        }
862
-        return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
863
-    }
864
-
865
-
866
-    /**
867
-     * Gets the string which represents the URL trigger for the invoice template in the message template system.
868
-     *
869
-     * @param string $messenger 'pdf' or 'html'.  Default 'html'.
870
-     * @return string
871
-     * @throws EE_Error
872
-     */
873
-    public function invoice_url($messenger = 'html')
874
-    {
875
-        /**
876
-         * The below will be deprecated one version after this.  We check first if there is a custom invoice template
877
-         * already in use on old system.  If there is then we just return the standard url for it.
878
-         *
879
-         * @since 4.5.0
880
-         */
881
-        $template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
882
-        $has_custom = EEH_Template::locate_template(
883
-            $template_relative_path,
884
-            array(),
885
-            true,
886
-            true,
887
-            true
888
-        );
889
-
890
-        if ($has_custom) {
891
-            if ($messenger == 'html') {
892
-                return $this->invoice_url('launch');
893
-            }
894
-            $route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
895
-
896
-            $query_args = array('ee' => $route, 'id' => $this->reg_url_link());
897
-            if ($messenger == 'html') {
898
-                $query_args['html'] = true;
899
-            }
900
-            return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
901
-        }
902
-        return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
903
-    }
904
-
905
-
906
-    /**
907
-     * get Registration URL Link
908
-     *
909
-     * @access public
910
-     * @return string
911
-     * @throws EE_Error
912
-     */
913
-    public function reg_url_link()
914
-    {
915
-        return (string) $this->get('REG_url_link');
916
-    }
917
-
918
-
919
-    /**
920
-     * Echoes out invoice_url()
921
-     *
922
-     * @param string $type 'download','launch', or 'html' (default is 'launch')
923
-     * @return void
924
-     * @throws EE_Error
925
-     */
926
-    public function e_invoice_url($type = 'launch')
927
-    {
928
-        echo esc_url_raw($this->invoice_url($type));
929
-    }
930
-
931
-
932
-    /**
933
-     * Echoes out payment_overview_url
934
-     */
935
-    public function e_payment_overview_url()
936
-    {
937
-        echo esc_url_raw($this->payment_overview_url());
938
-    }
939
-
940
-
941
-    /**
942
-     * Gets the URL for the checkout payment options reg step
943
-     * with this registration's REG_url_link added as a query parameter
944
-     *
945
-     * @param bool $clear_session Set to true when you want to clear the session on revisiting the
946
-     *                            payment overview url.
947
-     * @return string
948
-     * @throws InvalidInterfaceException
949
-     * @throws InvalidDataTypeException
950
-     * @throws EE_Error
951
-     * @throws InvalidArgumentException
952
-     */
953
-    public function payment_overview_url($clear_session = false)
954
-    {
955
-        return add_query_arg(
956
-            (array) apply_filters(
957
-                'FHEE__EE_Registration__payment_overview_url__query_args',
958
-                array(
959
-                    'e_reg_url_link' => $this->reg_url_link(),
960
-                    'step'           => 'payment_options',
961
-                    'revisit'        => true,
962
-                    'clear_session'  => (bool) $clear_session,
963
-                ),
964
-                $this
965
-            ),
966
-            EE_Registry::instance()->CFG->core->reg_page_url()
967
-        );
968
-    }
969
-
970
-
971
-    /**
972
-     * Gets the URL for the checkout attendee information reg step
973
-     * with this registration's REG_url_link added as a query parameter
974
-     *
975
-     * @return string
976
-     * @throws InvalidInterfaceException
977
-     * @throws InvalidDataTypeException
978
-     * @throws EE_Error
979
-     * @throws InvalidArgumentException
980
-     */
981
-    public function edit_attendee_information_url()
982
-    {
983
-        return add_query_arg(
984
-            (array) apply_filters(
985
-                'FHEE__EE_Registration__edit_attendee_information_url__query_args',
986
-                array(
987
-                    'e_reg_url_link' => $this->reg_url_link(),
988
-                    'step'           => 'attendee_information',
989
-                    'revisit'        => true,
990
-                ),
991
-                $this
992
-            ),
993
-            EE_Registry::instance()->CFG->core->reg_page_url()
994
-        );
995
-    }
996
-
997
-
998
-    /**
999
-     * Simply generates and returns the appropriate admin_url link to edit this registration
1000
-     *
1001
-     * @return string
1002
-     * @throws EE_Error
1003
-     */
1004
-    public function get_admin_edit_url()
1005
-    {
1006
-        return EEH_URL::add_query_args_and_nonce(
1007
-            array(
1008
-                'page'    => 'espresso_registrations',
1009
-                'action'  => 'view_registration',
1010
-                '_REG_ID' => $this->ID(),
1011
-            ),
1012
-            admin_url('admin.php')
1013
-        );
1014
-    }
1015
-
1016
-
1017
-    /**
1018
-     *    is_primary_registrant?
1019
-     */
1020
-    public function is_primary_registrant()
1021
-    {
1022
-        return $this->get('REG_count') === 1 ? true : false;
1023
-    }
1024
-
1025
-
1026
-    /**
1027
-     * This returns the primary registration object for this registration group (which may be this object).
1028
-     *
1029
-     * @return EE_Registration
1030
-     * @throws EE_Error
1031
-     */
1032
-    public function get_primary_registration()
1033
-    {
1034
-        if ($this->is_primary_registrant()) {
1035
-            return $this;
1036
-        }
1037
-
1038
-        // k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1039
-        /** @var EE_Registration $primary_registrant */
1040
-        $primary_registrant = EEM_Registration::instance()->get_one(
1041
-            array(
1042
-                array(
1043
-                    'TXN_ID'    => $this->transaction_ID(),
1044
-                    'REG_count' => 1,
1045
-                ),
1046
-            )
1047
-        );
1048
-        return $primary_registrant;
1049
-    }
1050
-
1051
-
1052
-    /**
1053
-     *        get  Attendee Number
1054
-     *
1055
-     * @access        public
1056
-     */
1057
-    public function count()
1058
-    {
1059
-        return $this->get('REG_count');
1060
-    }
1061
-
1062
-
1063
-    /**
1064
-     *        get Group Size
1065
-     */
1066
-    public function group_size()
1067
-    {
1068
-        return $this->get('REG_group_size');
1069
-    }
1070
-
1071
-
1072
-    /**
1073
-     *        get Registration Date
1074
-     */
1075
-    public function date()
1076
-    {
1077
-        return $this->get('REG_date');
1078
-    }
1079
-
1080
-
1081
-    /**
1082
-     * gets a pretty date
1083
-     *
1084
-     * @param string $date_format
1085
-     * @param string $time_format
1086
-     * @return string
1087
-     * @throws EE_Error
1088
-     */
1089
-    public function pretty_date($date_format = null, $time_format = null)
1090
-    {
1091
-        return $this->get_datetime('REG_date', $date_format, $time_format);
1092
-    }
1093
-
1094
-
1095
-    /**
1096
-     * final_price
1097
-     * the registration's share of the transaction total, so that the
1098
-     * sum of all the transaction's REG_final_prices equal the transaction's total
1099
-     *
1100
-     * @return float
1101
-     * @throws EE_Error
1102
-     */
1103
-    public function final_price()
1104
-    {
1105
-        return $this->get('REG_final_price');
1106
-    }
1107
-
1108
-
1109
-    /**
1110
-     * pretty_final_price
1111
-     *  final price as formatted string, with correct decimal places and currency symbol
1112
-     *
1113
-     * @return string
1114
-     * @throws EE_Error
1115
-     */
1116
-    public function pretty_final_price()
1117
-    {
1118
-        return $this->get_pretty('REG_final_price');
1119
-    }
1120
-
1121
-
1122
-    /**
1123
-     * get paid (yeah)
1124
-     *
1125
-     * @return float
1126
-     * @throws EE_Error
1127
-     */
1128
-    public function paid()
1129
-    {
1130
-        return $this->get('REG_paid');
1131
-    }
1132
-
1133
-
1134
-    /**
1135
-     * pretty_paid
1136
-     *
1137
-     * @return float
1138
-     * @throws EE_Error
1139
-     */
1140
-    public function pretty_paid()
1141
-    {
1142
-        return $this->get_pretty('REG_paid');
1143
-    }
1144
-
1145
-
1146
-    /**
1147
-     * owes_monies_and_can_pay
1148
-     * whether or not this registration has monies owing and it's' status allows payment
1149
-     *
1150
-     * @param array $requires_payment
1151
-     * @return bool
1152
-     * @throws EE_Error
1153
-     */
1154
-    public function owes_monies_and_can_pay($requires_payment = array())
1155
-    {
1156
-        // these reg statuses require payment (if event is not free)
1157
-        $requires_payment = ! empty($requires_payment)
1158
-            ? $requires_payment
1159
-            : EEM_Registration::reg_statuses_that_allow_payment();
1160
-        if (
1161
-            in_array($this->status_ID(), $requires_payment) &&
1162
-            $this->final_price() != 0 &&
1163
-            $this->final_price() != $this->paid()
1164
-        ) {
1165
-            return true;
1166
-        } else {
1167
-            return false;
1168
-        }
1169
-    }
1170
-
1171
-
1172
-    /**
1173
-     * Prints out the return value of $this->pretty_status()
1174
-     *
1175
-     * @param bool $show_icons
1176
-     * @return void
1177
-     * @throws EE_Error
1178
-     */
1179
-    public function e_pretty_status($show_icons = false)
1180
-    {
1181
-        echo wp_kses($this->pretty_status($show_icons), AllowedTags::getAllowedTags());
1182
-    }
1183
-
1184
-
1185
-    /**
1186
-     * Returns a nice version of the status for displaying to customers
1187
-     *
1188
-     * @param bool $show_icons
1189
-     * @return string
1190
-     * @throws EE_Error
1191
-     */
1192
-    public function pretty_status($show_icons = false)
1193
-    {
1194
-        $status = EEM_Status::instance()->localized_status(
1195
-            array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1196
-            false,
1197
-            'sentence'
1198
-        );
1199
-        $icon = '';
1200
-        switch ($this->status_ID()) {
1201
-            case EEM_Registration::status_id_approved:
1202
-                $icon = $show_icons
1203
-                    ? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1204
-                    : '';
1205
-                break;
1206
-            case EEM_Registration::status_id_pending_payment:
1207
-                $icon = $show_icons
1208
-                    ? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1209
-                    : '';
1210
-                break;
1211
-            case EEM_Registration::status_id_not_approved:
1212
-                $icon = $show_icons
1213
-                    ? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1214
-                    : '';
1215
-                break;
1216
-            case EEM_Registration::status_id_cancelled:
1217
-                $icon = $show_icons
1218
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1219
-                    : '';
1220
-                break;
1221
-            case EEM_Registration::status_id_incomplete:
1222
-                $icon = $show_icons
1223
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1224
-                    : '';
1225
-                break;
1226
-            case EEM_Registration::status_id_declined:
1227
-                $icon = $show_icons
1228
-                    ? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1229
-                    : '';
1230
-                break;
1231
-            case EEM_Registration::status_id_wait_list:
1232
-                $icon = $show_icons
1233
-                    ? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1234
-                    : '';
1235
-                break;
1236
-        }
1237
-        return $icon . $status[ $this->status_ID() ];
1238
-    }
1239
-
1240
-
1241
-    /**
1242
-     *        get Attendee Is Going
1243
-     */
1244
-    public function att_is_going()
1245
-    {
1246
-        return $this->get('REG_att_is_going');
1247
-    }
1248
-
1249
-
1250
-    /**
1251
-     * Gets related answers
1252
-     *
1253
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1254
-     * @return EE_Answer[]
1255
-     * @throws EE_Error
1256
-     */
1257
-    public function answers($query_params = null)
1258
-    {
1259
-        return $this->get_many_related('Answer', $query_params);
1260
-    }
1261
-
1262
-
1263
-    /**
1264
-     * Gets the registration's answer value to the specified question
1265
-     * (either the question's ID or a question object)
1266
-     *
1267
-     * @param EE_Question|int $question
1268
-     * @param bool            $pretty_value
1269
-     * @return array|string if pretty_value= true, the result will always be a string
1270
-     * (because the answer might be an array of answer values, so passing pretty_value=true
1271
-     * will convert it into some kind of string)
1272
-     * @throws EE_Error
1273
-     */
1274
-    public function answer_value_to_question($question, $pretty_value = true)
1275
-    {
1276
-        $question_id = EEM_Question::instance()->ensure_is_ID($question);
1277
-        return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1278
-    }
1279
-
1280
-
1281
-    /**
1282
-     * question_groups
1283
-     * returns an array of EE_Question_Group objects for this registration
1284
-     *
1285
-     * @return EE_Question_Group[]
1286
-     * @throws EE_Error
1287
-     * @throws InvalidArgumentException
1288
-     * @throws InvalidDataTypeException
1289
-     * @throws InvalidInterfaceException
1290
-     * @throws ReflectionException
1291
-     */
1292
-    public function question_groups()
1293
-    {
1294
-        return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1295
-    }
1296
-
1297
-
1298
-    /**
1299
-     * count_question_groups
1300
-     * returns a count of the number of EE_Question_Group objects for this registration
1301
-     *
1302
-     * @return int
1303
-     * @throws EE_Error
1304
-     * @throws EntityNotFoundException
1305
-     * @throws InvalidArgumentException
1306
-     * @throws InvalidDataTypeException
1307
-     * @throws InvalidInterfaceException
1308
-     * @throws ReflectionException
1309
-     */
1310
-    public function count_question_groups()
1311
-    {
1312
-        return EEM_Event::instance()->count_related(
1313
-            $this->event_ID(),
1314
-            'Question_Group',
1315
-            [
1316
-                [
1317
-                    'Event_Question_Group.'
1318
-                    . EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1319
-                ]
1320
-            ]
1321
-        );
1322
-    }
1323
-
1324
-
1325
-    /**
1326
-     * Returns the registration date in the 'standard' string format
1327
-     * (function may be improved in the future to allow for different formats and timezones)
1328
-     *
1329
-     * @return string
1330
-     * @throws EE_Error
1331
-     */
1332
-    public function reg_date()
1333
-    {
1334
-        return $this->get_datetime('REG_date');
1335
-    }
1336
-
1337
-
1338
-    /**
1339
-     * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1340
-     * the ticket this registration purchased, or the datetime they have registered
1341
-     * to attend)
1342
-     *
1343
-     * @return EE_Datetime_Ticket
1344
-     * @throws EE_Error
1345
-     */
1346
-    public function datetime_ticket()
1347
-    {
1348
-        return $this->get_first_related('Datetime_Ticket');
1349
-    }
1350
-
1351
-
1352
-    /**
1353
-     * Sets the registration's datetime_ticket.
1354
-     *
1355
-     * @param EE_Datetime_Ticket $datetime_ticket
1356
-     * @return EE_Datetime_Ticket
1357
-     * @throws EE_Error
1358
-     */
1359
-    public function set_datetime_ticket($datetime_ticket)
1360
-    {
1361
-        return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1362
-    }
1363
-
1364
-    /**
1365
-     * Gets deleted
1366
-     *
1367
-     * @return bool
1368
-     * @throws EE_Error
1369
-     */
1370
-    public function deleted()
1371
-    {
1372
-        return $this->get('REG_deleted');
1373
-    }
1374
-
1375
-    /**
1376
-     * Sets deleted
1377
-     *
1378
-     * @param boolean $deleted
1379
-     * @return bool
1380
-     * @throws EE_Error
1381
-     * @throws RuntimeException
1382
-     */
1383
-    public function set_deleted($deleted)
1384
-    {
1385
-        if ($deleted) {
1386
-            $this->delete();
1387
-        } else {
1388
-            $this->restore();
1389
-        }
1390
-    }
1391
-
1392
-
1393
-    /**
1394
-     * Get the status object of this object
1395
-     *
1396
-     * @return EE_Status
1397
-     * @throws EE_Error
1398
-     */
1399
-    public function status_obj()
1400
-    {
1401
-        return $this->get_first_related('Status');
1402
-    }
1403
-
1404
-
1405
-    /**
1406
-     * Returns the number of times this registration has checked into any of the datetimes
1407
-     * its available for
1408
-     *
1409
-     * @return int
1410
-     * @throws EE_Error
1411
-     */
1412
-    public function count_checkins()
1413
-    {
1414
-        return $this->get_model()->count_related($this, 'Checkin');
1415
-    }
1416
-
1417
-
1418
-    /**
1419
-     * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1420
-     * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1421
-     *
1422
-     * @return int
1423
-     * @throws EE_Error
1424
-     */
1425
-    public function count_checkins_not_checkedout()
1426
-    {
1427
-        return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1428
-    }
1429
-
1430
-
1431
-    /**
1432
-     * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1433
-     *
1434
-     * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1435
-     * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1436
-     *                                          consider registration status as well as datetime access.
1437
-     * @return bool
1438
-     * @throws EE_Error
1439
-     */
1440
-    public function can_checkin($DTT_OR_ID, $check_approved = true)
1441
-    {
1442
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1443
-
1444
-        // first check registration status
1445
-        if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1446
-            return false;
1447
-        }
1448
-        // is there a datetime ticket that matches this dtt_ID?
1449
-        if (
1450
-            ! (EEM_Datetime_Ticket::instance()->exists(
1451
-                array(
1452
-                array(
1453
-                    'TKT_ID' => $this->get('TKT_ID'),
1454
-                    'DTT_ID' => $DTT_ID,
1455
-                ),
1456
-                )
1457
-            ))
1458
-        ) {
1459
-            return false;
1460
-        }
1461
-
1462
-        // final check is against TKT_uses
1463
-        return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1464
-    }
1465
-
1466
-
1467
-    /**
1468
-     * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1469
-     * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1470
-     * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1471
-     * then return false.  Otherwise return true.
1472
-     *
1473
-     * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1474
-     * @return bool true means can checkin.  false means cannot checkin.
1475
-     * @throws EE_Error
1476
-     */
1477
-    public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1478
-    {
1479
-        $DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1480
-
1481
-        if (! $DTT_ID) {
1482
-            return false;
1483
-        }
1484
-
1485
-        $max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1486
-
1487
-        // if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1488
-        // check-in or not.
1489
-        if (! $max_uses || $max_uses === EE_INF) {
1490
-            return true;
1491
-        }
1492
-
1493
-        // does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1494
-        // go ahead and toggle.
1495
-        if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1496
-            return true;
1497
-        }
1498
-
1499
-        // made it here so the last check is whether the number of checkins per unique datetime on this registration
1500
-        // disallows further check-ins.
1501
-        $count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1502
-            array(
1503
-                array(
1504
-                    'REG_ID' => $this->ID(),
1505
-                    'CHK_in' => true,
1506
-                ),
1507
-            ),
1508
-            'DTT_ID',
1509
-            true
1510
-        );
1511
-        // checkins have already reached their max number of uses
1512
-        // so registrant can NOT checkin
1513
-        if ($count_unique_dtt_checkins >= $max_uses) {
1514
-            EE_Error::add_error(
1515
-                esc_html__(
1516
-                    'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1517
-                    'event_espresso'
1518
-                ),
1519
-                __FILE__,
1520
-                __FUNCTION__,
1521
-                __LINE__
1522
-            );
1523
-            return false;
1524
-        }
1525
-        return true;
1526
-    }
1527
-
1528
-
1529
-    /**
1530
-     * toggle Check-in status for this registration
1531
-     * Check-ins are toggled in the following order:
1532
-     * never checked in -> checked in
1533
-     * checked in -> checked out
1534
-     * checked out -> checked in
1535
-     *
1536
-     * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1537
-     *                      If not included or null, then it is assumed latest datetime is being toggled.
1538
-     * @param bool $verify  If true then can_checkin() is used to verify whether the person
1539
-     *                      can be checked in or not.  Otherwise this forces change in checkin status.
1540
-     * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1541
-     * @throws EE_Error
1542
-     */
1543
-    public function toggle_checkin_status($DTT_ID = null, $verify = false)
1544
-    {
1545
-        if (empty($DTT_ID)) {
1546
-            $datetime = $this->get_latest_related_datetime();
1547
-            $DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1548
-            // verify the registration can checkin for the given DTT_ID
1549
-        } elseif (! $this->can_checkin($DTT_ID, $verify)) {
1550
-            EE_Error::add_error(
1551
-                sprintf(
1552
-                    esc_html__(
1553
-                        'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1554
-                        'event_espresso'
1555
-                    ),
1556
-                    $this->ID(),
1557
-                    $DTT_ID
1558
-                ),
1559
-                __FILE__,
1560
-                __FUNCTION__,
1561
-                __LINE__
1562
-            );
1563
-            return false;
1564
-        }
1565
-        $status_paths = array(
1566
-            EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1567
-            EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1568
-            EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1569
-        );
1570
-        // start by getting the current status so we know what status we'll be changing to.
1571
-        $cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1572
-        $status_to = $status_paths[ $cur_status ];
1573
-        // database only records true for checked IN or false for checked OUT
1574
-        // no record ( null ) means checked in NEVER, but we obviously don't save that
1575
-        $new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1576
-        // add relation - note Check-ins are always creating new rows
1577
-        // because we are keeping track of Check-ins over time.
1578
-        // Eventually we'll probably want to show a list table
1579
-        // for the individual Check-ins so that they can be managed.
1580
-        $checkin = EE_Checkin::new_instance(
1581
-            array(
1582
-                'REG_ID' => $this->ID(),
1583
-                'DTT_ID' => $DTT_ID,
1584
-                'CHK_in' => $new_status,
1585
-            )
1586
-        );
1587
-        // if the record could not be saved then return false
1588
-        if ($checkin->save() === 0) {
1589
-            if (WP_DEBUG) {
1590
-                global $wpdb;
1591
-                $error = sprintf(
1592
-                    esc_html__(
1593
-                        'Registration check in update failed because of the following database error: %1$s%2$s',
1594
-                        'event_espresso'
1595
-                    ),
1596
-                    '<br />',
1597
-                    $wpdb->last_error
1598
-                );
1599
-            } else {
1600
-                $error = esc_html__(
1601
-                    'Registration check in update failed because of an unknown database error',
1602
-                    'event_espresso'
1603
-                );
1604
-            }
1605
-            EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1606
-            return false;
1607
-        }
1608
-        // Fire a checked_in and checkout_out action.
1609
-        $checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1610
-        do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1611
-        return $status_to;
1612
-    }
1613
-
1614
-
1615
-    /**
1616
-     * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1617
-     * "Latest" is defined by the `DTT_EVT_start` column.
1618
-     *
1619
-     * @return EE_Datetime|null
1620
-     * @throws EE_Error
1621
-     */
1622
-    public function get_latest_related_datetime()
1623
-    {
1624
-        return EEM_Datetime::instance()->get_one(
1625
-            array(
1626
-                array(
1627
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1628
-                ),
1629
-                'order_by' => array('DTT_EVT_start' => 'DESC'),
1630
-            )
1631
-        );
1632
-    }
1633
-
1634
-
1635
-    /**
1636
-     * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1637
-     * "Earliest" is defined by the `DTT_EVT_start` column.
1638
-     *
1639
-     * @throws EE_Error
1640
-     */
1641
-    public function get_earliest_related_datetime()
1642
-    {
1643
-        return EEM_Datetime::instance()->get_one(
1644
-            array(
1645
-                array(
1646
-                    'Ticket.Registration.REG_ID' => $this->ID(),
1647
-                ),
1648
-                'order_by' => array('DTT_EVT_start' => 'ASC'),
1649
-            )
1650
-        );
1651
-    }
1652
-
1653
-
1654
-    /**
1655
-     * This method simply returns the check-in status for this registration and the given datetime.
1656
-     * If neither the datetime nor the checkin values are provided as arguments,
1657
-     * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1658
-     *
1659
-     * @param  int       $DTT_ID  The ID of the datetime we're checking against
1660
-     *                            (if empty we'll get the primary datetime for
1661
-     *                            this registration (via event) and use it's ID);
1662
-     * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1663
-     *
1664
-     * @return int                Integer representing Check-in status.
1665
-     * @throws EE_Error
1666
-     */
1667
-    public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1668
-    {
1669
-        $checkin_query_params = array(
1670
-            'order_by' => array('CHK_timestamp' => 'DESC'),
1671
-        );
1672
-
1673
-        if ($DTT_ID > 0) {
1674
-            $checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1675
-        }
1676
-
1677
-        // get checkin object (if exists)
1678
-        $checkin = $checkin instanceof EE_Checkin
1679
-            ? $checkin
1680
-            : $this->get_first_related('Checkin', $checkin_query_params);
1681
-        if ($checkin instanceof EE_Checkin) {
1682
-            if ($checkin->get('CHK_in')) {
1683
-                return EE_Checkin::status_checked_in; // checked in
1684
-            }
1685
-            return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1686
-        }
1687
-        return EE_Checkin::status_checked_never; // never been checked in
1688
-    }
1689
-
1690
-
1691
-    /**
1692
-     * This method returns a localized message for the toggled Check-in message.
1693
-     *
1694
-     * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1695
-     *                     then it is assumed Check-in for primary datetime was toggled.
1696
-     * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1697
-     *                     message can be customized with the attendee name.
1698
-     * @return string internationalized message
1699
-     * @throws EE_Error
1700
-     */
1701
-    public function get_checkin_msg($DTT_ID, $error = false)
1702
-    {
1703
-        // let's get the attendee first so we can include the name of the attendee
1704
-        $attendee = $this->get_first_related('Attendee');
1705
-        if ($attendee instanceof EE_Attendee) {
1706
-            if ($error) {
1707
-                return sprintf(esc_html__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1708
-            }
1709
-            $cur_status = $this->check_in_status_for_datetime($DTT_ID);
1710
-            // what is the status message going to be?
1711
-            switch ($cur_status) {
1712
-                case EE_Checkin::status_checked_never:
1713
-                    return sprintf(
1714
-                        esc_html__("%s has been removed from Check-in records", "event_espresso"),
1715
-                        $attendee->full_name()
1716
-                    );
1717
-                    break;
1718
-                case EE_Checkin::status_checked_in:
1719
-                    return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1720
-                    break;
1721
-                case EE_Checkin::status_checked_out:
1722
-                    return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1723
-                    break;
1724
-            }
1725
-        }
1726
-        return esc_html__("The check-in status could not be determined.", "event_espresso");
1727
-    }
1728
-
1729
-
1730
-    /**
1731
-     * Returns the related EE_Transaction to this registration
1732
-     *
1733
-     * @return EE_Transaction
1734
-     * @throws EE_Error
1735
-     * @throws EntityNotFoundException
1736
-     */
1737
-    public function transaction()
1738
-    {
1739
-        $transaction = $this->get_first_related('Transaction');
1740
-        if (! $transaction instanceof \EE_Transaction) {
1741
-            throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1742
-        }
1743
-        return $transaction;
1744
-    }
1745
-
1746
-
1747
-    /**
1748
-     *        get Registration Code
1749
-     */
1750
-    public function reg_code()
1751
-    {
1752
-        return $this->get('REG_code');
1753
-    }
1754
-
1755
-
1756
-    /**
1757
-     *        get Transaction ID
1758
-     */
1759
-    public function transaction_ID()
1760
-    {
1761
-        return $this->get('TXN_ID');
1762
-    }
1763
-
1764
-
1765
-    /**
1766
-     * @return int
1767
-     * @throws EE_Error
1768
-     */
1769
-    public function ticket_ID()
1770
-    {
1771
-        return $this->get('TKT_ID');
1772
-    }
1773
-
1774
-
1775
-    /**
1776
-     *        Set Registration Code
1777
-     *
1778
-     * @access    public
1779
-     * @param    string  $REG_code Registration Code
1780
-     * @param    boolean $use_default
1781
-     * @throws EE_Error
1782
-     */
1783
-    public function set_reg_code($REG_code, $use_default = false)
1784
-    {
1785
-        if (empty($REG_code)) {
1786
-            EE_Error::add_error(
1787
-                esc_html__('REG_code can not be empty.', 'event_espresso'),
1788
-                __FILE__,
1789
-                __FUNCTION__,
1790
-                __LINE__
1791
-            );
1792
-            return;
1793
-        }
1794
-        if (! $this->reg_code()) {
1795
-            parent::set('REG_code', $REG_code, $use_default);
1796
-        } else {
1797
-            EE_Error::doing_it_wrong(
1798
-                __CLASS__ . '::' . __FUNCTION__,
1799
-                esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1800
-                '4.6.0'
1801
-            );
1802
-        }
1803
-    }
1804
-
1805
-
1806
-    /**
1807
-     * Returns all other registrations in the same group as this registrant who have the same ticket option.
1808
-     * Note, if you want to just get all registrations in the same transaction (group), use:
1809
-     *    $registration->transaction()->registrations();
1810
-     *
1811
-     * @since 4.5.0
1812
-     * @return EE_Registration[] or empty array if this isn't a group registration.
1813
-     * @throws EE_Error
1814
-     */
1815
-    public function get_all_other_registrations_in_group()
1816
-    {
1817
-        if ($this->group_size() < 2) {
1818
-            return array();
1819
-        }
1820
-
1821
-        $query[0] = array(
1822
-            'TXN_ID' => $this->transaction_ID(),
1823
-            'REG_ID' => array('!=', $this->ID()),
1824
-            'TKT_ID' => $this->ticket_ID(),
1825
-        );
1826
-        /** @var EE_Registration[] $registrations */
1827
-        $registrations = $this->get_model()->get_all($query);
1828
-        return $registrations;
1829
-    }
1830
-
1831
-    /**
1832
-     * Return the link to the admin details for the object.
1833
-     *
1834
-     * @return string
1835
-     * @throws EE_Error
1836
-     */
1837
-    public function get_admin_details_link()
1838
-    {
1839
-        EE_Registry::instance()->load_helper('URL');
1840
-        return EEH_URL::add_query_args_and_nonce(
1841
-            array(
1842
-                'page'    => 'espresso_registrations',
1843
-                'action'  => 'view_registration',
1844
-                '_REG_ID' => $this->ID(),
1845
-            ),
1846
-            admin_url('admin.php')
1847
-        );
1848
-    }
1849
-
1850
-    /**
1851
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1852
-     *
1853
-     * @return string
1854
-     * @throws EE_Error
1855
-     */
1856
-    public function get_admin_edit_link()
1857
-    {
1858
-        return $this->get_admin_details_link();
1859
-    }
1860
-
1861
-    /**
1862
-     * Returns the link to a settings page for the object.
1863
-     *
1864
-     * @return string
1865
-     * @throws EE_Error
1866
-     */
1867
-    public function get_admin_settings_link()
1868
-    {
1869
-        return $this->get_admin_details_link();
1870
-    }
1871
-
1872
-    /**
1873
-     * Returns the link to the "overview" for the object (typically the "list table" view).
1874
-     *
1875
-     * @return string
1876
-     */
1877
-    public function get_admin_overview_link()
1878
-    {
1879
-        EE_Registry::instance()->load_helper('URL');
1880
-        return EEH_URL::add_query_args_and_nonce(
1881
-            array(
1882
-                'page' => 'espresso_registrations',
1883
-            ),
1884
-            admin_url('admin.php')
1885
-        );
1886
-    }
1887
-
1888
-
1889
-    /**
1890
-     * @param array $query_params
1891
-     *
1892
-     * @return \EE_Registration[]
1893
-     * @throws EE_Error
1894
-     */
1895
-    public function payments($query_params = array())
1896
-    {
1897
-        return $this->get_many_related('Payment', $query_params);
1898
-    }
1899
-
1900
-
1901
-    /**
1902
-     * @param array $query_params
1903
-     *
1904
-     * @return \EE_Registration_Payment[]
1905
-     * @throws EE_Error
1906
-     */
1907
-    public function registration_payments($query_params = array())
1908
-    {
1909
-        return $this->get_many_related('Registration_Payment', $query_params);
1910
-    }
1911
-
1912
-
1913
-    /**
1914
-     * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1915
-     * Note: if there are no payments on the registration there will be no payment method returned.
1916
-     *
1917
-     * @return EE_Payment_Method|null
1918
-     */
1919
-    public function payment_method()
1920
-    {
1921
-        return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1922
-    }
1923
-
1924
-
1925
-    /**
1926
-     * @return \EE_Line_Item
1927
-     * @throws EntityNotFoundException
1928
-     * @throws EE_Error
1929
-     */
1930
-    public function ticket_line_item()
1931
-    {
1932
-        $ticket = $this->ticket();
1933
-        $transaction = $this->transaction();
1934
-        $line_item = null;
1935
-        $ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1936
-            $transaction->total_line_item(),
1937
-            'Ticket',
1938
-            array($ticket->ID())
1939
-        );
1940
-        foreach ($ticket_line_items as $ticket_line_item) {
1941
-            if (
1942
-                $ticket_line_item instanceof \EE_Line_Item
1943
-                && $ticket_line_item->OBJ_type() === 'Ticket'
1944
-                && $ticket_line_item->OBJ_ID() === $ticket->ID()
1945
-            ) {
1946
-                $line_item = $ticket_line_item;
1947
-                break;
1948
-            }
1949
-        }
1950
-        if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1951
-            throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1952
-        }
1953
-        return $line_item;
1954
-    }
1955
-
1956
-
1957
-    /**
1958
-     * Soft Deletes this model object.
1959
-     *
1960
-     * @return boolean | int
1961
-     * @throws RuntimeException
1962
-     * @throws EE_Error
1963
-     */
1964
-    public function delete()
1965
-    {
1966
-        if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1967
-            $this->set_status(EEM_Registration::status_id_cancelled);
1968
-        }
1969
-        return parent::delete();
1970
-    }
1971
-
1972
-
1973
-    /**
1974
-     * Restores whatever the previous status was on a registration before it was trashed (if possible)
1975
-     *
1976
-     * @throws EE_Error
1977
-     * @throws RuntimeException
1978
-     */
1979
-    public function restore()
1980
-    {
1981
-        $previous_status = $this->get_extra_meta(
1982
-            EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1983
-            true,
1984
-            EEM_Registration::status_id_cancelled
1985
-        );
1986
-        if ($previous_status) {
1987
-            $this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1988
-            $this->set_status($previous_status);
1989
-        }
1990
-        return parent::restore();
1991
-    }
1992
-
1993
-
1994
-    /**
1995
-     * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1996
-     *
1997
-     * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1998
-     *                                           depending on whether the reg status changes to or from "Approved"
1999
-     * @return boolean whether the Registration status was updated
2000
-     * @throws EE_Error
2001
-     * @throws RuntimeException
2002
-     */
2003
-    public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2004
-    {
2005
-        $paid = $this->paid();
2006
-        $price = $this->final_price();
2007
-        switch (true) {
2008
-            // overpaid or paid
2009
-            case EEH_Money::compare_floats($paid, $price, '>'):
2010
-            case EEH_Money::compare_floats($paid, $price):
2011
-                $new_status = EEM_Registration::status_id_approved;
2012
-                break;
2013
-            //  underpaid
2014
-            case EEH_Money::compare_floats($paid, $price, '<'):
2015
-                $new_status = EEM_Registration::status_id_pending_payment;
2016
-                break;
2017
-            // uhhh Houston...
2018
-            default:
2019
-                throw new RuntimeException(
2020
-                    esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2021
-                );
2022
-        }
2023
-        if ($new_status !== $this->status_ID()) {
2024
-            if ($trigger_set_status_logic) {
2025
-                return $this->set_status($new_status);
2026
-            }
2027
-            parent::set('STS_ID', $new_status);
2028
-            return true;
2029
-        }
2030
-        return false;
2031
-    }
2032
-
2033
-
2034
-    /*************************** DEPRECATED ***************************/
2035
-
2036
-
2037
-    /**
2038
-     * @deprecated
2039
-     * @since     4.7.0
2040
-     * @access    public
2041
-     */
2042
-    public function price_paid()
2043
-    {
2044
-        EE_Error::doing_it_wrong(
2045
-            'EE_Registration::price_paid()',
2046
-            esc_html__(
2047
-                'This method is deprecated, please use EE_Registration::final_price() instead.',
2048
-                'event_espresso'
2049
-            ),
2050
-            '4.7.0'
2051
-        );
2052
-        return $this->final_price();
2053
-    }
2054
-
2055
-
2056
-    /**
2057
-     * @deprecated
2058
-     * @since     4.7.0
2059
-     * @access    public
2060
-     * @param    float $REG_final_price
2061
-     * @throws EE_Error
2062
-     * @throws RuntimeException
2063
-     */
2064
-    public function set_price_paid($REG_final_price = 0.00)
2065
-    {
2066
-        EE_Error::doing_it_wrong(
2067
-            'EE_Registration::set_price_paid()',
2068
-            esc_html__(
2069
-                'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2070
-                'event_espresso'
2071
-            ),
2072
-            '4.7.0'
2073
-        );
2074
-        $this->set_final_price($REG_final_price);
2075
-    }
2076
-
2077
-
2078
-    /**
2079
-     * @deprecated
2080
-     * @since 4.7.0
2081
-     * @return string
2082
-     * @throws EE_Error
2083
-     */
2084
-    public function pretty_price_paid()
2085
-    {
2086
-        EE_Error::doing_it_wrong(
2087
-            'EE_Registration::pretty_price_paid()',
2088
-            esc_html__(
2089
-                'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2090
-                'event_espresso'
2091
-            ),
2092
-            '4.7.0'
2093
-        );
2094
-        return $this->pretty_final_price();
2095
-    }
2096
-
2097
-
2098
-    /**
2099
-     * Gets the primary datetime related to this registration via the related Event to this registration
2100
-     *
2101
-     * @deprecated 4.9.17
2102
-     * @return EE_Datetime
2103
-     * @throws EE_Error
2104
-     * @throws EntityNotFoundException
2105
-     */
2106
-    public function get_related_primary_datetime()
2107
-    {
2108
-        EE_Error::doing_it_wrong(
2109
-            __METHOD__,
2110
-            esc_html__(
2111
-                'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2112
-                'event_espresso'
2113
-            ),
2114
-            '4.9.17',
2115
-            '5.0.0'
2116
-        );
2117
-        return $this->event()->primary_datetime();
2118
-    }
2119
-
2120
-    /**
2121
-     * Returns the contact's name (or "Unknown" if there is no contact.)
2122
-     * @since 4.10.12.p
2123
-     * @return string
2124
-     * @throws EE_Error
2125
-     * @throws InvalidArgumentException
2126
-     * @throws InvalidDataTypeException
2127
-     * @throws InvalidInterfaceException
2128
-     * @throws ReflectionException
2129
-     */
2130
-    public function name()
2131
-    {
2132
-        return $this->attendeeName();
2133
-    }
21
+	/**
22
+	 * Used to reference when a registration has never been checked in.
23
+	 *
24
+	 * @deprecated use \EE_Checkin::status_checked_never instead
25
+	 * @type int
26
+	 */
27
+	const checkin_status_never = 2;
28
+
29
+	/**
30
+	 * Used to reference when a registration has been checked in.
31
+	 *
32
+	 * @deprecated use \EE_Checkin::status_checked_in instead
33
+	 * @type int
34
+	 */
35
+	const checkin_status_in = 1;
36
+
37
+
38
+	/**
39
+	 * Used to reference when a registration has been checked out.
40
+	 *
41
+	 * @deprecated use \EE_Checkin::status_checked_out instead
42
+	 * @type int
43
+	 */
44
+	const checkin_status_out = 0;
45
+
46
+
47
+	/**
48
+	 * extra meta key for tracking reg status os trashed registrations
49
+	 *
50
+	 * @type string
51
+	 */
52
+	const PRE_TRASH_REG_STATUS_KEY = 'pre_trash_registration_status';
53
+
54
+
55
+	/**
56
+	 * extra meta key for tracking if registration has reserved ticket
57
+	 *
58
+	 * @type string
59
+	 */
60
+	const HAS_RESERVED_TICKET_KEY = 'has_reserved_ticket';
61
+
62
+
63
+	/**
64
+	 * @param array  $props_n_values          incoming values
65
+	 * @param string $timezone                incoming timezone (if not set the timezone set for the website will be
66
+	 *                                        used.)
67
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
68
+	 *                                        date_format and the second value is the time format
69
+	 * @return EE_Registration
70
+	 * @throws EE_Error
71
+	 */
72
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
73
+	{
74
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
75
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
76
+	}
77
+
78
+
79
+	/**
80
+	 * @param array  $props_n_values  incoming values from the database
81
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
82
+	 *                                the website will be used.
83
+	 * @return EE_Registration
84
+	 */
85
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
86
+	{
87
+		return new self($props_n_values, true, $timezone);
88
+	}
89
+
90
+
91
+	/**
92
+	 *        Set Event ID
93
+	 *
94
+	 * @param        int $EVT_ID Event ID
95
+	 * @throws EE_Error
96
+	 * @throws RuntimeException
97
+	 */
98
+	public function set_event($EVT_ID = 0)
99
+	{
100
+		$this->set('EVT_ID', $EVT_ID);
101
+	}
102
+
103
+
104
+	/**
105
+	 * Overrides parent set() method so that all calls to set( 'REG_code', $REG_code ) OR set( 'STS_ID', $STS_ID ) can
106
+	 * be routed to internal methods
107
+	 *
108
+	 * @param string $field_name
109
+	 * @param mixed  $field_value
110
+	 * @param bool   $use_default
111
+	 * @throws EE_Error
112
+	 * @throws EntityNotFoundException
113
+	 * @throws InvalidArgumentException
114
+	 * @throws InvalidDataTypeException
115
+	 * @throws InvalidInterfaceException
116
+	 * @throws ReflectionException
117
+	 * @throws RuntimeException
118
+	 */
119
+	public function set($field_name, $field_value, $use_default = false)
120
+	{
121
+		switch ($field_name) {
122
+			case 'REG_code':
123
+				if (! empty($field_value) && $this->reg_code() === null) {
124
+					$this->set_reg_code($field_value, $use_default);
125
+				}
126
+				break;
127
+			case 'STS_ID':
128
+				$this->set_status($field_value, $use_default);
129
+				break;
130
+			default:
131
+				parent::set($field_name, $field_value, $use_default);
132
+		}
133
+	}
134
+
135
+
136
+	/**
137
+	 * Set Status ID
138
+	 * updates the registration status and ALSO...
139
+	 * calls reserve_registration_space() if the reg status changes TO approved from any other reg status
140
+	 * calls release_registration_space() if the reg status changes FROM approved to any other reg status
141
+	 *
142
+	 * @param string                $new_STS_ID
143
+	 * @param boolean               $use_default
144
+	 * @param ContextInterface|null $context
145
+	 * @return bool
146
+	 * @throws DomainException
147
+	 * @throws EE_Error
148
+	 * @throws EntityNotFoundException
149
+	 * @throws InvalidArgumentException
150
+	 * @throws InvalidDataTypeException
151
+	 * @throws InvalidInterfaceException
152
+	 * @throws ReflectionException
153
+	 * @throws RuntimeException
154
+	 * @throws UnexpectedEntityException
155
+	 */
156
+	public function set_status($new_STS_ID = null, $use_default = false, ContextInterface $context = null)
157
+	{
158
+		// get current REG_Status
159
+		$old_STS_ID = $this->status_ID();
160
+		// if status has changed
161
+		if (
162
+			$old_STS_ID !== $new_STS_ID // and that status has actually changed
163
+			&& ! empty($old_STS_ID) // and that old status is actually set
164
+			&& ! empty($new_STS_ID) // as well as the new status
165
+			&& $this->ID() // ensure registration is in the db
166
+		) {
167
+			// update internal status first
168
+			parent::set('STS_ID', $new_STS_ID, $use_default);
169
+			// THEN handle other changes that occur when reg status changes
170
+			// TO approved
171
+			if ($new_STS_ID === EEM_Registration::status_id_approved) {
172
+				// reserve a space by incrementing ticket and datetime sold values
173
+				$this->reserveRegistrationSpace();
174
+				do_action('AHEE__EE_Registration__set_status__to_approved', $this, $old_STS_ID, $new_STS_ID, $context);
175
+				// OR FROM  approved
176
+			} elseif ($old_STS_ID === EEM_Registration::status_id_approved) {
177
+				// release a space by decrementing ticket and datetime sold values
178
+				$this->releaseRegistrationSpace();
179
+				do_action(
180
+					'AHEE__EE_Registration__set_status__from_approved',
181
+					$this,
182
+					$old_STS_ID,
183
+					$new_STS_ID,
184
+					$context
185
+				);
186
+			}
187
+			// update status
188
+			parent::set('STS_ID', $new_STS_ID, $use_default);
189
+			$this->updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, $context);
190
+			if ($this->statusChangeUpdatesTransaction($context)) {
191
+				$this->updateTransactionAfterStatusChange();
192
+			}
193
+			do_action('AHEE__EE_Registration__set_status__after_update', $this, $old_STS_ID, $new_STS_ID, $context);
194
+			return true;
195
+		}
196
+		// even though the old value matches the new value, it's still good to
197
+		// allow the parent set method to have a say
198
+		parent::set('STS_ID', $new_STS_ID, $use_default);
199
+		return true;
200
+	}
201
+
202
+
203
+	/**
204
+	 * update REGs and TXN when cancelled or declined registrations involved
205
+	 *
206
+	 * @param string                $new_STS_ID
207
+	 * @param string                $old_STS_ID
208
+	 * @param ContextInterface|null $context
209
+	 * @throws EE_Error
210
+	 * @throws InvalidArgumentException
211
+	 * @throws InvalidDataTypeException
212
+	 * @throws InvalidInterfaceException
213
+	 * @throws ReflectionException
214
+	 * @throws RuntimeException
215
+	 */
216
+	private function updateIfCanceledOrReinstated($new_STS_ID, $old_STS_ID, ContextInterface $context = null)
217
+	{
218
+		// these reg statuses should not be considered in any calculations involving monies owing
219
+		$closed_reg_statuses = EEM_Registration::closed_reg_statuses();
220
+		// true if registration has been cancelled or declined
221
+		$this->updateIfCanceled(
222
+			$closed_reg_statuses,
223
+			$new_STS_ID,
224
+			$old_STS_ID,
225
+			$context
226
+		);
227
+		$this->updateIfReinstated(
228
+			$closed_reg_statuses,
229
+			$new_STS_ID,
230
+			$old_STS_ID,
231
+			$context
232
+		);
233
+	}
234
+
235
+
236
+	/**
237
+	 * update REGs and TXN when cancelled or declined registrations involved
238
+	 *
239
+	 * @param array                 $closed_reg_statuses
240
+	 * @param string                $new_STS_ID
241
+	 * @param string                $old_STS_ID
242
+	 * @param ContextInterface|null $context
243
+	 * @throws EE_Error
244
+	 * @throws InvalidArgumentException
245
+	 * @throws InvalidDataTypeException
246
+	 * @throws InvalidInterfaceException
247
+	 * @throws ReflectionException
248
+	 * @throws RuntimeException
249
+	 */
250
+	private function updateIfCanceled(
251
+		array $closed_reg_statuses,
252
+		$new_STS_ID,
253
+		$old_STS_ID,
254
+		ContextInterface $context = null
255
+	) {
256
+		// true if registration has been cancelled or declined
257
+		if (
258
+			in_array($new_STS_ID, $closed_reg_statuses, true)
259
+			&& ! in_array($old_STS_ID, $closed_reg_statuses, true)
260
+		) {
261
+			/** @type EE_Registration_Processor $registration_processor */
262
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
263
+			/** @type EE_Transaction_Processor $transaction_processor */
264
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
265
+			// cancelled or declined registration
266
+			$registration_processor->update_registration_after_being_canceled_or_declined(
267
+				$this,
268
+				$closed_reg_statuses
269
+			);
270
+			$transaction_processor->update_transaction_after_canceled_or_declined_registration(
271
+				$this,
272
+				$closed_reg_statuses,
273
+				false
274
+			);
275
+			do_action(
276
+				'AHEE__EE_Registration__set_status__canceled_or_declined',
277
+				$this,
278
+				$old_STS_ID,
279
+				$new_STS_ID,
280
+				$context
281
+			);
282
+			return;
283
+		}
284
+	}
285
+
286
+
287
+	/**
288
+	 * update REGs and TXN when cancelled or declined registrations involved
289
+	 *
290
+	 * @param array                 $closed_reg_statuses
291
+	 * @param string                $new_STS_ID
292
+	 * @param string                $old_STS_ID
293
+	 * @param ContextInterface|null $context
294
+	 * @throws EE_Error
295
+	 * @throws InvalidArgumentException
296
+	 * @throws InvalidDataTypeException
297
+	 * @throws InvalidInterfaceException
298
+	 * @throws ReflectionException
299
+	 */
300
+	private function updateIfReinstated(
301
+		array $closed_reg_statuses,
302
+		$new_STS_ID,
303
+		$old_STS_ID,
304
+		ContextInterface $context = null
305
+	) {
306
+		// true if reinstating cancelled or declined registration
307
+		if (
308
+			in_array($old_STS_ID, $closed_reg_statuses, true)
309
+			&& ! in_array($new_STS_ID, $closed_reg_statuses, true)
310
+		) {
311
+			/** @type EE_Registration_Processor $registration_processor */
312
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
313
+			/** @type EE_Transaction_Processor $transaction_processor */
314
+			$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
315
+			// reinstating cancelled or declined registration
316
+			$registration_processor->update_canceled_or_declined_registration_after_being_reinstated(
317
+				$this,
318
+				$closed_reg_statuses
319
+			);
320
+			$transaction_processor->update_transaction_after_reinstating_canceled_registration(
321
+				$this,
322
+				$closed_reg_statuses,
323
+				false
324
+			);
325
+			do_action(
326
+				'AHEE__EE_Registration__set_status__after_reinstated',
327
+				$this,
328
+				$old_STS_ID,
329
+				$new_STS_ID,
330
+				$context
331
+			);
332
+		}
333
+	}
334
+
335
+
336
+	/**
337
+	 * @param ContextInterface|null $context
338
+	 * @return bool
339
+	 */
340
+	private function statusChangeUpdatesTransaction(ContextInterface $context = null)
341
+	{
342
+		$contexts_that_do_not_update_transaction = (array) apply_filters(
343
+			'AHEE__EE_Registration__statusChangeUpdatesTransaction__contexts_that_do_not_update_transaction',
344
+			array('spco_reg_step_attendee_information_process_registrations'),
345
+			$context,
346
+			$this
347
+		);
348
+		return ! (
349
+			$context instanceof ContextInterface
350
+			&& in_array($context->slug(), $contexts_that_do_not_update_transaction, true)
351
+		);
352
+	}
353
+
354
+
355
+	/**
356
+	 * @throws EE_Error
357
+	 * @throws EntityNotFoundException
358
+	 * @throws InvalidArgumentException
359
+	 * @throws InvalidDataTypeException
360
+	 * @throws InvalidInterfaceException
361
+	 * @throws ReflectionException
362
+	 * @throws RuntimeException
363
+	 */
364
+	private function updateTransactionAfterStatusChange()
365
+	{
366
+		/** @type EE_Transaction_Payments $transaction_payments */
367
+		$transaction_payments = EE_Registry::instance()->load_class('Transaction_Payments');
368
+		$transaction_payments->recalculate_transaction_total($this->transaction(), false);
369
+		$this->transaction()->update_status_based_on_total_paid(true);
370
+	}
371
+
372
+
373
+	/**
374
+	 *        get Status ID
375
+	 */
376
+	public function status_ID()
377
+	{
378
+		return $this->get('STS_ID');
379
+	}
380
+
381
+
382
+	/**
383
+	 * Gets the ticket this registration is for
384
+	 *
385
+	 * @param boolean $include_archived whether to include archived tickets or not.
386
+	 *
387
+	 * @return EE_Ticket|EE_Base_Class
388
+	 * @throws EE_Error
389
+	 */
390
+	public function ticket($include_archived = true)
391
+	{
392
+		$query_params = array();
393
+		if ($include_archived) {
394
+			$query_params['default_where_conditions'] = 'none';
395
+		}
396
+		return $this->get_first_related('Ticket', $query_params);
397
+	}
398
+
399
+
400
+	/**
401
+	 * Gets the event this registration is for
402
+	 *
403
+	 * @return EE_Event
404
+	 * @throws EE_Error
405
+	 * @throws EntityNotFoundException
406
+	 */
407
+	public function event()
408
+	{
409
+		$event = $this->get_first_related('Event');
410
+		if (! $event instanceof \EE_Event) {
411
+			throw new EntityNotFoundException('Event ID', $this->event_ID());
412
+		}
413
+		return $event;
414
+	}
415
+
416
+
417
+	/**
418
+	 * Gets the "author" of the registration.  Note that for the purposes of registrations, the author will correspond
419
+	 * with the author of the event this registration is for.
420
+	 *
421
+	 * @since 4.5.0
422
+	 * @return int
423
+	 * @throws EE_Error
424
+	 * @throws EntityNotFoundException
425
+	 */
426
+	public function wp_user()
427
+	{
428
+		$event = $this->event();
429
+		if ($event instanceof EE_Event) {
430
+			return $event->wp_user();
431
+		}
432
+		return 0;
433
+	}
434
+
435
+
436
+	/**
437
+	 * increments this registration's related ticket sold and corresponding datetime sold values
438
+	 *
439
+	 * @return void
440
+	 * @throws DomainException
441
+	 * @throws EE_Error
442
+	 * @throws EntityNotFoundException
443
+	 * @throws InvalidArgumentException
444
+	 * @throws InvalidDataTypeException
445
+	 * @throws InvalidInterfaceException
446
+	 * @throws ReflectionException
447
+	 * @throws UnexpectedEntityException
448
+	 */
449
+	private function reserveRegistrationSpace()
450
+	{
451
+		// reserved ticket and datetime counts will be decremented as sold counts are incremented
452
+		// so stop tracking that this reg has a ticket reserved
453
+		$this->release_reserved_ticket(false, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
454
+		$ticket = $this->ticket();
455
+		$ticket->increaseSold();
456
+		// possibly set event status to sold out
457
+		$this->event()->perform_sold_out_status_check();
458
+	}
459
+
460
+
461
+	/**
462
+	 * decrements (subtracts) this registration's related ticket sold and corresponding datetime sold values
463
+	 *
464
+	 * @return void
465
+	 * @throws DomainException
466
+	 * @throws EE_Error
467
+	 * @throws EntityNotFoundException
468
+	 * @throws InvalidArgumentException
469
+	 * @throws InvalidDataTypeException
470
+	 * @throws InvalidInterfaceException
471
+	 * @throws ReflectionException
472
+	 * @throws UnexpectedEntityException
473
+	 */
474
+	private function releaseRegistrationSpace()
475
+	{
476
+		$ticket = $this->ticket();
477
+		$ticket->decreaseSold();
478
+		// possibly change event status from sold out back to previous status
479
+		$this->event()->perform_sold_out_status_check();
480
+	}
481
+
482
+
483
+	/**
484
+	 * tracks this registration's ticket reservation in extra meta
485
+	 * and can increment related ticket reserved and corresponding datetime reserved values
486
+	 *
487
+	 * @param bool $update_ticket if true, will increment ticket and datetime reserved count
488
+	 * @return void
489
+	 * @throws EE_Error
490
+	 * @throws InvalidArgumentException
491
+	 * @throws InvalidDataTypeException
492
+	 * @throws InvalidInterfaceException
493
+	 * @throws ReflectionException
494
+	 */
495
+	public function reserve_ticket($update_ticket = false, $source = 'unknown')
496
+	{
497
+		// only reserve ticket if space is not currently reserved
498
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) !== true) {
499
+			$this->update_extra_meta('reserve_ticket', "{$this->ticket_ID()} from {$source}");
500
+			// IMPORTANT !!!
501
+			// although checking $update_ticket first would be more efficient,
502
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
503
+			if (
504
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true)
505
+				&& $update_ticket
506
+			) {
507
+				$ticket = $this->ticket();
508
+				$ticket->increaseReserved(1, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
509
+				$ticket->save();
510
+			}
511
+		}
512
+	}
513
+
514
+
515
+	/**
516
+	 * stops tracking this registration's ticket reservation in extra meta
517
+	 * decrements (subtracts) related ticket reserved and corresponding datetime reserved values
518
+	 *
519
+	 * @param bool $update_ticket if true, will decrement ticket and datetime reserved count
520
+	 * @return void
521
+	 * @throws EE_Error
522
+	 * @throws InvalidArgumentException
523
+	 * @throws InvalidDataTypeException
524
+	 * @throws InvalidInterfaceException
525
+	 * @throws ReflectionException
526
+	 */
527
+	public function release_reserved_ticket($update_ticket = false, $source = 'unknown')
528
+	{
529
+		// only release ticket if space is currently reserved
530
+		if ((bool) $this->get_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, true) === true) {
531
+			$this->update_extra_meta('release_reserved_ticket', "{$this->ticket_ID()} from {$source}");
532
+			// IMPORTANT !!!
533
+			// although checking $update_ticket first would be more efficient,
534
+			// we NEED to ALWAYS call update_extra_meta(), which is why that is done first
535
+			if (
536
+				$this->update_extra_meta(EE_Registration::HAS_RESERVED_TICKET_KEY, false)
537
+				&& $update_ticket
538
+			) {
539
+				$ticket = $this->ticket();
540
+				$ticket->decreaseReserved(1, true, "REG: {$this->ID()} (ln:" . __LINE__ . ')');
541
+			}
542
+		}
543
+	}
544
+
545
+
546
+	/**
547
+	 * Set Attendee ID
548
+	 *
549
+	 * @param        int $ATT_ID Attendee ID
550
+	 * @throws EE_Error
551
+	 * @throws RuntimeException
552
+	 */
553
+	public function set_attendee_id($ATT_ID = 0)
554
+	{
555
+		$this->set('ATT_ID', $ATT_ID);
556
+	}
557
+
558
+
559
+	/**
560
+	 *        Set Transaction ID
561
+	 *
562
+	 * @param        int $TXN_ID Transaction ID
563
+	 * @throws EE_Error
564
+	 * @throws RuntimeException
565
+	 */
566
+	public function set_transaction_id($TXN_ID = 0)
567
+	{
568
+		$this->set('TXN_ID', $TXN_ID);
569
+	}
570
+
571
+
572
+	/**
573
+	 *        Set Session
574
+	 *
575
+	 * @param    string $REG_session PHP Session ID
576
+	 * @throws EE_Error
577
+	 * @throws RuntimeException
578
+	 */
579
+	public function set_session($REG_session = '')
580
+	{
581
+		$this->set('REG_session', $REG_session);
582
+	}
583
+
584
+
585
+	/**
586
+	 *        Set Registration URL Link
587
+	 *
588
+	 * @param    string $REG_url_link Registration URL Link
589
+	 * @throws EE_Error
590
+	 * @throws RuntimeException
591
+	 */
592
+	public function set_reg_url_link($REG_url_link = '')
593
+	{
594
+		$this->set('REG_url_link', $REG_url_link);
595
+	}
596
+
597
+
598
+	/**
599
+	 *        Set Attendee Counter
600
+	 *
601
+	 * @param        int $REG_count Primary Attendee
602
+	 * @throws EE_Error
603
+	 * @throws RuntimeException
604
+	 */
605
+	public function set_count($REG_count = 1)
606
+	{
607
+		$this->set('REG_count', $REG_count);
608
+	}
609
+
610
+
611
+	/**
612
+	 *        Set Group Size
613
+	 *
614
+	 * @param        boolean $REG_group_size Group Registration
615
+	 * @throws EE_Error
616
+	 * @throws RuntimeException
617
+	 */
618
+	public function set_group_size($REG_group_size = false)
619
+	{
620
+		$this->set('REG_group_size', $REG_group_size);
621
+	}
622
+
623
+
624
+	/**
625
+	 *    is_not_approved -  convenience method that returns TRUE if REG status ID ==
626
+	 *    EEM_Registration::status_id_not_approved
627
+	 *
628
+	 * @return        boolean
629
+	 */
630
+	public function is_not_approved()
631
+	{
632
+		return $this->status_ID() == EEM_Registration::status_id_not_approved ? true : false;
633
+	}
634
+
635
+
636
+	/**
637
+	 *    is_pending_payment -  convenience method that returns TRUE if REG status ID ==
638
+	 *    EEM_Registration::status_id_pending_payment
639
+	 *
640
+	 * @return        boolean
641
+	 */
642
+	public function is_pending_payment()
643
+	{
644
+		return $this->status_ID() == EEM_Registration::status_id_pending_payment ? true : false;
645
+	}
646
+
647
+
648
+	/**
649
+	 *    is_approved -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_approved
650
+	 *
651
+	 * @return        boolean
652
+	 */
653
+	public function is_approved()
654
+	{
655
+		return $this->status_ID() == EEM_Registration::status_id_approved ? true : false;
656
+	}
657
+
658
+
659
+	/**
660
+	 *    is_cancelled -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_cancelled
661
+	 *
662
+	 * @return        boolean
663
+	 */
664
+	public function is_cancelled()
665
+	{
666
+		return $this->status_ID() == EEM_Registration::status_id_cancelled ? true : false;
667
+	}
668
+
669
+
670
+	/**
671
+	 *    is_declined -  convenience method that returns TRUE if REG status ID == EEM_Registration::status_id_declined
672
+	 *
673
+	 * @return        boolean
674
+	 */
675
+	public function is_declined()
676
+	{
677
+		return $this->status_ID() == EEM_Registration::status_id_declined ? true : false;
678
+	}
679
+
680
+
681
+	/**
682
+	 *    is_incomplete -  convenience method that returns TRUE if REG status ID ==
683
+	 *    EEM_Registration::status_id_incomplete
684
+	 *
685
+	 * @return        boolean
686
+	 */
687
+	public function is_incomplete()
688
+	{
689
+		return $this->status_ID() == EEM_Registration::status_id_incomplete ? true : false;
690
+	}
691
+
692
+
693
+	/**
694
+	 *        Set Registration Date
695
+	 *
696
+	 * @param        mixed ( int or string ) $REG_date Registration Date - Unix timestamp or string representation of
697
+	 *                                                 Date
698
+	 * @throws EE_Error
699
+	 * @throws RuntimeException
700
+	 */
701
+	public function set_reg_date($REG_date = false)
702
+	{
703
+		$this->set('REG_date', $REG_date);
704
+	}
705
+
706
+
707
+	/**
708
+	 *    Set final price owing for this registration after all ticket/price modifications
709
+	 *
710
+	 * @access    public
711
+	 * @param    float $REG_final_price
712
+	 * @throws EE_Error
713
+	 * @throws RuntimeException
714
+	 */
715
+	public function set_final_price($REG_final_price = 0.00)
716
+	{
717
+		$this->set('REG_final_price', $REG_final_price);
718
+	}
719
+
720
+
721
+	/**
722
+	 *    Set amount paid towards this registration's final price
723
+	 *
724
+	 * @access    public
725
+	 * @param    float $REG_paid
726
+	 * @throws EE_Error
727
+	 * @throws RuntimeException
728
+	 */
729
+	public function set_paid($REG_paid = 0.00)
730
+	{
731
+		$this->set('REG_paid', $REG_paid);
732
+	}
733
+
734
+
735
+	/**
736
+	 *        Attendee Is Going
737
+	 *
738
+	 * @param        boolean $REG_att_is_going Attendee Is Going
739
+	 * @throws EE_Error
740
+	 * @throws RuntimeException
741
+	 */
742
+	public function set_att_is_going($REG_att_is_going = false)
743
+	{
744
+		$this->set('REG_att_is_going', $REG_att_is_going);
745
+	}
746
+
747
+
748
+	/**
749
+	 * Gets the related attendee
750
+	 *
751
+	 * @return EE_Attendee
752
+	 * @throws EE_Error
753
+	 */
754
+	public function attendee()
755
+	{
756
+		return $this->get_first_related('Attendee');
757
+	}
758
+
759
+	/**
760
+	 * Gets the name of the attendee.
761
+	 * @since 4.10.12.p
762
+	 * @param bool $apply_html_entities set to true if you want to use HTML entities.
763
+	 * @return string
764
+	 * @throws EE_Error
765
+	 * @throws InvalidArgumentException
766
+	 * @throws InvalidDataTypeException
767
+	 * @throws InvalidInterfaceException
768
+	 * @throws ReflectionException
769
+	 */
770
+	public function attendeeName($apply_html_entities = false)
771
+	{
772
+		$attendee = $this->get_first_related('Attendee');
773
+		if ($attendee instanceof EE_Attendee) {
774
+			$attendee_name = $attendee->full_name($apply_html_entities);
775
+		} else {
776
+			$attendee_name = esc_html__('Unknown', 'event_espresso');
777
+		}
778
+		return $attendee_name;
779
+	}
780
+
781
+
782
+	/**
783
+	 *        get Event ID
784
+	 */
785
+	public function event_ID()
786
+	{
787
+		return $this->get('EVT_ID');
788
+	}
789
+
790
+
791
+	/**
792
+	 *        get Event ID
793
+	 */
794
+	public function event_name()
795
+	{
796
+		$event = $this->event_obj();
797
+		if ($event) {
798
+			return $event->name();
799
+		} else {
800
+			return null;
801
+		}
802
+	}
803
+
804
+
805
+	/**
806
+	 * Fetches the event this registration is for
807
+	 *
808
+	 * @return EE_Event
809
+	 * @throws EE_Error
810
+	 */
811
+	public function event_obj()
812
+	{
813
+		return $this->get_first_related('Event');
814
+	}
815
+
816
+
817
+	/**
818
+	 *        get Attendee ID
819
+	 */
820
+	public function attendee_ID()
821
+	{
822
+		return $this->get('ATT_ID');
823
+	}
824
+
825
+
826
+	/**
827
+	 *        get PHP Session ID
828
+	 */
829
+	public function session_ID()
830
+	{
831
+		return $this->get('REG_session');
832
+	}
833
+
834
+
835
+	/**
836
+	 * Gets the string which represents the URL trigger for the receipt template in the message template system.
837
+	 *
838
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
839
+	 * @return string
840
+	 */
841
+	public function receipt_url($messenger = 'html')
842
+	{
843
+
844
+		/**
845
+		 * The below will be deprecated one version after this.  We check first if there is a custom receipt template
846
+		 * already in use on old system.  If there is then we just return the standard url for it.
847
+		 *
848
+		 * @since 4.5.0
849
+		 */
850
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/receipt_body.template.php';
851
+		$has_custom = EEH_Template::locate_template(
852
+			$template_relative_path,
853
+			array(),
854
+			true,
855
+			true,
856
+			true
857
+		);
858
+
859
+		if ($has_custom) {
860
+			return add_query_arg(array('receipt' => 'true'), $this->invoice_url('launch'));
861
+		}
862
+		return apply_filters('FHEE__EE_Registration__receipt_url__receipt_url', '', $this, $messenger, 'receipt');
863
+	}
864
+
865
+
866
+	/**
867
+	 * Gets the string which represents the URL trigger for the invoice template in the message template system.
868
+	 *
869
+	 * @param string $messenger 'pdf' or 'html'.  Default 'html'.
870
+	 * @return string
871
+	 * @throws EE_Error
872
+	 */
873
+	public function invoice_url($messenger = 'html')
874
+	{
875
+		/**
876
+		 * The below will be deprecated one version after this.  We check first if there is a custom invoice template
877
+		 * already in use on old system.  If there is then we just return the standard url for it.
878
+		 *
879
+		 * @since 4.5.0
880
+		 */
881
+		$template_relative_path = 'modules/gateways/Invoice/lib/templates/invoice_body.template.php';
882
+		$has_custom = EEH_Template::locate_template(
883
+			$template_relative_path,
884
+			array(),
885
+			true,
886
+			true,
887
+			true
888
+		);
889
+
890
+		if ($has_custom) {
891
+			if ($messenger == 'html') {
892
+				return $this->invoice_url('launch');
893
+			}
894
+			$route = $messenger == 'download' || $messenger == 'pdf' ? 'download_invoice' : 'launch_invoice';
895
+
896
+			$query_args = array('ee' => $route, 'id' => $this->reg_url_link());
897
+			if ($messenger == 'html') {
898
+				$query_args['html'] = true;
899
+			}
900
+			return add_query_arg($query_args, get_permalink(EE_Registry::instance()->CFG->core->thank_you_page_id));
901
+		}
902
+		return apply_filters('FHEE__EE_Registration__invoice_url__invoice_url', '', $this, $messenger, 'invoice');
903
+	}
904
+
905
+
906
+	/**
907
+	 * get Registration URL Link
908
+	 *
909
+	 * @access public
910
+	 * @return string
911
+	 * @throws EE_Error
912
+	 */
913
+	public function reg_url_link()
914
+	{
915
+		return (string) $this->get('REG_url_link');
916
+	}
917
+
918
+
919
+	/**
920
+	 * Echoes out invoice_url()
921
+	 *
922
+	 * @param string $type 'download','launch', or 'html' (default is 'launch')
923
+	 * @return void
924
+	 * @throws EE_Error
925
+	 */
926
+	public function e_invoice_url($type = 'launch')
927
+	{
928
+		echo esc_url_raw($this->invoice_url($type));
929
+	}
930
+
931
+
932
+	/**
933
+	 * Echoes out payment_overview_url
934
+	 */
935
+	public function e_payment_overview_url()
936
+	{
937
+		echo esc_url_raw($this->payment_overview_url());
938
+	}
939
+
940
+
941
+	/**
942
+	 * Gets the URL for the checkout payment options reg step
943
+	 * with this registration's REG_url_link added as a query parameter
944
+	 *
945
+	 * @param bool $clear_session Set to true when you want to clear the session on revisiting the
946
+	 *                            payment overview url.
947
+	 * @return string
948
+	 * @throws InvalidInterfaceException
949
+	 * @throws InvalidDataTypeException
950
+	 * @throws EE_Error
951
+	 * @throws InvalidArgumentException
952
+	 */
953
+	public function payment_overview_url($clear_session = false)
954
+	{
955
+		return add_query_arg(
956
+			(array) apply_filters(
957
+				'FHEE__EE_Registration__payment_overview_url__query_args',
958
+				array(
959
+					'e_reg_url_link' => $this->reg_url_link(),
960
+					'step'           => 'payment_options',
961
+					'revisit'        => true,
962
+					'clear_session'  => (bool) $clear_session,
963
+				),
964
+				$this
965
+			),
966
+			EE_Registry::instance()->CFG->core->reg_page_url()
967
+		);
968
+	}
969
+
970
+
971
+	/**
972
+	 * Gets the URL for the checkout attendee information reg step
973
+	 * with this registration's REG_url_link added as a query parameter
974
+	 *
975
+	 * @return string
976
+	 * @throws InvalidInterfaceException
977
+	 * @throws InvalidDataTypeException
978
+	 * @throws EE_Error
979
+	 * @throws InvalidArgumentException
980
+	 */
981
+	public function edit_attendee_information_url()
982
+	{
983
+		return add_query_arg(
984
+			(array) apply_filters(
985
+				'FHEE__EE_Registration__edit_attendee_information_url__query_args',
986
+				array(
987
+					'e_reg_url_link' => $this->reg_url_link(),
988
+					'step'           => 'attendee_information',
989
+					'revisit'        => true,
990
+				),
991
+				$this
992
+			),
993
+			EE_Registry::instance()->CFG->core->reg_page_url()
994
+		);
995
+	}
996
+
997
+
998
+	/**
999
+	 * Simply generates and returns the appropriate admin_url link to edit this registration
1000
+	 *
1001
+	 * @return string
1002
+	 * @throws EE_Error
1003
+	 */
1004
+	public function get_admin_edit_url()
1005
+	{
1006
+		return EEH_URL::add_query_args_and_nonce(
1007
+			array(
1008
+				'page'    => 'espresso_registrations',
1009
+				'action'  => 'view_registration',
1010
+				'_REG_ID' => $this->ID(),
1011
+			),
1012
+			admin_url('admin.php')
1013
+		);
1014
+	}
1015
+
1016
+
1017
+	/**
1018
+	 *    is_primary_registrant?
1019
+	 */
1020
+	public function is_primary_registrant()
1021
+	{
1022
+		return $this->get('REG_count') === 1 ? true : false;
1023
+	}
1024
+
1025
+
1026
+	/**
1027
+	 * This returns the primary registration object for this registration group (which may be this object).
1028
+	 *
1029
+	 * @return EE_Registration
1030
+	 * @throws EE_Error
1031
+	 */
1032
+	public function get_primary_registration()
1033
+	{
1034
+		if ($this->is_primary_registrant()) {
1035
+			return $this;
1036
+		}
1037
+
1038
+		// k reg_count !== 1 so let's get the EE_Registration object matching this txn_id and reg_count == 1
1039
+		/** @var EE_Registration $primary_registrant */
1040
+		$primary_registrant = EEM_Registration::instance()->get_one(
1041
+			array(
1042
+				array(
1043
+					'TXN_ID'    => $this->transaction_ID(),
1044
+					'REG_count' => 1,
1045
+				),
1046
+			)
1047
+		);
1048
+		return $primary_registrant;
1049
+	}
1050
+
1051
+
1052
+	/**
1053
+	 *        get  Attendee Number
1054
+	 *
1055
+	 * @access        public
1056
+	 */
1057
+	public function count()
1058
+	{
1059
+		return $this->get('REG_count');
1060
+	}
1061
+
1062
+
1063
+	/**
1064
+	 *        get Group Size
1065
+	 */
1066
+	public function group_size()
1067
+	{
1068
+		return $this->get('REG_group_size');
1069
+	}
1070
+
1071
+
1072
+	/**
1073
+	 *        get Registration Date
1074
+	 */
1075
+	public function date()
1076
+	{
1077
+		return $this->get('REG_date');
1078
+	}
1079
+
1080
+
1081
+	/**
1082
+	 * gets a pretty date
1083
+	 *
1084
+	 * @param string $date_format
1085
+	 * @param string $time_format
1086
+	 * @return string
1087
+	 * @throws EE_Error
1088
+	 */
1089
+	public function pretty_date($date_format = null, $time_format = null)
1090
+	{
1091
+		return $this->get_datetime('REG_date', $date_format, $time_format);
1092
+	}
1093
+
1094
+
1095
+	/**
1096
+	 * final_price
1097
+	 * the registration's share of the transaction total, so that the
1098
+	 * sum of all the transaction's REG_final_prices equal the transaction's total
1099
+	 *
1100
+	 * @return float
1101
+	 * @throws EE_Error
1102
+	 */
1103
+	public function final_price()
1104
+	{
1105
+		return $this->get('REG_final_price');
1106
+	}
1107
+
1108
+
1109
+	/**
1110
+	 * pretty_final_price
1111
+	 *  final price as formatted string, with correct decimal places and currency symbol
1112
+	 *
1113
+	 * @return string
1114
+	 * @throws EE_Error
1115
+	 */
1116
+	public function pretty_final_price()
1117
+	{
1118
+		return $this->get_pretty('REG_final_price');
1119
+	}
1120
+
1121
+
1122
+	/**
1123
+	 * get paid (yeah)
1124
+	 *
1125
+	 * @return float
1126
+	 * @throws EE_Error
1127
+	 */
1128
+	public function paid()
1129
+	{
1130
+		return $this->get('REG_paid');
1131
+	}
1132
+
1133
+
1134
+	/**
1135
+	 * pretty_paid
1136
+	 *
1137
+	 * @return float
1138
+	 * @throws EE_Error
1139
+	 */
1140
+	public function pretty_paid()
1141
+	{
1142
+		return $this->get_pretty('REG_paid');
1143
+	}
1144
+
1145
+
1146
+	/**
1147
+	 * owes_monies_and_can_pay
1148
+	 * whether or not this registration has monies owing and it's' status allows payment
1149
+	 *
1150
+	 * @param array $requires_payment
1151
+	 * @return bool
1152
+	 * @throws EE_Error
1153
+	 */
1154
+	public function owes_monies_and_can_pay($requires_payment = array())
1155
+	{
1156
+		// these reg statuses require payment (if event is not free)
1157
+		$requires_payment = ! empty($requires_payment)
1158
+			? $requires_payment
1159
+			: EEM_Registration::reg_statuses_that_allow_payment();
1160
+		if (
1161
+			in_array($this->status_ID(), $requires_payment) &&
1162
+			$this->final_price() != 0 &&
1163
+			$this->final_price() != $this->paid()
1164
+		) {
1165
+			return true;
1166
+		} else {
1167
+			return false;
1168
+		}
1169
+	}
1170
+
1171
+
1172
+	/**
1173
+	 * Prints out the return value of $this->pretty_status()
1174
+	 *
1175
+	 * @param bool $show_icons
1176
+	 * @return void
1177
+	 * @throws EE_Error
1178
+	 */
1179
+	public function e_pretty_status($show_icons = false)
1180
+	{
1181
+		echo wp_kses($this->pretty_status($show_icons), AllowedTags::getAllowedTags());
1182
+	}
1183
+
1184
+
1185
+	/**
1186
+	 * Returns a nice version of the status for displaying to customers
1187
+	 *
1188
+	 * @param bool $show_icons
1189
+	 * @return string
1190
+	 * @throws EE_Error
1191
+	 */
1192
+	public function pretty_status($show_icons = false)
1193
+	{
1194
+		$status = EEM_Status::instance()->localized_status(
1195
+			array($this->status_ID() => esc_html__('unknown', 'event_espresso')),
1196
+			false,
1197
+			'sentence'
1198
+		);
1199
+		$icon = '';
1200
+		switch ($this->status_ID()) {
1201
+			case EEM_Registration::status_id_approved:
1202
+				$icon = $show_icons
1203
+					? '<span class="dashicons dashicons-star-filled ee-icon-size-16 green-text"></span>'
1204
+					: '';
1205
+				break;
1206
+			case EEM_Registration::status_id_pending_payment:
1207
+				$icon = $show_icons
1208
+					? '<span class="dashicons dashicons-star-half ee-icon-size-16 orange-text"></span>'
1209
+					: '';
1210
+				break;
1211
+			case EEM_Registration::status_id_not_approved:
1212
+				$icon = $show_icons
1213
+					? '<span class="dashicons dashicons-marker ee-icon-size-16 orange-text"></span>'
1214
+					: '';
1215
+				break;
1216
+			case EEM_Registration::status_id_cancelled:
1217
+				$icon = $show_icons
1218
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-grey-text"></span>'
1219
+					: '';
1220
+				break;
1221
+			case EEM_Registration::status_id_incomplete:
1222
+				$icon = $show_icons
1223
+					? '<span class="dashicons dashicons-no ee-icon-size-16 lt-orange-text"></span>'
1224
+					: '';
1225
+				break;
1226
+			case EEM_Registration::status_id_declined:
1227
+				$icon = $show_icons
1228
+					? '<span class="dashicons dashicons-no ee-icon-size-16 red-text"></span>'
1229
+					: '';
1230
+				break;
1231
+			case EEM_Registration::status_id_wait_list:
1232
+				$icon = $show_icons
1233
+					? '<span class="dashicons dashicons-clipboard ee-icon-size-16 purple-text"></span>'
1234
+					: '';
1235
+				break;
1236
+		}
1237
+		return $icon . $status[ $this->status_ID() ];
1238
+	}
1239
+
1240
+
1241
+	/**
1242
+	 *        get Attendee Is Going
1243
+	 */
1244
+	public function att_is_going()
1245
+	{
1246
+		return $this->get('REG_att_is_going');
1247
+	}
1248
+
1249
+
1250
+	/**
1251
+	 * Gets related answers
1252
+	 *
1253
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1254
+	 * @return EE_Answer[]
1255
+	 * @throws EE_Error
1256
+	 */
1257
+	public function answers($query_params = null)
1258
+	{
1259
+		return $this->get_many_related('Answer', $query_params);
1260
+	}
1261
+
1262
+
1263
+	/**
1264
+	 * Gets the registration's answer value to the specified question
1265
+	 * (either the question's ID or a question object)
1266
+	 *
1267
+	 * @param EE_Question|int $question
1268
+	 * @param bool            $pretty_value
1269
+	 * @return array|string if pretty_value= true, the result will always be a string
1270
+	 * (because the answer might be an array of answer values, so passing pretty_value=true
1271
+	 * will convert it into some kind of string)
1272
+	 * @throws EE_Error
1273
+	 */
1274
+	public function answer_value_to_question($question, $pretty_value = true)
1275
+	{
1276
+		$question_id = EEM_Question::instance()->ensure_is_ID($question);
1277
+		return EEM_Answer::instance()->get_answer_value_to_question($this, $question_id, $pretty_value);
1278
+	}
1279
+
1280
+
1281
+	/**
1282
+	 * question_groups
1283
+	 * returns an array of EE_Question_Group objects for this registration
1284
+	 *
1285
+	 * @return EE_Question_Group[]
1286
+	 * @throws EE_Error
1287
+	 * @throws InvalidArgumentException
1288
+	 * @throws InvalidDataTypeException
1289
+	 * @throws InvalidInterfaceException
1290
+	 * @throws ReflectionException
1291
+	 */
1292
+	public function question_groups()
1293
+	{
1294
+		return EEM_Event::instance()->get_question_groups_for_event($this->event_ID(), $this);
1295
+	}
1296
+
1297
+
1298
+	/**
1299
+	 * count_question_groups
1300
+	 * returns a count of the number of EE_Question_Group objects for this registration
1301
+	 *
1302
+	 * @return int
1303
+	 * @throws EE_Error
1304
+	 * @throws EntityNotFoundException
1305
+	 * @throws InvalidArgumentException
1306
+	 * @throws InvalidDataTypeException
1307
+	 * @throws InvalidInterfaceException
1308
+	 * @throws ReflectionException
1309
+	 */
1310
+	public function count_question_groups()
1311
+	{
1312
+		return EEM_Event::instance()->count_related(
1313
+			$this->event_ID(),
1314
+			'Question_Group',
1315
+			[
1316
+				[
1317
+					'Event_Question_Group.'
1318
+					. EEM_Event_Question_Group::instance()->fieldNameForContext($this->is_primary_registrant()) => true,
1319
+				]
1320
+			]
1321
+		);
1322
+	}
1323
+
1324
+
1325
+	/**
1326
+	 * Returns the registration date in the 'standard' string format
1327
+	 * (function may be improved in the future to allow for different formats and timezones)
1328
+	 *
1329
+	 * @return string
1330
+	 * @throws EE_Error
1331
+	 */
1332
+	public function reg_date()
1333
+	{
1334
+		return $this->get_datetime('REG_date');
1335
+	}
1336
+
1337
+
1338
+	/**
1339
+	 * Gets the datetime-ticket for this registration (ie, it can be used to isolate
1340
+	 * the ticket this registration purchased, or the datetime they have registered
1341
+	 * to attend)
1342
+	 *
1343
+	 * @return EE_Datetime_Ticket
1344
+	 * @throws EE_Error
1345
+	 */
1346
+	public function datetime_ticket()
1347
+	{
1348
+		return $this->get_first_related('Datetime_Ticket');
1349
+	}
1350
+
1351
+
1352
+	/**
1353
+	 * Sets the registration's datetime_ticket.
1354
+	 *
1355
+	 * @param EE_Datetime_Ticket $datetime_ticket
1356
+	 * @return EE_Datetime_Ticket
1357
+	 * @throws EE_Error
1358
+	 */
1359
+	public function set_datetime_ticket($datetime_ticket)
1360
+	{
1361
+		return $this->_add_relation_to($datetime_ticket, 'Datetime_Ticket');
1362
+	}
1363
+
1364
+	/**
1365
+	 * Gets deleted
1366
+	 *
1367
+	 * @return bool
1368
+	 * @throws EE_Error
1369
+	 */
1370
+	public function deleted()
1371
+	{
1372
+		return $this->get('REG_deleted');
1373
+	}
1374
+
1375
+	/**
1376
+	 * Sets deleted
1377
+	 *
1378
+	 * @param boolean $deleted
1379
+	 * @return bool
1380
+	 * @throws EE_Error
1381
+	 * @throws RuntimeException
1382
+	 */
1383
+	public function set_deleted($deleted)
1384
+	{
1385
+		if ($deleted) {
1386
+			$this->delete();
1387
+		} else {
1388
+			$this->restore();
1389
+		}
1390
+	}
1391
+
1392
+
1393
+	/**
1394
+	 * Get the status object of this object
1395
+	 *
1396
+	 * @return EE_Status
1397
+	 * @throws EE_Error
1398
+	 */
1399
+	public function status_obj()
1400
+	{
1401
+		return $this->get_first_related('Status');
1402
+	}
1403
+
1404
+
1405
+	/**
1406
+	 * Returns the number of times this registration has checked into any of the datetimes
1407
+	 * its available for
1408
+	 *
1409
+	 * @return int
1410
+	 * @throws EE_Error
1411
+	 */
1412
+	public function count_checkins()
1413
+	{
1414
+		return $this->get_model()->count_related($this, 'Checkin');
1415
+	}
1416
+
1417
+
1418
+	/**
1419
+	 * Returns the number of current Check-ins this registration is checked into for any of the datetimes the
1420
+	 * registration is for.  Note, this is ONLY checked in (does not include checkedout)
1421
+	 *
1422
+	 * @return int
1423
+	 * @throws EE_Error
1424
+	 */
1425
+	public function count_checkins_not_checkedout()
1426
+	{
1427
+		return $this->get_model()->count_related($this, 'Checkin', array(array('CHK_in' => 1)));
1428
+	}
1429
+
1430
+
1431
+	/**
1432
+	 * The purpose of this method is simply to check whether this registration can checkin to the given datetime.
1433
+	 *
1434
+	 * @param int | EE_Datetime $DTT_OR_ID      The datetime the registration is being checked against
1435
+	 * @param bool              $check_approved This is used to indicate whether the caller wants can_checkin to also
1436
+	 *                                          consider registration status as well as datetime access.
1437
+	 * @return bool
1438
+	 * @throws EE_Error
1439
+	 */
1440
+	public function can_checkin($DTT_OR_ID, $check_approved = true)
1441
+	{
1442
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1443
+
1444
+		// first check registration status
1445
+		if (($check_approved && ! $this->is_approved()) || ! $DTT_ID) {
1446
+			return false;
1447
+		}
1448
+		// is there a datetime ticket that matches this dtt_ID?
1449
+		if (
1450
+			! (EEM_Datetime_Ticket::instance()->exists(
1451
+				array(
1452
+				array(
1453
+					'TKT_ID' => $this->get('TKT_ID'),
1454
+					'DTT_ID' => $DTT_ID,
1455
+				),
1456
+				)
1457
+			))
1458
+		) {
1459
+			return false;
1460
+		}
1461
+
1462
+		// final check is against TKT_uses
1463
+		return $this->verify_can_checkin_against_TKT_uses($DTT_ID);
1464
+	}
1465
+
1466
+
1467
+	/**
1468
+	 * This method verifies whether the user can checkin for the given datetime considering the max uses value set on
1469
+	 * the ticket. To do this,  a query is done to get the count of the datetime records already checked into.  If the
1470
+	 * datetime given does not have a check-in record and checking in for that datetime will exceed the allowed uses,
1471
+	 * then return false.  Otherwise return true.
1472
+	 *
1473
+	 * @param int | EE_Datetime $DTT_OR_ID The datetime the registration is being checked against
1474
+	 * @return bool true means can checkin.  false means cannot checkin.
1475
+	 * @throws EE_Error
1476
+	 */
1477
+	public function verify_can_checkin_against_TKT_uses($DTT_OR_ID)
1478
+	{
1479
+		$DTT_ID = EEM_Datetime::instance()->ensure_is_ID($DTT_OR_ID);
1480
+
1481
+		if (! $DTT_ID) {
1482
+			return false;
1483
+		}
1484
+
1485
+		$max_uses = $this->ticket() instanceof EE_Ticket ? $this->ticket()->uses() : EE_INF;
1486
+
1487
+		// if max uses is not set or equals infinity then return true cause its not a factor for whether user can
1488
+		// check-in or not.
1489
+		if (! $max_uses || $max_uses === EE_INF) {
1490
+			return true;
1491
+		}
1492
+
1493
+		// does this datetime have a checkin record?  If so, then the dtt count has already been verified so we can just
1494
+		// go ahead and toggle.
1495
+		if (EEM_Checkin::instance()->exists(array(array('REG_ID' => $this->ID(), 'DTT_ID' => $DTT_ID)))) {
1496
+			return true;
1497
+		}
1498
+
1499
+		// made it here so the last check is whether the number of checkins per unique datetime on this registration
1500
+		// disallows further check-ins.
1501
+		$count_unique_dtt_checkins = EEM_Checkin::instance()->count(
1502
+			array(
1503
+				array(
1504
+					'REG_ID' => $this->ID(),
1505
+					'CHK_in' => true,
1506
+				),
1507
+			),
1508
+			'DTT_ID',
1509
+			true
1510
+		);
1511
+		// checkins have already reached their max number of uses
1512
+		// so registrant can NOT checkin
1513
+		if ($count_unique_dtt_checkins >= $max_uses) {
1514
+			EE_Error::add_error(
1515
+				esc_html__(
1516
+					'Check-in denied because number of datetime uses for the ticket has been reached or exceeded.',
1517
+					'event_espresso'
1518
+				),
1519
+				__FILE__,
1520
+				__FUNCTION__,
1521
+				__LINE__
1522
+			);
1523
+			return false;
1524
+		}
1525
+		return true;
1526
+	}
1527
+
1528
+
1529
+	/**
1530
+	 * toggle Check-in status for this registration
1531
+	 * Check-ins are toggled in the following order:
1532
+	 * never checked in -> checked in
1533
+	 * checked in -> checked out
1534
+	 * checked out -> checked in
1535
+	 *
1536
+	 * @param  int $DTT_ID  include specific datetime to toggle Check-in for.
1537
+	 *                      If not included or null, then it is assumed latest datetime is being toggled.
1538
+	 * @param bool $verify  If true then can_checkin() is used to verify whether the person
1539
+	 *                      can be checked in or not.  Otherwise this forces change in checkin status.
1540
+	 * @return bool|int     the chk_in status toggled to OR false if nothing got changed.
1541
+	 * @throws EE_Error
1542
+	 */
1543
+	public function toggle_checkin_status($DTT_ID = null, $verify = false)
1544
+	{
1545
+		if (empty($DTT_ID)) {
1546
+			$datetime = $this->get_latest_related_datetime();
1547
+			$DTT_ID = $datetime instanceof EE_Datetime ? $datetime->ID() : 0;
1548
+			// verify the registration can checkin for the given DTT_ID
1549
+		} elseif (! $this->can_checkin($DTT_ID, $verify)) {
1550
+			EE_Error::add_error(
1551
+				sprintf(
1552
+					esc_html__(
1553
+						'The given registration (ID:%1$d) can not be checked in to the given DTT_ID (%2$d), because the registration does not have access',
1554
+						'event_espresso'
1555
+					),
1556
+					$this->ID(),
1557
+					$DTT_ID
1558
+				),
1559
+				__FILE__,
1560
+				__FUNCTION__,
1561
+				__LINE__
1562
+			);
1563
+			return false;
1564
+		}
1565
+		$status_paths = array(
1566
+			EE_Checkin::status_checked_never => EE_Checkin::status_checked_in,
1567
+			EE_Checkin::status_checked_in    => EE_Checkin::status_checked_out,
1568
+			EE_Checkin::status_checked_out   => EE_Checkin::status_checked_in,
1569
+		);
1570
+		// start by getting the current status so we know what status we'll be changing to.
1571
+		$cur_status = $this->check_in_status_for_datetime($DTT_ID, null);
1572
+		$status_to = $status_paths[ $cur_status ];
1573
+		// database only records true for checked IN or false for checked OUT
1574
+		// no record ( null ) means checked in NEVER, but we obviously don't save that
1575
+		$new_status = $status_to === EE_Checkin::status_checked_in ? true : false;
1576
+		// add relation - note Check-ins are always creating new rows
1577
+		// because we are keeping track of Check-ins over time.
1578
+		// Eventually we'll probably want to show a list table
1579
+		// for the individual Check-ins so that they can be managed.
1580
+		$checkin = EE_Checkin::new_instance(
1581
+			array(
1582
+				'REG_ID' => $this->ID(),
1583
+				'DTT_ID' => $DTT_ID,
1584
+				'CHK_in' => $new_status,
1585
+			)
1586
+		);
1587
+		// if the record could not be saved then return false
1588
+		if ($checkin->save() === 0) {
1589
+			if (WP_DEBUG) {
1590
+				global $wpdb;
1591
+				$error = sprintf(
1592
+					esc_html__(
1593
+						'Registration check in update failed because of the following database error: %1$s%2$s',
1594
+						'event_espresso'
1595
+					),
1596
+					'<br />',
1597
+					$wpdb->last_error
1598
+				);
1599
+			} else {
1600
+				$error = esc_html__(
1601
+					'Registration check in update failed because of an unknown database error',
1602
+					'event_espresso'
1603
+				);
1604
+			}
1605
+			EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
1606
+			return false;
1607
+		}
1608
+		// Fire a checked_in and checkout_out action.
1609
+		$checked_status = $status_to === EE_Checkin::status_checked_in ? 'checked_in' : 'checked_out';
1610
+		do_action("AHEE__EE_Registration__toggle_checkin_status__{$checked_status}", $this, $DTT_ID);
1611
+		return $status_to;
1612
+	}
1613
+
1614
+
1615
+	/**
1616
+	 * Returns the latest datetime related to this registration (via the ticket attached to the registration).
1617
+	 * "Latest" is defined by the `DTT_EVT_start` column.
1618
+	 *
1619
+	 * @return EE_Datetime|null
1620
+	 * @throws EE_Error
1621
+	 */
1622
+	public function get_latest_related_datetime()
1623
+	{
1624
+		return EEM_Datetime::instance()->get_one(
1625
+			array(
1626
+				array(
1627
+					'Ticket.Registration.REG_ID' => $this->ID(),
1628
+				),
1629
+				'order_by' => array('DTT_EVT_start' => 'DESC'),
1630
+			)
1631
+		);
1632
+	}
1633
+
1634
+
1635
+	/**
1636
+	 * Returns the earliest datetime related to this registration (via the ticket attached to the registration).
1637
+	 * "Earliest" is defined by the `DTT_EVT_start` column.
1638
+	 *
1639
+	 * @throws EE_Error
1640
+	 */
1641
+	public function get_earliest_related_datetime()
1642
+	{
1643
+		return EEM_Datetime::instance()->get_one(
1644
+			array(
1645
+				array(
1646
+					'Ticket.Registration.REG_ID' => $this->ID(),
1647
+				),
1648
+				'order_by' => array('DTT_EVT_start' => 'ASC'),
1649
+			)
1650
+		);
1651
+	}
1652
+
1653
+
1654
+	/**
1655
+	 * This method simply returns the check-in status for this registration and the given datetime.
1656
+	 * If neither the datetime nor the checkin values are provided as arguments,
1657
+	 * then this will return the LATEST check-in status for the registration across all datetimes it belongs to.
1658
+	 *
1659
+	 * @param  int       $DTT_ID  The ID of the datetime we're checking against
1660
+	 *                            (if empty we'll get the primary datetime for
1661
+	 *                            this registration (via event) and use it's ID);
1662
+	 * @param EE_Checkin $checkin If present, we use the given checkin object rather than the dtt_id.
1663
+	 *
1664
+	 * @return int                Integer representing Check-in status.
1665
+	 * @throws EE_Error
1666
+	 */
1667
+	public function check_in_status_for_datetime($DTT_ID = 0, $checkin = null)
1668
+	{
1669
+		$checkin_query_params = array(
1670
+			'order_by' => array('CHK_timestamp' => 'DESC'),
1671
+		);
1672
+
1673
+		if ($DTT_ID > 0) {
1674
+			$checkin_query_params[0] = array('DTT_ID' => $DTT_ID);
1675
+		}
1676
+
1677
+		// get checkin object (if exists)
1678
+		$checkin = $checkin instanceof EE_Checkin
1679
+			? $checkin
1680
+			: $this->get_first_related('Checkin', $checkin_query_params);
1681
+		if ($checkin instanceof EE_Checkin) {
1682
+			if ($checkin->get('CHK_in')) {
1683
+				return EE_Checkin::status_checked_in; // checked in
1684
+			}
1685
+			return EE_Checkin::status_checked_out; // had checked in but is now checked out.
1686
+		}
1687
+		return EE_Checkin::status_checked_never; // never been checked in
1688
+	}
1689
+
1690
+
1691
+	/**
1692
+	 * This method returns a localized message for the toggled Check-in message.
1693
+	 *
1694
+	 * @param  int $DTT_ID include specific datetime to get the correct Check-in message.  If not included or null,
1695
+	 *                     then it is assumed Check-in for primary datetime was toggled.
1696
+	 * @param bool $error  This just flags that you want an error message returned. This is put in so that the error
1697
+	 *                     message can be customized with the attendee name.
1698
+	 * @return string internationalized message
1699
+	 * @throws EE_Error
1700
+	 */
1701
+	public function get_checkin_msg($DTT_ID, $error = false)
1702
+	{
1703
+		// let's get the attendee first so we can include the name of the attendee
1704
+		$attendee = $this->get_first_related('Attendee');
1705
+		if ($attendee instanceof EE_Attendee) {
1706
+			if ($error) {
1707
+				return sprintf(esc_html__("%s's check-in status was not changed.", "event_espresso"), $attendee->full_name());
1708
+			}
1709
+			$cur_status = $this->check_in_status_for_datetime($DTT_ID);
1710
+			// what is the status message going to be?
1711
+			switch ($cur_status) {
1712
+				case EE_Checkin::status_checked_never:
1713
+					return sprintf(
1714
+						esc_html__("%s has been removed from Check-in records", "event_espresso"),
1715
+						$attendee->full_name()
1716
+					);
1717
+					break;
1718
+				case EE_Checkin::status_checked_in:
1719
+					return sprintf(esc_html__('%s has been checked in', 'event_espresso'), $attendee->full_name());
1720
+					break;
1721
+				case EE_Checkin::status_checked_out:
1722
+					return sprintf(esc_html__('%s has been checked out', 'event_espresso'), $attendee->full_name());
1723
+					break;
1724
+			}
1725
+		}
1726
+		return esc_html__("The check-in status could not be determined.", "event_espresso");
1727
+	}
1728
+
1729
+
1730
+	/**
1731
+	 * Returns the related EE_Transaction to this registration
1732
+	 *
1733
+	 * @return EE_Transaction
1734
+	 * @throws EE_Error
1735
+	 * @throws EntityNotFoundException
1736
+	 */
1737
+	public function transaction()
1738
+	{
1739
+		$transaction = $this->get_first_related('Transaction');
1740
+		if (! $transaction instanceof \EE_Transaction) {
1741
+			throw new EntityNotFoundException('Transaction ID', $this->transaction_ID());
1742
+		}
1743
+		return $transaction;
1744
+	}
1745
+
1746
+
1747
+	/**
1748
+	 *        get Registration Code
1749
+	 */
1750
+	public function reg_code()
1751
+	{
1752
+		return $this->get('REG_code');
1753
+	}
1754
+
1755
+
1756
+	/**
1757
+	 *        get Transaction ID
1758
+	 */
1759
+	public function transaction_ID()
1760
+	{
1761
+		return $this->get('TXN_ID');
1762
+	}
1763
+
1764
+
1765
+	/**
1766
+	 * @return int
1767
+	 * @throws EE_Error
1768
+	 */
1769
+	public function ticket_ID()
1770
+	{
1771
+		return $this->get('TKT_ID');
1772
+	}
1773
+
1774
+
1775
+	/**
1776
+	 *        Set Registration Code
1777
+	 *
1778
+	 * @access    public
1779
+	 * @param    string  $REG_code Registration Code
1780
+	 * @param    boolean $use_default
1781
+	 * @throws EE_Error
1782
+	 */
1783
+	public function set_reg_code($REG_code, $use_default = false)
1784
+	{
1785
+		if (empty($REG_code)) {
1786
+			EE_Error::add_error(
1787
+				esc_html__('REG_code can not be empty.', 'event_espresso'),
1788
+				__FILE__,
1789
+				__FUNCTION__,
1790
+				__LINE__
1791
+			);
1792
+			return;
1793
+		}
1794
+		if (! $this->reg_code()) {
1795
+			parent::set('REG_code', $REG_code, $use_default);
1796
+		} else {
1797
+			EE_Error::doing_it_wrong(
1798
+				__CLASS__ . '::' . __FUNCTION__,
1799
+				esc_html__('Can not change a registration REG_code once it has been set.', 'event_espresso'),
1800
+				'4.6.0'
1801
+			);
1802
+		}
1803
+	}
1804
+
1805
+
1806
+	/**
1807
+	 * Returns all other registrations in the same group as this registrant who have the same ticket option.
1808
+	 * Note, if you want to just get all registrations in the same transaction (group), use:
1809
+	 *    $registration->transaction()->registrations();
1810
+	 *
1811
+	 * @since 4.5.0
1812
+	 * @return EE_Registration[] or empty array if this isn't a group registration.
1813
+	 * @throws EE_Error
1814
+	 */
1815
+	public function get_all_other_registrations_in_group()
1816
+	{
1817
+		if ($this->group_size() < 2) {
1818
+			return array();
1819
+		}
1820
+
1821
+		$query[0] = array(
1822
+			'TXN_ID' => $this->transaction_ID(),
1823
+			'REG_ID' => array('!=', $this->ID()),
1824
+			'TKT_ID' => $this->ticket_ID(),
1825
+		);
1826
+		/** @var EE_Registration[] $registrations */
1827
+		$registrations = $this->get_model()->get_all($query);
1828
+		return $registrations;
1829
+	}
1830
+
1831
+	/**
1832
+	 * Return the link to the admin details for the object.
1833
+	 *
1834
+	 * @return string
1835
+	 * @throws EE_Error
1836
+	 */
1837
+	public function get_admin_details_link()
1838
+	{
1839
+		EE_Registry::instance()->load_helper('URL');
1840
+		return EEH_URL::add_query_args_and_nonce(
1841
+			array(
1842
+				'page'    => 'espresso_registrations',
1843
+				'action'  => 'view_registration',
1844
+				'_REG_ID' => $this->ID(),
1845
+			),
1846
+			admin_url('admin.php')
1847
+		);
1848
+	}
1849
+
1850
+	/**
1851
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
1852
+	 *
1853
+	 * @return string
1854
+	 * @throws EE_Error
1855
+	 */
1856
+	public function get_admin_edit_link()
1857
+	{
1858
+		return $this->get_admin_details_link();
1859
+	}
1860
+
1861
+	/**
1862
+	 * Returns the link to a settings page for the object.
1863
+	 *
1864
+	 * @return string
1865
+	 * @throws EE_Error
1866
+	 */
1867
+	public function get_admin_settings_link()
1868
+	{
1869
+		return $this->get_admin_details_link();
1870
+	}
1871
+
1872
+	/**
1873
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
1874
+	 *
1875
+	 * @return string
1876
+	 */
1877
+	public function get_admin_overview_link()
1878
+	{
1879
+		EE_Registry::instance()->load_helper('URL');
1880
+		return EEH_URL::add_query_args_and_nonce(
1881
+			array(
1882
+				'page' => 'espresso_registrations',
1883
+			),
1884
+			admin_url('admin.php')
1885
+		);
1886
+	}
1887
+
1888
+
1889
+	/**
1890
+	 * @param array $query_params
1891
+	 *
1892
+	 * @return \EE_Registration[]
1893
+	 * @throws EE_Error
1894
+	 */
1895
+	public function payments($query_params = array())
1896
+	{
1897
+		return $this->get_many_related('Payment', $query_params);
1898
+	}
1899
+
1900
+
1901
+	/**
1902
+	 * @param array $query_params
1903
+	 *
1904
+	 * @return \EE_Registration_Payment[]
1905
+	 * @throws EE_Error
1906
+	 */
1907
+	public function registration_payments($query_params = array())
1908
+	{
1909
+		return $this->get_many_related('Registration_Payment', $query_params);
1910
+	}
1911
+
1912
+
1913
+	/**
1914
+	 * This grabs the payment method corresponding to the last payment made for the amount owing on the registration.
1915
+	 * Note: if there are no payments on the registration there will be no payment method returned.
1916
+	 *
1917
+	 * @return EE_Payment_Method|null
1918
+	 */
1919
+	public function payment_method()
1920
+	{
1921
+		return EEM_Payment_Method::instance()->get_last_used_for_registration($this);
1922
+	}
1923
+
1924
+
1925
+	/**
1926
+	 * @return \EE_Line_Item
1927
+	 * @throws EntityNotFoundException
1928
+	 * @throws EE_Error
1929
+	 */
1930
+	public function ticket_line_item()
1931
+	{
1932
+		$ticket = $this->ticket();
1933
+		$transaction = $this->transaction();
1934
+		$line_item = null;
1935
+		$ticket_line_items = \EEH_Line_Item::get_line_items_by_object_type_and_IDs(
1936
+			$transaction->total_line_item(),
1937
+			'Ticket',
1938
+			array($ticket->ID())
1939
+		);
1940
+		foreach ($ticket_line_items as $ticket_line_item) {
1941
+			if (
1942
+				$ticket_line_item instanceof \EE_Line_Item
1943
+				&& $ticket_line_item->OBJ_type() === 'Ticket'
1944
+				&& $ticket_line_item->OBJ_ID() === $ticket->ID()
1945
+			) {
1946
+				$line_item = $ticket_line_item;
1947
+				break;
1948
+			}
1949
+		}
1950
+		if (! ($line_item instanceof \EE_Line_Item && $line_item->OBJ_type() === 'Ticket')) {
1951
+			throw new EntityNotFoundException('Line Item Ticket ID', $ticket->ID());
1952
+		}
1953
+		return $line_item;
1954
+	}
1955
+
1956
+
1957
+	/**
1958
+	 * Soft Deletes this model object.
1959
+	 *
1960
+	 * @return boolean | int
1961
+	 * @throws RuntimeException
1962
+	 * @throws EE_Error
1963
+	 */
1964
+	public function delete()
1965
+	{
1966
+		if ($this->update_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY, $this->status_ID()) === true) {
1967
+			$this->set_status(EEM_Registration::status_id_cancelled);
1968
+		}
1969
+		return parent::delete();
1970
+	}
1971
+
1972
+
1973
+	/**
1974
+	 * Restores whatever the previous status was on a registration before it was trashed (if possible)
1975
+	 *
1976
+	 * @throws EE_Error
1977
+	 * @throws RuntimeException
1978
+	 */
1979
+	public function restore()
1980
+	{
1981
+		$previous_status = $this->get_extra_meta(
1982
+			EE_Registration::PRE_TRASH_REG_STATUS_KEY,
1983
+			true,
1984
+			EEM_Registration::status_id_cancelled
1985
+		);
1986
+		if ($previous_status) {
1987
+			$this->delete_extra_meta(EE_Registration::PRE_TRASH_REG_STATUS_KEY);
1988
+			$this->set_status($previous_status);
1989
+		}
1990
+		return parent::restore();
1991
+	}
1992
+
1993
+
1994
+	/**
1995
+	 * possibly toggle Registration status based on comparison of REG_paid vs REG_final_price
1996
+	 *
1997
+	 * @param  boolean $trigger_set_status_logic EE_Registration::set_status() can trigger additional logic
1998
+	 *                                           depending on whether the reg status changes to or from "Approved"
1999
+	 * @return boolean whether the Registration status was updated
2000
+	 * @throws EE_Error
2001
+	 * @throws RuntimeException
2002
+	 */
2003
+	public function updateStatusBasedOnTotalPaid($trigger_set_status_logic = true)
2004
+	{
2005
+		$paid = $this->paid();
2006
+		$price = $this->final_price();
2007
+		switch (true) {
2008
+			// overpaid or paid
2009
+			case EEH_Money::compare_floats($paid, $price, '>'):
2010
+			case EEH_Money::compare_floats($paid, $price):
2011
+				$new_status = EEM_Registration::status_id_approved;
2012
+				break;
2013
+			//  underpaid
2014
+			case EEH_Money::compare_floats($paid, $price, '<'):
2015
+				$new_status = EEM_Registration::status_id_pending_payment;
2016
+				break;
2017
+			// uhhh Houston...
2018
+			default:
2019
+				throw new RuntimeException(
2020
+					esc_html__('The total paid calculation for this registration is inaccurate.', 'event_espresso')
2021
+				);
2022
+		}
2023
+		if ($new_status !== $this->status_ID()) {
2024
+			if ($trigger_set_status_logic) {
2025
+				return $this->set_status($new_status);
2026
+			}
2027
+			parent::set('STS_ID', $new_status);
2028
+			return true;
2029
+		}
2030
+		return false;
2031
+	}
2032
+
2033
+
2034
+	/*************************** DEPRECATED ***************************/
2035
+
2036
+
2037
+	/**
2038
+	 * @deprecated
2039
+	 * @since     4.7.0
2040
+	 * @access    public
2041
+	 */
2042
+	public function price_paid()
2043
+	{
2044
+		EE_Error::doing_it_wrong(
2045
+			'EE_Registration::price_paid()',
2046
+			esc_html__(
2047
+				'This method is deprecated, please use EE_Registration::final_price() instead.',
2048
+				'event_espresso'
2049
+			),
2050
+			'4.7.0'
2051
+		);
2052
+		return $this->final_price();
2053
+	}
2054
+
2055
+
2056
+	/**
2057
+	 * @deprecated
2058
+	 * @since     4.7.0
2059
+	 * @access    public
2060
+	 * @param    float $REG_final_price
2061
+	 * @throws EE_Error
2062
+	 * @throws RuntimeException
2063
+	 */
2064
+	public function set_price_paid($REG_final_price = 0.00)
2065
+	{
2066
+		EE_Error::doing_it_wrong(
2067
+			'EE_Registration::set_price_paid()',
2068
+			esc_html__(
2069
+				'This method is deprecated, please use EE_Registration::set_final_price() instead.',
2070
+				'event_espresso'
2071
+			),
2072
+			'4.7.0'
2073
+		);
2074
+		$this->set_final_price($REG_final_price);
2075
+	}
2076
+
2077
+
2078
+	/**
2079
+	 * @deprecated
2080
+	 * @since 4.7.0
2081
+	 * @return string
2082
+	 * @throws EE_Error
2083
+	 */
2084
+	public function pretty_price_paid()
2085
+	{
2086
+		EE_Error::doing_it_wrong(
2087
+			'EE_Registration::pretty_price_paid()',
2088
+			esc_html__(
2089
+				'This method is deprecated, please use EE_Registration::pretty_final_price() instead.',
2090
+				'event_espresso'
2091
+			),
2092
+			'4.7.0'
2093
+		);
2094
+		return $this->pretty_final_price();
2095
+	}
2096
+
2097
+
2098
+	/**
2099
+	 * Gets the primary datetime related to this registration via the related Event to this registration
2100
+	 *
2101
+	 * @deprecated 4.9.17
2102
+	 * @return EE_Datetime
2103
+	 * @throws EE_Error
2104
+	 * @throws EntityNotFoundException
2105
+	 */
2106
+	public function get_related_primary_datetime()
2107
+	{
2108
+		EE_Error::doing_it_wrong(
2109
+			__METHOD__,
2110
+			esc_html__(
2111
+				'Use EE_Registration::get_latest_related_datetime() or EE_Registration::get_earliest_related_datetime()',
2112
+				'event_espresso'
2113
+			),
2114
+			'4.9.17',
2115
+			'5.0.0'
2116
+		);
2117
+		return $this->event()->primary_datetime();
2118
+	}
2119
+
2120
+	/**
2121
+	 * Returns the contact's name (or "Unknown" if there is no contact.)
2122
+	 * @since 4.10.12.p
2123
+	 * @return string
2124
+	 * @throws EE_Error
2125
+	 * @throws InvalidArgumentException
2126
+	 * @throws InvalidDataTypeException
2127
+	 * @throws InvalidInterfaceException
2128
+	 * @throws ReflectionException
2129
+	 */
2130
+	public function name()
2131
+	{
2132
+		return $this->attendeeName();
2133
+	}
2134 2134
 }
Please login to merge, or discard this patch.