Completed
Branch more-reg-csv-fixes (87a98f)
by
unknown
30:58 queued 28:58
created
core/domain/services/capabilities/CapabilitiesChecker.php 2 patches
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -18,86 +18,86 @@
 block discarded – undo
18 18
 class CapabilitiesChecker implements CapabilitiesCheckerInterface
19 19
 {
20 20
 
21
-    /**
22
-     * @type EE_Capabilities $capabilities
23
-     */
24
-    private $capabilities;
21
+	/**
22
+	 * @type EE_Capabilities $capabilities
23
+	 */
24
+	private $capabilities;
25 25
 
26 26
 
27
-    /**
28
-     * CapabilitiesChecker constructor
29
-     *
30
-     * @param EE_Capabilities $capabilities
31
-     */
32
-    public function __construct(EE_Capabilities $capabilities)
33
-    {
34
-        $this->capabilities = $capabilities;
35
-    }
27
+	/**
28
+	 * CapabilitiesChecker constructor
29
+	 *
30
+	 * @param EE_Capabilities $capabilities
31
+	 */
32
+	public function __construct(EE_Capabilities $capabilities)
33
+	{
34
+		$this->capabilities = $capabilities;
35
+	}
36 36
 
37 37
 
38
-    /**
39
-     * @return EE_Capabilities
40
-     */
41
-    protected function capabilities()
42
-    {
43
-        return $this->capabilities;
44
-    }
38
+	/**
39
+	 * @return EE_Capabilities
40
+	 */
41
+	protected function capabilities()
42
+	{
43
+		return $this->capabilities;
44
+	}
45 45
 
46 46
 
47
-    /**
48
-     * Verifies that the current user has ALL of the capabilities listed in the CapCheck DTO.
49
-     * If any of the individual capability checks fails, then the command will NOT be executed.
50
-     *
51
-     * @param CapCheckInterface|CapCheckInterface[] $cap_check
52
-     * @return bool
53
-     * @throws InvalidClassException
54
-     * @throws InsufficientPermissionsException
55
-     */
56
-    public function processCapCheck($cap_check)
57
-    {
58
-        if (is_array($cap_check)) {
59
-            foreach ($cap_check as $check) {
60
-                $this->processCapCheck($check);
61
-            }
62
-            return true;
63
-        }
64
-        // at this point, $cap_check should be an individual instance of CapCheck
65
-        if (! $cap_check instanceof CapCheckInterface) {
66
-            throw new InvalidClassException(
67
-                '\EventEspresso\core\domain\services\capabilities\CapCheckInterface'
68
-            );
69
-        }
70
-        // sometimes cap checks are conditional, and no capabilities are required
71
-        if ($cap_check instanceof PublicCapabilities) {
72
-            return true;
73
-        }
74
-        $capabilities = (array) $cap_check->capability();
75
-        foreach ($capabilities as $capability) {
76
-            if (
77
-                ! $this->capabilities()->current_user_can(
78
-                    $capability,
79
-                    $cap_check->context(),
80
-                    $cap_check->ID()
81
-                )
82
-            ) {
83
-                throw new InsufficientPermissionsException($cap_check->context());
84
-            }
85
-        }
86
-        return true;
87
-    }
47
+	/**
48
+	 * Verifies that the current user has ALL of the capabilities listed in the CapCheck DTO.
49
+	 * If any of the individual capability checks fails, then the command will NOT be executed.
50
+	 *
51
+	 * @param CapCheckInterface|CapCheckInterface[] $cap_check
52
+	 * @return bool
53
+	 * @throws InvalidClassException
54
+	 * @throws InsufficientPermissionsException
55
+	 */
56
+	public function processCapCheck($cap_check)
57
+	{
58
+		if (is_array($cap_check)) {
59
+			foreach ($cap_check as $check) {
60
+				$this->processCapCheck($check);
61
+			}
62
+			return true;
63
+		}
64
+		// at this point, $cap_check should be an individual instance of CapCheck
65
+		if (! $cap_check instanceof CapCheckInterface) {
66
+			throw new InvalidClassException(
67
+				'\EventEspresso\core\domain\services\capabilities\CapCheckInterface'
68
+			);
69
+		}
70
+		// sometimes cap checks are conditional, and no capabilities are required
71
+		if ($cap_check instanceof PublicCapabilities) {
72
+			return true;
73
+		}
74
+		$capabilities = (array) $cap_check->capability();
75
+		foreach ($capabilities as $capability) {
76
+			if (
77
+				! $this->capabilities()->current_user_can(
78
+					$capability,
79
+					$cap_check->context(),
80
+					$cap_check->ID()
81
+				)
82
+			) {
83
+				throw new InsufficientPermissionsException($cap_check->context());
84
+			}
85
+		}
86
+		return true;
87
+	}
88 88
 
89 89
 
90
-    /**
91
-     * @param string $capability - the capability to be checked, like: 'ee_edit_registrations'
92
-     * @param string $context    - what the user is attempting to do, like: 'Edit Registration'
93
-     * @param int    $ID         - (optional) ID for item where current_user_can is being called from
94
-     * @return bool
95
-     * @throws InvalidDataTypeException
96
-     * @throws InsufficientPermissionsException
97
-     * @throws InvalidClassException
98
-     */
99
-    public function process($capability, $context, $ID = 0)
100
-    {
101
-        return $this->processCapCheck(new CapCheck($capability, $context, $ID));
102
-    }
90
+	/**
91
+	 * @param string $capability - the capability to be checked, like: 'ee_edit_registrations'
92
+	 * @param string $context    - what the user is attempting to do, like: 'Edit Registration'
93
+	 * @param int    $ID         - (optional) ID for item where current_user_can is being called from
94
+	 * @return bool
95
+	 * @throws InvalidDataTypeException
96
+	 * @throws InsufficientPermissionsException
97
+	 * @throws InvalidClassException
98
+	 */
99
+	public function process($capability, $context, $ID = 0)
100
+	{
101
+		return $this->processCapCheck(new CapCheck($capability, $context, $ID));
102
+	}
103 103
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -62,7 +62,7 @@
 block discarded – undo
62 62
             return true;
63 63
         }
64 64
         // at this point, $cap_check should be an individual instance of CapCheck
65
-        if (! $cap_check instanceof CapCheckInterface) {
65
+        if ( ! $cap_check instanceof CapCheckInterface) {
66 66
             throw new InvalidClassException(
67 67
                 '\EventEspresso\core\domain\services\capabilities\CapCheckInterface'
68 68
             );
Please login to merge, or discard this patch.
core/domain/services/event/EventSpacesCalculator.php 2 patches
Indentation   +715 added lines, -715 removed lines patch added patch discarded remove patch
@@ -26,719 +26,719 @@
 block discarded – undo
26 26
 class EventSpacesCalculator
27 27
 {
28 28
 
29
-    /**
30
-     * @var EE_Event $event
31
-     */
32
-    private $event;
33
-
34
-    /**
35
-     * @var array $datetime_query_params
36
-     */
37
-    private $datetime_query_params;
38
-
39
-    /**
40
-     * @var EE_Ticket[] $active_tickets
41
-     */
42
-    private $active_tickets = array();
43
-
44
-    /**
45
-     * @var EE_Datetime[] $datetimes
46
-     */
47
-    private $datetimes = array();
48
-
49
-    /**
50
-     * Array of Ticket IDs grouped by Datetime
51
-     *
52
-     * @var array $datetimes
53
-     */
54
-    private $datetime_tickets = array();
55
-
56
-    /**
57
-     * Max spaces for each Datetime (reg limit - previous sold)
58
-     *
59
-     * @var array $datetime_spaces
60
-     */
61
-    private $datetime_spaces = array();
62
-
63
-    /**
64
-     * Array of Datetime IDs grouped by Ticket
65
-     *
66
-     * @var array[] $ticket_datetimes
67
-     */
68
-    private $ticket_datetimes = array();
69
-
70
-    /**
71
-     * maximum ticket quantities for each ticket (adjusted for reg limit)
72
-     *
73
-     * @var array $ticket_quantities
74
-     */
75
-    private $ticket_quantities = array();
76
-
77
-    /**
78
-     * total quantity of sold and reserved for each ticket
79
-     *
80
-     * @var array $tickets_sold
81
-     */
82
-    private $tickets_sold = array();
83
-
84
-    /**
85
-     * total spaces available across all datetimes
86
-     *
87
-     * @var array $total_spaces
88
-     */
89
-    private $total_spaces = array();
90
-
91
-    /**
92
-     * @var boolean $debug
93
-     */
94
-    private $debug = false; // true false
95
-
96
-    /**
97
-     * @var null|int $spaces_remaining
98
-     */
99
-    private $spaces_remaining;
100
-
101
-    /**
102
-     * @var null|int $total_spaces_available
103
-     */
104
-    private $total_spaces_available;
105
-
106
-
107
-    /**
108
-     * EventSpacesCalculator constructor.
109
-     *
110
-     * @param EE_Event $event
111
-     * @param array    $datetime_query_params
112
-     * @throws EE_Error
113
-     */
114
-    public function __construct(EE_Event $event, array $datetime_query_params = array())
115
-    {
116
-        if ($this->debug) {
117
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 1);
118
-            \EEH_Debug_Tools::printr((string) $event->ID(), 'For event', __FILE__, __LINE__);
119
-        }
120
-        $this->event = $event;
121
-        $this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
122
-        $this->setHooks();
123
-    }
124
-
125
-
126
-    /**
127
-     * @return void
128
-     */
129
-    private function setHooks()
130
-    {
131
-        add_action('AHEE__EE_Ticket__increase_sold', array($this, 'clearResults'));
132
-        add_action('AHEE__EE_Ticket__decrease_sold', array($this, 'clearResults'));
133
-        add_action('AHEE__EE_Datetime__increase_sold', array($this, 'clearResults'));
134
-        add_action('AHEE__EE_Datetime__decrease_sold', array($this, 'clearResults'));
135
-        add_action('AHEE__EE_Ticket__increase_reserved', array($this, 'clearResults'));
136
-        add_action('AHEE__EE_Ticket__decrease_reserved', array($this, 'clearResults'));
137
-        add_action('AHEE__EE_Datetime__increase_reserved', array($this, 'clearResults'));
138
-        add_action('AHEE__EE_Datetime__decrease_reserved', array($this, 'clearResults'));
139
-    }
140
-
141
-
142
-    /**
143
-     * @return void
144
-     */
145
-    public function clearResults()
146
-    {
147
-        if ($this->debug) {
148
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 1);
149
-        }
150
-        $this->spaces_remaining = null;
151
-        $this->total_spaces_available = null;
152
-    }
153
-
154
-
155
-    /**
156
-     * @return EE_Ticket[]
157
-     * @throws EE_Error
158
-     * @throws InvalidDataTypeException
159
-     * @throws InvalidInterfaceException
160
-     * @throws InvalidArgumentException
161
-     */
162
-    public function getActiveTickets()
163
-    {
164
-        if (empty($this->active_tickets)) {
165
-            $this->active_tickets = $this->event->tickets(
166
-                array(
167
-                    array('TKT_deleted' => false),
168
-                    'order_by' => array('TKT_qty' => 'ASC'),
169
-                )
170
-            );
171
-        }
172
-        return $this->active_tickets;
173
-    }
174
-
175
-
176
-    /**
177
-     * @param EE_Ticket[] $active_tickets
178
-     * @throws EE_Error
179
-     * @throws DomainException
180
-     * @throws UnexpectedEntityException
181
-     */
182
-    public function setActiveTickets(array $active_tickets = array())
183
-    {
184
-        if (! empty($active_tickets)) {
185
-            foreach ($active_tickets as $active_ticket) {
186
-                $this->validateTicket($active_ticket);
187
-            }
188
-            // sort incoming array by ticket quantity (asc)
189
-            usort(
190
-                $active_tickets,
191
-                function (EE_Ticket $a, EE_Ticket $b) {
192
-                    if ($a->qty() === $b->qty()) {
193
-                        return 0;
194
-                    }
195
-                    return ($a->qty() < $b->qty())
196
-                        ? -1
197
-                        : 1;
198
-                }
199
-            );
200
-        }
201
-        $this->active_tickets = $active_tickets;
202
-    }
203
-
204
-
205
-    /**
206
-     * @param $ticket
207
-     * @throws DomainException
208
-     * @throws EE_Error
209
-     * @throws UnexpectedEntityException
210
-     */
211
-    private function validateTicket($ticket)
212
-    {
213
-        if (! $ticket instanceof EE_Ticket) {
214
-            throw new DomainException(
215
-                esc_html__(
216
-                    'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
217
-                    'event_espresso'
218
-                )
219
-            );
220
-        }
221
-        if ($ticket->get_event_ID() !== $this->event->ID()) {
222
-            throw new DomainException(
223
-                sprintf(
224
-                    esc_html__(
225
-                        'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
226
-                        'event_espresso'
227
-                    ),
228
-                    $ticket->get_event_ID(),
229
-                    $this->event->ID()
230
-                )
231
-            );
232
-        }
233
-    }
234
-
235
-
236
-    /**
237
-     * @return EE_Datetime[]
238
-     */
239
-    public function getDatetimes()
240
-    {
241
-        return $this->datetimes;
242
-    }
243
-
244
-
245
-    /**
246
-     * @param EE_Datetime $datetime
247
-     * @throws EE_Error
248
-     * @throws DomainException
249
-     */
250
-    public function setDatetime(EE_Datetime $datetime)
251
-    {
252
-        if ($datetime->event()->ID() !== $this->event->ID()) {
253
-            throw new DomainException(
254
-                sprintf(
255
-                    esc_html__(
256
-                        'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
257
-                        'event_espresso'
258
-                    ),
259
-                    $datetime->event()->ID(),
260
-                    $this->event->ID()
261
-                )
262
-            );
263
-        }
264
-        $this->datetimes[ $datetime->ID() ] = $datetime;
265
-    }
266
-
267
-
268
-    /**
269
-     * calculate spaces remaining based on "saleable" tickets
270
-     *
271
-     * @return float|int
272
-     * @throws EE_Error
273
-     * @throws DomainException
274
-     * @throws UnexpectedEntityException
275
-     * @throws InvalidDataTypeException
276
-     * @throws InvalidInterfaceException
277
-     * @throws InvalidArgumentException
278
-     */
279
-    public function spacesRemaining()
280
-    {
281
-        if ($this->debug) {
282
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
283
-        }
284
-        if ($this->spaces_remaining === null) {
285
-            $this->initialize();
286
-            $this->spaces_remaining = $this->calculate();
287
-        }
288
-        return $this->spaces_remaining;
289
-    }
290
-
291
-
292
-    /**
293
-     * calculates total available spaces for an event with no regard for sold tickets
294
-     *
295
-     * @return int|float
296
-     * @throws EE_Error
297
-     * @throws DomainException
298
-     * @throws UnexpectedEntityException
299
-     * @throws InvalidDataTypeException
300
-     * @throws InvalidInterfaceException
301
-     * @throws InvalidArgumentException
302
-     */
303
-    public function totalSpacesAvailable()
304
-    {
305
-        if ($this->debug) {
306
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
307
-        }
308
-        if ($this->total_spaces_available === null) {
309
-            $this->initialize();
310
-            $this->total_spaces_available = $this->calculate(false);
311
-        }
312
-        return $this->total_spaces_available;
313
-    }
314
-
315
-
316
-    /**
317
-     * Loops through the active tickets for the event
318
-     * and builds a series of data arrays that will be used for calculating
319
-     * the total maximum available spaces, as well as the spaces remaining.
320
-     * Because ticket quantities affect datetime spaces and vice versa,
321
-     * we need to be constantly updating these data arrays as things change,
322
-     * which is the entire reason for their existence.
323
-     *
324
-     * @throws EE_Error
325
-     * @throws DomainException
326
-     * @throws UnexpectedEntityException
327
-     * @throws InvalidDataTypeException
328
-     * @throws InvalidInterfaceException
329
-     * @throws InvalidArgumentException
330
-     */
331
-    private function initialize()
332
-    {
333
-        if ($this->debug) {
334
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
335
-        }
336
-        $this->datetime_tickets = array();
337
-        $this->datetime_spaces = array();
338
-        $this->ticket_datetimes = array();
339
-        $this->ticket_quantities = array();
340
-        $this->tickets_sold = array();
341
-        $this->total_spaces = array();
342
-        $active_tickets = $this->getActiveTickets();
343
-        if (! empty($active_tickets)) {
344
-            foreach ($active_tickets as $ticket) {
345
-                $this->validateTicket($ticket);
346
-                // we need to index our data arrays using strings for the purpose of sorting,
347
-                // but we also need them to be unique, so  we'll just prepend a letter T to the ID
348
-                $ticket_identifier = "T{$ticket->ID()}";
349
-                // to start, we'll just consider the raw qty to be the maximum availability for this ticket,
350
-                // unless the ticket is past its "sell until" date, in which case the qty will be 0
351
-                $max_tickets = $ticket->is_expired() ? 0 : $ticket->qty();
352
-                // but we'll adjust that after looping over each datetime for the ticket and checking reg limits
353
-                $ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
354
-                foreach ($ticket_datetimes as $datetime) {
355
-                    // save all datetimes
356
-                    $this->setDatetime($datetime);
357
-                    $datetime_identifier = "D{$datetime->ID()}";
358
-                    $reg_limit = $datetime->reg_limit();
359
-                    // ticket quantity can not exceed datetime reg limit
360
-                    $max_tickets = min($max_tickets, $reg_limit);
361
-                    // as described earlier, because we need to be able to constantly adjust numbers for things,
362
-                    // we are going to move all of our data into the following arrays:
363
-                    // datetime spaces initially represents the reg limit for each datetime,
364
-                    // but this will get adjusted as tickets are accounted for
365
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
366
-                    // just an array of ticket IDs grouped by datetime
367
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
368
-                    // and an array of datetime IDs grouped by ticket
369
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
370
-                }
371
-                // total quantity of sold and reserved for each ticket
372
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
373
-                // and the maximum ticket quantities for each ticket (adjusted for reg limit)
374
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
375
-            }
376
-        }
377
-        // sort datetime spaces by reg limit, but maintain our string indexes
378
-        asort($this->datetime_spaces, SORT_NUMERIC);
379
-        // datetime tickets need to be sorted in the SAME order as the above array...
380
-        // so we'll just use array_merge() to take the structure of datetime_spaces
381
-        // but overwrite all of the data with that from datetime_tickets
382
-        $this->datetime_tickets = array_merge(
383
-            $this->datetime_spaces,
384
-            $this->datetime_tickets
385
-        );
386
-        if ($this->debug) {
387
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
388
-            \EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
389
-            \EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
390
-        }
391
-    }
392
-
393
-
394
-    /**
395
-     * performs calculations on initialized data
396
-     *
397
-     * @param bool $consider_sold
398
-     * @return int|float
399
-     */
400
-    private function calculate($consider_sold = true)
401
-    {
402
-        if ($this->debug) {
403
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
404
-            \EEH_Debug_Tools::printr($consider_sold, '$consider_sold', __FILE__, __LINE__);
405
-        }
406
-        if ($consider_sold) {
407
-            // subtract amounts sold from all ticket quantities and datetime spaces
408
-            $this->adjustTicketQuantitiesDueToSales();
409
-        }
410
-        foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
411
-            $this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
412
-        }
413
-        // total spaces available is just the sum of the spaces available for each datetime
414
-        $spaces_remaining = array_sum($this->total_spaces);
415
-        if ($this->debug) {
416
-            \EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
417
-            \EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
418
-            \EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
419
-        }
420
-        return $spaces_remaining;
421
-    }
422
-
423
-
424
-    /**
425
-     * subtracts amount of  tickets sold from ticket quantities and datetime spaces
426
-     */
427
-    private function adjustTicketQuantitiesDueToSales()
428
-    {
429
-        if ($this->debug) {
430
-            \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
431
-        }
432
-        foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
433
-            if (isset($this->ticket_quantities[ $ticket_identifier ])) {
434
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
435
-                // don't let values go below zero
436
-                $this->ticket_quantities[ $ticket_identifier ] = max(
437
-                    $this->ticket_quantities[ $ticket_identifier ],
438
-                    0
439
-                );
440
-                if ($this->debug) {
441
-                    \EEH_Debug_Tools::printr(
442
-                        "{$tickets_sold} sales for ticket {$ticket_identifier} ",
443
-                        'subtracting',
444
-                        __FILE__,
445
-                        __LINE__
446
-                    );
447
-                }
448
-            }
449
-            if (
450
-                isset($this->ticket_datetimes[ $ticket_identifier ])
451
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
452
-            ) {
453
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
454
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
455
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
456
-                        // don't let values go below zero
457
-                        $this->datetime_spaces[ $ticket_datetime ] = max(
458
-                            $this->datetime_spaces[ $ticket_datetime ],
459
-                            0
460
-                        );
461
-                        if ($this->debug) {
462
-                            \EEH_Debug_Tools::printr(
463
-                                "{$tickets_sold} sales for datetime {$ticket_datetime} ",
464
-                                'subtracting',
465
-                                __FILE__,
466
-                                __LINE__
467
-                            );
468
-                        }
469
-                    }
470
-                }
471
-            }
472
-        }
473
-    }
474
-
475
-
476
-    /**
477
-     * @param string $datetime_identifier
478
-     * @param array  $tickets
479
-     */
480
-    private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
481
-    {
482
-        // make sure a reg limit is set for the datetime
483
-        $reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
484
-            ? $this->datetime_spaces[ $datetime_identifier ]
485
-            : 0;
486
-        // and bail if it is not
487
-        if (! $reg_limit) {
488
-            if ($this->debug) {
489
-                \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
490
-            }
491
-            return;
492
-        }
493
-        if ($this->debug) {
494
-            \EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
495
-            \EEH_Debug_Tools::printr(
496
-                "{$reg_limit}",
497
-                'REG LIMIT',
498
-                __FILE__,
499
-                __LINE__
500
-            );
501
-        }
502
-        // number of allocated spaces always starts at zero
503
-        $spaces_allocated = 0;
504
-        $this->total_spaces[ $datetime_identifier ] = 0;
505
-        foreach ($tickets as $ticket_identifier) {
506
-            $spaces_allocated = $this->calculateAvailableSpacesForTicket(
507
-                $datetime_identifier,
508
-                $reg_limit,
509
-                $ticket_identifier,
510
-                $spaces_allocated
511
-            );
512
-        }
513
-        // spaces can't be negative
514
-        $spaces_allocated = max($spaces_allocated, 0);
515
-        if ($spaces_allocated) {
516
-            // track any non-zero values
517
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
518
-            if ($this->debug) {
519
-                \EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
520
-            }
521
-        } else {
522
-            if ($this->debug) {
523
-                \EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
524
-            }
525
-        }
526
-        if ($this->debug) {
527
-            \EEH_Debug_Tools::printr(
528
-                $this->total_spaces[ $datetime_identifier ],
529
-                '$total_spaces',
530
-                __FILE__,
531
-                __LINE__
532
-            );
533
-            \EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
534
-            \EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
535
-        }
536
-    }
537
-
538
-
539
-    /**
540
-     * @param string $datetime_identifier
541
-     * @param int    $reg_limit
542
-     * @param string $ticket_identifier
543
-     * @param int    $spaces_allocated
544
-     * @return int
545
-     */
546
-    private function calculateAvailableSpacesForTicket(
547
-        $datetime_identifier,
548
-        $reg_limit,
549
-        $ticket_identifier,
550
-        $spaces_allocated
551
-    ) {
552
-        // make sure ticket quantity is set
553
-        $ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
554
-            ? $this->ticket_quantities[ $ticket_identifier ]
555
-            : 0;
556
-        if ($this->debug) {
557
-            \EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
558
-            \EEH_Debug_Tools::printr(
559
-                "{$ticket_quantity}",
560
-                "ticket $ticket_identifier quantity: ",
561
-                __FILE__,
562
-                __LINE__,
563
-                2
564
-            );
565
-        }
566
-        if ($ticket_quantity) {
567
-            if ($this->debug) {
568
-                \EEH_Debug_Tools::printr(
569
-                    ($spaces_allocated <= $reg_limit)
570
-                        ? 'true'
571
-                        : 'false',
572
-                    ' . spaces_allocated <= reg_limit = ',
573
-                    __FILE__,
574
-                    __LINE__
575
-                );
576
-            }
577
-            // if the datetime is NOT at full capacity yet
578
-            if ($spaces_allocated <= $reg_limit) {
579
-                // then the maximum ticket quantity we can allocate is the lowest value of either:
580
-                //  the number of remaining spaces for the datetime, which is the limit - spaces already taken
581
-                //  or the maximum ticket quantity
582
-                $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
583
-                // adjust the available quantity in our tracking array
584
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
585
-                // and increment spaces allocated for this datetime
586
-                $spaces_allocated += $ticket_quantity;
587
-                $at_capacity = $spaces_allocated >= $reg_limit;
588
-                if ($this->debug) {
589
-                    \EEH_Debug_Tools::printr(
590
-                        "{$ticket_quantity} {$ticket_identifier} tickets",
591
-                        ' > > allocate ',
592
-                        __FILE__,
593
-                        __LINE__,
594
-                        3
595
-                    );
596
-                    if ($at_capacity) {
597
-                        \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
598
-                    }
599
-                }
600
-                // now adjust all other datetimes that allow access to this ticket
601
-                $this->adjustDatetimes(
602
-                    $datetime_identifier,
603
-                    $ticket_identifier,
604
-                    $ticket_quantity,
605
-                    $at_capacity
606
-                );
607
-            }
608
-        }
609
-        return $spaces_allocated;
610
-    }
611
-
612
-
613
-    /**
614
-     * subtracts ticket amounts from all datetime reg limits
615
-     * that allow access to the ticket specified,
616
-     * because that ticket could be used
617
-     * to attend any of the datetimes it has access to
618
-     *
619
-     * @param string $datetime_identifier
620
-     * @param string $ticket_identifier
621
-     * @param bool   $at_capacity
622
-     * @param int    $ticket_quantity
623
-     */
624
-    private function adjustDatetimes(
625
-        $datetime_identifier,
626
-        $ticket_identifier,
627
-        $ticket_quantity,
628
-        $at_capacity
629
-    ) {
630
-        /** @var array $datetime_tickets */
631
-        foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
632
-            if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
633
-                continue;
634
-            }
635
-            $adjusted = $this->adjustDatetimeSpaces(
636
-                $datetime_ID,
637
-                $ticket_identifier,
638
-                $ticket_quantity
639
-            );
640
-            // skip to next ticket if nothing changed
641
-            if (! ($adjusted || $at_capacity)) {
642
-                continue;
643
-            }
644
-            // then all of it's tickets are now unavailable
645
-            foreach ($datetime_tickets as $datetime_ticket) {
646
-                if (
647
-                    ($ticket_identifier === $datetime_ticket || $at_capacity)
648
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
649
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
650
-                ) {
651
-                    if ($this->debug) {
652
-                        \EEH_Debug_Tools::printr(
653
-                            $datetime_ticket,
654
-                            ' . . . adjust ticket quantities for',
655
-                            __FILE__,
656
-                            __LINE__
657
-                        );
658
-                    }
659
-                    // if this datetime is at full capacity, set any tracked available quantities to zero
660
-                    // otherwise just subtract the ticket quantity
661
-                    $new_quantity = $at_capacity
662
-                        ? 0
663
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
664
-                    // don't let ticket quantity go below zero
665
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
666
-                    if ($this->debug) {
667
-                        \EEH_Debug_Tools::printr(
668
-                            $at_capacity
669
-                                ? "0 because Datetime {$datetime_identifier} is at capacity"
670
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
671
-                            " . . . . {$datetime_ticket} quantity set to ",
672
-                            __FILE__,
673
-                            __LINE__
674
-                        );
675
-                    }
676
-                }
677
-                // but we also need to adjust spaces for any other datetimes this ticket has access to
678
-                if ($datetime_ticket === $ticket_identifier) {
679
-                    if (
680
-                        isset($this->ticket_datetimes[ $datetime_ticket ])
681
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
682
-                    ) {
683
-                        if ($this->debug) {
684
-                            \EEH_Debug_Tools::printr(
685
-                                $datetime_ticket,
686
-                                ' . . adjust other Datetimes for',
687
-                                __FILE__,
688
-                                __LINE__
689
-                            );
690
-                        }
691
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
692
-                            // don't adjust the current datetime twice
693
-                            if ($datetime !== $datetime_identifier) {
694
-                                $this->adjustDatetimeSpaces(
695
-                                    $datetime,
696
-                                    $datetime_ticket,
697
-                                    $ticket_quantity
698
-                                );
699
-                            }
700
-                        }
701
-                    }
702
-                }
703
-            }
704
-        }
705
-    }
706
-
707
-    private function adjustDatetimeSpaces($datetime_identifier, $ticket_identifier, $ticket_quantity = 0)
708
-    {
709
-        // does datetime have spaces available?
710
-        // and does the supplied ticket have access to this datetime ?
711
-        if (
712
-            $this->datetime_spaces[ $datetime_identifier ] > 0
713
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
714
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
715
-        ) {
716
-            if ($this->debug) {
717
-                \EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
718
-                \EEH_Debug_Tools::printr(
719
-                    "{$this->datetime_spaces[ $datetime_identifier ]}",
720
-                    " . . current  {$datetime_identifier} spaces available",
721
-                    __FILE__,
722
-                    __LINE__
723
-                );
724
-            }
725
-            // then decrement the available spaces for the datetime
726
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
727
-            // but don't let quantities go below zero
728
-            $this->datetime_spaces[ $datetime_identifier ] = max(
729
-                $this->datetime_spaces[ $datetime_identifier ],
730
-                0
731
-            );
732
-            if ($this->debug) {
733
-                \EEH_Debug_Tools::printr(
734
-                    "{$ticket_quantity}",
735
-                    " . . . {$datetime_identifier} capacity reduced by",
736
-                    __FILE__,
737
-                    __LINE__
738
-                );
739
-            }
740
-            return true;
741
-        }
742
-        return false;
743
-    }
29
+	/**
30
+	 * @var EE_Event $event
31
+	 */
32
+	private $event;
33
+
34
+	/**
35
+	 * @var array $datetime_query_params
36
+	 */
37
+	private $datetime_query_params;
38
+
39
+	/**
40
+	 * @var EE_Ticket[] $active_tickets
41
+	 */
42
+	private $active_tickets = array();
43
+
44
+	/**
45
+	 * @var EE_Datetime[] $datetimes
46
+	 */
47
+	private $datetimes = array();
48
+
49
+	/**
50
+	 * Array of Ticket IDs grouped by Datetime
51
+	 *
52
+	 * @var array $datetimes
53
+	 */
54
+	private $datetime_tickets = array();
55
+
56
+	/**
57
+	 * Max spaces for each Datetime (reg limit - previous sold)
58
+	 *
59
+	 * @var array $datetime_spaces
60
+	 */
61
+	private $datetime_spaces = array();
62
+
63
+	/**
64
+	 * Array of Datetime IDs grouped by Ticket
65
+	 *
66
+	 * @var array[] $ticket_datetimes
67
+	 */
68
+	private $ticket_datetimes = array();
69
+
70
+	/**
71
+	 * maximum ticket quantities for each ticket (adjusted for reg limit)
72
+	 *
73
+	 * @var array $ticket_quantities
74
+	 */
75
+	private $ticket_quantities = array();
76
+
77
+	/**
78
+	 * total quantity of sold and reserved for each ticket
79
+	 *
80
+	 * @var array $tickets_sold
81
+	 */
82
+	private $tickets_sold = array();
83
+
84
+	/**
85
+	 * total spaces available across all datetimes
86
+	 *
87
+	 * @var array $total_spaces
88
+	 */
89
+	private $total_spaces = array();
90
+
91
+	/**
92
+	 * @var boolean $debug
93
+	 */
94
+	private $debug = false; // true false
95
+
96
+	/**
97
+	 * @var null|int $spaces_remaining
98
+	 */
99
+	private $spaces_remaining;
100
+
101
+	/**
102
+	 * @var null|int $total_spaces_available
103
+	 */
104
+	private $total_spaces_available;
105
+
106
+
107
+	/**
108
+	 * EventSpacesCalculator constructor.
109
+	 *
110
+	 * @param EE_Event $event
111
+	 * @param array    $datetime_query_params
112
+	 * @throws EE_Error
113
+	 */
114
+	public function __construct(EE_Event $event, array $datetime_query_params = array())
115
+	{
116
+		if ($this->debug) {
117
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 1);
118
+			\EEH_Debug_Tools::printr((string) $event->ID(), 'For event', __FILE__, __LINE__);
119
+		}
120
+		$this->event = $event;
121
+		$this->datetime_query_params = $datetime_query_params + array('order_by' => array('DTT_reg_limit' => 'ASC'));
122
+		$this->setHooks();
123
+	}
124
+
125
+
126
+	/**
127
+	 * @return void
128
+	 */
129
+	private function setHooks()
130
+	{
131
+		add_action('AHEE__EE_Ticket__increase_sold', array($this, 'clearResults'));
132
+		add_action('AHEE__EE_Ticket__decrease_sold', array($this, 'clearResults'));
133
+		add_action('AHEE__EE_Datetime__increase_sold', array($this, 'clearResults'));
134
+		add_action('AHEE__EE_Datetime__decrease_sold', array($this, 'clearResults'));
135
+		add_action('AHEE__EE_Ticket__increase_reserved', array($this, 'clearResults'));
136
+		add_action('AHEE__EE_Ticket__decrease_reserved', array($this, 'clearResults'));
137
+		add_action('AHEE__EE_Datetime__increase_reserved', array($this, 'clearResults'));
138
+		add_action('AHEE__EE_Datetime__decrease_reserved', array($this, 'clearResults'));
139
+	}
140
+
141
+
142
+	/**
143
+	 * @return void
144
+	 */
145
+	public function clearResults()
146
+	{
147
+		if ($this->debug) {
148
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 1);
149
+		}
150
+		$this->spaces_remaining = null;
151
+		$this->total_spaces_available = null;
152
+	}
153
+
154
+
155
+	/**
156
+	 * @return EE_Ticket[]
157
+	 * @throws EE_Error
158
+	 * @throws InvalidDataTypeException
159
+	 * @throws InvalidInterfaceException
160
+	 * @throws InvalidArgumentException
161
+	 */
162
+	public function getActiveTickets()
163
+	{
164
+		if (empty($this->active_tickets)) {
165
+			$this->active_tickets = $this->event->tickets(
166
+				array(
167
+					array('TKT_deleted' => false),
168
+					'order_by' => array('TKT_qty' => 'ASC'),
169
+				)
170
+			);
171
+		}
172
+		return $this->active_tickets;
173
+	}
174
+
175
+
176
+	/**
177
+	 * @param EE_Ticket[] $active_tickets
178
+	 * @throws EE_Error
179
+	 * @throws DomainException
180
+	 * @throws UnexpectedEntityException
181
+	 */
182
+	public function setActiveTickets(array $active_tickets = array())
183
+	{
184
+		if (! empty($active_tickets)) {
185
+			foreach ($active_tickets as $active_ticket) {
186
+				$this->validateTicket($active_ticket);
187
+			}
188
+			// sort incoming array by ticket quantity (asc)
189
+			usort(
190
+				$active_tickets,
191
+				function (EE_Ticket $a, EE_Ticket $b) {
192
+					if ($a->qty() === $b->qty()) {
193
+						return 0;
194
+					}
195
+					return ($a->qty() < $b->qty())
196
+						? -1
197
+						: 1;
198
+				}
199
+			);
200
+		}
201
+		$this->active_tickets = $active_tickets;
202
+	}
203
+
204
+
205
+	/**
206
+	 * @param $ticket
207
+	 * @throws DomainException
208
+	 * @throws EE_Error
209
+	 * @throws UnexpectedEntityException
210
+	 */
211
+	private function validateTicket($ticket)
212
+	{
213
+		if (! $ticket instanceof EE_Ticket) {
214
+			throw new DomainException(
215
+				esc_html__(
216
+					'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
217
+					'event_espresso'
218
+				)
219
+			);
220
+		}
221
+		if ($ticket->get_event_ID() !== $this->event->ID()) {
222
+			throw new DomainException(
223
+				sprintf(
224
+					esc_html__(
225
+						'An EE_Ticket for Event %1$d was supplied while calculating event space availability for Event %2$d.',
226
+						'event_espresso'
227
+					),
228
+					$ticket->get_event_ID(),
229
+					$this->event->ID()
230
+				)
231
+			);
232
+		}
233
+	}
234
+
235
+
236
+	/**
237
+	 * @return EE_Datetime[]
238
+	 */
239
+	public function getDatetimes()
240
+	{
241
+		return $this->datetimes;
242
+	}
243
+
244
+
245
+	/**
246
+	 * @param EE_Datetime $datetime
247
+	 * @throws EE_Error
248
+	 * @throws DomainException
249
+	 */
250
+	public function setDatetime(EE_Datetime $datetime)
251
+	{
252
+		if ($datetime->event()->ID() !== $this->event->ID()) {
253
+			throw new DomainException(
254
+				sprintf(
255
+					esc_html__(
256
+						'An EE_Datetime for Event %1$d was supplied while calculating event space availability for Event %2$d.',
257
+						'event_espresso'
258
+					),
259
+					$datetime->event()->ID(),
260
+					$this->event->ID()
261
+				)
262
+			);
263
+		}
264
+		$this->datetimes[ $datetime->ID() ] = $datetime;
265
+	}
266
+
267
+
268
+	/**
269
+	 * calculate spaces remaining based on "saleable" tickets
270
+	 *
271
+	 * @return float|int
272
+	 * @throws EE_Error
273
+	 * @throws DomainException
274
+	 * @throws UnexpectedEntityException
275
+	 * @throws InvalidDataTypeException
276
+	 * @throws InvalidInterfaceException
277
+	 * @throws InvalidArgumentException
278
+	 */
279
+	public function spacesRemaining()
280
+	{
281
+		if ($this->debug) {
282
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
283
+		}
284
+		if ($this->spaces_remaining === null) {
285
+			$this->initialize();
286
+			$this->spaces_remaining = $this->calculate();
287
+		}
288
+		return $this->spaces_remaining;
289
+	}
290
+
291
+
292
+	/**
293
+	 * calculates total available spaces for an event with no regard for sold tickets
294
+	 *
295
+	 * @return int|float
296
+	 * @throws EE_Error
297
+	 * @throws DomainException
298
+	 * @throws UnexpectedEntityException
299
+	 * @throws InvalidDataTypeException
300
+	 * @throws InvalidInterfaceException
301
+	 * @throws InvalidArgumentException
302
+	 */
303
+	public function totalSpacesAvailable()
304
+	{
305
+		if ($this->debug) {
306
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
307
+		}
308
+		if ($this->total_spaces_available === null) {
309
+			$this->initialize();
310
+			$this->total_spaces_available = $this->calculate(false);
311
+		}
312
+		return $this->total_spaces_available;
313
+	}
314
+
315
+
316
+	/**
317
+	 * Loops through the active tickets for the event
318
+	 * and builds a series of data arrays that will be used for calculating
319
+	 * the total maximum available spaces, as well as the spaces remaining.
320
+	 * Because ticket quantities affect datetime spaces and vice versa,
321
+	 * we need to be constantly updating these data arrays as things change,
322
+	 * which is the entire reason for their existence.
323
+	 *
324
+	 * @throws EE_Error
325
+	 * @throws DomainException
326
+	 * @throws UnexpectedEntityException
327
+	 * @throws InvalidDataTypeException
328
+	 * @throws InvalidInterfaceException
329
+	 * @throws InvalidArgumentException
330
+	 */
331
+	private function initialize()
332
+	{
333
+		if ($this->debug) {
334
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
335
+		}
336
+		$this->datetime_tickets = array();
337
+		$this->datetime_spaces = array();
338
+		$this->ticket_datetimes = array();
339
+		$this->ticket_quantities = array();
340
+		$this->tickets_sold = array();
341
+		$this->total_spaces = array();
342
+		$active_tickets = $this->getActiveTickets();
343
+		if (! empty($active_tickets)) {
344
+			foreach ($active_tickets as $ticket) {
345
+				$this->validateTicket($ticket);
346
+				// we need to index our data arrays using strings for the purpose of sorting,
347
+				// but we also need them to be unique, so  we'll just prepend a letter T to the ID
348
+				$ticket_identifier = "T{$ticket->ID()}";
349
+				// to start, we'll just consider the raw qty to be the maximum availability for this ticket,
350
+				// unless the ticket is past its "sell until" date, in which case the qty will be 0
351
+				$max_tickets = $ticket->is_expired() ? 0 : $ticket->qty();
352
+				// but we'll adjust that after looping over each datetime for the ticket and checking reg limits
353
+				$ticket_datetimes = $ticket->datetimes($this->datetime_query_params);
354
+				foreach ($ticket_datetimes as $datetime) {
355
+					// save all datetimes
356
+					$this->setDatetime($datetime);
357
+					$datetime_identifier = "D{$datetime->ID()}";
358
+					$reg_limit = $datetime->reg_limit();
359
+					// ticket quantity can not exceed datetime reg limit
360
+					$max_tickets = min($max_tickets, $reg_limit);
361
+					// as described earlier, because we need to be able to constantly adjust numbers for things,
362
+					// we are going to move all of our data into the following arrays:
363
+					// datetime spaces initially represents the reg limit for each datetime,
364
+					// but this will get adjusted as tickets are accounted for
365
+					$this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
366
+					// just an array of ticket IDs grouped by datetime
367
+					$this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
368
+					// and an array of datetime IDs grouped by ticket
369
+					$this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
370
+				}
371
+				// total quantity of sold and reserved for each ticket
372
+				$this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
373
+				// and the maximum ticket quantities for each ticket (adjusted for reg limit)
374
+				$this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
375
+			}
376
+		}
377
+		// sort datetime spaces by reg limit, but maintain our string indexes
378
+		asort($this->datetime_spaces, SORT_NUMERIC);
379
+		// datetime tickets need to be sorted in the SAME order as the above array...
380
+		// so we'll just use array_merge() to take the structure of datetime_spaces
381
+		// but overwrite all of the data with that from datetime_tickets
382
+		$this->datetime_tickets = array_merge(
383
+			$this->datetime_spaces,
384
+			$this->datetime_tickets
385
+		);
386
+		if ($this->debug) {
387
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
388
+			\EEH_Debug_Tools::printr($this->datetime_tickets, 'datetime_tickets', __FILE__, __LINE__);
389
+			\EEH_Debug_Tools::printr($this->ticket_quantities, 'ticket_quantities', __FILE__, __LINE__);
390
+		}
391
+	}
392
+
393
+
394
+	/**
395
+	 * performs calculations on initialized data
396
+	 *
397
+	 * @param bool $consider_sold
398
+	 * @return int|float
399
+	 */
400
+	private function calculate($consider_sold = true)
401
+	{
402
+		if ($this->debug) {
403
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
404
+			\EEH_Debug_Tools::printr($consider_sold, '$consider_sold', __FILE__, __LINE__);
405
+		}
406
+		if ($consider_sold) {
407
+			// subtract amounts sold from all ticket quantities and datetime spaces
408
+			$this->adjustTicketQuantitiesDueToSales();
409
+		}
410
+		foreach ($this->datetime_tickets as $datetime_identifier => $tickets) {
411
+			$this->trackAvailableSpacesForDatetimes($datetime_identifier, $tickets);
412
+		}
413
+		// total spaces available is just the sum of the spaces available for each datetime
414
+		$spaces_remaining = array_sum($this->total_spaces);
415
+		if ($this->debug) {
416
+			\EEH_Debug_Tools::printr($this->total_spaces, '$this->total_spaces', __FILE__, __LINE__);
417
+			\EEH_Debug_Tools::printr($this->tickets_sold, '$this->tickets_sold', __FILE__, __LINE__);
418
+			\EEH_Debug_Tools::printr($spaces_remaining, '$spaces_remaining', __FILE__, __LINE__);
419
+		}
420
+		return $spaces_remaining;
421
+	}
422
+
423
+
424
+	/**
425
+	 * subtracts amount of  tickets sold from ticket quantities and datetime spaces
426
+	 */
427
+	private function adjustTicketQuantitiesDueToSales()
428
+	{
429
+		if ($this->debug) {
430
+			\EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
431
+		}
432
+		foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
433
+			if (isset($this->ticket_quantities[ $ticket_identifier ])) {
434
+				$this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
435
+				// don't let values go below zero
436
+				$this->ticket_quantities[ $ticket_identifier ] = max(
437
+					$this->ticket_quantities[ $ticket_identifier ],
438
+					0
439
+				);
440
+				if ($this->debug) {
441
+					\EEH_Debug_Tools::printr(
442
+						"{$tickets_sold} sales for ticket {$ticket_identifier} ",
443
+						'subtracting',
444
+						__FILE__,
445
+						__LINE__
446
+					);
447
+				}
448
+			}
449
+			if (
450
+				isset($this->ticket_datetimes[ $ticket_identifier ])
451
+				&& is_array($this->ticket_datetimes[ $ticket_identifier ])
452
+			) {
453
+				foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
454
+					if (isset($this->ticket_quantities[ $ticket_identifier ])) {
455
+						$this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
456
+						// don't let values go below zero
457
+						$this->datetime_spaces[ $ticket_datetime ] = max(
458
+							$this->datetime_spaces[ $ticket_datetime ],
459
+							0
460
+						);
461
+						if ($this->debug) {
462
+							\EEH_Debug_Tools::printr(
463
+								"{$tickets_sold} sales for datetime {$ticket_datetime} ",
464
+								'subtracting',
465
+								__FILE__,
466
+								__LINE__
467
+							);
468
+						}
469
+					}
470
+				}
471
+			}
472
+		}
473
+	}
474
+
475
+
476
+	/**
477
+	 * @param string $datetime_identifier
478
+	 * @param array  $tickets
479
+	 */
480
+	private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
481
+	{
482
+		// make sure a reg limit is set for the datetime
483
+		$reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
484
+			? $this->datetime_spaces[ $datetime_identifier ]
485
+			: 0;
486
+		// and bail if it is not
487
+		if (! $reg_limit) {
488
+			if ($this->debug) {
489
+				\EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
490
+			}
491
+			return;
492
+		}
493
+		if ($this->debug) {
494
+			\EEH_Debug_Tools::printr($datetime_identifier, '* $datetime_identifier', __FILE__, __LINE__, 1);
495
+			\EEH_Debug_Tools::printr(
496
+				"{$reg_limit}",
497
+				'REG LIMIT',
498
+				__FILE__,
499
+				__LINE__
500
+			);
501
+		}
502
+		// number of allocated spaces always starts at zero
503
+		$spaces_allocated = 0;
504
+		$this->total_spaces[ $datetime_identifier ] = 0;
505
+		foreach ($tickets as $ticket_identifier) {
506
+			$spaces_allocated = $this->calculateAvailableSpacesForTicket(
507
+				$datetime_identifier,
508
+				$reg_limit,
509
+				$ticket_identifier,
510
+				$spaces_allocated
511
+			);
512
+		}
513
+		// spaces can't be negative
514
+		$spaces_allocated = max($spaces_allocated, 0);
515
+		if ($spaces_allocated) {
516
+			// track any non-zero values
517
+			$this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
518
+			if ($this->debug) {
519
+				\EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
520
+			}
521
+		} else {
522
+			if ($this->debug) {
523
+				\EEH_Debug_Tools::printr(' ', ' . NO TICKETS AVAILABLE FOR DATETIME', __FILE__, __LINE__);
524
+			}
525
+		}
526
+		if ($this->debug) {
527
+			\EEH_Debug_Tools::printr(
528
+				$this->total_spaces[ $datetime_identifier ],
529
+				'$total_spaces',
530
+				__FILE__,
531
+				__LINE__
532
+			);
533
+			\EEH_Debug_Tools::printr($this->ticket_quantities, '$ticket_quantities', __FILE__, __LINE__);
534
+			\EEH_Debug_Tools::printr($this->datetime_spaces, 'datetime_spaces', __FILE__, __LINE__);
535
+		}
536
+	}
537
+
538
+
539
+	/**
540
+	 * @param string $datetime_identifier
541
+	 * @param int    $reg_limit
542
+	 * @param string $ticket_identifier
543
+	 * @param int    $spaces_allocated
544
+	 * @return int
545
+	 */
546
+	private function calculateAvailableSpacesForTicket(
547
+		$datetime_identifier,
548
+		$reg_limit,
549
+		$ticket_identifier,
550
+		$spaces_allocated
551
+	) {
552
+		// make sure ticket quantity is set
553
+		$ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
554
+			? $this->ticket_quantities[ $ticket_identifier ]
555
+			: 0;
556
+		if ($this->debug) {
557
+			\EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
558
+			\EEH_Debug_Tools::printr(
559
+				"{$ticket_quantity}",
560
+				"ticket $ticket_identifier quantity: ",
561
+				__FILE__,
562
+				__LINE__,
563
+				2
564
+			);
565
+		}
566
+		if ($ticket_quantity) {
567
+			if ($this->debug) {
568
+				\EEH_Debug_Tools::printr(
569
+					($spaces_allocated <= $reg_limit)
570
+						? 'true'
571
+						: 'false',
572
+					' . spaces_allocated <= reg_limit = ',
573
+					__FILE__,
574
+					__LINE__
575
+				);
576
+			}
577
+			// if the datetime is NOT at full capacity yet
578
+			if ($spaces_allocated <= $reg_limit) {
579
+				// then the maximum ticket quantity we can allocate is the lowest value of either:
580
+				//  the number of remaining spaces for the datetime, which is the limit - spaces already taken
581
+				//  or the maximum ticket quantity
582
+				$ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
583
+				// adjust the available quantity in our tracking array
584
+				$this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
585
+				// and increment spaces allocated for this datetime
586
+				$spaces_allocated += $ticket_quantity;
587
+				$at_capacity = $spaces_allocated >= $reg_limit;
588
+				if ($this->debug) {
589
+					\EEH_Debug_Tools::printr(
590
+						"{$ticket_quantity} {$ticket_identifier} tickets",
591
+						' > > allocate ',
592
+						__FILE__,
593
+						__LINE__,
594
+						3
595
+					);
596
+					if ($at_capacity) {
597
+						\EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__, 3);
598
+					}
599
+				}
600
+				// now adjust all other datetimes that allow access to this ticket
601
+				$this->adjustDatetimes(
602
+					$datetime_identifier,
603
+					$ticket_identifier,
604
+					$ticket_quantity,
605
+					$at_capacity
606
+				);
607
+			}
608
+		}
609
+		return $spaces_allocated;
610
+	}
611
+
612
+
613
+	/**
614
+	 * subtracts ticket amounts from all datetime reg limits
615
+	 * that allow access to the ticket specified,
616
+	 * because that ticket could be used
617
+	 * to attend any of the datetimes it has access to
618
+	 *
619
+	 * @param string $datetime_identifier
620
+	 * @param string $ticket_identifier
621
+	 * @param bool   $at_capacity
622
+	 * @param int    $ticket_quantity
623
+	 */
624
+	private function adjustDatetimes(
625
+		$datetime_identifier,
626
+		$ticket_identifier,
627
+		$ticket_quantity,
628
+		$at_capacity
629
+	) {
630
+		/** @var array $datetime_tickets */
631
+		foreach ($this->datetime_tickets as $datetime_ID => $datetime_tickets) {
632
+			if ($datetime_ID !== $datetime_identifier || ! is_array($datetime_tickets)) {
633
+				continue;
634
+			}
635
+			$adjusted = $this->adjustDatetimeSpaces(
636
+				$datetime_ID,
637
+				$ticket_identifier,
638
+				$ticket_quantity
639
+			);
640
+			// skip to next ticket if nothing changed
641
+			if (! ($adjusted || $at_capacity)) {
642
+				continue;
643
+			}
644
+			// then all of it's tickets are now unavailable
645
+			foreach ($datetime_tickets as $datetime_ticket) {
646
+				if (
647
+					($ticket_identifier === $datetime_ticket || $at_capacity)
648
+					&& isset($this->ticket_quantities[ $datetime_ticket ])
649
+					&& $this->ticket_quantities[ $datetime_ticket ] > 0
650
+				) {
651
+					if ($this->debug) {
652
+						\EEH_Debug_Tools::printr(
653
+							$datetime_ticket,
654
+							' . . . adjust ticket quantities for',
655
+							__FILE__,
656
+							__LINE__
657
+						);
658
+					}
659
+					// if this datetime is at full capacity, set any tracked available quantities to zero
660
+					// otherwise just subtract the ticket quantity
661
+					$new_quantity = $at_capacity
662
+						? 0
663
+						: $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
664
+					// don't let ticket quantity go below zero
665
+					$this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
666
+					if ($this->debug) {
667
+						\EEH_Debug_Tools::printr(
668
+							$at_capacity
669
+								? "0 because Datetime {$datetime_identifier} is at capacity"
670
+								: "{$this->ticket_quantities[ $datetime_ticket ]}",
671
+							" . . . . {$datetime_ticket} quantity set to ",
672
+							__FILE__,
673
+							__LINE__
674
+						);
675
+					}
676
+				}
677
+				// but we also need to adjust spaces for any other datetimes this ticket has access to
678
+				if ($datetime_ticket === $ticket_identifier) {
679
+					if (
680
+						isset($this->ticket_datetimes[ $datetime_ticket ])
681
+						&& is_array($this->ticket_datetimes[ $datetime_ticket ])
682
+					) {
683
+						if ($this->debug) {
684
+							\EEH_Debug_Tools::printr(
685
+								$datetime_ticket,
686
+								' . . adjust other Datetimes for',
687
+								__FILE__,
688
+								__LINE__
689
+							);
690
+						}
691
+						foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
692
+							// don't adjust the current datetime twice
693
+							if ($datetime !== $datetime_identifier) {
694
+								$this->adjustDatetimeSpaces(
695
+									$datetime,
696
+									$datetime_ticket,
697
+									$ticket_quantity
698
+								);
699
+							}
700
+						}
701
+					}
702
+				}
703
+			}
704
+		}
705
+	}
706
+
707
+	private function adjustDatetimeSpaces($datetime_identifier, $ticket_identifier, $ticket_quantity = 0)
708
+	{
709
+		// does datetime have spaces available?
710
+		// and does the supplied ticket have access to this datetime ?
711
+		if (
712
+			$this->datetime_spaces[ $datetime_identifier ] > 0
713
+			&& isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
714
+			&& in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
715
+		) {
716
+			if ($this->debug) {
717
+				\EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
718
+				\EEH_Debug_Tools::printr(
719
+					"{$this->datetime_spaces[ $datetime_identifier ]}",
720
+					" . . current  {$datetime_identifier} spaces available",
721
+					__FILE__,
722
+					__LINE__
723
+				);
724
+			}
725
+			// then decrement the available spaces for the datetime
726
+			$this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
727
+			// but don't let quantities go below zero
728
+			$this->datetime_spaces[ $datetime_identifier ] = max(
729
+				$this->datetime_spaces[ $datetime_identifier ],
730
+				0
731
+			);
732
+			if ($this->debug) {
733
+				\EEH_Debug_Tools::printr(
734
+					"{$ticket_quantity}",
735
+					" . . . {$datetime_identifier} capacity reduced by",
736
+					__FILE__,
737
+					__LINE__
738
+				);
739
+			}
740
+			return true;
741
+		}
742
+		return false;
743
+	}
744 744
 }
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -181,14 +181,14 @@  discard block
 block discarded – undo
181 181
      */
182 182
     public function setActiveTickets(array $active_tickets = array())
183 183
     {
184
-        if (! empty($active_tickets)) {
184
+        if ( ! empty($active_tickets)) {
185 185
             foreach ($active_tickets as $active_ticket) {
186 186
                 $this->validateTicket($active_ticket);
187 187
             }
188 188
             // sort incoming array by ticket quantity (asc)
189 189
             usort(
190 190
                 $active_tickets,
191
-                function (EE_Ticket $a, EE_Ticket $b) {
191
+                function(EE_Ticket $a, EE_Ticket $b) {
192 192
                     if ($a->qty() === $b->qty()) {
193 193
                         return 0;
194 194
                     }
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
      */
211 211
     private function validateTicket($ticket)
212 212
     {
213
-        if (! $ticket instanceof EE_Ticket) {
213
+        if ( ! $ticket instanceof EE_Ticket) {
214 214
             throw new DomainException(
215 215
                 esc_html__(
216 216
                     'Invalid Ticket. Only EE_Ticket objects can be used to calculate event space availability.',
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
                 )
262 262
             );
263 263
         }
264
-        $this->datetimes[ $datetime->ID() ] = $datetime;
264
+        $this->datetimes[$datetime->ID()] = $datetime;
265 265
     }
266 266
 
267 267
 
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
         $this->tickets_sold = array();
341 341
         $this->total_spaces = array();
342 342
         $active_tickets = $this->getActiveTickets();
343
-        if (! empty($active_tickets)) {
343
+        if ( ! empty($active_tickets)) {
344 344
             foreach ($active_tickets as $ticket) {
345 345
                 $this->validateTicket($ticket);
346 346
                 // we need to index our data arrays using strings for the purpose of sorting,
@@ -362,16 +362,16 @@  discard block
 block discarded – undo
362 362
                     // we are going to move all of our data into the following arrays:
363 363
                     // datetime spaces initially represents the reg limit for each datetime,
364 364
                     // but this will get adjusted as tickets are accounted for
365
-                    $this->datetime_spaces[ $datetime_identifier ] = $reg_limit;
365
+                    $this->datetime_spaces[$datetime_identifier] = $reg_limit;
366 366
                     // just an array of ticket IDs grouped by datetime
367
-                    $this->datetime_tickets[ $datetime_identifier ][] = $ticket_identifier;
367
+                    $this->datetime_tickets[$datetime_identifier][] = $ticket_identifier;
368 368
                     // and an array of datetime IDs grouped by ticket
369
-                    $this->ticket_datetimes[ $ticket_identifier ][] = $datetime_identifier;
369
+                    $this->ticket_datetimes[$ticket_identifier][] = $datetime_identifier;
370 370
                 }
371 371
                 // total quantity of sold and reserved for each ticket
372
-                $this->tickets_sold[ $ticket_identifier ] = $ticket->sold() + $ticket->reserved();
372
+                $this->tickets_sold[$ticket_identifier] = $ticket->sold() + $ticket->reserved();
373 373
                 // and the maximum ticket quantities for each ticket (adjusted for reg limit)
374
-                $this->ticket_quantities[ $ticket_identifier ] = $max_tickets;
374
+                $this->ticket_quantities[$ticket_identifier] = $max_tickets;
375 375
             }
376 376
         }
377 377
         // sort datetime spaces by reg limit, but maintain our string indexes
@@ -430,11 +430,11 @@  discard block
 block discarded – undo
430 430
             \EEH_Debug_Tools::printr(__FUNCTION__, __CLASS__, __FILE__, __LINE__, 2);
431 431
         }
432 432
         foreach ($this->tickets_sold as $ticket_identifier => $tickets_sold) {
433
-            if (isset($this->ticket_quantities[ $ticket_identifier ])) {
434
-                $this->ticket_quantities[ $ticket_identifier ] -= $tickets_sold;
433
+            if (isset($this->ticket_quantities[$ticket_identifier])) {
434
+                $this->ticket_quantities[$ticket_identifier] -= $tickets_sold;
435 435
                 // don't let values go below zero
436
-                $this->ticket_quantities[ $ticket_identifier ] = max(
437
-                    $this->ticket_quantities[ $ticket_identifier ],
436
+                $this->ticket_quantities[$ticket_identifier] = max(
437
+                    $this->ticket_quantities[$ticket_identifier],
438 438
                     0
439 439
                 );
440 440
                 if ($this->debug) {
@@ -447,15 +447,15 @@  discard block
 block discarded – undo
447 447
                 }
448 448
             }
449 449
             if (
450
-                isset($this->ticket_datetimes[ $ticket_identifier ])
451
-                && is_array($this->ticket_datetimes[ $ticket_identifier ])
450
+                isset($this->ticket_datetimes[$ticket_identifier])
451
+                && is_array($this->ticket_datetimes[$ticket_identifier])
452 452
             ) {
453
-                foreach ($this->ticket_datetimes[ $ticket_identifier ] as $ticket_datetime) {
454
-                    if (isset($this->ticket_quantities[ $ticket_identifier ])) {
455
-                        $this->datetime_spaces[ $ticket_datetime ] -= $tickets_sold;
453
+                foreach ($this->ticket_datetimes[$ticket_identifier] as $ticket_datetime) {
454
+                    if (isset($this->ticket_quantities[$ticket_identifier])) {
455
+                        $this->datetime_spaces[$ticket_datetime] -= $tickets_sold;
456 456
                         // don't let values go below zero
457
-                        $this->datetime_spaces[ $ticket_datetime ] = max(
458
-                            $this->datetime_spaces[ $ticket_datetime ],
457
+                        $this->datetime_spaces[$ticket_datetime] = max(
458
+                            $this->datetime_spaces[$ticket_datetime],
459 459
                             0
460 460
                         );
461 461
                         if ($this->debug) {
@@ -480,11 +480,11 @@  discard block
 block discarded – undo
480 480
     private function trackAvailableSpacesForDatetimes($datetime_identifier, array $tickets)
481 481
     {
482 482
         // make sure a reg limit is set for the datetime
483
-        $reg_limit = isset($this->datetime_spaces[ $datetime_identifier ])
484
-            ? $this->datetime_spaces[ $datetime_identifier ]
483
+        $reg_limit = isset($this->datetime_spaces[$datetime_identifier])
484
+            ? $this->datetime_spaces[$datetime_identifier]
485 485
             : 0;
486 486
         // and bail if it is not
487
-        if (! $reg_limit) {
487
+        if ( ! $reg_limit) {
488 488
             if ($this->debug) {
489 489
                 \EEH_Debug_Tools::printr('AT CAPACITY', " . {$datetime_identifier}", __FILE__, __LINE__);
490 490
             }
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
         }
502 502
         // number of allocated spaces always starts at zero
503 503
         $spaces_allocated = 0;
504
-        $this->total_spaces[ $datetime_identifier ] = 0;
504
+        $this->total_spaces[$datetime_identifier] = 0;
505 505
         foreach ($tickets as $ticket_identifier) {
506 506
             $spaces_allocated = $this->calculateAvailableSpacesForTicket(
507 507
                 $datetime_identifier,
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
         $spaces_allocated = max($spaces_allocated, 0);
515 515
         if ($spaces_allocated) {
516 516
             // track any non-zero values
517
-            $this->total_spaces[ $datetime_identifier ] += $spaces_allocated;
517
+            $this->total_spaces[$datetime_identifier] += $spaces_allocated;
518 518
             if ($this->debug) {
519 519
                 \EEH_Debug_Tools::printr((string) $spaces_allocated, ' . $spaces_allocated: ', __FILE__, __LINE__);
520 520
             }
@@ -525,7 +525,7 @@  discard block
 block discarded – undo
525 525
         }
526 526
         if ($this->debug) {
527 527
             \EEH_Debug_Tools::printr(
528
-                $this->total_spaces[ $datetime_identifier ],
528
+                $this->total_spaces[$datetime_identifier],
529 529
                 '$total_spaces',
530 530
                 __FILE__,
531 531
                 __LINE__
@@ -550,8 +550,8 @@  discard block
 block discarded – undo
550 550
         $spaces_allocated
551 551
     ) {
552 552
         // make sure ticket quantity is set
553
-        $ticket_quantity = isset($this->ticket_quantities[ $ticket_identifier ])
554
-            ? $this->ticket_quantities[ $ticket_identifier ]
553
+        $ticket_quantity = isset($this->ticket_quantities[$ticket_identifier])
554
+            ? $this->ticket_quantities[$ticket_identifier]
555 555
             : 0;
556 556
         if ($this->debug) {
557 557
             \EEH_Debug_Tools::printr("{$spaces_allocated}", '$spaces_allocated', __FILE__, __LINE__);
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
                 //  or the maximum ticket quantity
582 582
                 $ticket_quantity = min($reg_limit - $spaces_allocated, $ticket_quantity);
583 583
                 // adjust the available quantity in our tracking array
584
-                $this->ticket_quantities[ $ticket_identifier ] -= $ticket_quantity;
584
+                $this->ticket_quantities[$ticket_identifier] -= $ticket_quantity;
585 585
                 // and increment spaces allocated for this datetime
586 586
                 $spaces_allocated += $ticket_quantity;
587 587
                 $at_capacity = $spaces_allocated >= $reg_limit;
@@ -638,15 +638,15 @@  discard block
 block discarded – undo
638 638
                 $ticket_quantity
639 639
             );
640 640
             // skip to next ticket if nothing changed
641
-            if (! ($adjusted || $at_capacity)) {
641
+            if ( ! ($adjusted || $at_capacity)) {
642 642
                 continue;
643 643
             }
644 644
             // then all of it's tickets are now unavailable
645 645
             foreach ($datetime_tickets as $datetime_ticket) {
646 646
                 if (
647 647
                     ($ticket_identifier === $datetime_ticket || $at_capacity)
648
-                    && isset($this->ticket_quantities[ $datetime_ticket ])
649
-                    && $this->ticket_quantities[ $datetime_ticket ] > 0
648
+                    && isset($this->ticket_quantities[$datetime_ticket])
649
+                    && $this->ticket_quantities[$datetime_ticket] > 0
650 650
                 ) {
651 651
                     if ($this->debug) {
652 652
                         \EEH_Debug_Tools::printr(
@@ -660,14 +660,14 @@  discard block
 block discarded – undo
660 660
                     // otherwise just subtract the ticket quantity
661 661
                     $new_quantity = $at_capacity
662 662
                         ? 0
663
-                        : $this->ticket_quantities[ $datetime_ticket ] - $ticket_quantity;
663
+                        : $this->ticket_quantities[$datetime_ticket] - $ticket_quantity;
664 664
                     // don't let ticket quantity go below zero
665
-                    $this->ticket_quantities[ $datetime_ticket ] = max($new_quantity, 0);
665
+                    $this->ticket_quantities[$datetime_ticket] = max($new_quantity, 0);
666 666
                     if ($this->debug) {
667 667
                         \EEH_Debug_Tools::printr(
668 668
                             $at_capacity
669 669
                                 ? "0 because Datetime {$datetime_identifier} is at capacity"
670
-                                : "{$this->ticket_quantities[ $datetime_ticket ]}",
670
+                                : "{$this->ticket_quantities[$datetime_ticket]}",
671 671
                             " . . . . {$datetime_ticket} quantity set to ",
672 672
                             __FILE__,
673 673
                             __LINE__
@@ -677,8 +677,8 @@  discard block
 block discarded – undo
677 677
                 // but we also need to adjust spaces for any other datetimes this ticket has access to
678 678
                 if ($datetime_ticket === $ticket_identifier) {
679 679
                     if (
680
-                        isset($this->ticket_datetimes[ $datetime_ticket ])
681
-                        && is_array($this->ticket_datetimes[ $datetime_ticket ])
680
+                        isset($this->ticket_datetimes[$datetime_ticket])
681
+                        && is_array($this->ticket_datetimes[$datetime_ticket])
682 682
                     ) {
683 683
                         if ($this->debug) {
684 684
                             \EEH_Debug_Tools::printr(
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
                                 __LINE__
689 689
                             );
690 690
                         }
691
-                        foreach ($this->ticket_datetimes[ $datetime_ticket ] as $datetime) {
691
+                        foreach ($this->ticket_datetimes[$datetime_ticket] as $datetime) {
692 692
                             // don't adjust the current datetime twice
693 693
                             if ($datetime !== $datetime_identifier) {
694 694
                                 $this->adjustDatetimeSpaces(
@@ -709,24 +709,24 @@  discard block
 block discarded – undo
709 709
         // does datetime have spaces available?
710 710
         // and does the supplied ticket have access to this datetime ?
711 711
         if (
712
-            $this->datetime_spaces[ $datetime_identifier ] > 0
713
-            && isset($this->datetime_spaces[ $datetime_identifier ], $this->datetime_tickets[ $datetime_identifier ])
714
-            && in_array($ticket_identifier, $this->datetime_tickets[ $datetime_identifier ], true)
712
+            $this->datetime_spaces[$datetime_identifier] > 0
713
+            && isset($this->datetime_spaces[$datetime_identifier], $this->datetime_tickets[$datetime_identifier])
714
+            && in_array($ticket_identifier, $this->datetime_tickets[$datetime_identifier], true)
715 715
         ) {
716 716
             if ($this->debug) {
717 717
                 \EEH_Debug_Tools::printr($datetime_identifier, ' . . adjust Datetime Spaces for', __FILE__, __LINE__);
718 718
                 \EEH_Debug_Tools::printr(
719
-                    "{$this->datetime_spaces[ $datetime_identifier ]}",
719
+                    "{$this->datetime_spaces[$datetime_identifier]}",
720 720
                     " . . current  {$datetime_identifier} spaces available",
721 721
                     __FILE__,
722 722
                     __LINE__
723 723
                 );
724 724
             }
725 725
             // then decrement the available spaces for the datetime
726
-            $this->datetime_spaces[ $datetime_identifier ] -= $ticket_quantity;
726
+            $this->datetime_spaces[$datetime_identifier] -= $ticket_quantity;
727 727
             // but don't let quantities go below zero
728
-            $this->datetime_spaces[ $datetime_identifier ] = max(
729
-                $this->datetime_spaces[ $datetime_identifier ],
728
+            $this->datetime_spaces[$datetime_identifier] = max(
729
+                $this->datetime_spaces[$datetime_identifier],
730 730
                 0
731 731
             );
732 732
             if ($this->debug) {
Please login to merge, or discard this patch.
core/domain/entities/shortcodes/EspressoEventAttendees.php 2 patches
Indentation   +310 added lines, -310 removed lines patch added patch discarded remove patch
@@ -31,339 +31,339 @@
 block discarded – undo
31 31
 class EspressoEventAttendees extends EspressoShortcode
32 32
 {
33 33
 
34
-    private $query_params = array(
35
-        0 => array(),
36
-    );
34
+	private $query_params = array(
35
+		0 => array(),
36
+	);
37 37
 
38
-    private $template_args = array(
39
-        'contacts' => array(),
40
-        'event'    => null,
41
-        'datetime' => null,
42
-        'ticket'   => null,
43
-    );
38
+	private $template_args = array(
39
+		'contacts' => array(),
40
+		'event'    => null,
41
+		'datetime' => null,
42
+		'ticket'   => null,
43
+	);
44 44
 
45
-    /**
46
-     * the actual shortcode tag that gets registered with WordPress
47
-     *
48
-     * @return string
49
-     */
50
-    public function getTag()
51
-    {
52
-        return 'ESPRESSO_EVENT_ATTENDEES';
53
-    }
45
+	/**
46
+	 * the actual shortcode tag that gets registered with WordPress
47
+	 *
48
+	 * @return string
49
+	 */
50
+	public function getTag()
51
+	{
52
+		return 'ESPRESSO_EVENT_ATTENDEES';
53
+	}
54 54
 
55 55
 
56
-    /**
57
-     * the time in seconds to cache the results of the processShortcode() method
58
-     * 0 means the processShortcode() results will NOT be cached at all
59
-     *
60
-     * @return int
61
-     */
62
-    public function cacheExpiration()
63
-    {
64
-        return 0;
65
-    }
56
+	/**
57
+	 * the time in seconds to cache the results of the processShortcode() method
58
+	 * 0 means the processShortcode() results will NOT be cached at all
59
+	 *
60
+	 * @return int
61
+	 */
62
+	public function cacheExpiration()
63
+	{
64
+		return 0;
65
+	}
66 66
 
67 67
 
68
-    /**
69
-     * a place for adding any initialization code that needs to run prior to wp_header().
70
-     * this may be required for shortcodes that utilize a corresponding module,
71
-     * and need to enqueue assets for that module
72
-     *
73
-     * @return void
74
-     */
75
-    public function initializeShortcode()
76
-    {
77
-        $this->shortcodeHasBeenInitialized();
78
-    }
68
+	/**
69
+	 * a place for adding any initialization code that needs to run prior to wp_header().
70
+	 * this may be required for shortcodes that utilize a corresponding module,
71
+	 * and need to enqueue assets for that module
72
+	 *
73
+	 * @return void
74
+	 */
75
+	public function initializeShortcode()
76
+	{
77
+		$this->shortcodeHasBeenInitialized();
78
+	}
79 79
 
80 80
 
81
-    /**
82
-     * process_shortcode - ESPRESSO_EVENT_ATTENDEES - Returns a list of attendees to an event.
83
-     *  [ESPRESSO_EVENT_ATTENDEES]
84
-     *  - defaults to attendees for earliest active event, or earliest upcoming event.
85
-     *  [ESPRESSO_EVENT_ATTENDEES event_id=123]
86
-     *  - attendees for specific event.
87
-     *  [ESPRESSO_EVENT_ATTENDEES datetime_id=245]
88
-     *  - attendees for a specific datetime.
89
-     *  [ESPRESSO_EVENT_ATTENDEES ticket_id=123]
90
-     *  - attendees for a specific ticket.
91
-     *  [ESPRESSO_EVENT_ATTENDEES status=all]
92
-     *  - specific registration status (use status id) or all for all attendees regardless of status.
93
-     *  Note default is to only return approved attendees
94
-     *  [ESPRESSO_EVENT_ATTENDEES show_gravatar=true]
95
-     *  - default is to not return gravatar.  Otherwise if this is set then return gravatar for email address given.
96
-     *  [ESPRESSO_EVENT_ATTENDEES display_on_archives=true]
97
-     *  - default is to not display attendees list on archive pages.
98
-     * Note: because of the relationship between event_id, ticket_id, and datetime_id:
99
-     * If more than one of those params is included, then preference is given to the following:
100
-     *  - event_id is used whenever its present and any others are ignored.
101
-     *  - if no event_id then datetime is used whenever its present and any others are ignored.
102
-     *  - otherwise ticket_id is used if present.
103
-     *
104
-     * @param array $attributes
105
-     * @return string
106
-     * @throws EE_Error
107
-     * @throws InvalidDataTypeException
108
-     * @throws InvalidInterfaceException
109
-     * @throws InvalidArgumentException
110
-     * @throws DomainException
111
-     */
112
-    public function processShortcode($attributes = array())
113
-    {
114
-        // grab attributes and merge with defaults
115
-        $attributes = $this->getAttributes((array) $attributes);
116
-        $attributes['limit'] = (int) $attributes['limit'];
117
-        $display_on_archives = filter_var($attributes['display_on_archives'], FILTER_VALIDATE_BOOLEAN);
118
-        // don't display on archives unless 'display_on_archives' is true
119
-        if ($attributes['limit'] === 0 || (! $display_on_archives && is_archive())) {
120
-            return '';
121
-        }
122
-        try {
123
-            $this->setBaseTemplateArguments($attributes);
124
-            $this->validateEntities($attributes);
125
-            $this->setBaseQueryParams();
126
-        } catch (EntityNotFoundException $e) {
127
-            if (WP_DEBUG) {
128
-                return '<div class="important-notice ee-error">'
129
-                       . $e->getMessage()
130
-                       . '</div>';
131
-            }
132
-            return '';
133
-        }
134
-        $this->setAdditionalQueryParams($attributes);
135
-        // get contacts!
136
-        $this->template_args['contacts'] = EEM_Attendee::instance()->get_all($this->query_params);
137
-        // all set let's load up the template and return.
138
-        return EEH_Template::locate_template(
139
-            'loop-espresso_event_attendees.php',
140
-            $this->template_args
141
-        );
142
-    }
81
+	/**
82
+	 * process_shortcode - ESPRESSO_EVENT_ATTENDEES - Returns a list of attendees to an event.
83
+	 *  [ESPRESSO_EVENT_ATTENDEES]
84
+	 *  - defaults to attendees for earliest active event, or earliest upcoming event.
85
+	 *  [ESPRESSO_EVENT_ATTENDEES event_id=123]
86
+	 *  - attendees for specific event.
87
+	 *  [ESPRESSO_EVENT_ATTENDEES datetime_id=245]
88
+	 *  - attendees for a specific datetime.
89
+	 *  [ESPRESSO_EVENT_ATTENDEES ticket_id=123]
90
+	 *  - attendees for a specific ticket.
91
+	 *  [ESPRESSO_EVENT_ATTENDEES status=all]
92
+	 *  - specific registration status (use status id) or all for all attendees regardless of status.
93
+	 *  Note default is to only return approved attendees
94
+	 *  [ESPRESSO_EVENT_ATTENDEES show_gravatar=true]
95
+	 *  - default is to not return gravatar.  Otherwise if this is set then return gravatar for email address given.
96
+	 *  [ESPRESSO_EVENT_ATTENDEES display_on_archives=true]
97
+	 *  - default is to not display attendees list on archive pages.
98
+	 * Note: because of the relationship between event_id, ticket_id, and datetime_id:
99
+	 * If more than one of those params is included, then preference is given to the following:
100
+	 *  - event_id is used whenever its present and any others are ignored.
101
+	 *  - if no event_id then datetime is used whenever its present and any others are ignored.
102
+	 *  - otherwise ticket_id is used if present.
103
+	 *
104
+	 * @param array $attributes
105
+	 * @return string
106
+	 * @throws EE_Error
107
+	 * @throws InvalidDataTypeException
108
+	 * @throws InvalidInterfaceException
109
+	 * @throws InvalidArgumentException
110
+	 * @throws DomainException
111
+	 */
112
+	public function processShortcode($attributes = array())
113
+	{
114
+		// grab attributes and merge with defaults
115
+		$attributes = $this->getAttributes((array) $attributes);
116
+		$attributes['limit'] = (int) $attributes['limit'];
117
+		$display_on_archives = filter_var($attributes['display_on_archives'], FILTER_VALIDATE_BOOLEAN);
118
+		// don't display on archives unless 'display_on_archives' is true
119
+		if ($attributes['limit'] === 0 || (! $display_on_archives && is_archive())) {
120
+			return '';
121
+		}
122
+		try {
123
+			$this->setBaseTemplateArguments($attributes);
124
+			$this->validateEntities($attributes);
125
+			$this->setBaseQueryParams();
126
+		} catch (EntityNotFoundException $e) {
127
+			if (WP_DEBUG) {
128
+				return '<div class="important-notice ee-error">'
129
+					   . $e->getMessage()
130
+					   . '</div>';
131
+			}
132
+			return '';
133
+		}
134
+		$this->setAdditionalQueryParams($attributes);
135
+		// get contacts!
136
+		$this->template_args['contacts'] = EEM_Attendee::instance()->get_all($this->query_params);
137
+		// all set let's load up the template and return.
138
+		return EEH_Template::locate_template(
139
+			'loop-espresso_event_attendees.php',
140
+			$this->template_args
141
+		);
142
+	}
143 143
 
144 144
 
145
-    /**
146
-     * merge incoming attributes with filtered defaults
147
-     *
148
-     * @param array $attributes
149
-     * @return array
150
-     */
151
-    private function getAttributes(array $attributes)
152
-    {
153
-        return (array) apply_filters(
154
-            'EES_Espresso_Event_Attendees__process_shortcode__default_shortcode_atts',
155
-            $attributes + array(
156
-                'event_id'            => null,
157
-                'datetime_id'         => null,
158
-                'ticket_id'           => null,
159
-                'status'              => EEM_Registration::status_id_approved,
160
-                'show_gravatar'       => false,
161
-                'display_on_archives' => false,
162
-                'limit'               => 999,
163
-            )
164
-        );
165
-    }
145
+	/**
146
+	 * merge incoming attributes with filtered defaults
147
+	 *
148
+	 * @param array $attributes
149
+	 * @return array
150
+	 */
151
+	private function getAttributes(array $attributes)
152
+	{
153
+		return (array) apply_filters(
154
+			'EES_Espresso_Event_Attendees__process_shortcode__default_shortcode_atts',
155
+			$attributes + array(
156
+				'event_id'            => null,
157
+				'datetime_id'         => null,
158
+				'ticket_id'           => null,
159
+				'status'              => EEM_Registration::status_id_approved,
160
+				'show_gravatar'       => false,
161
+				'display_on_archives' => false,
162
+				'limit'               => 999,
163
+			)
164
+		);
165
+	}
166 166
 
167 167
 
168
-    /**
169
-     * Set all the base template arguments from the incoming attributes.
170
-     * * Note: because of the relationship between event_id, ticket_id, and datetime_id:
171
-     * If more than one of those params is included, then preference is given to the following:
172
-     *  - event_id is used whenever its present and any others are ignored.
173
-     *  - if no event_id then datetime is used whenever its present and any others are ignored.
174
-     *  - otherwise ticket_id is used if present.
175
-     *
176
-     * @param array $attributes
177
-     * @throws EE_Error
178
-     * @throws InvalidDataTypeException
179
-     * @throws InvalidInterfaceException
180
-     * @throws InvalidArgumentException
181
-     */
182
-    private function setBaseTemplateArguments(array $attributes)
183
-    {
184
-        $this->template_args['show_gravatar'] = $attributes['show_gravatar'];
185
-        $this->template_args['event'] = $this->getEvent($attributes);
186
-        $this->template_args['datetime'] = empty($attributes['event_id'])
187
-            ? $this->getDatetime($attributes)
188
-            : null;
189
-        $this->template_args['ticket'] = empty($attributes['datetime_id']) && empty($attributes['event_id'])
190
-            ? $this->getTicket($attributes)
191
-            : null;
192
-    }
168
+	/**
169
+	 * Set all the base template arguments from the incoming attributes.
170
+	 * * Note: because of the relationship between event_id, ticket_id, and datetime_id:
171
+	 * If more than one of those params is included, then preference is given to the following:
172
+	 *  - event_id is used whenever its present and any others are ignored.
173
+	 *  - if no event_id then datetime is used whenever its present and any others are ignored.
174
+	 *  - otherwise ticket_id is used if present.
175
+	 *
176
+	 * @param array $attributes
177
+	 * @throws EE_Error
178
+	 * @throws InvalidDataTypeException
179
+	 * @throws InvalidInterfaceException
180
+	 * @throws InvalidArgumentException
181
+	 */
182
+	private function setBaseTemplateArguments(array $attributes)
183
+	{
184
+		$this->template_args['show_gravatar'] = $attributes['show_gravatar'];
185
+		$this->template_args['event'] = $this->getEvent($attributes);
186
+		$this->template_args['datetime'] = empty($attributes['event_id'])
187
+			? $this->getDatetime($attributes)
188
+			: null;
189
+		$this->template_args['ticket'] = empty($attributes['datetime_id']) && empty($attributes['event_id'])
190
+			? $this->getTicket($attributes)
191
+			: null;
192
+	}
193 193
 
194 194
 
195
-    /**
196
-     * Validates the presence of entities for the given attribute values.
197
-     *
198
-     * @param array $attributes
199
-     * @throws EntityNotFoundException
200
-     */
201
-    private function validateEntities(array $attributes)
202
-    {
203
-        if (
204
-            ! $this->template_args['event'] instanceof EE_Event
205
-            || (
206
-                empty($attributes['event_id'])
207
-                && $attributes['datetime_id']
208
-                && ! $this->template_args['datetime'] instanceof EE_Datetime
209
-            )
210
-            || (
211
-                empty($attributes['event_id'])
212
-                && empty($attributes['datetime_id'])
213
-                && $attributes['ticket_id']
214
-                && ! $this->template_args['ticket'] instanceof EE_Ticket
215
-            )
216
-        ) {
217
-            throw new EntityNotFoundException(
218
-                '',
219
-                '',
220
-                esc_html__(
221
-                    'The [ESPRESSO_EVENT_ATTENDEES] shortcode has been used incorrectly.  Please double check the arguments you used for any typos.  In the case of ID type arguments, its possible the given ID does not correspond to existing data in the database.',
222
-                    'event_espresso'
223
-                )
224
-            );
225
-        }
226
-    }
195
+	/**
196
+	 * Validates the presence of entities for the given attribute values.
197
+	 *
198
+	 * @param array $attributes
199
+	 * @throws EntityNotFoundException
200
+	 */
201
+	private function validateEntities(array $attributes)
202
+	{
203
+		if (
204
+			! $this->template_args['event'] instanceof EE_Event
205
+			|| (
206
+				empty($attributes['event_id'])
207
+				&& $attributes['datetime_id']
208
+				&& ! $this->template_args['datetime'] instanceof EE_Datetime
209
+			)
210
+			|| (
211
+				empty($attributes['event_id'])
212
+				&& empty($attributes['datetime_id'])
213
+				&& $attributes['ticket_id']
214
+				&& ! $this->template_args['ticket'] instanceof EE_Ticket
215
+			)
216
+		) {
217
+			throw new EntityNotFoundException(
218
+				'',
219
+				'',
220
+				esc_html__(
221
+					'The [ESPRESSO_EVENT_ATTENDEES] shortcode has been used incorrectly.  Please double check the arguments you used for any typos.  In the case of ID type arguments, its possible the given ID does not correspond to existing data in the database.',
222
+					'event_espresso'
223
+				)
224
+			);
225
+		}
226
+	}
227 227
 
228 228
 
229
-    /**
230
-     * Sets the query params for the base query elements.
231
-     */
232
-    private function setBaseQueryParams()
233
-    {
234
-        switch (true) {
235
-            case $this->template_args['datetime'] instanceof EE_Datetime:
236
-                $this->query_params = array(
237
-                    0                          => array(
238
-                        'Registration.Ticket.Datetime.DTT_ID' => $this->template_args['datetime']->ID(),
239
-                    ),
240
-                    'default_where_conditions' => 'this_model_only',
241
-                );
242
-                break;
243
-            case $this->template_args['ticket'] instanceof EE_Ticket:
244
-                $this->query_params[0] = array(
245
-                    'Registration.TKT_ID' => $this->template_args['ticket']->ID(),
246
-                );
247
-                break;
248
-            case $this->template_args['event'] instanceof EE_Event:
249
-                $this->query_params[0] = array(
250
-                    'Registration.EVT_ID' => $this->template_args['event']->ID(),
251
-                );
252
-                break;
253
-        }
254
-    }
229
+	/**
230
+	 * Sets the query params for the base query elements.
231
+	 */
232
+	private function setBaseQueryParams()
233
+	{
234
+		switch (true) {
235
+			case $this->template_args['datetime'] instanceof EE_Datetime:
236
+				$this->query_params = array(
237
+					0                          => array(
238
+						'Registration.Ticket.Datetime.DTT_ID' => $this->template_args['datetime']->ID(),
239
+					),
240
+					'default_where_conditions' => 'this_model_only',
241
+				);
242
+				break;
243
+			case $this->template_args['ticket'] instanceof EE_Ticket:
244
+				$this->query_params[0] = array(
245
+					'Registration.TKT_ID' => $this->template_args['ticket']->ID(),
246
+				);
247
+				break;
248
+			case $this->template_args['event'] instanceof EE_Event:
249
+				$this->query_params[0] = array(
250
+					'Registration.EVT_ID' => $this->template_args['event']->ID(),
251
+				);
252
+				break;
253
+		}
254
+	}
255 255
 
256 256
 
257
-    /**
258
-     * @param array $attributes
259
-     * @return EE_Event|null
260
-     * @throws EE_Error
261
-     * @throws InvalidDataTypeException
262
-     * @throws InvalidInterfaceException
263
-     * @throws InvalidArgumentException
264
-     */
265
-    private function getEvent(array $attributes)
266
-    {
267
-        switch (true) {
268
-            case ! empty($attributes['event_id']):
269
-                $event = EEM_Event::instance()->get_one_by_ID($attributes['event_id']);
270
-                break;
271
-            case ! empty($attributes['datetime_id']):
272
-                $event = EEM_Event::instance()->get_one(array(
273
-                    array(
274
-                        'Datetime.DTT_ID' => $attributes['datetime_id'],
275
-                    ),
276
-                ));
277
-                break;
278
-            case ! empty($attributes['ticket_id']):
279
-                $event = EEM_Event::instance()->get_one(array(
280
-                    array(
281
-                        'Datetime.Ticket.TKT_ID' => $attributes['ticket_id'],
282
-                    ),
283
-                    'default_where_conditions' => 'none'
284
-                ));
285
-                break;
286
-            case is_espresso_event():
287
-                $event = EEH_Event_View::get_event();
288
-                break;
289
-            default:
290
-                // one last shot...
291
-                // try getting the earliest active event
292
-                $events = EEM_Event::instance()->get_active_events(array(
293
-                    'limit'    => 1,
294
-                    'order_by' => array('Datetime.DTT_EVT_start' => 'ASC'),
295
-                ));
296
-                //  if none then get the next upcoming
297
-                $events = empty($events)
298
-                    ? EEM_Event::instance()->get_upcoming_events(array(
299
-                        'limit'    => 1,
300
-                        'order_by' => array('Datetime.DTT_EVT_start' => 'ASC'),
301
-                    ))
302
-                    : $events;
303
-                $event = reset($events);
304
-        }
257
+	/**
258
+	 * @param array $attributes
259
+	 * @return EE_Event|null
260
+	 * @throws EE_Error
261
+	 * @throws InvalidDataTypeException
262
+	 * @throws InvalidInterfaceException
263
+	 * @throws InvalidArgumentException
264
+	 */
265
+	private function getEvent(array $attributes)
266
+	{
267
+		switch (true) {
268
+			case ! empty($attributes['event_id']):
269
+				$event = EEM_Event::instance()->get_one_by_ID($attributes['event_id']);
270
+				break;
271
+			case ! empty($attributes['datetime_id']):
272
+				$event = EEM_Event::instance()->get_one(array(
273
+					array(
274
+						'Datetime.DTT_ID' => $attributes['datetime_id'],
275
+					),
276
+				));
277
+				break;
278
+			case ! empty($attributes['ticket_id']):
279
+				$event = EEM_Event::instance()->get_one(array(
280
+					array(
281
+						'Datetime.Ticket.TKT_ID' => $attributes['ticket_id'],
282
+					),
283
+					'default_where_conditions' => 'none'
284
+				));
285
+				break;
286
+			case is_espresso_event():
287
+				$event = EEH_Event_View::get_event();
288
+				break;
289
+			default:
290
+				// one last shot...
291
+				// try getting the earliest active event
292
+				$events = EEM_Event::instance()->get_active_events(array(
293
+					'limit'    => 1,
294
+					'order_by' => array('Datetime.DTT_EVT_start' => 'ASC'),
295
+				));
296
+				//  if none then get the next upcoming
297
+				$events = empty($events)
298
+					? EEM_Event::instance()->get_upcoming_events(array(
299
+						'limit'    => 1,
300
+						'order_by' => array('Datetime.DTT_EVT_start' => 'ASC'),
301
+					))
302
+					: $events;
303
+				$event = reset($events);
304
+		}
305 305
 
306
-        return $event instanceof EE_Event ? $event : null;
307
-    }
306
+		return $event instanceof EE_Event ? $event : null;
307
+	}
308 308
 
309 309
 
310
-    /**
311
-     * @param array $attributes
312
-     * @return EE_Datetime|null
313
-     * @throws EE_Error
314
-     * @throws InvalidDataTypeException
315
-     * @throws InvalidInterfaceException
316
-     * @throws InvalidArgumentException
317
-     */
318
-    private function getDatetime(array $attributes)
319
-    {
320
-        if (! empty($attributes['datetime_id'])) {
321
-            $datetime = EEM_Datetime::instance()->get_one_by_ID($attributes['datetime_id']);
322
-            if ($datetime instanceof EE_Datetime) {
323
-                return $datetime;
324
-            }
325
-        }
326
-        return null;
327
-    }
310
+	/**
311
+	 * @param array $attributes
312
+	 * @return EE_Datetime|null
313
+	 * @throws EE_Error
314
+	 * @throws InvalidDataTypeException
315
+	 * @throws InvalidInterfaceException
316
+	 * @throws InvalidArgumentException
317
+	 */
318
+	private function getDatetime(array $attributes)
319
+	{
320
+		if (! empty($attributes['datetime_id'])) {
321
+			$datetime = EEM_Datetime::instance()->get_one_by_ID($attributes['datetime_id']);
322
+			if ($datetime instanceof EE_Datetime) {
323
+				return $datetime;
324
+			}
325
+		}
326
+		return null;
327
+	}
328 328
 
329 329
 
330
-    /**
331
-     * @param array $attributes
332
-     * @return \EE_Base_Class|EE_Ticket|null
333
-     * @throws EE_Error
334
-     * @throws InvalidDataTypeException
335
-     * @throws InvalidInterfaceException
336
-     * @throws InvalidArgumentException
337
-     */
338
-    private function getTicket(array $attributes)
339
-    {
340
-        if (! empty($attributes['ticket_id'])) {
341
-            $ticket = EEM_Ticket::instance()->get_one_by_ID($attributes['ticket_id']);
342
-            if ($ticket instanceof EE_Ticket) {
343
-                return $ticket;
344
-            }
345
-        }
346
-        return null;
347
-    }
330
+	/**
331
+	 * @param array $attributes
332
+	 * @return \EE_Base_Class|EE_Ticket|null
333
+	 * @throws EE_Error
334
+	 * @throws InvalidDataTypeException
335
+	 * @throws InvalidInterfaceException
336
+	 * @throws InvalidArgumentException
337
+	 */
338
+	private function getTicket(array $attributes)
339
+	{
340
+		if (! empty($attributes['ticket_id'])) {
341
+			$ticket = EEM_Ticket::instance()->get_one_by_ID($attributes['ticket_id']);
342
+			if ($ticket instanceof EE_Ticket) {
343
+				return $ticket;
344
+			}
345
+		}
346
+		return null;
347
+	}
348 348
 
349 349
 
350
-    /**
351
-     * @param array $attributes
352
-     * @throws EE_Error
353
-     */
354
-    private function setAdditionalQueryParams(array $attributes)
355
-    {
356
-        $reg_status_array = EEM_Registration::reg_status_array();
357
-        if (isset($reg_status_array[ $attributes['status'] ])) {
358
-            $this->query_params[0]['Registration.STS_ID'] = $attributes['status'];
359
-        }
360
-        if (absint($attributes['limit'])) {
361
-            $this->query_params['limit'] = $attributes['limit'];
362
-        }
363
-        $this->query_params['group_by'] = array('ATT_ID');
364
-        $this->query_params['order_by'] = (array) apply_filters(
365
-            'FHEE__EES_Espresso_Event_Attendees__process_shortcode__order_by',
366
-            array('ATT_lname' => 'ASC', 'ATT_fname' => 'ASC')
367
-        );
368
-    }
350
+	/**
351
+	 * @param array $attributes
352
+	 * @throws EE_Error
353
+	 */
354
+	private function setAdditionalQueryParams(array $attributes)
355
+	{
356
+		$reg_status_array = EEM_Registration::reg_status_array();
357
+		if (isset($reg_status_array[ $attributes['status'] ])) {
358
+			$this->query_params[0]['Registration.STS_ID'] = $attributes['status'];
359
+		}
360
+		if (absint($attributes['limit'])) {
361
+			$this->query_params['limit'] = $attributes['limit'];
362
+		}
363
+		$this->query_params['group_by'] = array('ATT_ID');
364
+		$this->query_params['order_by'] = (array) apply_filters(
365
+			'FHEE__EES_Espresso_Event_Attendees__process_shortcode__order_by',
366
+			array('ATT_lname' => 'ASC', 'ATT_fname' => 'ASC')
367
+		);
368
+	}
369 369
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
         $attributes['limit'] = (int) $attributes['limit'];
117 117
         $display_on_archives = filter_var($attributes['display_on_archives'], FILTER_VALIDATE_BOOLEAN);
118 118
         // don't display on archives unless 'display_on_archives' is true
119
-        if ($attributes['limit'] === 0 || (! $display_on_archives && is_archive())) {
119
+        if ($attributes['limit'] === 0 || ( ! $display_on_archives && is_archive())) {
120 120
             return '';
121 121
         }
122 122
         try {
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
      */
318 318
     private function getDatetime(array $attributes)
319 319
     {
320
-        if (! empty($attributes['datetime_id'])) {
320
+        if ( ! empty($attributes['datetime_id'])) {
321 321
             $datetime = EEM_Datetime::instance()->get_one_by_ID($attributes['datetime_id']);
322 322
             if ($datetime instanceof EE_Datetime) {
323 323
                 return $datetime;
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
      */
338 338
     private function getTicket(array $attributes)
339 339
     {
340
-        if (! empty($attributes['ticket_id'])) {
340
+        if ( ! empty($attributes['ticket_id'])) {
341 341
             $ticket = EEM_Ticket::instance()->get_one_by_ID($attributes['ticket_id']);
342 342
             if ($ticket instanceof EE_Ticket) {
343 343
                 return $ticket;
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
     private function setAdditionalQueryParams(array $attributes)
355 355
     {
356 356
         $reg_status_array = EEM_Registration::reg_status_array();
357
-        if (isset($reg_status_array[ $attributes['status'] ])) {
357
+        if (isset($reg_status_array[$attributes['status']])) {
358 358
             $this->query_params[0]['Registration.STS_ID'] = $attributes['status'];
359 359
         }
360 360
         if (absint($attributes['limit'])) {
Please login to merge, or discard this patch.
core/CPTs/EE_CPT_Strategy.core.php 2 patches
Indentation   +445 added lines, -445 removed lines patch added patch discarded remove patch
@@ -16,449 +16,449 @@
 block discarded – undo
16 16
 class EE_CPT_Strategy extends EE_Base
17 17
 {
18 18
 
19
-    /**
20
-     * @var EE_CPT_Strategy $_instance
21
-     */
22
-    private static $_instance;
23
-
24
-    /**
25
-     * the current page, if it utilizes CPTs
26
-     *
27
-     * @var array $CPT
28
-     */
29
-    protected $CPT;
30
-
31
-    /**
32
-     * return value from CustomPostTypeDefinitions::getDefinitions()
33
-     *
34
-     * @var array $_CPTs
35
-     */
36
-    protected $_CPTs = array();
37
-
38
-    /**
39
-     * @var array $_CPT_taxonomies
40
-     */
41
-    protected $_CPT_taxonomies = array();
42
-
43
-    /**
44
-     * @var array $_CPT_terms
45
-     */
46
-    protected $_CPT_terms = array();
47
-
48
-    /**
49
-     * @var array $_CPT_endpoints
50
-     */
51
-    protected $_CPT_endpoints = array();
52
-
53
-    /**
54
-     * @var EEM_Base $CPT_model
55
-     */
56
-    protected $CPT_model;
57
-
58
-    /**
59
-     * @var EventEspresso\Core\CPTs\CptQueryModifier $query_modifier
60
-     */
61
-    protected $query_modifier;
62
-
63
-
64
-    /**
65
-     * @singleton method used to instantiate class object
66
-     * @param CustomPostTypeDefinitions|null $custom_post_types
67
-     * @param CustomTaxonomyDefinitions|null $taxonomies
68
-     * @return EE_CPT_Strategy
69
-     */
70
-    public static function instance(
71
-        CustomPostTypeDefinitions $custom_post_types = null,
72
-        CustomTaxonomyDefinitions $taxonomies = null
73
-    ) {
74
-        // check if class object is instantiated
75
-        if (
76
-            ! self::$_instance instanceof EE_CPT_Strategy
77
-            && $custom_post_types instanceof CustomPostTypeDefinitions
78
-            && $taxonomies instanceof CustomTaxonomyDefinitions
79
-        ) {
80
-            self::$_instance = new self($custom_post_types, $taxonomies);
81
-        }
82
-        return self::$_instance;
83
-    }
84
-
85
-
86
-    /**
87
-     * @param CustomPostTypeDefinitions $custom_post_types
88
-     * @param CustomTaxonomyDefinitions $taxonomies
89
-     */
90
-    protected function __construct(
91
-        CustomPostTypeDefinitions $custom_post_types,
92
-        CustomTaxonomyDefinitions $taxonomies
93
-    ) {
94
-        // get CPT data
95
-        $this->_CPTs = $custom_post_types->getDefinitions();
96
-        $this->_CPT_endpoints = $this->_set_CPT_endpoints();
97
-        $this->_CPT_taxonomies = $taxonomies->getCustomTaxonomyDefinitions();
98
-        add_action('pre_get_posts', array($this, 'pre_get_posts'), 5);
99
-    }
100
-
101
-
102
-    /**
103
-     * @return array
104
-     */
105
-    public function get_CPT_endpoints()
106
-    {
107
-        return $this->_CPT_endpoints;
108
-    }
109
-
110
-
111
-    /**
112
-     * @return array
113
-     */
114
-    public function get_CPT_taxonomies()
115
-    {
116
-        return $this->_CPT_taxonomies;
117
-    }
118
-
119
-
120
-    /**
121
-     * add CPT "slugs" to array of default espresso "pages"
122
-     *
123
-     * @return array
124
-     */
125
-    private function _set_CPT_endpoints()
126
-    {
127
-        $_CPT_endpoints = array();
128
-        if (is_array($this->_CPTs)) {
129
-            foreach ($this->_CPTs as $CPT_type => $CPT) {
130
-                if (isset($CPT['plural_slug'])) {
131
-                    $_CPT_endpoints [ (string) $CPT['plural_slug'] ] = $CPT_type;
132
-                }
133
-            }
134
-        }
135
-        return $_CPT_endpoints;
136
-    }
137
-
138
-
139
-    /**
140
-     * If this query (not just "main" queries (ie, for WP's infamous "loop")) is for an EE CPT, then we want to
141
-     * supercharge the get_posts query to add our EE stuff (like joining to our tables, selecting extra columns, and
142
-     * adding EE objects to the post to facilitate further querying of related data etc)
143
-     *
144
-     * @param WP_Query $WP_Query
145
-     * @return void
146
-     * @throws \EE_Error
147
-     * @throws \InvalidArgumentException
148
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
149
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
150
-     */
151
-    public function pre_get_posts($WP_Query)
152
-    {
153
-        // check that post-type is set
154
-        if (! $WP_Query instanceof WP_Query) {
155
-            return;
156
-        }
157
-        // add our conditionals
158
-        $this->_set_EE_tags_on_WP_Query($WP_Query);
159
-        // check for terms
160
-        $this->_set_post_type_for_terms($WP_Query);
161
-        // make sure paging is always set
162
-        $this->_set_paging($WP_Query);
163
-        // is a taxonomy set ?
164
-        $this->_set_CPT_taxonomies_on_WP_Query($WP_Query);
165
-        // loop thru post_types if set
166
-        $this->_process_WP_Query_post_types($WP_Query);
167
-    }
168
-
169
-
170
-    /**
171
-     * @param WP_Query $WP_Query
172
-     * @return void
173
-     */
174
-    private function _set_EE_tags_on_WP_Query(WP_Query $WP_Query)
175
-    {
176
-        $WP_Query->is_espresso_event_single = false;
177
-        $WP_Query->is_espresso_event_archive = false;
178
-        $WP_Query->is_espresso_event_taxonomy = false;
179
-        $WP_Query->is_espresso_venue_single = false;
180
-        $WP_Query->is_espresso_venue_archive = false;
181
-        $WP_Query->is_espresso_venue_taxonomy = false;
182
-    }
183
-
184
-
185
-    /**
186
-     * @return void
187
-     * @throws EE_Error
188
-     * @throws InvalidArgumentException
189
-     * @throws InvalidDataTypeException
190
-     * @throws InvalidInterfaceException
191
-     */
192
-    private function _set_CPT_terms()
193
-    {
194
-        if (empty($this->_CPT_terms)) {
195
-            $terms = EEM_Term::instance()->get_all_CPT_post_tags();
196
-            foreach ($terms as $term) {
197
-                if ($term instanceof EE_Term) {
198
-                    $this->_CPT_terms[ $term->slug() ] = $term;
199
-                }
200
-            }
201
-        }
202
-    }
203
-
204
-
205
-    /**
206
-     * @param WP_Query $WP_Query
207
-     * @return void
208
-     * @throws EE_Error
209
-     * @throws InvalidArgumentException
210
-     * @throws InvalidDataTypeException
211
-     * @throws InvalidInterfaceException
212
-     */
213
-    private function _set_post_type_for_terms(WP_Query $WP_Query)
214
-    {
215
-        // is a tag set ?
216
-        if (isset($WP_Query->query['tag'])) {
217
-            // get term for tag
218
-            $term = EEM_Term::instance()->get_post_tag_for_event_or_venue($WP_Query->query['tag']);
219
-            // verify the term
220
-            if ($term instanceof EE_Term) {
221
-                $term->post_type = array_merge(array('post', 'page'), (array) $term->post_type);
222
-                $term->post_type = apply_filters(
223
-                    'FHEE__EE_CPT_Strategy___set_post_type_for_terms__term_post_type',
224
-                    $term->post_type,
225
-                    $term
226
-                );
227
-                // if a post type is already set
228
-                if (isset($WP_Query->query_vars['post_type'])) {
229
-                    // add to existing array
230
-                    $term->post_type = array_merge((array) $WP_Query->query_vars['post_type'], $term->post_type);
231
-                }
232
-                // just set post_type to our CPT
233
-                $WP_Query->set('post_type', array_unique($term->post_type));
234
-            }
235
-        }
236
-    }
237
-
238
-
239
-    /**
240
-     * @param WP_Query $WP_Query
241
-     * @return void
242
-     */
243
-    public function _set_paging($WP_Query)
244
-    {
245
-        if ($WP_Query->is_main_query() && apply_filters('FHEE__EE_CPT_Strategy___set_paging', true)) {
246
-            $page = get_query_var('page') ? get_query_var('page') : null;
247
-            $paged = get_query_var('paged') ? get_query_var('paged') : $page;
248
-            $WP_Query->set('paged', $paged);
249
-        }
250
-    }
251
-
252
-
253
-    /**
254
-     * @param \WP_Query $WP_Query
255
-     */
256
-    protected function _set_CPT_taxonomies_on_WP_Query(WP_Query $WP_Query)
257
-    {
258
-        // is a taxonomy set ?
259
-        if ($WP_Query->is_tax) {
260
-            // loop thru our taxonomies
261
-            foreach ($this->_CPT_taxonomies as $CPT_taxonomy => $CPT_taxonomy_details) {
262
-                // check if one of our taxonomies is set as a query var
263
-                if (isset($WP_Query->query[ $CPT_taxonomy ])) {
264
-                    // but which CPT does that correspond to??? hmmm... guess we gotta go looping
265
-                    foreach ($this->_CPTs as $post_type => $CPT) {
266
-                        // verify our CPT has args, is public and has taxonomies set
267
-                        if (
268
-                            isset($CPT['args']['public'])
269
-                            && $CPT['args']['public']
270
-                            && ! empty($CPT['args']['taxonomies'])
271
-                            && in_array($CPT_taxonomy, $CPT['args']['taxonomies'], true)
272
-                        ) {
273
-                            // if so, then add this CPT post_type to the current query's array of post_types'
274
-                            $WP_Query->query_vars['post_type'] = isset($WP_Query->query_vars['post_type'])
275
-                                ? (array) $WP_Query->query_vars['post_type']
276
-                                : array();
277
-                            $WP_Query->query_vars['post_type'][] = $post_type;
278
-                            switch ($post_type) {
279
-                                case 'espresso_events':
280
-                                    $WP_Query->is_espresso_event_taxonomy = true;
281
-                                    break;
282
-                                case 'espresso_venues':
283
-                                    $WP_Query->is_espresso_venue_taxonomy = true;
284
-                                    break;
285
-                                default:
286
-                                    do_action(
287
-                                        'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_' . $post_type . '_post_type',
288
-                                        $WP_Query,
289
-                                        $this
290
-                                    );
291
-                            }
292
-                        }
293
-                    }
294
-                }
295
-            }
296
-        }
297
-    }
298
-
299
-
300
-    /**
301
-     * @param \WP_Query $WP_Query
302
-     * @throws InvalidArgumentException
303
-     * @throws InvalidDataTypeException
304
-     * @throws InvalidInterfaceException
305
-     */
306
-    protected function _process_WP_Query_post_types(WP_Query $WP_Query)
307
-    {
308
-        if (isset($WP_Query->query_vars['post_type'])) {
309
-            // loop thru post_types as array
310
-            foreach ((array) $WP_Query->query_vars['post_type'] as $post_type) {
311
-                // is current query for an EE CPT ?
312
-                if (isset($this->_CPTs[ $post_type ])) {
313
-                    // is EE on or off ?
314
-                    if (EE_Maintenance_Mode::instance()->level()) {
315
-                        // reroute CPT template view to maintenance_mode.template.php
316
-                        if (! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
317
-                            add_filter('template_include', array('EE_Maintenance_Mode', 'template_include'), 99999);
318
-                        }
319
-                        if (has_filter('the_content', array(EE_Maintenance_Mode::instance(), 'the_content'))) {
320
-                            add_filter('the_content', array($this, 'inject_EE_shortcode_placeholder'), 1);
321
-                        }
322
-                        return;
323
-                    }
324
-                    $this->_generate_CptQueryModifier($WP_Query, $post_type);
325
-                }
326
-            }
327
-        }
328
-    }
329
-
330
-
331
-    /**
332
-     * @param \WP_Query $WP_Query
333
-     * @param string    $post_type
334
-     * @throws InvalidArgumentException
335
-     * @throws InvalidDataTypeException
336
-     * @throws InvalidInterfaceException
337
-     */
338
-    protected function _generate_CptQueryModifier(WP_Query $WP_Query, $post_type)
339
-    {
340
-        $this->query_modifier = LoaderFactory::getLoader()->getShared(
341
-            'EventEspresso\core\CPTs\CptQueryModifier',
342
-            array(
343
-                $post_type,
344
-                $this->_CPTs[ $post_type ],
345
-                $WP_Query,
346
-            )
347
-        );
348
-        $this->_CPT_taxonomies = $this->query_modifier->taxonomies();
349
-    }
350
-
351
-
352
-    /**
353
-     * inject_EE_shortcode_placeholder
354
-     * in order to display the M-Mode notice on our CPT routes,
355
-     * we need to first inject what looks like one of our shortcodes,
356
-     * so that it can be replaced with the actual M-Mode notice
357
-     *
358
-     * @return string
359
-     */
360
-    public function inject_EE_shortcode_placeholder()
361
-    {
362
-        return '[ESPRESSO_';
363
-    }
364
-
365
-
366
-    /**
367
-     * @deprecated
368
-     * @since  4.8.41
369
-     * @return void
370
-     */
371
-    public function _possibly_set_ee_request_var()
372
-    {
373
-        $this->query_modifier->setRequestVarsIfCpt();
374
-    }
375
-
376
-
377
-    /**
378
-     * @deprecated
379
-     * @since  4.8.41
380
-     * @param  $SQL
381
-     * @return string
382
-     */
383
-    public function posts_fields($SQL)
384
-    {
385
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
386
-            return $this->query_modifier->postsFields($SQL);
387
-        }
388
-        return $SQL;
389
-    }
390
-
391
-
392
-    /**
393
-     * @deprecated
394
-     * @since  4.8.41
395
-     * @param  $SQL
396
-     * @return string
397
-     */
398
-    public function posts_join($SQL)
399
-    {
400
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
401
-            return $this->query_modifier->postsJoin($SQL);
402
-        }
403
-        return $SQL;
404
-    }
405
-
406
-
407
-    /**
408
-     * @deprecated
409
-     * @since  4.8.41
410
-     * @param  \WP_Post[] $posts
411
-     * @return \WP_Post[]
412
-     */
413
-    public function the_posts($posts)
414
-    {
415
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
416
-            $this->query_modifier->thePosts($posts);
417
-        }
418
-        return $posts;
419
-    }
420
-
421
-
422
-    /**
423
-     * @deprecated
424
-     * @since  4.8.41
425
-     * @param $url
426
-     * @param $ID
427
-     * @return string
428
-     */
429
-    public function get_edit_post_link($url, $ID)
430
-    {
431
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
432
-            return $this->query_modifier->getEditPostLink($url, $ID);
433
-        }
434
-        return '';
435
-    }
436
-
437
-
438
-    /**
439
-     * @deprecated
440
-     * @since  4.8.41
441
-     * @param null $WP_Query
442
-     */
443
-    protected function _do_template_filters($WP_Query = null)
444
-    {
445
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
446
-            $this->query_modifier->addTemplateFilters();
447
-        }
448
-    }
449
-
450
-
451
-    /**
452
-     * @deprecated
453
-     * @since  4.8.41
454
-     * @param string $current_template Existing default template path derived for this page call.
455
-     * @return string the path to the full template file.
456
-     */
457
-    public function single_cpt_template($current_template)
458
-    {
459
-        if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
460
-            return $this->query_modifier->singleCptTemplate($current_template);
461
-        }
462
-        return $current_template;
463
-    }
19
+	/**
20
+	 * @var EE_CPT_Strategy $_instance
21
+	 */
22
+	private static $_instance;
23
+
24
+	/**
25
+	 * the current page, if it utilizes CPTs
26
+	 *
27
+	 * @var array $CPT
28
+	 */
29
+	protected $CPT;
30
+
31
+	/**
32
+	 * return value from CustomPostTypeDefinitions::getDefinitions()
33
+	 *
34
+	 * @var array $_CPTs
35
+	 */
36
+	protected $_CPTs = array();
37
+
38
+	/**
39
+	 * @var array $_CPT_taxonomies
40
+	 */
41
+	protected $_CPT_taxonomies = array();
42
+
43
+	/**
44
+	 * @var array $_CPT_terms
45
+	 */
46
+	protected $_CPT_terms = array();
47
+
48
+	/**
49
+	 * @var array $_CPT_endpoints
50
+	 */
51
+	protected $_CPT_endpoints = array();
52
+
53
+	/**
54
+	 * @var EEM_Base $CPT_model
55
+	 */
56
+	protected $CPT_model;
57
+
58
+	/**
59
+	 * @var EventEspresso\Core\CPTs\CptQueryModifier $query_modifier
60
+	 */
61
+	protected $query_modifier;
62
+
63
+
64
+	/**
65
+	 * @singleton method used to instantiate class object
66
+	 * @param CustomPostTypeDefinitions|null $custom_post_types
67
+	 * @param CustomTaxonomyDefinitions|null $taxonomies
68
+	 * @return EE_CPT_Strategy
69
+	 */
70
+	public static function instance(
71
+		CustomPostTypeDefinitions $custom_post_types = null,
72
+		CustomTaxonomyDefinitions $taxonomies = null
73
+	) {
74
+		// check if class object is instantiated
75
+		if (
76
+			! self::$_instance instanceof EE_CPT_Strategy
77
+			&& $custom_post_types instanceof CustomPostTypeDefinitions
78
+			&& $taxonomies instanceof CustomTaxonomyDefinitions
79
+		) {
80
+			self::$_instance = new self($custom_post_types, $taxonomies);
81
+		}
82
+		return self::$_instance;
83
+	}
84
+
85
+
86
+	/**
87
+	 * @param CustomPostTypeDefinitions $custom_post_types
88
+	 * @param CustomTaxonomyDefinitions $taxonomies
89
+	 */
90
+	protected function __construct(
91
+		CustomPostTypeDefinitions $custom_post_types,
92
+		CustomTaxonomyDefinitions $taxonomies
93
+	) {
94
+		// get CPT data
95
+		$this->_CPTs = $custom_post_types->getDefinitions();
96
+		$this->_CPT_endpoints = $this->_set_CPT_endpoints();
97
+		$this->_CPT_taxonomies = $taxonomies->getCustomTaxonomyDefinitions();
98
+		add_action('pre_get_posts', array($this, 'pre_get_posts'), 5);
99
+	}
100
+
101
+
102
+	/**
103
+	 * @return array
104
+	 */
105
+	public function get_CPT_endpoints()
106
+	{
107
+		return $this->_CPT_endpoints;
108
+	}
109
+
110
+
111
+	/**
112
+	 * @return array
113
+	 */
114
+	public function get_CPT_taxonomies()
115
+	{
116
+		return $this->_CPT_taxonomies;
117
+	}
118
+
119
+
120
+	/**
121
+	 * add CPT "slugs" to array of default espresso "pages"
122
+	 *
123
+	 * @return array
124
+	 */
125
+	private function _set_CPT_endpoints()
126
+	{
127
+		$_CPT_endpoints = array();
128
+		if (is_array($this->_CPTs)) {
129
+			foreach ($this->_CPTs as $CPT_type => $CPT) {
130
+				if (isset($CPT['plural_slug'])) {
131
+					$_CPT_endpoints [ (string) $CPT['plural_slug'] ] = $CPT_type;
132
+				}
133
+			}
134
+		}
135
+		return $_CPT_endpoints;
136
+	}
137
+
138
+
139
+	/**
140
+	 * If this query (not just "main" queries (ie, for WP's infamous "loop")) is for an EE CPT, then we want to
141
+	 * supercharge the get_posts query to add our EE stuff (like joining to our tables, selecting extra columns, and
142
+	 * adding EE objects to the post to facilitate further querying of related data etc)
143
+	 *
144
+	 * @param WP_Query $WP_Query
145
+	 * @return void
146
+	 * @throws \EE_Error
147
+	 * @throws \InvalidArgumentException
148
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
149
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
150
+	 */
151
+	public function pre_get_posts($WP_Query)
152
+	{
153
+		// check that post-type is set
154
+		if (! $WP_Query instanceof WP_Query) {
155
+			return;
156
+		}
157
+		// add our conditionals
158
+		$this->_set_EE_tags_on_WP_Query($WP_Query);
159
+		// check for terms
160
+		$this->_set_post_type_for_terms($WP_Query);
161
+		// make sure paging is always set
162
+		$this->_set_paging($WP_Query);
163
+		// is a taxonomy set ?
164
+		$this->_set_CPT_taxonomies_on_WP_Query($WP_Query);
165
+		// loop thru post_types if set
166
+		$this->_process_WP_Query_post_types($WP_Query);
167
+	}
168
+
169
+
170
+	/**
171
+	 * @param WP_Query $WP_Query
172
+	 * @return void
173
+	 */
174
+	private function _set_EE_tags_on_WP_Query(WP_Query $WP_Query)
175
+	{
176
+		$WP_Query->is_espresso_event_single = false;
177
+		$WP_Query->is_espresso_event_archive = false;
178
+		$WP_Query->is_espresso_event_taxonomy = false;
179
+		$WP_Query->is_espresso_venue_single = false;
180
+		$WP_Query->is_espresso_venue_archive = false;
181
+		$WP_Query->is_espresso_venue_taxonomy = false;
182
+	}
183
+
184
+
185
+	/**
186
+	 * @return void
187
+	 * @throws EE_Error
188
+	 * @throws InvalidArgumentException
189
+	 * @throws InvalidDataTypeException
190
+	 * @throws InvalidInterfaceException
191
+	 */
192
+	private function _set_CPT_terms()
193
+	{
194
+		if (empty($this->_CPT_terms)) {
195
+			$terms = EEM_Term::instance()->get_all_CPT_post_tags();
196
+			foreach ($terms as $term) {
197
+				if ($term instanceof EE_Term) {
198
+					$this->_CPT_terms[ $term->slug() ] = $term;
199
+				}
200
+			}
201
+		}
202
+	}
203
+
204
+
205
+	/**
206
+	 * @param WP_Query $WP_Query
207
+	 * @return void
208
+	 * @throws EE_Error
209
+	 * @throws InvalidArgumentException
210
+	 * @throws InvalidDataTypeException
211
+	 * @throws InvalidInterfaceException
212
+	 */
213
+	private function _set_post_type_for_terms(WP_Query $WP_Query)
214
+	{
215
+		// is a tag set ?
216
+		if (isset($WP_Query->query['tag'])) {
217
+			// get term for tag
218
+			$term = EEM_Term::instance()->get_post_tag_for_event_or_venue($WP_Query->query['tag']);
219
+			// verify the term
220
+			if ($term instanceof EE_Term) {
221
+				$term->post_type = array_merge(array('post', 'page'), (array) $term->post_type);
222
+				$term->post_type = apply_filters(
223
+					'FHEE__EE_CPT_Strategy___set_post_type_for_terms__term_post_type',
224
+					$term->post_type,
225
+					$term
226
+				);
227
+				// if a post type is already set
228
+				if (isset($WP_Query->query_vars['post_type'])) {
229
+					// add to existing array
230
+					$term->post_type = array_merge((array) $WP_Query->query_vars['post_type'], $term->post_type);
231
+				}
232
+				// just set post_type to our CPT
233
+				$WP_Query->set('post_type', array_unique($term->post_type));
234
+			}
235
+		}
236
+	}
237
+
238
+
239
+	/**
240
+	 * @param WP_Query $WP_Query
241
+	 * @return void
242
+	 */
243
+	public function _set_paging($WP_Query)
244
+	{
245
+		if ($WP_Query->is_main_query() && apply_filters('FHEE__EE_CPT_Strategy___set_paging', true)) {
246
+			$page = get_query_var('page') ? get_query_var('page') : null;
247
+			$paged = get_query_var('paged') ? get_query_var('paged') : $page;
248
+			$WP_Query->set('paged', $paged);
249
+		}
250
+	}
251
+
252
+
253
+	/**
254
+	 * @param \WP_Query $WP_Query
255
+	 */
256
+	protected function _set_CPT_taxonomies_on_WP_Query(WP_Query $WP_Query)
257
+	{
258
+		// is a taxonomy set ?
259
+		if ($WP_Query->is_tax) {
260
+			// loop thru our taxonomies
261
+			foreach ($this->_CPT_taxonomies as $CPT_taxonomy => $CPT_taxonomy_details) {
262
+				// check if one of our taxonomies is set as a query var
263
+				if (isset($WP_Query->query[ $CPT_taxonomy ])) {
264
+					// but which CPT does that correspond to??? hmmm... guess we gotta go looping
265
+					foreach ($this->_CPTs as $post_type => $CPT) {
266
+						// verify our CPT has args, is public and has taxonomies set
267
+						if (
268
+							isset($CPT['args']['public'])
269
+							&& $CPT['args']['public']
270
+							&& ! empty($CPT['args']['taxonomies'])
271
+							&& in_array($CPT_taxonomy, $CPT['args']['taxonomies'], true)
272
+						) {
273
+							// if so, then add this CPT post_type to the current query's array of post_types'
274
+							$WP_Query->query_vars['post_type'] = isset($WP_Query->query_vars['post_type'])
275
+								? (array) $WP_Query->query_vars['post_type']
276
+								: array();
277
+							$WP_Query->query_vars['post_type'][] = $post_type;
278
+							switch ($post_type) {
279
+								case 'espresso_events':
280
+									$WP_Query->is_espresso_event_taxonomy = true;
281
+									break;
282
+								case 'espresso_venues':
283
+									$WP_Query->is_espresso_venue_taxonomy = true;
284
+									break;
285
+								default:
286
+									do_action(
287
+										'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_' . $post_type . '_post_type',
288
+										$WP_Query,
289
+										$this
290
+									);
291
+							}
292
+						}
293
+					}
294
+				}
295
+			}
296
+		}
297
+	}
298
+
299
+
300
+	/**
301
+	 * @param \WP_Query $WP_Query
302
+	 * @throws InvalidArgumentException
303
+	 * @throws InvalidDataTypeException
304
+	 * @throws InvalidInterfaceException
305
+	 */
306
+	protected function _process_WP_Query_post_types(WP_Query $WP_Query)
307
+	{
308
+		if (isset($WP_Query->query_vars['post_type'])) {
309
+			// loop thru post_types as array
310
+			foreach ((array) $WP_Query->query_vars['post_type'] as $post_type) {
311
+				// is current query for an EE CPT ?
312
+				if (isset($this->_CPTs[ $post_type ])) {
313
+					// is EE on or off ?
314
+					if (EE_Maintenance_Mode::instance()->level()) {
315
+						// reroute CPT template view to maintenance_mode.template.php
316
+						if (! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
317
+							add_filter('template_include', array('EE_Maintenance_Mode', 'template_include'), 99999);
318
+						}
319
+						if (has_filter('the_content', array(EE_Maintenance_Mode::instance(), 'the_content'))) {
320
+							add_filter('the_content', array($this, 'inject_EE_shortcode_placeholder'), 1);
321
+						}
322
+						return;
323
+					}
324
+					$this->_generate_CptQueryModifier($WP_Query, $post_type);
325
+				}
326
+			}
327
+		}
328
+	}
329
+
330
+
331
+	/**
332
+	 * @param \WP_Query $WP_Query
333
+	 * @param string    $post_type
334
+	 * @throws InvalidArgumentException
335
+	 * @throws InvalidDataTypeException
336
+	 * @throws InvalidInterfaceException
337
+	 */
338
+	protected function _generate_CptQueryModifier(WP_Query $WP_Query, $post_type)
339
+	{
340
+		$this->query_modifier = LoaderFactory::getLoader()->getShared(
341
+			'EventEspresso\core\CPTs\CptQueryModifier',
342
+			array(
343
+				$post_type,
344
+				$this->_CPTs[ $post_type ],
345
+				$WP_Query,
346
+			)
347
+		);
348
+		$this->_CPT_taxonomies = $this->query_modifier->taxonomies();
349
+	}
350
+
351
+
352
+	/**
353
+	 * inject_EE_shortcode_placeholder
354
+	 * in order to display the M-Mode notice on our CPT routes,
355
+	 * we need to first inject what looks like one of our shortcodes,
356
+	 * so that it can be replaced with the actual M-Mode notice
357
+	 *
358
+	 * @return string
359
+	 */
360
+	public function inject_EE_shortcode_placeholder()
361
+	{
362
+		return '[ESPRESSO_';
363
+	}
364
+
365
+
366
+	/**
367
+	 * @deprecated
368
+	 * @since  4.8.41
369
+	 * @return void
370
+	 */
371
+	public function _possibly_set_ee_request_var()
372
+	{
373
+		$this->query_modifier->setRequestVarsIfCpt();
374
+	}
375
+
376
+
377
+	/**
378
+	 * @deprecated
379
+	 * @since  4.8.41
380
+	 * @param  $SQL
381
+	 * @return string
382
+	 */
383
+	public function posts_fields($SQL)
384
+	{
385
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
386
+			return $this->query_modifier->postsFields($SQL);
387
+		}
388
+		return $SQL;
389
+	}
390
+
391
+
392
+	/**
393
+	 * @deprecated
394
+	 * @since  4.8.41
395
+	 * @param  $SQL
396
+	 * @return string
397
+	 */
398
+	public function posts_join($SQL)
399
+	{
400
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
401
+			return $this->query_modifier->postsJoin($SQL);
402
+		}
403
+		return $SQL;
404
+	}
405
+
406
+
407
+	/**
408
+	 * @deprecated
409
+	 * @since  4.8.41
410
+	 * @param  \WP_Post[] $posts
411
+	 * @return \WP_Post[]
412
+	 */
413
+	public function the_posts($posts)
414
+	{
415
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
416
+			$this->query_modifier->thePosts($posts);
417
+		}
418
+		return $posts;
419
+	}
420
+
421
+
422
+	/**
423
+	 * @deprecated
424
+	 * @since  4.8.41
425
+	 * @param $url
426
+	 * @param $ID
427
+	 * @return string
428
+	 */
429
+	public function get_edit_post_link($url, $ID)
430
+	{
431
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
432
+			return $this->query_modifier->getEditPostLink($url, $ID);
433
+		}
434
+		return '';
435
+	}
436
+
437
+
438
+	/**
439
+	 * @deprecated
440
+	 * @since  4.8.41
441
+	 * @param null $WP_Query
442
+	 */
443
+	protected function _do_template_filters($WP_Query = null)
444
+	{
445
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
446
+			$this->query_modifier->addTemplateFilters();
447
+		}
448
+	}
449
+
450
+
451
+	/**
452
+	 * @deprecated
453
+	 * @since  4.8.41
454
+	 * @param string $current_template Existing default template path derived for this page call.
455
+	 * @return string the path to the full template file.
456
+	 */
457
+	public function single_cpt_template($current_template)
458
+	{
459
+		if ($this->query_modifier instanceof EventEspresso\Core\CPTs\CptQueryModifier) {
460
+			return $this->query_modifier->singleCptTemplate($current_template);
461
+		}
462
+		return $current_template;
463
+	}
464 464
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
         if (is_array($this->_CPTs)) {
129 129
             foreach ($this->_CPTs as $CPT_type => $CPT) {
130 130
                 if (isset($CPT['plural_slug'])) {
131
-                    $_CPT_endpoints [ (string) $CPT['plural_slug'] ] = $CPT_type;
131
+                    $_CPT_endpoints [(string) $CPT['plural_slug']] = $CPT_type;
132 132
                 }
133 133
             }
134 134
         }
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
     public function pre_get_posts($WP_Query)
152 152
     {
153 153
         // check that post-type is set
154
-        if (! $WP_Query instanceof WP_Query) {
154
+        if ( ! $WP_Query instanceof WP_Query) {
155 155
             return;
156 156
         }
157 157
         // add our conditionals
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
             $terms = EEM_Term::instance()->get_all_CPT_post_tags();
196 196
             foreach ($terms as $term) {
197 197
                 if ($term instanceof EE_Term) {
198
-                    $this->_CPT_terms[ $term->slug() ] = $term;
198
+                    $this->_CPT_terms[$term->slug()] = $term;
199 199
                 }
200 200
             }
201 201
         }
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
             // loop thru our taxonomies
261 261
             foreach ($this->_CPT_taxonomies as $CPT_taxonomy => $CPT_taxonomy_details) {
262 262
                 // check if one of our taxonomies is set as a query var
263
-                if (isset($WP_Query->query[ $CPT_taxonomy ])) {
263
+                if (isset($WP_Query->query[$CPT_taxonomy])) {
264 264
                     // but which CPT does that correspond to??? hmmm... guess we gotta go looping
265 265
                     foreach ($this->_CPTs as $post_type => $CPT) {
266 266
                         // verify our CPT has args, is public and has taxonomies set
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
                                     break;
285 285
                                 default:
286 286
                                     do_action(
287
-                                        'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_' . $post_type . '_post_type',
287
+                                        'AHEE__EE_CPT_Strategy___set_CPT_taxonomies_on_WP_Query__for_'.$post_type.'_post_type',
288 288
                                         $WP_Query,
289 289
                                         $this
290 290
                                     );
@@ -309,11 +309,11 @@  discard block
 block discarded – undo
309 309
             // loop thru post_types as array
310 310
             foreach ((array) $WP_Query->query_vars['post_type'] as $post_type) {
311 311
                 // is current query for an EE CPT ?
312
-                if (isset($this->_CPTs[ $post_type ])) {
312
+                if (isset($this->_CPTs[$post_type])) {
313 313
                     // is EE on or off ?
314 314
                     if (EE_Maintenance_Mode::instance()->level()) {
315 315
                         // reroute CPT template view to maintenance_mode.template.php
316
-                        if (! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
316
+                        if ( ! has_filter('template_include', array('EE_Maintenance_Mode', 'template_include'))) {
317 317
                             add_filter('template_include', array('EE_Maintenance_Mode', 'template_include'), 99999);
318 318
                         }
319 319
                         if (has_filter('the_content', array(EE_Maintenance_Mode::instance(), 'the_content'))) {
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
             'EventEspresso\core\CPTs\CptQueryModifier',
342 342
             array(
343 343
                 $post_type,
344
-                $this->_CPTs[ $post_type ],
344
+                $this->_CPTs[$post_type],
345 345
                 $WP_Query,
346 346
             )
347 347
         );
Please login to merge, or discard this patch.
core/CPTs/EE_CPT_Venue_Strategy.core.php 1 patch
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -12,55 +12,55 @@
 block discarded – undo
12 12
 class EE_CPT_Venue_Strategy
13 13
 {
14 14
 
15
-    /**
16
-     * $CPT - the current page, if it utilizes CPTs
17
-     *
18
-     * @var    array
19
-     * @access    protected
20
-     */
21
-    protected $CPT = null;
15
+	/**
16
+	 * $CPT - the current page, if it utilizes CPTs
17
+	 *
18
+	 * @var    array
19
+	 * @access    protected
20
+	 */
21
+	protected $CPT = null;
22 22
 
23 23
 
24
-    /**
25
-     *    class constructor
26
-     *
27
-     * @access    public
28
-     * @param    array $arguments
29
-     * @return \EE_CPT_Venue_Strategy
30
-     */
31
-    public function __construct($arguments = array())
32
-    {
33
-        $this->CPT = isset($arguments['CPT']) ? $arguments['CPT'] : null;
34
-        $WP_Query = isset($arguments['WP_Query']) ? $arguments['WP_Query'] : null;
35
-        if ($WP_Query instanceof WP_Query && ! $WP_Query->is_tag) {
36
-            $WP_Query->is_espresso_venue_single = is_singular()
37
-                                                  && isset($WP_Query->query->post_type)
38
-                                                  && $WP_Query->query->post_type == 'espresso_venues';
39
-            $WP_Query->is_espresso_venue_archive = is_post_type_archive('espresso_venues') ? true : false;
40
-            $WP_Query->is_espresso_venue_taxonomy = is_tax('espresso_venue_categories') ? true : false;
41
-        }
42
-        add_filter('the_posts', array($this, 'the_posts'), 1, 2);
43
-    }
24
+	/**
25
+	 *    class constructor
26
+	 *
27
+	 * @access    public
28
+	 * @param    array $arguments
29
+	 * @return \EE_CPT_Venue_Strategy
30
+	 */
31
+	public function __construct($arguments = array())
32
+	{
33
+		$this->CPT = isset($arguments['CPT']) ? $arguments['CPT'] : null;
34
+		$WP_Query = isset($arguments['WP_Query']) ? $arguments['WP_Query'] : null;
35
+		if ($WP_Query instanceof WP_Query && ! $WP_Query->is_tag) {
36
+			$WP_Query->is_espresso_venue_single = is_singular()
37
+												  && isset($WP_Query->query->post_type)
38
+												  && $WP_Query->query->post_type == 'espresso_venues';
39
+			$WP_Query->is_espresso_venue_archive = is_post_type_archive('espresso_venues') ? true : false;
40
+			$WP_Query->is_espresso_venue_taxonomy = is_tax('espresso_venue_categories') ? true : false;
41
+		}
42
+		add_filter('the_posts', array($this, 'the_posts'), 1, 2);
43
+	}
44 44
 
45 45
 
46
-    /**
47
-     *    the_posts
48
-     *
49
-     * @access    public
50
-     * @param          $posts
51
-     * @param WP_Query $wp_query
52
-     * @return    void
53
-     */
54
-    public function the_posts($posts, WP_Query $wp_query)
55
-    {
56
-        // automagically load the EEH_Venue_View helper so that it's functions are available
57
-        if (
58
-            isset(EE_Registry::instance()->CFG->map_settings->use_google_maps)
59
-            && EE_Registry::instance()->CFG->map_settings->use_google_maps
60
-        ) {
61
-            EEH_Maps::espresso_google_map_js();
62
-        }
63
-        remove_filter('the_posts', array($this, 'the_posts'), 1, 2);
64
-        return $posts;
65
-    }
46
+	/**
47
+	 *    the_posts
48
+	 *
49
+	 * @access    public
50
+	 * @param          $posts
51
+	 * @param WP_Query $wp_query
52
+	 * @return    void
53
+	 */
54
+	public function the_posts($posts, WP_Query $wp_query)
55
+	{
56
+		// automagically load the EEH_Venue_View helper so that it's functions are available
57
+		if (
58
+			isset(EE_Registry::instance()->CFG->map_settings->use_google_maps)
59
+			&& EE_Registry::instance()->CFG->map_settings->use_google_maps
60
+		) {
61
+			EEH_Maps::espresso_google_map_js();
62
+		}
63
+		remove_filter('the_posts', array($this, 'the_posts'), 1, 2);
64
+		return $posts;
65
+	}
66 66
 }
Please login to merge, or discard this patch.
core/CPTs/EE_CPT_Event_Strategy.core.php 2 patches
Indentation   +232 added lines, -232 removed lines patch added patch discarded remove patch
@@ -13,258 +13,258 @@
 block discarded – undo
13 13
 class EE_CPT_Event_Strategy
14 14
 {
15 15
 
16
-    /**
17
-     * the current page, if it utilizes CPTs
18
-     *
19
-     * @var object $CPT
20
-     */
21
-    protected $CPT;
16
+	/**
17
+	 * the current page, if it utilizes CPTs
18
+	 *
19
+	 * @var object $CPT
20
+	 */
21
+	protected $CPT;
22 22
 
23 23
 
24
-    /**
25
-     * @param WP_Query $wp_query
26
-     * @param array    $CPT
27
-     */
28
-    public function __construct($wp_query, $CPT = array())
29
-    {
30
-        if ($wp_query instanceof WP_Query) {
31
-            $WP_Query = $wp_query;
32
-            $this->CPT = $CPT;
33
-        } else {
34
-            $WP_Query = isset($wp_query['WP_Query']) ? $wp_query['WP_Query'] : null;
35
-            $this->CPT = isset($wp_query['CPT']) ? $wp_query['CPT'] : null;
36
-        }
37
-        // !!!!!!!!!!  IMPORTANT !!!!!!!!!!!!
38
-        // here's the list of available filters in the WP_Query object
39
-        // 'posts_where'
40
-        // 'posts_where_paged'
41
-        // 'posts_groupby'
42
-        // 'posts_join_paged'
43
-        // 'posts_orderby'
44
-        // 'posts_distinct'
45
-        // 'post_limits'
46
-        // 'posts_fields'
47
-        // 'posts_join'
48
-        $this->_add_filters();
49
-        if ($WP_Query instanceof WP_Query) {
50
-            $WP_Query->is_espresso_event_single = is_singular()
51
-                                                  && isset($WP_Query->query->post_type)
52
-                                                  && $WP_Query->query->post_type === 'espresso_events';
53
-            $WP_Query->is_espresso_event_archive = is_post_type_archive('espresso_events');
54
-            $WP_Query->is_espresso_event_taxonomy = is_tax('espresso_event_categories');
55
-        }
56
-    }
24
+	/**
25
+	 * @param WP_Query $wp_query
26
+	 * @param array    $CPT
27
+	 */
28
+	public function __construct($wp_query, $CPT = array())
29
+	{
30
+		if ($wp_query instanceof WP_Query) {
31
+			$WP_Query = $wp_query;
32
+			$this->CPT = $CPT;
33
+		} else {
34
+			$WP_Query = isset($wp_query['WP_Query']) ? $wp_query['WP_Query'] : null;
35
+			$this->CPT = isset($wp_query['CPT']) ? $wp_query['CPT'] : null;
36
+		}
37
+		// !!!!!!!!!!  IMPORTANT !!!!!!!!!!!!
38
+		// here's the list of available filters in the WP_Query object
39
+		// 'posts_where'
40
+		// 'posts_where_paged'
41
+		// 'posts_groupby'
42
+		// 'posts_join_paged'
43
+		// 'posts_orderby'
44
+		// 'posts_distinct'
45
+		// 'post_limits'
46
+		// 'posts_fields'
47
+		// 'posts_join'
48
+		$this->_add_filters();
49
+		if ($WP_Query instanceof WP_Query) {
50
+			$WP_Query->is_espresso_event_single = is_singular()
51
+												  && isset($WP_Query->query->post_type)
52
+												  && $WP_Query->query->post_type === 'espresso_events';
53
+			$WP_Query->is_espresso_event_archive = is_post_type_archive('espresso_events');
54
+			$WP_Query->is_espresso_event_taxonomy = is_tax('espresso_event_categories');
55
+		}
56
+	}
57 57
 
58 58
 
59
-    /**
60
-     * When an instance of this class is created, we add our filters
61
-     * (which will get removed in case the next call to get_posts ISN'T
62
-     * for event CPTs)
63
-     */
64
-    protected function _add_filters()
65
-    {
66
-        add_filter('posts_fields', array($this, 'posts_fields'), 1, 2);
67
-        add_filter('posts_join', array($this, 'posts_join'), 1, 2);
68
-        add_filter('posts_where', array($this, 'posts_where'), 10, 2);
69
-        // add_filter( 'the_posts', array( $this, 'the_posts' ), 1, 2 );
70
-        add_filter('posts_orderby', array($this, 'posts_orderby'), 1, 2);
71
-        add_filter('posts_groupby', array($this, 'posts_groupby'), 1, 2);
72
-        add_action('posts_selection', array($this, 'remove_filters'));
73
-    }
59
+	/**
60
+	 * When an instance of this class is created, we add our filters
61
+	 * (which will get removed in case the next call to get_posts ISN'T
62
+	 * for event CPTs)
63
+	 */
64
+	protected function _add_filters()
65
+	{
66
+		add_filter('posts_fields', array($this, 'posts_fields'), 1, 2);
67
+		add_filter('posts_join', array($this, 'posts_join'), 1, 2);
68
+		add_filter('posts_where', array($this, 'posts_where'), 10, 2);
69
+		// add_filter( 'the_posts', array( $this, 'the_posts' ), 1, 2 );
70
+		add_filter('posts_orderby', array($this, 'posts_orderby'), 1, 2);
71
+		add_filter('posts_groupby', array($this, 'posts_groupby'), 1, 2);
72
+		add_action('posts_selection', array($this, 'remove_filters'));
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * public access to _remove_filters()
78
-     *
79
-     * @since 4.9.63.p
80
-     */
81
-    public function remove_filters()
82
-    {
83
-        $this->_remove_filters();
84
-    }
76
+	/**
77
+	 * public access to _remove_filters()
78
+	 *
79
+	 * @since 4.9.63.p
80
+	 */
81
+	public function remove_filters()
82
+	{
83
+		$this->_remove_filters();
84
+	}
85 85
 
86 86
 
87
-    /**
88
-     * Should eb called when the last filter or hook is fired for this CPT strategy.
89
-     * This is to avoid applying this CPT strategy for other posts or CPTs (eg,
90
-     * we don't want to join to the datetime table when querying for venues, do we!?)
91
-     */
92
-    protected function _remove_filters()
93
-    {
94
-        remove_filter('posts_fields', array($this, 'posts_fields'), 1);
95
-        remove_filter('posts_join', array($this, 'posts_join'), 1);
96
-        remove_filter('posts_where', array($this, 'posts_where'), 10);
97
-        // remove_filter( 'the_posts', array( $this, 'the_posts' ), 1 );
98
-        remove_filter('posts_orderby', array($this, 'posts_orderby'), 1);
99
-        remove_filter('posts_groupby', array($this, 'posts_groupby'), 1);
100
-        remove_action('posts_selection', array($this, 'remove_filters'));
101
-    }
87
+	/**
88
+	 * Should eb called when the last filter or hook is fired for this CPT strategy.
89
+	 * This is to avoid applying this CPT strategy for other posts or CPTs (eg,
90
+	 * we don't want to join to the datetime table when querying for venues, do we!?)
91
+	 */
92
+	protected function _remove_filters()
93
+	{
94
+		remove_filter('posts_fields', array($this, 'posts_fields'), 1);
95
+		remove_filter('posts_join', array($this, 'posts_join'), 1);
96
+		remove_filter('posts_where', array($this, 'posts_where'), 10);
97
+		// remove_filter( 'the_posts', array( $this, 'the_posts' ), 1 );
98
+		remove_filter('posts_orderby', array($this, 'posts_orderby'), 1);
99
+		remove_filter('posts_groupby', array($this, 'posts_groupby'), 1);
100
+		remove_action('posts_selection', array($this, 'remove_filters'));
101
+	}
102 102
 
103 103
 
104
-    /**
105
-     * @param string   $SQL
106
-     * @param WP_Query $wp_query
107
-     * @return    string
108
-     * @throws EE_Error
109
-     * @throws InvalidArgumentException
110
-     * @throws InvalidDataTypeException
111
-     * @throws InvalidInterfaceException
112
-     */
113
-    public function posts_fields($SQL, WP_Query $wp_query)
114
-    {
115
-        if (
116
-            $wp_query instanceof WP_Query
117
-            &&
118
-            (
119
-                $wp_query->is_espresso_event_single
120
-                || $wp_query->is_espresso_event_archive
121
-                || $wp_query->is_espresso_event_taxonomy
122
-            )
123
-        ) {
124
-            // adds something like ", wp_esp_datetime.* " to WP Query SELECT statement
125
-            $SQL .= ', ' . EEM_Datetime::instance()->table() . '.* ';
126
-            if ($wp_query->is_espresso_event_archive || $wp_query->is_espresso_event_taxonomy) {
127
-                // because we only want to retrieve the next upcoming datetime for each event:
128
-                // add something like:
129
-                // ", MIN( wp_esp_datetime.DTT_EVT_start ) as event_start_date "
130
-                // to WP Query SELECT statement
131
-                $SQL .= ', MIN( ' . EEM_Datetime::instance()->table() . '.DTT_EVT_start ) as event_start_date ';
132
-            }
133
-        }
134
-        return $SQL;
135
-    }
104
+	/**
105
+	 * @param string   $SQL
106
+	 * @param WP_Query $wp_query
107
+	 * @return    string
108
+	 * @throws EE_Error
109
+	 * @throws InvalidArgumentException
110
+	 * @throws InvalidDataTypeException
111
+	 * @throws InvalidInterfaceException
112
+	 */
113
+	public function posts_fields($SQL, WP_Query $wp_query)
114
+	{
115
+		if (
116
+			$wp_query instanceof WP_Query
117
+			&&
118
+			(
119
+				$wp_query->is_espresso_event_single
120
+				|| $wp_query->is_espresso_event_archive
121
+				|| $wp_query->is_espresso_event_taxonomy
122
+			)
123
+		) {
124
+			// adds something like ", wp_esp_datetime.* " to WP Query SELECT statement
125
+			$SQL .= ', ' . EEM_Datetime::instance()->table() . '.* ';
126
+			if ($wp_query->is_espresso_event_archive || $wp_query->is_espresso_event_taxonomy) {
127
+				// because we only want to retrieve the next upcoming datetime for each event:
128
+				// add something like:
129
+				// ", MIN( wp_esp_datetime.DTT_EVT_start ) as event_start_date "
130
+				// to WP Query SELECT statement
131
+				$SQL .= ', MIN( ' . EEM_Datetime::instance()->table() . '.DTT_EVT_start ) as event_start_date ';
132
+			}
133
+		}
134
+		return $SQL;
135
+	}
136 136
 
137 137
 
138
-    /**
139
-     * @param string   $SQL
140
-     * @param WP_Query $wp_query
141
-     * @return string
142
-     * @throws EE_Error
143
-     * @throws InvalidArgumentException
144
-     * @throws InvalidDataTypeException
145
-     * @throws InvalidInterfaceException
146
-     */
147
-    public function posts_join($SQL, WP_Query $wp_query)
148
-    {
149
-        if (
150
-            $wp_query instanceof WP_Query
151
-            &&
152
-            (
153
-                $wp_query->is_espresso_event_single
154
-                || $wp_query->is_espresso_event_archive
155
-                || $wp_query->is_espresso_event_taxonomy
156
-            )
157
-        ) {
158
-            // adds something like:
159
-            // " LEFT JOIN wp_esp_datetime ON ( wp_esp_datetime.EVT_ID = wp_posts.ID ) "
160
-            // to WP Query JOIN statement
161
-            $SQL .= ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . EEM_Event::instance()->table()
162
-                    . '.ID = ' . EEM_Datetime::instance()->table() . '.'
163
-                    . EEM_Event::instance()->primary_key_name() . ' ) ';
164
-        }
165
-        return $SQL;
166
-    }
138
+	/**
139
+	 * @param string   $SQL
140
+	 * @param WP_Query $wp_query
141
+	 * @return string
142
+	 * @throws EE_Error
143
+	 * @throws InvalidArgumentException
144
+	 * @throws InvalidDataTypeException
145
+	 * @throws InvalidInterfaceException
146
+	 */
147
+	public function posts_join($SQL, WP_Query $wp_query)
148
+	{
149
+		if (
150
+			$wp_query instanceof WP_Query
151
+			&&
152
+			(
153
+				$wp_query->is_espresso_event_single
154
+				|| $wp_query->is_espresso_event_archive
155
+				|| $wp_query->is_espresso_event_taxonomy
156
+			)
157
+		) {
158
+			// adds something like:
159
+			// " LEFT JOIN wp_esp_datetime ON ( wp_esp_datetime.EVT_ID = wp_posts.ID ) "
160
+			// to WP Query JOIN statement
161
+			$SQL .= ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . EEM_Event::instance()->table()
162
+					. '.ID = ' . EEM_Datetime::instance()->table() . '.'
163
+					. EEM_Event::instance()->primary_key_name() . ' ) ';
164
+		}
165
+		return $SQL;
166
+	}
167 167
 
168 168
 
169
-    /**
170
-     * @param string   $SQL
171
-     * @param WP_Query $wp_query
172
-     * @return string
173
-     * @throws EE_Error
174
-     * @throws InvalidArgumentException
175
-     * @throws InvalidDataTypeException
176
-     * @throws InvalidInterfaceException
177
-     */
178
-    public function posts_where($SQL, WP_Query $wp_query)
179
-    {
180
-        if (
181
-            $wp_query instanceof WP_Query
182
-            &&
183
-            (
184
-                $wp_query->is_espresso_event_archive
185
-                || $wp_query->is_espresso_event_taxonomy
186
-            )
187
-        ) {
188
-            if (
189
-                ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive)
190
-                || ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events)
191
-                || ! EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events
192
-            ) {
193
-                $SQL .= ' AND ' . EEM_Datetime::instance()->table() . ".DTT_EVT_end > '"
194
-                        . current_time('mysql', true) . "' ";
195
-            }
196
-        }
197
-        return $SQL;
198
-    }
169
+	/**
170
+	 * @param string   $SQL
171
+	 * @param WP_Query $wp_query
172
+	 * @return string
173
+	 * @throws EE_Error
174
+	 * @throws InvalidArgumentException
175
+	 * @throws InvalidDataTypeException
176
+	 * @throws InvalidInterfaceException
177
+	 */
178
+	public function posts_where($SQL, WP_Query $wp_query)
179
+	{
180
+		if (
181
+			$wp_query instanceof WP_Query
182
+			&&
183
+			(
184
+				$wp_query->is_espresso_event_archive
185
+				|| $wp_query->is_espresso_event_taxonomy
186
+			)
187
+		) {
188
+			if (
189
+				! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive)
190
+				|| ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events)
191
+				|| ! EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events
192
+			) {
193
+				$SQL .= ' AND ' . EEM_Datetime::instance()->table() . ".DTT_EVT_end > '"
194
+						. current_time('mysql', true) . "' ";
195
+			}
196
+		}
197
+		return $SQL;
198
+	}
199 199
 
200 200
 
201
-    /**
202
-     * @param string   $SQL
203
-     * @param WP_Query $wp_query
204
-     * @return string
205
-     */
206
-    public function posts_orderby($SQL, WP_Query $wp_query)
207
-    {
208
-        if (
209
-            $wp_query instanceof WP_Query
210
-            &&
211
-            (
212
-                $wp_query->is_espresso_event_archive
213
-                || $wp_query->is_espresso_event_taxonomy
214
-            )
215
-        ) {
216
-            $SQL = ' event_start_date ASC ';
217
-        }
218
-        return $SQL;
219
-    }
201
+	/**
202
+	 * @param string   $SQL
203
+	 * @param WP_Query $wp_query
204
+	 * @return string
205
+	 */
206
+	public function posts_orderby($SQL, WP_Query $wp_query)
207
+	{
208
+		if (
209
+			$wp_query instanceof WP_Query
210
+			&&
211
+			(
212
+				$wp_query->is_espresso_event_archive
213
+				|| $wp_query->is_espresso_event_taxonomy
214
+			)
215
+		) {
216
+			$SQL = ' event_start_date ASC ';
217
+		}
218
+		return $SQL;
219
+	}
220 220
 
221 221
 
222
-    /**
223
-     * @param string   $SQL
224
-     * @param WP_Query $wp_query
225
-     * @return string
226
-     */
227
-    public function posts_groupby($SQL, WP_Query $wp_query)
228
-    {
229
-        if (
230
-            $wp_query instanceof WP_Query
231
-            &&
232
-            (
233
-                $wp_query->is_espresso_event_archive
234
-                || $wp_query->is_espresso_event_taxonomy
235
-            )
236
-        ) {
237
-            // TODO: add event list option for displaying ALL datetimes in event list or only primary datetime (default)
238
-            // we're joining to the datetimes table, where there can be MANY datetimes for a single event,
239
-            // but we want to only show each event only once
240
-            // (whereas if we didn't group them by the post's ID, then we would end up with many repeats)
241
-            global $wpdb;
242
-            $SQL = $wpdb->posts . '.ID ';
243
-        }
244
-        return $SQL;
245
-    }
222
+	/**
223
+	 * @param string   $SQL
224
+	 * @param WP_Query $wp_query
225
+	 * @return string
226
+	 */
227
+	public function posts_groupby($SQL, WP_Query $wp_query)
228
+	{
229
+		if (
230
+			$wp_query instanceof WP_Query
231
+			&&
232
+			(
233
+				$wp_query->is_espresso_event_archive
234
+				|| $wp_query->is_espresso_event_taxonomy
235
+			)
236
+		) {
237
+			// TODO: add event list option for displaying ALL datetimes in event list or only primary datetime (default)
238
+			// we're joining to the datetimes table, where there can be MANY datetimes for a single event,
239
+			// but we want to only show each event only once
240
+			// (whereas if we didn't group them by the post's ID, then we would end up with many repeats)
241
+			global $wpdb;
242
+			$SQL = $wpdb->posts . '.ID ';
243
+		}
244
+		return $SQL;
245
+	}
246 246
 
247 247
 
248
-    /**
249
-     * @param array    $posts
250
-     * @param WP_Query $wp_query
251
-     * @return array
252
-     */
253
-    public function the_posts($posts, WP_Query $wp_query)
254
-    {
255
-        return $posts;
256
-    }
248
+	/**
249
+	 * @param array    $posts
250
+	 * @param WP_Query $wp_query
251
+	 * @return array
252
+	 */
253
+	public function the_posts($posts, WP_Query $wp_query)
254
+	{
255
+		return $posts;
256
+	}
257 257
 
258 258
 
259
-    /**
260
-     * @param null $meta_value
261
-     * @param      $post_id
262
-     * @param      $meta_key
263
-     * @param      $single
264
-     * @return    string
265
-     */
266
-    public function get_EE_post_type_metadata($meta_value = null, $post_id, $meta_key, $single)
267
-    {
268
-        return $meta_value;
269
-    }
259
+	/**
260
+	 * @param null $meta_value
261
+	 * @param      $post_id
262
+	 * @param      $meta_key
263
+	 * @param      $single
264
+	 * @return    string
265
+	 */
266
+	public function get_EE_post_type_metadata($meta_value = null, $post_id, $meta_key, $single)
267
+	{
268
+		return $meta_value;
269
+	}
270 270
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -122,13 +122,13 @@  discard block
 block discarded – undo
122 122
             )
123 123
         ) {
124 124
             // adds something like ", wp_esp_datetime.* " to WP Query SELECT statement
125
-            $SQL .= ', ' . EEM_Datetime::instance()->table() . '.* ';
125
+            $SQL .= ', '.EEM_Datetime::instance()->table().'.* ';
126 126
             if ($wp_query->is_espresso_event_archive || $wp_query->is_espresso_event_taxonomy) {
127 127
                 // because we only want to retrieve the next upcoming datetime for each event:
128 128
                 // add something like:
129 129
                 // ", MIN( wp_esp_datetime.DTT_EVT_start ) as event_start_date "
130 130
                 // to WP Query SELECT statement
131
-                $SQL .= ', MIN( ' . EEM_Datetime::instance()->table() . '.DTT_EVT_start ) as event_start_date ';
131
+                $SQL .= ', MIN( '.EEM_Datetime::instance()->table().'.DTT_EVT_start ) as event_start_date ';
132 132
             }
133 133
         }
134 134
         return $SQL;
@@ -158,9 +158,9 @@  discard block
 block discarded – undo
158 158
             // adds something like:
159 159
             // " LEFT JOIN wp_esp_datetime ON ( wp_esp_datetime.EVT_ID = wp_posts.ID ) "
160 160
             // to WP Query JOIN statement
161
-            $SQL .= ' INNER JOIN ' . EEM_Datetime::instance()->table() . ' ON ( ' . EEM_Event::instance()->table()
162
-                    . '.ID = ' . EEM_Datetime::instance()->table() . '.'
163
-                    . EEM_Event::instance()->primary_key_name() . ' ) ';
161
+            $SQL .= ' INNER JOIN '.EEM_Datetime::instance()->table().' ON ( '.EEM_Event::instance()->table()
162
+                    . '.ID = '.EEM_Datetime::instance()->table().'.'
163
+                    . EEM_Event::instance()->primary_key_name().' ) ';
164 164
         }
165 165
         return $SQL;
166 166
     }
@@ -190,8 +190,8 @@  discard block
 block discarded – undo
190 190
                 || ! isset(EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events)
191 191
                 || ! EE_Registry::instance()->CFG->template_settings->EED_Events_Archive->display_expired_events
192 192
             ) {
193
-                $SQL .= ' AND ' . EEM_Datetime::instance()->table() . ".DTT_EVT_end > '"
194
-                        . current_time('mysql', true) . "' ";
193
+                $SQL .= ' AND '.EEM_Datetime::instance()->table().".DTT_EVT_end > '"
194
+                        . current_time('mysql', true)."' ";
195 195
             }
196 196
         }
197 197
         return $SQL;
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
             // but we want to only show each event only once
240 240
             // (whereas if we didn't group them by the post's ID, then we would end up with many repeats)
241 241
             global $wpdb;
242
-            $SQL = $wpdb->posts . '.ID ';
242
+            $SQL = $wpdb->posts.'.ID ';
243 243
         }
244 244
         return $SQL;
245 245
     }
Please login to merge, or discard this patch.
core/services/progress_steps/ProgressStepInterface.php 1 patch
Indentation   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -12,33 +12,33 @@
 block discarded – undo
12 12
 interface ProgressStepInterface
13 13
 {
14 14
 
15
-    /**
16
-     * @return boolean
17
-     */
18
-    public function isCurrent();
19
-
20
-    /**
21
-     * @param boolean $is_current
22
-     */
23
-    public function setIsCurrent($is_current = true);
24
-
25
-    /**
26
-     * @return string
27
-     */
28
-    public function id();
29
-
30
-    /**
31
-     * @return int
32
-     */
33
-    public function order();
34
-
35
-    /**
36
-     * @return string
37
-     */
38
-    public function htmlClass();
39
-
40
-    /**
41
-     * @return string
42
-     */
43
-    public function text();
15
+	/**
16
+	 * @return boolean
17
+	 */
18
+	public function isCurrent();
19
+
20
+	/**
21
+	 * @param boolean $is_current
22
+	 */
23
+	public function setIsCurrent($is_current = true);
24
+
25
+	/**
26
+	 * @return string
27
+	 */
28
+	public function id();
29
+
30
+	/**
31
+	 * @return int
32
+	 */
33
+	public function order();
34
+
35
+	/**
36
+	 * @return string
37
+	 */
38
+	public function htmlClass();
39
+
40
+	/**
41
+	 * @return string
42
+	 */
43
+	public function text();
44 44
 }
Please login to merge, or discard this patch.
core/services/commands/attendee/CreateAttendeeCommandHandler.php 1 patch
Indentation   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -21,135 +21,135 @@
 block discarded – undo
21 21
 {
22 22
 
23 23
 
24
-    /**
25
-     * @var EEM_Attendee $attendee_model
26
-     */
27
-    protected $attendee_model;
24
+	/**
25
+	 * @var EEM_Attendee $attendee_model
26
+	 */
27
+	protected $attendee_model;
28 28
 
29 29
 
30
-    /**
31
-     * @param EEM_Attendee $attendee_model
32
-     */
33
-    public function __construct(EEM_Attendee $attendee_model)
34
-    {
35
-        $this->attendee_model = $attendee_model;
36
-    }
30
+	/**
31
+	 * @param EEM_Attendee $attendee_model
32
+	 */
33
+	public function __construct(EEM_Attendee $attendee_model)
34
+	{
35
+		$this->attendee_model = $attendee_model;
36
+	}
37 37
 
38 38
 
39
-    /**
40
-     * @param CommandInterface|CreateAttendeeCommand $command
41
-     * @return EE_Attendee
42
-     * @throws EE_Error
43
-     * @throws InvalidEntityException
44
-     */
45
-    public function handle(CommandInterface $command)
46
-    {
47
-        // have we met before?
48
-        $attendee = $this->findExistingAttendee(
49
-            $command->registration(),
50
-            $command->attendeeDetails()
51
-        );
52
-        // did we find an already existing record for this attendee ?
53
-        if ($attendee instanceof EE_Attendee) {
54
-            $attendee = $this->updateExistingAttendeeData(
55
-                $attendee,
56
-                $command->attendeeDetails()
57
-            );
58
-        } else {
59
-            $attendee = $this->createNewAttendee(
60
-                $command->registration(),
61
-                $command->attendeeDetails()
62
-            );
63
-        }
64
-        return $attendee;
65
-    }
39
+	/**
40
+	 * @param CommandInterface|CreateAttendeeCommand $command
41
+	 * @return EE_Attendee
42
+	 * @throws EE_Error
43
+	 * @throws InvalidEntityException
44
+	 */
45
+	public function handle(CommandInterface $command)
46
+	{
47
+		// have we met before?
48
+		$attendee = $this->findExistingAttendee(
49
+			$command->registration(),
50
+			$command->attendeeDetails()
51
+		);
52
+		// did we find an already existing record for this attendee ?
53
+		if ($attendee instanceof EE_Attendee) {
54
+			$attendee = $this->updateExistingAttendeeData(
55
+				$attendee,
56
+				$command->attendeeDetails()
57
+			);
58
+		} else {
59
+			$attendee = $this->createNewAttendee(
60
+				$command->registration(),
61
+				$command->attendeeDetails()
62
+			);
63
+		}
64
+		return $attendee;
65
+	}
66 66
 
67 67
 
68
-    /**
69
-     * find_existing_attendee
70
-     *
71
-     * @param EE_Registration $registration
72
-     * @param  array          $attendee_data
73
-     * @return EE_Attendee
74
-     */
75
-    private function findExistingAttendee(EE_Registration $registration, array $attendee_data)
76
-    {
77
-        $existing_attendee = null;
78
-        // does this attendee already exist in the db ?
79
-        // we're searching using a combination of first name, last name, AND email address
80
-        $ATT_fname = ! empty($attendee_data['ATT_fname'])
81
-            ? $attendee_data['ATT_fname']
82
-            : '';
83
-        $ATT_lname = ! empty($attendee_data['ATT_lname'])
84
-            ? $attendee_data['ATT_lname']
85
-            : '';
86
-        $ATT_email = ! empty($attendee_data['ATT_email'])
87
-            ? $attendee_data['ATT_email']
88
-            : '';
89
-        // but only if those have values
90
-        if ($ATT_fname && $ATT_lname && $ATT_email) {
91
-            $existing_attendee = $this->attendee_model->find_existing_attendee(
92
-                array(
93
-                    'ATT_fname' => $ATT_fname,
94
-                    'ATT_lname' => $ATT_lname,
95
-                    'ATT_email' => $ATT_email,
96
-                )
97
-            );
98
-        }
99
-        return apply_filters(
100
-            'FHEE_EventEspresso_core_services_commands_attendee_CreateAttendeeCommandHandler__findExistingAttendee__existing_attendee',
101
-            $existing_attendee,
102
-            $registration,
103
-            $attendee_data
104
-        );
105
-    }
68
+	/**
69
+	 * find_existing_attendee
70
+	 *
71
+	 * @param EE_Registration $registration
72
+	 * @param  array          $attendee_data
73
+	 * @return EE_Attendee
74
+	 */
75
+	private function findExistingAttendee(EE_Registration $registration, array $attendee_data)
76
+	{
77
+		$existing_attendee = null;
78
+		// does this attendee already exist in the db ?
79
+		// we're searching using a combination of first name, last name, AND email address
80
+		$ATT_fname = ! empty($attendee_data['ATT_fname'])
81
+			? $attendee_data['ATT_fname']
82
+			: '';
83
+		$ATT_lname = ! empty($attendee_data['ATT_lname'])
84
+			? $attendee_data['ATT_lname']
85
+			: '';
86
+		$ATT_email = ! empty($attendee_data['ATT_email'])
87
+			? $attendee_data['ATT_email']
88
+			: '';
89
+		// but only if those have values
90
+		if ($ATT_fname && $ATT_lname && $ATT_email) {
91
+			$existing_attendee = $this->attendee_model->find_existing_attendee(
92
+				array(
93
+					'ATT_fname' => $ATT_fname,
94
+					'ATT_lname' => $ATT_lname,
95
+					'ATT_email' => $ATT_email,
96
+				)
97
+			);
98
+		}
99
+		return apply_filters(
100
+			'FHEE_EventEspresso_core_services_commands_attendee_CreateAttendeeCommandHandler__findExistingAttendee__existing_attendee',
101
+			$existing_attendee,
102
+			$registration,
103
+			$attendee_data
104
+		);
105
+	}
106 106
 
107 107
 
108
-    /**
109
-     * _update_existing_attendee_data
110
-     * in case it has changed since last time they registered for an event
111
-     *
112
-     * @param EE_Attendee $existing_attendee
113
-     * @param  array      $attendee_data
114
-     * @return EE_Attendee
115
-     * @throws EE_Error
116
-     */
117
-    private function updateExistingAttendeeData(EE_Attendee $existing_attendee, array $attendee_data)
118
-    {
119
-        // first remove fname, lname, and email from attendee data
120
-        // because these properties will be exactly the same as the returned attendee object,
121
-        // since they were used in the query to get the attendee object in the first place
122
-        $dont_set = array('ATT_fname', 'ATT_lname', 'ATT_email');
123
-        // now loop thru what's left and add to attendee CPT
124
-        foreach ($attendee_data as $property_name => $property_value) {
125
-            if (
126
-                ! in_array($property_name, $dont_set, true)
127
-                && $this->attendee_model->has_field($property_name)
128
-            ) {
129
-                $existing_attendee->set($property_name, $property_value);
130
-            }
131
-        }
132
-        // better save that now
133
-        $existing_attendee->save();
134
-        return $existing_attendee;
135
-    }
108
+	/**
109
+	 * _update_existing_attendee_data
110
+	 * in case it has changed since last time they registered for an event
111
+	 *
112
+	 * @param EE_Attendee $existing_attendee
113
+	 * @param  array      $attendee_data
114
+	 * @return EE_Attendee
115
+	 * @throws EE_Error
116
+	 */
117
+	private function updateExistingAttendeeData(EE_Attendee $existing_attendee, array $attendee_data)
118
+	{
119
+		// first remove fname, lname, and email from attendee data
120
+		// because these properties will be exactly the same as the returned attendee object,
121
+		// since they were used in the query to get the attendee object in the first place
122
+		$dont_set = array('ATT_fname', 'ATT_lname', 'ATT_email');
123
+		// now loop thru what's left and add to attendee CPT
124
+		foreach ($attendee_data as $property_name => $property_value) {
125
+			if (
126
+				! in_array($property_name, $dont_set, true)
127
+				&& $this->attendee_model->has_field($property_name)
128
+			) {
129
+				$existing_attendee->set($property_name, $property_value);
130
+			}
131
+		}
132
+		// better save that now
133
+		$existing_attendee->save();
134
+		return $existing_attendee;
135
+	}
136 136
 
137 137
 
138
-    /**
139
-     * create_new_attendee
140
-     *
141
-     * @param EE_Registration $registration
142
-     * @param  array          $attendee_data
143
-     * @return EE_Attendee
144
-     * @throws EE_Error
145
-     */
146
-    private function createNewAttendee(EE_Registration $registration, array $attendee_data)
147
-    {
148
-        // create new attendee object
149
-        $new_attendee = EE_Attendee::new_instance($attendee_data);
150
-        // set author to event creator
151
-        $new_attendee->set('ATT_author', $registration->event()->wp_user());
152
-        $new_attendee->save();
153
-        return $new_attendee;
154
-    }
138
+	/**
139
+	 * create_new_attendee
140
+	 *
141
+	 * @param EE_Registration $registration
142
+	 * @param  array          $attendee_data
143
+	 * @return EE_Attendee
144
+	 * @throws EE_Error
145
+	 */
146
+	private function createNewAttendee(EE_Registration $registration, array $attendee_data)
147
+	{
148
+		// create new attendee object
149
+		$new_attendee = EE_Attendee::new_instance($attendee_data);
150
+		// set author to event creator
151
+		$new_attendee->set('ATT_author', $registration->event()->wp_user());
152
+		$new_attendee->save();
153
+		return $new_attendee;
154
+	}
155 155
 }
Please login to merge, or discard this patch.
core/services/address/CountrySubRegionDao.php 2 patches
Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -26,252 +26,252 @@
 block discarded – undo
26 26
 class CountrySubRegionDao
27 27
 {
28 28
 
29
-    const REPO_URL = 'https://raw.githubusercontent.com/eventespresso/countries-and-subregions/master/';
29
+	const REPO_URL = 'https://raw.githubusercontent.com/eventespresso/countries-and-subregions/master/';
30 30
 
31
-    const OPTION_NAME_COUNTRY_DATA_VERSION = 'espresso-country-sub-region-data-version';
31
+	const OPTION_NAME_COUNTRY_DATA_VERSION = 'espresso-country-sub-region-data-version';
32 32
 
33
-    /**
34
-     * @var EEM_State $state_model
35
-     */
36
-    private $state_model;
33
+	/**
34
+	 * @var EEM_State $state_model
35
+	 */
36
+	private $state_model;
37 37
 
38
-    /**
39
-     * @var JsonValidator $json_validator
40
-     */
41
-    private $json_validator;
38
+	/**
39
+	 * @var JsonValidator $json_validator
40
+	 */
41
+	private $json_validator;
42 42
 
43
-    /**
44
-     * @var string $data_version
45
-     */
46
-    private $data_version;
43
+	/**
44
+	 * @var string $data_version
45
+	 */
46
+	private $data_version;
47 47
 
48
-    /**
49
-     * @var array $countries
50
-     */
51
-    private $countries = array();
48
+	/**
49
+	 * @var array $countries
50
+	 */
51
+	private $countries = array();
52 52
 
53 53
 
54
-    /**
55
-     * CountrySubRegionDao constructor.
56
-     *
57
-     * @param EEM_State     $state_model
58
-     * @param JsonValidator $json_validator
59
-     */
60
-    public function __construct(EEM_State $state_model, JsonValidator $json_validator)
61
-    {
62
-        $this->state_model = $state_model;
63
-        $this->json_validator = $json_validator;
64
-    }
54
+	/**
55
+	 * CountrySubRegionDao constructor.
56
+	 *
57
+	 * @param EEM_State     $state_model
58
+	 * @param JsonValidator $json_validator
59
+	 */
60
+	public function __construct(EEM_State $state_model, JsonValidator $json_validator)
61
+	{
62
+		$this->state_model = $state_model;
63
+		$this->json_validator = $json_validator;
64
+	}
65 65
 
66 66
 
67
-    /**
68
-     * @param EE_Country $country_object
69
-     * @return bool
70
-     * @throws EE_Error
71
-     * @throws InvalidArgumentException
72
-     * @throws InvalidDataTypeException
73
-     * @throws InvalidInterfaceException
74
-     * @throws ReflectionException
75
-     */
76
-    public function saveCountrySubRegions(EE_Country $country_object)
77
-    {
78
-        $CNT_ISO = $country_object->ID();
79
-        $has_sub_regions = $this->state_model->count(array(array('Country.CNT_ISO' => $CNT_ISO)));
80
-        $data = [];
81
-        if (empty($this->countries)) {
82
-            $this->data_version = $this->getCountrySubRegionDataVersion();
83
-            $data = $this->retrieveJsonData(self::REPO_URL . 'countries.json');
84
-        }
85
-        if (empty($data)) {
86
-            EE_Error::add_error(
87
-                'Country Subregion Data could not be retrieved',
88
-                __FILE__,
89
-                __METHOD__,
90
-                __LINE__
91
-            );
92
-        }
93
-        if (
94
-            ! $has_sub_regions
95
-            || (isset($data->version) && version_compare($data->version, $this->data_version))
96
-        ) {
97
-            if (
98
-                isset($data->countries)
99
-                && $this->processCountryData($CNT_ISO, $data->countries) > 0
100
-            ) {
101
-                $this->countries = $data->countries;
102
-                $this->updateCountrySubRegionDataVersion($data->version);
103
-                return true;
104
-            }
105
-        }
106
-        return false;
107
-    }
67
+	/**
68
+	 * @param EE_Country $country_object
69
+	 * @return bool
70
+	 * @throws EE_Error
71
+	 * @throws InvalidArgumentException
72
+	 * @throws InvalidDataTypeException
73
+	 * @throws InvalidInterfaceException
74
+	 * @throws ReflectionException
75
+	 */
76
+	public function saveCountrySubRegions(EE_Country $country_object)
77
+	{
78
+		$CNT_ISO = $country_object->ID();
79
+		$has_sub_regions = $this->state_model->count(array(array('Country.CNT_ISO' => $CNT_ISO)));
80
+		$data = [];
81
+		if (empty($this->countries)) {
82
+			$this->data_version = $this->getCountrySubRegionDataVersion();
83
+			$data = $this->retrieveJsonData(self::REPO_URL . 'countries.json');
84
+		}
85
+		if (empty($data)) {
86
+			EE_Error::add_error(
87
+				'Country Subregion Data could not be retrieved',
88
+				__FILE__,
89
+				__METHOD__,
90
+				__LINE__
91
+			);
92
+		}
93
+		if (
94
+			! $has_sub_regions
95
+			|| (isset($data->version) && version_compare($data->version, $this->data_version))
96
+		) {
97
+			if (
98
+				isset($data->countries)
99
+				&& $this->processCountryData($CNT_ISO, $data->countries) > 0
100
+			) {
101
+				$this->countries = $data->countries;
102
+				$this->updateCountrySubRegionDataVersion($data->version);
103
+				return true;
104
+			}
105
+		}
106
+		return false;
107
+	}
108 108
 
109 109
 
110
-    /**
111
-     * @since 4.9.70.p
112
-     * @return string
113
-     */
114
-    private function getCountrySubRegionDataVersion()
115
-    {
116
-        return get_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, null);
117
-    }
110
+	/**
111
+	 * @since 4.9.70.p
112
+	 * @return string
113
+	 */
114
+	private function getCountrySubRegionDataVersion()
115
+	{
116
+		return get_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, null);
117
+	}
118 118
 
119 119
 
120
-    /**
121
-     * @param string $version
122
-     */
123
-    private function updateCountrySubRegionDataVersion($version = '')
124
-    {
125
-        // add version option if it has never been added before, or update existing
126
-        if ($this->data_version === null) {
127
-            add_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version, '', false);
128
-        } else {
129
-            update_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version);
130
-        }
131
-    }
120
+	/**
121
+	 * @param string $version
122
+	 */
123
+	private function updateCountrySubRegionDataVersion($version = '')
124
+	{
125
+		// add version option if it has never been added before, or update existing
126
+		if ($this->data_version === null) {
127
+			add_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version, '', false);
128
+		} else {
129
+			update_option(self::OPTION_NAME_COUNTRY_DATA_VERSION, $version);
130
+		}
131
+	}
132 132
 
133 133
 
134
-    /**
135
-     * @param string $CNT_ISO
136
-     * @param array  $countries
137
-     * @return int
138
-     * @throws EE_Error
139
-     * @throws InvalidArgumentException
140
-     * @throws InvalidDataTypeException
141
-     * @throws InvalidInterfaceException
142
-     * @throws ReflectionException
143
-     * @since 4.9.70.p
144
-     */
145
-    private function processCountryData($CNT_ISO, $countries = array())
146
-    {
147
-        if (! empty($countries)) {
148
-            foreach ($countries as $key => $country) {
149
-                if (
150
-                    $country instanceof stdClass
151
-                    && $country->code === $CNT_ISO
152
-                    && empty($country->sub_regions)
153
-                    && ! empty($country->filename)
154
-                ) {
155
-                    $country->sub_regions = $this->retrieveJsonData(
156
-                        self::REPO_URL . 'countries/' . $country->filename . '.json'
157
-                    );
158
-                    return $this->saveSubRegionData($country, $country->sub_regions);
159
-                }
160
-            }
161
-        }
162
-        return 0;
163
-    }
134
+	/**
135
+	 * @param string $CNT_ISO
136
+	 * @param array  $countries
137
+	 * @return int
138
+	 * @throws EE_Error
139
+	 * @throws InvalidArgumentException
140
+	 * @throws InvalidDataTypeException
141
+	 * @throws InvalidInterfaceException
142
+	 * @throws ReflectionException
143
+	 * @since 4.9.70.p
144
+	 */
145
+	private function processCountryData($CNT_ISO, $countries = array())
146
+	{
147
+		if (! empty($countries)) {
148
+			foreach ($countries as $key => $country) {
149
+				if (
150
+					$country instanceof stdClass
151
+					&& $country->code === $CNT_ISO
152
+					&& empty($country->sub_regions)
153
+					&& ! empty($country->filename)
154
+				) {
155
+					$country->sub_regions = $this->retrieveJsonData(
156
+						self::REPO_URL . 'countries/' . $country->filename . '.json'
157
+					);
158
+					return $this->saveSubRegionData($country, $country->sub_regions);
159
+				}
160
+			}
161
+		}
162
+		return 0;
163
+	}
164 164
 
165 165
 
166
-    /**
167
-     * @param string $url
168
-     * @return array
169
-     */
170
-    private function retrieveJsonData($url)
171
-    {
172
-        if (empty($url)) {
173
-            EE_Error::add_error(
174
-                'No URL was provided!',
175
-                __FILE__,
176
-                __METHOD__,
177
-                __LINE__
178
-            );
179
-            return array();
180
-        }
181
-        $request = wp_safe_remote_get($url);
182
-        if ($request instanceof WP_Error) {
183
-            EE_Error::add_error(
184
-                $request->get_error_message(),
185
-                __FILE__,
186
-                __METHOD__,
187
-                __LINE__
188
-            );
189
-            return array();
190
-        }
191
-        $body = wp_remote_retrieve_body($request);
192
-        $json = json_decode($body);
193
-        if ($this->json_validator->isValid(__FILE__, __METHOD__, __LINE__)) {
194
-            return $json;
195
-        }
196
-        return array();
197
-    }
166
+	/**
167
+	 * @param string $url
168
+	 * @return array
169
+	 */
170
+	private function retrieveJsonData($url)
171
+	{
172
+		if (empty($url)) {
173
+			EE_Error::add_error(
174
+				'No URL was provided!',
175
+				__FILE__,
176
+				__METHOD__,
177
+				__LINE__
178
+			);
179
+			return array();
180
+		}
181
+		$request = wp_safe_remote_get($url);
182
+		if ($request instanceof WP_Error) {
183
+			EE_Error::add_error(
184
+				$request->get_error_message(),
185
+				__FILE__,
186
+				__METHOD__,
187
+				__LINE__
188
+			);
189
+			return array();
190
+		}
191
+		$body = wp_remote_retrieve_body($request);
192
+		$json = json_decode($body);
193
+		if ($this->json_validator->isValid(__FILE__, __METHOD__, __LINE__)) {
194
+			return $json;
195
+		}
196
+		return array();
197
+	}
198 198
 
199 199
 
200
-    /**
201
-     * @param stdClass $country
202
-     * @param array    $sub_regions
203
-     * @return int
204
-     * @throws EE_Error
205
-     * @throws InvalidArgumentException
206
-     * @throws InvalidDataTypeException
207
-     * @throws InvalidInterfaceException
208
-     * @throws ReflectionException
209
-     */
210
-    private function saveSubRegionData(stdClass $country, $sub_regions = array())
211
-    {
212
-        $results = 0;
213
-        if (is_array($sub_regions)) {
214
-            $existing_sub_regions = $this->getExistingStateAbbreviations($country->code);
215
-            foreach ($sub_regions as $sub_region) {
216
-                // remove country code from sub region code
217
-                $abbrev = str_replace(
218
-                    $country->code . '-',
219
-                    '',
220
-                    sanitize_text_field($sub_region->code)
221
-                );
222
-                // but NOT if sub region code results in only a number
223
-                if (absint($abbrev) !== 0) {
224
-                    $abbrev = sanitize_text_field($sub_region->code);
225
-                }
226
-                if (
227
-                    ! in_array($abbrev, $existing_sub_regions, true)
228
-                    && $this->state_model->insert(
229
-                        [
230
-                            // STA_ID CNT_ISO STA_abbrev STA_name STA_active
231
-                            'CNT_ISO'    => $country->code,
232
-                            'STA_abbrev' => $abbrev,
233
-                            'STA_name'   => sanitize_text_field($sub_region->name),
234
-                            'STA_active' => 1,
235
-                        ]
236
-                    )
237
-                ) {
238
-                    $results++;
239
-                }
240
-            }
241
-        }
242
-        return $results;
243
-    }
200
+	/**
201
+	 * @param stdClass $country
202
+	 * @param array    $sub_regions
203
+	 * @return int
204
+	 * @throws EE_Error
205
+	 * @throws InvalidArgumentException
206
+	 * @throws InvalidDataTypeException
207
+	 * @throws InvalidInterfaceException
208
+	 * @throws ReflectionException
209
+	 */
210
+	private function saveSubRegionData(stdClass $country, $sub_regions = array())
211
+	{
212
+		$results = 0;
213
+		if (is_array($sub_regions)) {
214
+			$existing_sub_regions = $this->getExistingStateAbbreviations($country->code);
215
+			foreach ($sub_regions as $sub_region) {
216
+				// remove country code from sub region code
217
+				$abbrev = str_replace(
218
+					$country->code . '-',
219
+					'',
220
+					sanitize_text_field($sub_region->code)
221
+				);
222
+				// but NOT if sub region code results in only a number
223
+				if (absint($abbrev) !== 0) {
224
+					$abbrev = sanitize_text_field($sub_region->code);
225
+				}
226
+				if (
227
+					! in_array($abbrev, $existing_sub_regions, true)
228
+					&& $this->state_model->insert(
229
+						[
230
+							// STA_ID CNT_ISO STA_abbrev STA_name STA_active
231
+							'CNT_ISO'    => $country->code,
232
+							'STA_abbrev' => $abbrev,
233
+							'STA_name'   => sanitize_text_field($sub_region->name),
234
+							'STA_active' => 1,
235
+						]
236
+					)
237
+				) {
238
+					$results++;
239
+				}
240
+			}
241
+		}
242
+		return $results;
243
+	}
244 244
 
245 245
 
246
-    /**
247
-     * @param string $CNT_ISO
248
-     * @since 4.9.76.p
249
-     * @return array
250
-     * @throws EE_Error
251
-     * @throws InvalidArgumentException
252
-     * @throws InvalidDataTypeException
253
-     * @throws InvalidInterfaceException
254
-     * @throws ReflectionException
255
-     */
256
-    private function getExistingStateAbbreviations($CNT_ISO)
257
-    {
258
-        $existing_sub_region_IDs = [];
259
-        $existing_sub_regions = $this->state_model->get_all(array(
260
-            array(
261
-                'Country.CNT_ISO' => array(
262
-                    'IN',
263
-                    [$CNT_ISO]
264
-                )
265
-            ),
266
-            'order_by' => array('Country.CNT_name' => 'ASC', 'STA_name' => 'ASC')
267
-        ));
268
-        if (is_array($existing_sub_regions)) {
269
-            foreach ($existing_sub_regions as $existing_sub_region) {
270
-                if ($existing_sub_region instanceof EE_State) {
271
-                    $existing_sub_region_IDs[] = $existing_sub_region->abbrev();
272
-                }
273
-            }
274
-        }
275
-        return $existing_sub_region_IDs;
276
-    }
246
+	/**
247
+	 * @param string $CNT_ISO
248
+	 * @since 4.9.76.p
249
+	 * @return array
250
+	 * @throws EE_Error
251
+	 * @throws InvalidArgumentException
252
+	 * @throws InvalidDataTypeException
253
+	 * @throws InvalidInterfaceException
254
+	 * @throws ReflectionException
255
+	 */
256
+	private function getExistingStateAbbreviations($CNT_ISO)
257
+	{
258
+		$existing_sub_region_IDs = [];
259
+		$existing_sub_regions = $this->state_model->get_all(array(
260
+			array(
261
+				'Country.CNT_ISO' => array(
262
+					'IN',
263
+					[$CNT_ISO]
264
+				)
265
+			),
266
+			'order_by' => array('Country.CNT_name' => 'ASC', 'STA_name' => 'ASC')
267
+		));
268
+		if (is_array($existing_sub_regions)) {
269
+			foreach ($existing_sub_regions as $existing_sub_region) {
270
+				if ($existing_sub_region instanceof EE_State) {
271
+					$existing_sub_region_IDs[] = $existing_sub_region->abbrev();
272
+				}
273
+			}
274
+		}
275
+		return $existing_sub_region_IDs;
276
+	}
277 277
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
         $data = [];
81 81
         if (empty($this->countries)) {
82 82
             $this->data_version = $this->getCountrySubRegionDataVersion();
83
-            $data = $this->retrieveJsonData(self::REPO_URL . 'countries.json');
83
+            $data = $this->retrieveJsonData(self::REPO_URL.'countries.json');
84 84
         }
85 85
         if (empty($data)) {
86 86
             EE_Error::add_error(
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
      */
145 145
     private function processCountryData($CNT_ISO, $countries = array())
146 146
     {
147
-        if (! empty($countries)) {
147
+        if ( ! empty($countries)) {
148 148
             foreach ($countries as $key => $country) {
149 149
                 if (
150 150
                     $country instanceof stdClass
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
                     && ! empty($country->filename)
154 154
                 ) {
155 155
                     $country->sub_regions = $this->retrieveJsonData(
156
-                        self::REPO_URL . 'countries/' . $country->filename . '.json'
156
+                        self::REPO_URL.'countries/'.$country->filename.'.json'
157 157
                     );
158 158
                     return $this->saveSubRegionData($country, $country->sub_regions);
159 159
                 }
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
             foreach ($sub_regions as $sub_region) {
216 216
                 // remove country code from sub region code
217 217
                 $abbrev = str_replace(
218
-                    $country->code . '-',
218
+                    $country->code.'-',
219 219
                     '',
220 220
                     sanitize_text_field($sub_region->code)
221 221
                 );
Please login to merge, or discard this patch.